mini_client.cc 38.3 KB
Newer Older
unknown's avatar
unknown committed
1
/* Copyright (C) 2000 MySQL AB & MySQL Finland AB & TCX DataKonsult AB
unknown's avatar
unknown committed
2

unknown's avatar
unknown committed
3 4 5 6
   This program is free software; you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
   the Free Software Foundation; either version 2 of the License, or
   (at your option) any later version.
unknown's avatar
unknown committed
7

unknown's avatar
unknown committed
8 9 10 11
   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.
unknown's avatar
unknown committed
12

unknown's avatar
unknown committed
13 14 15 16 17 18 19 20 21 22
   You should have received a copy of the GNU General Public License
   along with this program; if not, write to the Free Software
   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA */

/*
 mini MySQL client to be included into the server to do server to server
 commincation by Sasha Pachev

 Note: all file-global symbols must begin with mc_ , even the static ones, just
 in case we decide to make them external at some point
unknown's avatar
unknown committed
23
*/
unknown's avatar
unknown committed
24

unknown's avatar
unknown committed
25
#include <my_global.h>
unknown's avatar
unknown committed
26 27 28 29 30
/* my_pthread must be included early to be able to fix things */
#if defined(THREAD)
#include <my_pthread.h>				/* because of signal()	*/
#endif
#include <thr_alarm.h>
31
#include <mysql_embed.h>
unknown's avatar
unknown committed
32
#include <mysql_com.h>
unknown's avatar
unknown committed
33
#include <violite.h>
unknown's avatar
unknown committed
34 35 36 37 38 39 40 41 42
#include <my_sys.h>
#include <mysys_err.h>
#include <m_string.h>
#include <m_ctype.h>
#include "mysql.h"
#include "mini_client.h"
#include "mysql_version.h"
#include "mysqld_error.h"
#include "errmsg.h"
unknown's avatar
unknown committed
43

unknown's avatar
unknown committed
44
#if defined( OS2) && defined(MYSQL_SERVER)
unknown's avatar
unknown committed
45 46 47 48
#undef  ER
#define ER CER
#endif

unknown's avatar
unknown committed
49
extern "C" {					// Because of SCO 3.2V4.2
unknown's avatar
unknown committed
50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65
#include <sys/stat.h>
#include <signal.h>
#ifdef	 HAVE_PWD_H
#include <pwd.h>
#endif
#if !defined(MSDOS) && !defined(__WIN__)
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#ifdef HAVE_SELECT_H
#  include <select.h>
#endif
#ifdef HAVE_SYS_SELECT_H
#include <sys/select.h>
#endif
unknown's avatar
unknown committed
66
#endif /*!defined(MSDOS) && !defined(__WIN__) */
unknown's avatar
unknown committed
67 68 69 70 71 72
#ifdef HAVE_SYS_UN_H
#  include <sys/un.h>
#endif
#ifndef INADDR_NONE
#define INADDR_NONE	-1
#endif
unknown's avatar
unknown committed
73
}
unknown's avatar
unknown committed
74

75
static void mc_free_rows(MYSQL_DATA *cur);
76
void mc_end_server(MYSQL *mysql);
unknown's avatar
unknown committed
77 78
static int mc_sock_connect(File s, const struct sockaddr *name, uint namelen, uint to);
static void mc_free_old_query(MYSQL *mysql);
79 80 81 82 83 84 85 86
static int mc_send_file_to_server(MYSQL *mysql, const char *filename);
static my_ulonglong mc_net_field_length_ll(uchar **packet);
static ulong mc_net_field_length(uchar **packet);
static int mc_read_one_row(MYSQL *mysql,uint fields,MYSQL_ROW row,
			   ulong *lengths);
static MYSQL_DATA *mc_read_rows(MYSQL *mysql,MYSQL_FIELD *mysql_fields,
				uint fields);

unknown's avatar
unknown committed
87 88 89 90 91 92 93


#define CLIENT_CAPABILITIES	(CLIENT_LONG_PASSWORD | CLIENT_LONG_FLAG | CLIENT_LOCAL_FILES)

#if defined(MSDOS) || defined(__WIN__)
#define perror(A)
#else
unknown's avatar
unknown committed
94
#include <errno.h>
unknown's avatar
unknown committed
95 96 97 98 99 100 101 102 103 104 105
#define SOCKET_ERROR -1
#endif

#ifdef __WIN__
static my_bool is_NT(void)
{
  char *os=getenv("OS");
  return (os && !strcmp(os, "Windows_NT")) ? 1 : 0;
}
#endif

unknown's avatar
unknown committed
106 107
extern ulong slave_net_timeout;

unknown's avatar
unknown committed
108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182
/*
** Create a named pipe connection
*/

#ifdef __WIN__

HANDLE create_named_pipe(NET *net, uint connect_timeout, char **arg_host,
			 char **arg_unix_socket)
{
  HANDLE hPipe=INVALID_HANDLE_VALUE;
  char szPipeName [ 257 ];
  DWORD dwMode;
  int i;
  my_bool testing_named_pipes=0;
  char *host= *arg_host, *unix_socket= *arg_unix_socket;

  if (!host || !strcmp(host,LOCAL_HOST))
    host=LOCAL_HOST_NAMEDPIPE;

  sprintf( szPipeName, "\\\\%s\\pipe\\%s", host, unix_socket);
  DBUG_PRINT("info",("Server name: '%s'.  Named Pipe: %s",
		     host, unix_socket));

  for (i=0 ; i < 100 ; i++)			/* Don't retry forever */
  {
    if ((hPipe = CreateFile(szPipeName,
			    GENERIC_READ | GENERIC_WRITE,
			    0,
			    NULL,
			    OPEN_EXISTING,
			    0,
			    NULL )) != INVALID_HANDLE_VALUE)
      break;
    if (GetLastError() != ERROR_PIPE_BUSY)
    {
      net->last_errno=CR_NAMEDPIPEOPEN_ERROR;
      sprintf(net->last_error,ER(net->last_errno),host, unix_socket,
	      (ulong) GetLastError());
      return INVALID_HANDLE_VALUE;
    }
    /* wait for for an other instance */
    if (! WaitNamedPipe(szPipeName, connect_timeout*1000) )
    {
      net->last_errno=CR_NAMEDPIPEWAIT_ERROR;
      sprintf(net->last_error,ER(net->last_errno),host, unix_socket,
	      (ulong) GetLastError());
      return INVALID_HANDLE_VALUE;
    }
  }
  if (hPipe == INVALID_HANDLE_VALUE)
  {
    net->last_errno=CR_NAMEDPIPEOPEN_ERROR;
    sprintf(net->last_error,ER(net->last_errno),host, unix_socket,
	    (ulong) GetLastError());
    return INVALID_HANDLE_VALUE;
  }
  dwMode = PIPE_READMODE_BYTE | PIPE_WAIT;
  if ( !SetNamedPipeHandleState(hPipe, &dwMode, NULL, NULL) )
  {
    CloseHandle( hPipe );
    net->last_errno=CR_NAMEDPIPESETSTATE_ERROR;
    sprintf(net->last_error,ER(net->last_errno),host, unix_socket,
	    (ulong) GetLastError());
    return INVALID_HANDLE_VALUE;
  }
  *arg_host=host ; *arg_unix_socket=unix_socket;	/* connect arg */
  return (hPipe);
}
#endif


/****************************************************************************
** Init MySQL structure or allocate one
****************************************************************************/

183
MYSQL *mc_mysql_init(MYSQL *mysql)
unknown's avatar
unknown committed
184 185 186 187 188 189 190 191 192 193 194 195 196 197
{
  init_client_errs();
  if (!mysql)
  {
    if (!(mysql=(MYSQL*) my_malloc(sizeof(*mysql),MYF(MY_WME | MY_ZEROFILL))))
      return 0;
    mysql->free_me=1;
    mysql->net.vio = 0;
  }
  else
    bzero((char*) (mysql),sizeof(*(mysql)));
#ifdef __WIN__
  mysql->options.connect_timeout=20;
#endif
198
  mysql->net.read_timeout = slave_net_timeout;
unknown's avatar
unknown committed
199 200 201 202 203 204 205
  return mysql;
}

/**************************************************************************
** Shut down connection
**************************************************************************/

206
void
unknown's avatar
unknown committed
207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224
mc_end_server(MYSQL *mysql)
{
  DBUG_ENTER("mc_end_server");
  if (mysql->net.vio != 0)
  {
    DBUG_PRINT("info",("Net: %s", vio_description(mysql->net.vio)));
    vio_delete(mysql->net.vio);
    mysql->net.vio= 0;          /* Marker */
  }
  net_end(&mysql->net);
  mc_free_old_query(mysql);
  DBUG_VOID_RETURN;
}

static void mc_free_old_query(MYSQL *mysql)
{
  DBUG_ENTER("mc_free_old_query");
  if (mysql->fields)
225 226 227
    free_root(&mysql->field_alloc,MYF(0));
  else
    init_alloc_root(&mysql->field_alloc,8192,0); /* Assume rowlength < 8192 */
unknown's avatar
unknown committed
228 229 230 231 232 233 234 235 236 237 238 239 240 241 242
  mysql->fields=0;
  mysql->field_count=0;				/* For API */
  DBUG_VOID_RETURN;
}


/****************************************************************************
* A modified version of connect().  mc_sock_connect() allows you to specify
* a timeout value, in seconds, that we should wait until we
* derermine we can't connect to a particular host.  If timeout is 0,
* mc_sock_connect() will behave exactly like connect().
*
* Base version coded by Steve Bernacki, Jr. <steve@navinet.net>
*****************************************************************************/

unknown's avatar
unknown committed
243 244
static int mc_sock_connect(my_socket s, const struct sockaddr *name,
			   uint namelen, uint to)
unknown's avatar
unknown committed
245
{
unknown's avatar
unknown committed
246
#if defined(__WIN__) || defined(OS2)
unknown's avatar
unknown committed
247 248 249
  return connect(s, (struct sockaddr*) name, namelen);
#else
  int flags, res, s_err;
unknown's avatar
unknown committed
250
  SOCKOPT_OPTLEN_TYPE s_err_size = sizeof(uint);
unknown's avatar
unknown committed
251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314
  fd_set sfds;
  struct timeval tv;

  /* If they passed us a timeout of zero, we should behave
   * exactly like the normal connect() call does.
   */

  if (to == 0)
    return connect(s, (struct sockaddr*) name, namelen);

  flags = fcntl(s, F_GETFL, 0);		  /* Set socket to not block */
#ifdef O_NONBLOCK
  fcntl(s, F_SETFL, flags | O_NONBLOCK);  /* and save the flags..  */
#endif

  res = connect(s, (struct sockaddr*) name, namelen);
  s_err = errno;			/* Save the error... */
  fcntl(s, F_SETFL, flags);
  if ((res != 0) && (s_err != EINPROGRESS))
  {
    errno = s_err;			/* Restore it */
    return(-1);
  }
  if (res == 0)				/* Connected quickly! */
    return(0);

  /* Otherwise, our connection is "in progress."  We can use
   * the select() call to wait up to a specified period of time
   * for the connection to suceed.  If select() returns 0
   * (after waiting howevermany seconds), our socket never became
   * writable (host is probably unreachable.)  Otherwise, if
   * select() returns 1, then one of two conditions exist:
   *
   * 1. An error occured.  We use getsockopt() to check for this.
   * 2. The connection was set up sucessfully: getsockopt() will
   * return 0 as an error.
   *
   * Thanks goes to Andrew Gierth <andrew@erlenstar.demon.co.uk>
   * who posted this method of timing out a connect() in
   * comp.unix.programmer on August 15th, 1997.
   */

  FD_ZERO(&sfds);
  FD_SET(s, &sfds);
  tv.tv_sec = (long) to;
  tv.tv_usec = 0;
#ifdef HPUX
  res = select(s+1, NULL, (int*) &sfds, NULL, &tv);
#else
  res = select(s+1, NULL, &sfds, NULL, &tv);
#endif
  if (res <= 0)					/* Never became writable */
    return(-1);

  /* select() returned something more interesting than zero, let's
   * see if we have any errors.  If the next two statements pass,
   * we've got an open socket!
   */

  s_err=0;
  if (getsockopt(s, SOL_SOCKET, SO_ERROR, (char*) &s_err, &s_err_size) != 0)
    return(-1);

  if (s_err)
unknown's avatar
unknown committed
315
  {						// getsockopt() could succeed
unknown's avatar
unknown committed
316
    errno = s_err;
unknown's avatar
unknown committed
317
    return(-1);					// but return an error...
unknown's avatar
unknown committed
318 319 320 321 322 323 324 325 326 327
  }
  return(0);					/* It's all good! */
#endif
}

/*****************************************************************************
** read a packet from server. Give error message if socket was down
** or packet is an error message
*****************************************************************************/

328
ulong 
unknown's avatar
unknown committed
329 330 331
mc_net_safe_read(MYSQL *mysql)
{
  NET *net= &mysql->net;
332
  ulong len=0;
unknown's avatar
unknown committed
333 334 335 336 337 338 339 340

  if (net->vio != 0)
    len=my_net_read(net);

  if (len == packet_error || len == 0)
  {
    DBUG_PRINT("error",("Wrong connection or packet. fd: %s  len: %d",
			vio_description(net->vio),len));
unknown's avatar
unknown committed
341
    if (socket_errno != SOCKET_EINTR)
unknown's avatar
unknown committed
342 343
    {
      mc_end_server(mysql);
344
      if (net->last_errno != ER_NET_PACKET_TOO_LARGE)
unknown's avatar
unknown committed
345
      {
unknown's avatar
unknown committed
346 347 348 349 350
	net->last_errno=CR_SERVER_LOST;
	strmov(net->last_error,ER(net->last_errno));
      }
      else
	strmov(net->last_error, "Packet too large - increase \
351
max_allowed_packet on this server");
352
    }
unknown's avatar
unknown committed
353 354 355 356 357 358 359 360 361 362 363 364
    return(packet_error);
  }
  if (net->read_pos[0] == 255)
  {
    if (len > 3)
    {
      char *pos=(char*) net->read_pos+1;
      if (mysql->protocol_version > 9)
      {						/* New client protocol */
	net->last_errno=uint2korr(pos);
	pos+=2;
	len-=2;
365
	if (!net->last_errno)
unknown's avatar
unknown committed
366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388
	  net->last_errno = CR_UNKNOWN_ERROR;
      }
      else
      {
	net->last_errno=CR_UNKNOWN_ERROR;
	len--;
      }
      (void) strmake(net->last_error,(char*) pos,
		     min(len,sizeof(net->last_error)-1));
    }
    else
    {
      net->last_errno=CR_UNKNOWN_ERROR;
      (void) strmov(net->last_error,ER(net->last_errno));
    }
    DBUG_PRINT("error",("Got error: %d (%s)", net->last_errno,
			net->last_error));
    return(packet_error);
  }
  return len;
}


unknown's avatar
unknown committed
389
char *mc_mysql_error(MYSQL *mysql)
unknown's avatar
unknown committed
390 391 392 393
{
  return (mysql)->net.last_error;
}

394
int  mc_mysql_errno(MYSQL *mysql)
unknown's avatar
unknown committed
395 396 397 398
{
  return (mysql)->net.last_errno;
}

unknown's avatar
unknown committed
399 400

my_bool mc_mysql_reconnect(MYSQL *mysql)
unknown's avatar
unknown committed
401 402 403 404
{
  MYSQL tmp_mysql;
  DBUG_ENTER("mc_mysql_reconnect");

405
  if (!mysql->reconnect)
406 407 408
  {
    mysql->net.last_errno=CR_SERVER_GONE_ERROR;
    strmov(mysql->net.last_error, ER(mysql->net.last_errno));
409
    DBUG_RETURN(1);
410
  }
unknown's avatar
unknown committed
411 412 413
  mc_mysql_init(&tmp_mysql);
  tmp_mysql.options=mysql->options;
  if (!mc_mysql_connect(&tmp_mysql,mysql->host,mysql->user,mysql->passwd,
unknown's avatar
unknown committed
414 415
			mysql->db, mysql->port, mysql->unix_socket,
			mysql->client_flag, mysql->net.read_timeout))
416
  {
unknown's avatar
unknown committed
417 418
    mysql->net.last_errno= tmp_mysql.net.last_errno;
    strmov(mysql->net.last_error, tmp_mysql.net.last_error);
419 420
    DBUG_RETURN(1);
  }
unknown's avatar
unknown committed
421 422 423 424 425 426 427 428 429 430 431 432
  tmp_mysql.free_me=mysql->free_me;
  mysql->free_me=0;
  bzero((char*) &mysql->options,sizeof(&mysql->options));
  mc_mysql_close(mysql);
  *mysql=tmp_mysql;
  net_clear(&mysql->net);
  mysql->affected_rows= ~(my_ulonglong) 0;
  DBUG_RETURN(0);
}



433
int 
unknown's avatar
unknown committed
434 435
mc_simple_command(MYSQL *mysql,enum enum_server_command command,
		  const char *arg, uint length, my_bool skipp_check)
unknown's avatar
unknown committed
436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459
{
  NET *net= &mysql->net;
  int result= -1;

  if (mysql->net.vio == 0)
  {						/* Do reconnect if possible */
    if (mc_mysql_reconnect(mysql))
      goto end;
  }
  if (mysql->status != MYSQL_STATUS_READY)
  {
    strmov(net->last_error,ER(mysql->net.last_errno=CR_COMMANDS_OUT_OF_SYNC));
    goto end;
  }

  mysql->net.last_error[0]=0;
  mysql->net.last_errno=0;
  mysql->info=0;
  mysql->affected_rows= ~(my_ulonglong) 0;
  net_clear(net);			/* Clear receive buffer */
  if (!arg)
    arg="";

  if (net_write_command(net,(uchar) command,arg,
unknown's avatar
unknown committed
460
			length ? length :(uint) strlen(arg)))
unknown's avatar
unknown committed
461
  {
unknown's avatar
unknown committed
462
    DBUG_PRINT("error",("Can't send command to server. Error: %d",socket_errno));
unknown's avatar
unknown committed
463
    mc_end_server(mysql);
464 465 466
    if (mc_mysql_reconnect(mysql))
      goto end;
    if (net_write_command(net,(uchar) command,arg,
unknown's avatar
unknown committed
467
			  length ? length :(uint) strlen(arg)))
unknown's avatar
unknown committed
468 469 470 471 472 473 474 475 476 477 478 479 480 481 482
    {
      net->last_errno=CR_SERVER_GONE_ERROR;
      strmov(net->last_error,ER(net->last_errno));
      goto end;
    }
  }
  result=0;
  if (!skipp_check)
    result= ((mysql->packet_length=mc_net_safe_read(mysql)) == packet_error ?
	     -1 : 0);
 end:
  return result;
}


483
MYSQL * 
unknown's avatar
unknown committed
484
mc_mysql_connect(MYSQL *mysql,const char *host, const char *user,
unknown's avatar
unknown committed
485 486 487
		 const char *passwd, const char *db,
		 uint port, const char *unix_socket,uint client_flag,
		 uint net_read_timeout)
unknown's avatar
unknown committed
488
{
unknown's avatar
unknown committed
489
  char		buff[NAME_LEN+USERNAME_LENGTH+100],*end,*host_info;
unknown's avatar
unknown committed
490
  my_socket	sock;
unknown's avatar
unknown committed
491 492
  ulong		ip_addr;
  struct	sockaddr_in sock_addr;
493
  ulong		pkt_length;
unknown's avatar
unknown committed
494
  NET		*net= &mysql->net;
495
  thr_alarm_t   alarmed;
unknown's avatar
unknown committed
496 497
  ALARM		alarm_buff;
  ulong		max_allowed_packet;
498

unknown's avatar
unknown committed
499 500 501 502 503 504
#ifdef __WIN__
  HANDLE	hPipe=INVALID_HANDLE_VALUE;
#endif
#ifdef HAVE_SYS_UN_H
  struct	sockaddr_un UNIXaddr;
#endif
505
  DBUG_ENTER("mc_mysql_connect");
506
  DBUG_PRINT("enter",("host: %s  db: %s  user: %s  connect_time_out: %u  read_timeout: %u",
unknown's avatar
unknown committed
507 508
		      host ? host : "(Null)",
		      db ? db : "(Null)",
509 510 511
		      user ? user : "(Null)",
		      net_read_timeout,
		      (uint) slave_net_timeout));
unknown's avatar
unknown committed
512 513 514 515 516 517 518 519 520

  net->vio = 0;				/* If something goes wrong */
  mysql->charset=default_charset_info;  /* Set character set */
  if (!port)
    port = MYSQL_PORT;			/* Should always be set by mysqld */
  if (!unix_socket)
    unix_socket=MYSQL_UNIX_ADDR;

  mysql->reconnect=1;			/* Reconnect as default */
unknown's avatar
unknown committed
521
  mysql->server_status=SERVER_STATUS_AUTOCOMMIT;
522 523
  if (!mysql->options.connect_timeout)
    mysql->options.connect_timeout= net_read_timeout;
unknown's avatar
unknown committed
524 525 526 527 528 529

  /*
  ** Grab a socket and connect it to the server
  */

#if defined(HAVE_SYS_UN_H)
unknown's avatar
unknown committed
530
  if ((!host || !strcmp(host,LOCAL_HOST)) && unix_socket)
unknown's avatar
unknown committed
531 532 533 534 535 536 537
  {
    host=LOCAL_HOST;
    host_info=(char*) ER(CR_LOCALHOST_CONNECTION);
    DBUG_PRINT("info",("Using UNIX sock '%s'",unix_socket));
    if ((sock = socket(AF_UNIX,SOCK_STREAM,0)) == SOCKET_ERROR)
    {
      net->last_errno=CR_SOCKET_CREATE_ERROR;
unknown's avatar
unknown committed
538
      sprintf(net->last_error,ER(net->last_errno),socket_errno);
unknown's avatar
unknown committed
539 540 541 542 543 544 545
      goto error;
    }
    net->vio = vio_new(sock, VIO_TYPE_SOCKET, TRUE);
    bzero((char*) &UNIXaddr,sizeof(UNIXaddr));
    UNIXaddr.sun_family = AF_UNIX;
    strmov(UNIXaddr.sun_path, unix_socket);
    if (mc_sock_connect(sock,(struct sockaddr *) &UNIXaddr, sizeof(UNIXaddr),
546
			mysql->options.connect_timeout) <0)
unknown's avatar
unknown committed
547
    {
unknown's avatar
unknown committed
548
      DBUG_PRINT("error",("Got error %d on connect to local server",socket_errno));
unknown's avatar
unknown committed
549
      net->last_errno=CR_CONNECTION_ERROR;
unknown's avatar
unknown committed
550
      sprintf(net->last_error,ER(net->last_errno),unix_socket,socket_errno);
unknown's avatar
unknown committed
551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594
      goto error;
    }
  }
  else
#elif defined(__WIN__)
  {
    if ((unix_socket ||
	 !host && is_NT() ||
	 host && !strcmp(host,LOCAL_HOST_NAMEDPIPE) ||
	 mysql->options.named_pipe || !have_tcpip))
    {
      sock=0;
      if ((hPipe=create_named_pipe(net, mysql->options.connect_timeout,
				   (char**) &host, (char**) &unix_socket)) ==
	  INVALID_HANDLE_VALUE)
      {
	DBUG_PRINT("error",
		   ("host: '%s'  socket: '%s'  named_pipe: %d  have_tcpip: %d",
		    host ? host : "<null>",
		    unix_socket ? unix_socket : "<null>",
		    (int) mysql->options.named_pipe,
		    (int) have_tcpip));
	if (mysql->options.named_pipe ||
	    (host && !strcmp(host,LOCAL_HOST_NAMEDPIPE)) ||
	    (unix_socket && !strcmp(unix_socket,MYSQL_NAMEDPIPE)))
	  goto error;		/* User only requested named pipes */
	/* Try also with TCP/IP */
      }
      else
      {
	net->vio=vio_new_win32pipe(hPipe);
	sprintf(host_info=buff, ER(CR_NAMEDPIPE_CONNECTION), host,
		unix_socket);
      }
    }
  }
  if (hPipe == INVALID_HANDLE_VALUE)
#endif
  {
    unix_socket=0;				/* This is not used */
    if (!host)
      host=LOCAL_HOST;
    sprintf(host_info=buff,ER(CR_TCP_CONNECTION),host);
    DBUG_PRINT("info",("Server name: '%s'.  TCP sock: %d", host,port));
595 596 597 598 599
    thr_alarm_init(&alarmed);
    thr_alarm(&alarmed, net_read_timeout, &alarm_buff);
    sock = (my_socket) socket(AF_INET,SOCK_STREAM,0);
    thr_end_alarm(&alarmed);
    if (sock == SOCKET_ERROR)
unknown's avatar
unknown committed
600 601
    {
      net->last_errno=CR_IPSOCK_ERROR;
unknown's avatar
unknown committed
602
      sprintf(net->last_error,ER(net->last_errno),socket_errno);
unknown's avatar
unknown committed
603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627
      goto error;
    }
    net->vio = vio_new(sock,VIO_TYPE_TCPIP,FALSE);
    bzero((char*) &sock_addr,sizeof(sock_addr));
    sock_addr.sin_family = AF_INET;

    /*
    ** The server name may be a host name or IP address
    */

    if ((int) (ip_addr = inet_addr(host)) != (int) INADDR_NONE)
    {
      memcpy_fixed(&sock_addr.sin_addr,&ip_addr,sizeof(ip_addr));
    }
    else
    {
      int tmp_errno;
      struct hostent tmp_hostent,*hp;
      char buff2[GETHOSTBYNAME_BUFF_SIZE];
      hp = my_gethostbyname_r(host,&tmp_hostent,buff2,sizeof(buff2),
			      &tmp_errno);
      if (!hp)
      {
	net->last_errno=CR_UNKNOWN_HOST;
	sprintf(net->last_error, ER(CR_UNKNOWN_HOST), host, tmp_errno);
unknown's avatar
unknown committed
628
	my_gethostbyname_r_free();
unknown's avatar
unknown committed
629 630 631
	goto error;
      }
      memcpy(&sock_addr.sin_addr,hp->h_addr, (size_t) hp->h_length);
unknown's avatar
unknown committed
632
      my_gethostbyname_r_free();
unknown's avatar
unknown committed
633 634 635
    }
    sock_addr.sin_port = (ushort) htons((ushort) port);
    if (mc_sock_connect(sock,(struct sockaddr *) &sock_addr, sizeof(sock_addr),
unknown's avatar
unknown committed
636
			mysql->options.connect_timeout) <0)
unknown's avatar
unknown committed
637
    {
unknown's avatar
unknown committed
638 639
      DBUG_PRINT("error",("Got error %d on connect to '%s'",
			  socket_errno,host));
unknown's avatar
unknown committed
640
      net->last_errno= CR_CONN_HOST_ERROR;
unknown's avatar
unknown committed
641
      sprintf(net->last_error ,ER(CR_CONN_HOST_ERROR), host, socket_errno);
unknown's avatar
unknown committed
642 643 644 645 646 647 648
      goto error;
    }
  }

  if (!net->vio || my_net_init(net, net->vio))
  {
    vio_delete(net->vio);
unknown's avatar
unknown committed
649
    net->vio = 0;
unknown's avatar
unknown committed
650 651 652 653 654
    net->last_errno=CR_OUT_OF_MEMORY;
    strmov(net->last_error,ER(net->last_errno));
    goto error;
  }
  vio_keepalive(net->vio,TRUE);
655
  net->read_timeout=slave_net_timeout;
unknown's avatar
unknown committed
656 657
  /* Get version info */
  mysql->protocol_version= PROTOCOL_VERSION;	/* Assume this */
unknown's avatar
unknown committed
658 659 660 661 662 663 664
  if (mysql->options.connect_timeout &&
      vio_poll_read(net->vio, mysql->options.connect_timeout))
  {
    net->last_errno= CR_SERVER_LOST;
    strmov(net->last_error,ER(net->last_errno));    
    goto error;
  }
unknown's avatar
unknown committed
665 666 667
  if ((pkt_length=mc_net_safe_read(mysql)) == packet_error)
    goto error;

668
  /* Check if version of protocol matches current one */
unknown's avatar
unknown committed
669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685

  mysql->protocol_version= net->read_pos[0];
  DBUG_DUMP("packet",(char*) net->read_pos,10);
  DBUG_PRINT("info",("mysql protocol version %d, server=%d",
		     PROTOCOL_VERSION, mysql->protocol_version));
  if (mysql->protocol_version != PROTOCOL_VERSION &&
      mysql->protocol_version != PROTOCOL_VERSION-1)
  {
    net->last_errno= CR_VERSION_ERROR;
    sprintf(net->last_error, ER(CR_VERSION_ERROR), mysql->protocol_version,
	    PROTOCOL_VERSION);
    goto error;
  }
  end=strend((char*) net->read_pos+1);
  mysql->thread_id=uint4korr(end+1);
  end+=5;
  strmake(mysql->scramble_buff,end,8);
unknown's avatar
unknown committed
686 687 688 689 690 691 692 693 694
  end+=9;
  if (pkt_length >= (uint) (end+1 - (char*) net->read_pos))
    mysql->server_capabilities=uint2korr(end);
  if (pkt_length >= (uint) (end+18 - (char*) net->read_pos))
  {
    /* New protocol with 16 bytes to describe server characteristics */
    mysql->server_language=end[2];
    mysql->server_status=uint2korr(end+3);
  }
unknown's avatar
unknown committed
695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720

  /* Save connection information */
  if (!user) user="";
  if (!passwd) passwd="";
  if (!my_multi_malloc(MYF(0),
		       &mysql->host_info, (uint) strlen(host_info)+1,
		       &mysql->host,      (uint) strlen(host)+1,
		       &mysql->unix_socket,
		       unix_socket ? (uint) strlen(unix_socket)+1 : (uint) 1,
		       &mysql->server_version,
		       (uint) (end - (char*) net->read_pos),
		       NullS) ||
      !(mysql->user=my_strdup(user,MYF(0))) ||
      !(mysql->passwd=my_strdup(passwd,MYF(0))))
  {
    strmov(net->last_error, ER(net->last_errno=CR_OUT_OF_MEMORY));
    goto error;
  }
  strmov(mysql->host_info,host_info);
  strmov(mysql->host,host);
  if (unix_socket)
    strmov(mysql->unix_socket,unix_socket);
  else
    mysql->unix_socket=0;
  strmov(mysql->server_version,(char*) net->read_pos+1);
  mysql->port=port;
unknown's avatar
unknown committed
721
  client_flag|=mysql->options.client_flag;
unknown's avatar
unknown committed
722 723 724 725 726 727 728
  DBUG_PRINT("info",("Server version = '%s'  capabilites: %ld",
		     mysql->server_version,mysql->server_capabilities));

  /* Send client information for access check */
  client_flag|=CLIENT_CAPABILITIES;

#ifdef HAVE_OPENSSL
unknown's avatar
unknown committed
729 730 731 732
  if (mysql->options.ssl_key || mysql->options.ssl_cert ||
      mysql->options.ssl_ca || mysql->options.ssl_capath ||
      mysql->options.ssl_cipher)
    mysql->options.use_ssl= 1;
unknown's avatar
unknown committed
733 734 735 736 737 738 739
  if (mysql->options.use_ssl)
    client_flag|=CLIENT_SSL;
#endif /* HAVE_OPENSSL */

  if (db)
    client_flag|=CLIENT_CONNECT_WITH_DB;
#ifdef HAVE_COMPRESS
unknown's avatar
unknown committed
740 741
  if ((mysql->server_capabilities & CLIENT_COMPRESS) &&
      (mysql->options.compress || (client_flag & CLIENT_COMPRESS)))
unknown's avatar
unknown committed
742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767
    client_flag|=CLIENT_COMPRESS;		/* We will use compression */
  else
#endif
    client_flag&= ~CLIENT_COMPRESS;

#ifdef HAVE_OPENSSL
  if ((mysql->server_capabilities & CLIENT_SSL) &&
      (mysql->options.use_ssl || (client_flag & CLIENT_SSL)))
  {
    DBUG_PRINT("info", ("Changing IO layer to SSL"));
    client_flag |= CLIENT_SSL;
  }
  else
  {
    if (client_flag & CLIENT_SSL)
    {
      DBUG_PRINT("info", ("Leaving IO layer intact because server doesn't support SSL"));
    }
    client_flag &= ~CLIENT_SSL;
  }
#endif /* HAVE_OPENSSL */

  int2store(buff,client_flag);
  mysql->client_flag=client_flag;

#ifdef HAVE_OPENSSL
unknown's avatar
unknown committed
768 769 770 771
  /*
    Oops.. are we careful enough to not send ANY information without
    encryption?
  */
unknown's avatar
unknown committed
772
  if (client_flag & CLIENT_SSL)
unknown's avatar
unknown committed
773 774
  {
    if (my_net_write(net,buff,(uint) (2)) || net_flush(net))
775 776 777
    {
      net->last_errno= CR_SERVER_LOST;
      strmov(net->last_error,ER(net->last_errno));    
unknown's avatar
unknown committed
778
      goto error;
779
    }
unknown's avatar
unknown committed
780
    /* Do the SSL layering. */
unknown's avatar
unknown committed
781 782
    DBUG_PRINT("info", ("IO layer change in progress..."));
    DBUG_PRINT("info", ("IO context %p",((struct st_VioSSLConnectorFd*)mysql->connector_fd)->ssl_context_));
unknown's avatar
unknown committed
783
    sslconnect((struct st_VioSSLConnectorFd*)(mysql->connector_fd),mysql->net.vio, (long)(mysql->options.connect_timeout));
unknown's avatar
unknown committed
784 785
    DBUG_PRINT("info", ("IO layer change done!"));
  }
unknown's avatar
unknown committed
786
#endif /* HAVE_OPENSSL */
unknown's avatar
unknown committed
787
  max_allowed_packet=mysql->net.max_packet_size;
unknown's avatar
unknown committed
788
  int3store(buff+2,max_allowed_packet);
unknown's avatar
unknown committed
789

unknown's avatar
unknown committed
790

unknown's avatar
unknown committed
791 792 793
  if (user && user[0])
    strmake(buff+5,user,32);
  else
unknown's avatar
unknown committed
794 795 796 797 798
  {
    user = getenv("USER");
    if (!user) user = "mysql";
    strmov((char*) buff+5, user );
  }
unknown's avatar
unknown committed
799 800 801 802 803 804

  DBUG_PRINT("info",("user: %s",buff+5));
  end=scramble(strend(buff+5)+1, mysql->scramble_buff, passwd,
	       (my_bool) (mysql->protocol_version == 9));
  if (db)
  {
unknown's avatar
unknown committed
805
    end=strmake(end+1,db,NAME_LEN);
unknown's avatar
unknown committed
806
    mysql->db=my_strdup(db,MYF(MY_WME));
unknown's avatar
unknown committed
807
    db=0;
unknown's avatar
unknown committed
808
  }
809 810 811 812 813 814 815
  if (my_net_write(net,buff,(ulong) (end-buff)) || net_flush(net))
  {
    net->last_errno= CR_SERVER_LOST;
    strmov(net->last_error,ER(net->last_errno));    
    goto error;
  }
  if (mc_net_safe_read(mysql) == packet_error)
unknown's avatar
unknown committed
816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834
    goto error;
  if (client_flag & CLIENT_COMPRESS)		/* We will use compression */
    net->compress=1;
  DBUG_PRINT("exit",("Mysql handler: %lx",mysql));
  DBUG_RETURN(mysql);

error:
  DBUG_PRINT("error",("message: %u (%s)",net->last_errno,net->last_error));
  {
    /* Free alloced memory */
    my_bool free_me=mysql->free_me;
    mc_end_server(mysql);
    mysql->free_me=0;
    mc_mysql_close(mysql);
    mysql->free_me=free_me;
  }
  DBUG_RETURN(0);
}

unknown's avatar
unknown committed
835 836 837 838 839 840 841 842

#ifdef HAVE_OPENSSL
/*
**************************************************************************
** Free strings in the SSL structure and clear 'use_ssl' flag.
** NB! Errors are not reported until you do mysql_real_connect.
**************************************************************************
*/
843
int 
unknown's avatar
unknown committed
844 845 846 847 848 849
mysql_ssl_clear(MYSQL *mysql)
{
  my_free(mysql->options.ssl_key, MYF(MY_ALLOW_ZERO_PTR));
  my_free(mysql->options.ssl_cert, MYF(MY_ALLOW_ZERO_PTR));
  my_free(mysql->options.ssl_ca, MYF(MY_ALLOW_ZERO_PTR));
  my_free(mysql->options.ssl_capath, MYF(MY_ALLOW_ZERO_PTR));
unknown's avatar
unknown committed
850
  my_free(mysql->options.ssl_cipher, MYF(MY_ALLOW_ZERO_PTR));
unknown's avatar
unknown committed
851 852 853 854
  mysql->options.ssl_key = 0;
  mysql->options.ssl_cert = 0;
  mysql->options.ssl_ca = 0;
  mysql->options.ssl_capath = 0;
unknown's avatar
unknown committed
855
  mysql->options.ssl_cipher= 0;
unknown's avatar
unknown committed
856 857 858 859 860 861 862
  mysql->options.use_ssl = FALSE;
  my_free(mysql->connector_fd,MYF(MY_ALLOW_ZERO_PTR));
  mysql->connector_fd = 0;
  return 0;
}
#endif /* HAVE_OPENSSL */

unknown's avatar
unknown committed
863 864 865 866 867
/*************************************************************************
** Send a QUIT to the server and close the connection
** If handle is alloced by mysql connect free it.
*************************************************************************/

868
void 
unknown's avatar
unknown committed
869 870 871 872 873 874 875 876 877
mc_mysql_close(MYSQL *mysql)
{
  DBUG_ENTER("mysql_close");
  if (mysql)					/* Some simple safety */
  {
    if (mysql->net.vio != 0)
    {
      mc_free_old_query(mysql);
      mysql->status=MYSQL_STATUS_READY; /* Force command */
878
      mysql->reconnect=0;
unknown's avatar
unknown committed
879 880 881 882 883 884 885 886 887 888 889
      mc_simple_command(mysql,COM_QUIT,NullS,0,1);
      mc_end_server(mysql);
    }
    my_free((gptr) mysql->host_info,MYF(MY_ALLOW_ZERO_PTR));
    my_free(mysql->user,MYF(MY_ALLOW_ZERO_PTR));
    my_free(mysql->passwd,MYF(MY_ALLOW_ZERO_PTR));
    my_free(mysql->db,MYF(MY_ALLOW_ZERO_PTR));
    /* Clear pointers for better safety */
    mysql->host_info=mysql->user=mysql->passwd=mysql->db=0;
    bzero((char*) &mysql->options,sizeof(mysql->options));
#ifdef HAVE_OPENSSL
unknown's avatar
unknown committed
890
    mysql_ssl_clear(mysql);
unknown's avatar
unknown committed
891 892 893 894 895 896
#endif /* HAVE_OPENSSL */
    if (mysql->free_me)
      my_free((gptr) mysql,MYF(0));
  }
  DBUG_VOID_RETURN;
}
897

unknown's avatar
unknown committed
898
void mc_mysql_free_result(MYSQL_RES *result)
899 900 901 902 903 904 905 906 907 908
{
  DBUG_ENTER("mc_mysql_free_result");
  DBUG_PRINT("enter",("mysql_res: %lx",result));
  if (result)
  {
    if (result->handle && result->handle->status == MYSQL_STATUS_USE_RESULT)
    {
      DBUG_PRINT("warning",("Not all rows in set were read; Ignoring rows"));
      for (;;)
      {
909 910
	ulong pkt_len;
	if ((pkt_len=mc_net_safe_read(result->handle)) == packet_error)
911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975
	  break;
	if (pkt_len == 1 && result->handle->net.read_pos[0] == 254)
	  break;				/* End of data */
      }
      result->handle->status=MYSQL_STATUS_READY;
    }
    mc_free_rows(result->data);
    if (result->fields)
      free_root(&result->field_alloc,MYF(0));
    if (result->row)
      my_free((gptr) result->row,MYF(0));
    my_free((gptr) result,MYF(0));
  }
  DBUG_VOID_RETURN;
}

static void mc_free_rows(MYSQL_DATA *cur)
{
  if (cur)
  {
    free_root(&cur->alloc,MYF(0));
    my_free((gptr) cur,MYF(0));
  }
}

static MYSQL_FIELD *
mc_unpack_fields(MYSQL_DATA *data,MEM_ROOT *alloc,uint fields,
	      my_bool default_value, my_bool long_flag_protocol)
{
  MYSQL_ROWS	*row;
  MYSQL_FIELD	*field,*result;
  DBUG_ENTER("unpack_fields");

  field=result=(MYSQL_FIELD*) alloc_root(alloc,sizeof(MYSQL_FIELD)*fields);
  if (!result)
    DBUG_RETURN(0);

  for (row=data->data; row ; row = row->next,field++)
  {
    field->table=  strdup_root(alloc,(char*) row->data[0]);
    field->name=   strdup_root(alloc,(char*) row->data[1]);
    field->length= (uint) uint3korr(row->data[2]);
    field->type=   (enum enum_field_types) (uchar) row->data[3][0];
    if (long_flag_protocol)
    {
      field->flags=   uint2korr(row->data[4]);
      field->decimals=(uint) (uchar) row->data[4][2];
    }
    else
    {
      field->flags=   (uint) (uchar) row->data[4][0];
      field->decimals=(uint) (uchar) row->data[4][1];
    }
    if (INTERNAL_NUM_FIELD(field))
      field->flags|= NUM_FLAG;
    if (default_value && row->data[5])
      field->def=strdup_root(alloc,(char*) row->data[5]);
    else
      field->def=0;
    field->max_length= 0;
  }
  mc_free_rows(data);				/* Free old data */
  DBUG_RETURN(result);
}

unknown's avatar
unknown committed
976
int mc_mysql_send_query(MYSQL* mysql, const char* query, uint length)
977 978 979 980
{
  return mc_simple_command(mysql, COM_QUERY, query, length, 1);
}

unknown's avatar
unknown committed
981 982

int mc_mysql_read_query_result(MYSQL *mysql)
983 984 985 986
{
  uchar *pos;
  ulong field_count;
  MYSQL_DATA *fields;
987
  ulong length;
988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029
  DBUG_ENTER("mc_mysql_read_query_result");

  if ((length = mc_net_safe_read(mysql)) == packet_error)
    DBUG_RETURN(-1);
  mc_free_old_query(mysql);			/* Free old result */
get_info:
  pos=(uchar*) mysql->net.read_pos;
  if ((field_count= mc_net_field_length(&pos)) == 0)
  {
    mysql->affected_rows= mc_net_field_length_ll(&pos);
    mysql->insert_id=	  mc_net_field_length_ll(&pos);
    if (mysql->server_capabilities & CLIENT_TRANSACTIONS)
    {
      mysql->server_status=uint2korr(pos); pos+=2;
    }
    if (pos < mysql->net.read_pos+length && mc_net_field_length(&pos))
      mysql->info=(char*) pos;
    DBUG_RETURN(0);
  }
  if (field_count == NULL_LENGTH)		/* LOAD DATA LOCAL INFILE */
  {
    int error=mc_send_file_to_server(mysql,(char*) pos);
    if ((length=mc_net_safe_read(mysql)) == packet_error || error)
      DBUG_RETURN(-1);
    goto get_info;				/* Get info packet */
  }
  if (!(mysql->server_status & SERVER_STATUS_AUTOCOMMIT))
    mysql->server_status|= SERVER_STATUS_IN_TRANS;

  mysql->extra_info= mc_net_field_length_ll(&pos); /* Maybe number of rec */
  if (!(fields=mc_read_rows(mysql,(MYSQL_FIELD*) 0,5)))
    DBUG_RETURN(-1);
  if (!(mysql->fields=mc_unpack_fields(fields,&mysql->field_alloc,
				    (uint) field_count,0,
				    (my_bool) test(mysql->server_capabilities &
						   CLIENT_LONG_FLAG))))
    DBUG_RETURN(-1);
  mysql->status=MYSQL_STATUS_GET_RESULT;
  mysql->field_count=field_count;
  DBUG_RETURN(0);
}

1030
int  mc_mysql_query(MYSQL *mysql, const char *query, uint length)
1031 1032 1033 1034
{
  DBUG_ENTER("mysql_real_query");
  DBUG_PRINT("enter",("handle: %lx",mysql));
  DBUG_PRINT("query",("Query = \"%s\"",query));
unknown's avatar
unknown committed
1035
  if (!length)
1036 1037 1038 1039 1040 1041 1042 1043
    length = strlen(query);
  if (mc_simple_command(mysql,COM_QUERY,query,length,1))
    DBUG_RETURN(-1);
  DBUG_RETURN(mc_mysql_read_query_result(mysql));
}

static int mc_send_file_to_server(MYSQL *mysql, const char *filename)
{
unknown's avatar
unknown committed
1044 1045 1046
  int fd, readcount, result= -1;
  uint packet_length=MY_ALIGN(mysql->net.max_packet-16,IO_SIZE);
  char *buf, tmp_name[FN_REFLEN];
1047 1048
  DBUG_ENTER("send_file_to_server");

unknown's avatar
unknown committed
1049
  if (!(buf=my_malloc(packet_length,MYF(0))))
1050 1051 1052 1053
  {
    strmov(mysql->net.last_error, ER(mysql->net.last_errno=CR_OUT_OF_MEMORY));
    DBUG_RETURN(-1);
  }
unknown's avatar
unknown committed
1054 1055

  fn_format(tmp_name,filename,"","",4);		/* Convert to client format */
1056 1057
  if ((fd = my_open(tmp_name,O_RDONLY, MYF(0))) < 0)
  {
unknown's avatar
unknown committed
1058 1059
    my_net_write(&mysql->net,"",0);		// Server needs one packet
    net_flush(&mysql->net);
1060
    mysql->net.last_errno=EE_FILENOTFOUND;
unknown's avatar
unknown committed
1061 1062
    my_snprintf(mysql->net.last_error,sizeof(mysql->net.last_error)-1,
		EE(mysql->net.last_errno),tmp_name, errno);
unknown's avatar
unknown committed
1063
    goto err;
1064 1065
  }

unknown's avatar
unknown committed
1066
  while ((readcount = (int) my_read(fd,(byte*) buf,packet_length,MYF(0))) > 0)
1067 1068 1069
  {
    if (my_net_write(&mysql->net,buf,readcount))
    {
unknown's avatar
unknown committed
1070
      DBUG_PRINT("error",("Lost connection to MySQL server during LOAD DATA of local file"));
1071 1072
      mysql->net.last_errno=CR_SERVER_LOST;
      strmov(mysql->net.last_error,ER(mysql->net.last_errno));
unknown's avatar
unknown committed
1073
      goto err;
1074 1075 1076 1077 1078 1079 1080
    }
  }
  /* Send empty packet to mark end of file */
  if (my_net_write(&mysql->net,"",0) || net_flush(&mysql->net))
  {
    mysql->net.last_errno=CR_SERVER_LOST;
    sprintf(mysql->net.last_error,ER(mysql->net.last_errno),errno);
unknown's avatar
unknown committed
1081
    goto err;
1082 1083 1084 1085
  }
  if (readcount < 0)
  {
    mysql->net.last_errno=EE_READ; /* the errmsg for not entire file read */
unknown's avatar
unknown committed
1086 1087
    my_snprintf(mysql->net.last_error,sizeof(mysql->net.last_error)-1,
		tmp_name,errno);
unknown's avatar
unknown committed
1088
    goto err;
1089
  }
unknown's avatar
unknown committed
1090 1091 1092 1093 1094 1095 1096
  result=0;					// Ok

err:
  if (fd >= 0)
    (void) my_close(fd,MYF(0));
  my_free(buf,MYF(0));
  DBUG_RETURN(result);
1097 1098
}

unknown's avatar
unknown committed
1099

1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165
/* Get the length of next field. Change parameter to point at fieldstart */
static ulong mc_net_field_length(uchar **packet)
{
  reg1 uchar *pos= *packet;
  if (*pos < 251)
  {
    (*packet)++;
    return (ulong) *pos;
  }
  if (*pos == 251)
  {
    (*packet)++;
    return NULL_LENGTH;
  }
  if (*pos == 252)
  {
    (*packet)+=3;
    return (ulong) uint2korr(pos+1);
  }
  if (*pos == 253)
  {
    (*packet)+=4;
    return (ulong) uint3korr(pos+1);
  }
  (*packet)+=9;					/* Must be 254 when here */
  return (ulong) uint4korr(pos+1);
}

/* Same as above, but returns ulonglong values */

static my_ulonglong mc_net_field_length_ll(uchar **packet)
{
  reg1 uchar *pos= *packet;
  if (*pos < 251)
  {
    (*packet)++;
    return (my_ulonglong) *pos;
  }
  if (*pos == 251)
  {
    (*packet)++;
    return (my_ulonglong) NULL_LENGTH;
  }
  if (*pos == 252)
  {
    (*packet)+=3;
    return (my_ulonglong) uint2korr(pos+1);
  }
  if (*pos == 253)
  {
    (*packet)+=4;
    return (my_ulonglong) uint3korr(pos+1);
  }
  (*packet)+=9;					/* Must be 254 when here */
#ifdef NO_CLIENT_LONGLONG
  return (my_ulonglong) uint4korr(pos+1);
#else
  return (my_ulonglong) uint8korr(pos+1);
#endif
}

/* Read all rows (fields or data) from server */

static MYSQL_DATA *mc_read_rows(MYSQL *mysql,MYSQL_FIELD *mysql_fields,
			     uint fields)
{
1166 1167
  uint	field;
  ulong pkt_len;
1168 1169 1170 1171 1172 1173 1174 1175
  ulong len;
  uchar *cp;
  char	*to;
  MYSQL_DATA *result;
  MYSQL_ROWS **prev_ptr,*cur;
  NET *net = &mysql->net;
  DBUG_ENTER("mc_read_rows");

1176
  if ((pkt_len=mc_net_safe_read(mysql)) == packet_error)
1177 1178
    DBUG_RETURN(0);
  if (!(result=(MYSQL_DATA*) my_malloc(sizeof(MYSQL_DATA),
unknown's avatar
unknown committed
1179
				       MYF(MY_ZEROFILL))))
1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252
  {
    net->last_errno=CR_OUT_OF_MEMORY;
    strmov(net->last_error,ER(net->last_errno));
    DBUG_RETURN(0);
  }
  init_alloc_root(&result->alloc,8192,0);	/* Assume rowlength < 8192 */
  result->alloc.min_malloc=sizeof(MYSQL_ROWS);
  prev_ptr= &result->data;
  result->rows=0;
  result->fields=fields;

  while (*(cp=net->read_pos) != 254 || pkt_len != 1)
  {
    result->rows++;
    if (!(cur= (MYSQL_ROWS*) alloc_root(&result->alloc,
					    sizeof(MYSQL_ROWS))) ||
	!(cur->data= ((MYSQL_ROW)
		      alloc_root(&result->alloc,
				     (fields+1)*sizeof(char *)+pkt_len))))
    {
      mc_free_rows(result);
      net->last_errno=CR_OUT_OF_MEMORY;
      strmov(net->last_error,ER(net->last_errno));
      DBUG_RETURN(0);
    }
    *prev_ptr=cur;
    prev_ptr= &cur->next;
    to= (char*) (cur->data+fields+1);
    for (field=0 ; field < fields ; field++)
    {
      if ((len=(ulong) mc_net_field_length(&cp)) == NULL_LENGTH)
      {						/* null field */
	cur->data[field] = 0;
      }
      else
      {
	cur->data[field] = to;
	memcpy(to,(char*) cp,len); to[len]=0;
	to+=len+1;
	cp+=len;
	if (mysql_fields)
	{
	  if (mysql_fields[field].max_length < len)
	    mysql_fields[field].max_length=len;
	}
      }
    }
    cur->data[field]=to;			/* End of last field */
    if ((pkt_len=mc_net_safe_read(mysql)) == packet_error)
    {
      mc_free_rows(result);
      DBUG_RETURN(0);
    }
  }
  *prev_ptr=0;					/* last pointer is null */
  DBUG_PRINT("exit",("Got %d rows",result->rows));
  DBUG_RETURN(result);
}


/*
** Read one row. Uses packet buffer as storage for fields.
** When next packet is read, the previous field values are destroyed
*/


static int mc_read_one_row(MYSQL *mysql,uint fields,MYSQL_ROW row,
			   ulong *lengths)
{
  uint field;
  ulong pkt_len,len;
  uchar *pos,*prev_pos;

1253
  if ((pkt_len=mc_net_safe_read(mysql)) == packet_error)
1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280
    return -1;
  if (pkt_len == 1 && mysql->net.read_pos[0] == 254)
    return 1;				/* End of data */
  prev_pos= 0;				/* allowed to write at packet[-1] */
  pos=mysql->net.read_pos;
  for (field=0 ; field < fields ; field++)
  {
    if ((len=(ulong) mc_net_field_length(&pos)) == NULL_LENGTH)
    {						/* null field */
      row[field] = 0;
      *lengths++=0;
    }
    else
    {
      row[field] = (char*) pos;
      pos+=len;
      *lengths++=len;
    }
    if (prev_pos)
      *prev_pos=0;				/* Terminate prev field */
    prev_pos=pos;
  }
  row[field]=(char*) prev_pos+1;		/* End of last field */
  *prev_pos=0;					/* Terminate last field */
  return 0;
}

unknown's avatar
unknown committed
1281
my_ulonglong mc_mysql_num_rows(MYSQL_RES *res)
1282 1283 1284 1285
{
  return res->row_count;
}

unknown's avatar
unknown committed
1286
unsigned int mc_mysql_num_fields(MYSQL_RES *res)
1287 1288 1289 1290
{
  return res->field_count;
}

unknown's avatar
unknown committed
1291
void mc_mysql_data_seek(MYSQL_RES *result, my_ulonglong row)
1292 1293 1294 1295 1296 1297 1298 1299 1300
{
  MYSQL_ROWS	*tmp=0;
  DBUG_PRINT("info",("mysql_data_seek(%ld)",(long) row));
  if (result->data)
    for (tmp=result->data->data; row-- && tmp ; tmp = tmp->next) ;
  result->current_row=0;
  result->data_cursor = tmp;
}

unknown's avatar
unknown committed
1301
MYSQL_ROW STDCALL mc_mysql_fetch_row(MYSQL_RES *res)
1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335
{
  DBUG_ENTER("mc_mysql_fetch_row");
  if (!res->data)
  {						/* Unbufferred fetch */
    if (!res->eof)
    {
      if (!(mc_read_one_row(res->handle,res->field_count,res->row,
			    res->lengths)))
      {
	res->row_count++;
	DBUG_RETURN(res->current_row=res->row);
      }
      else
      {
	DBUG_PRINT("info",("end of data"));
	res->eof=1;
	res->handle->status=MYSQL_STATUS_READY;
      }
    }
    DBUG_RETURN((MYSQL_ROW) NULL);
  }
  {
    MYSQL_ROW tmp;
    if (!res->data_cursor)
    {
      DBUG_PRINT("info",("end of data"));
      DBUG_RETURN(res->current_row=(MYSQL_ROW) NULL);
    }
    tmp = res->data_cursor->data;
    res->data_cursor = res->data_cursor->next;
    DBUG_RETURN(res->current_row=tmp);
  }
}

unknown's avatar
unknown committed
1336
int mc_mysql_select_db(MYSQL *mysql, const char *db)
1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349
{
  int error;
  DBUG_ENTER("mysql_select_db");
  DBUG_PRINT("enter",("db: '%s'",db));

  if ((error=mc_simple_command(mysql,COM_INIT_DB,db,(uint) strlen(db),0)))
    DBUG_RETURN(error);
  my_free(mysql->db,MYF(MY_ALLOW_ZERO_PTR));
  mysql->db=my_strdup(db,MYF(MY_WME));
  DBUG_RETURN(0);
}


1350
MYSQL_RES *mc_mysql_store_result(MYSQL *mysql)
1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365
{
  MYSQL_RES *result;
  DBUG_ENTER("mysql_store_result");

  if (!mysql->fields)
    DBUG_RETURN(0);
  if (mysql->status != MYSQL_STATUS_GET_RESULT)
  {
    strmov(mysql->net.last_error,
	   ER(mysql->net.last_errno=CR_COMMANDS_OUT_OF_SYNC));
    DBUG_RETURN(0);
  }
  mysql->status=MYSQL_STATUS_READY;		/* server is ready */
  if (!(result=(MYSQL_RES*) my_malloc(sizeof(MYSQL_RES)+
				      sizeof(ulong)*mysql->field_count,
unknown's avatar
unknown committed
1366
				      MYF(MY_ZEROFILL))))
1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388
  {
    mysql->net.last_errno=CR_OUT_OF_MEMORY;
    strmov(mysql->net.last_error, ER(mysql->net.last_errno));
    DBUG_RETURN(0);
  }
  result->eof=1;				/* Marker for buffered */
  result->lengths=(ulong*) (result+1);
  if (!(result->data=mc_read_rows(mysql,mysql->fields,mysql->field_count)))
  {
    my_free((gptr) result,MYF(0));
    DBUG_RETURN(0);
  }
  mysql->affected_rows= result->row_count= result->data->rows;
  result->data_cursor=	result->data->data;
  result->fields=	mysql->fields;
  result->field_alloc=	mysql->field_alloc;
  result->field_count=	mysql->field_count;
  result->current_field=0;
  result->current_row=0;			/* Must do a fetch first */
  mysql->fields=0;				/* fields is now in result */
  DBUG_RETURN(result);				/* Data fetched */
}