mini_client.cc 41.3 KB
Newer Older
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1
/* Copyright (C) 2000 MySQL AB & MySQL Finland AB & TCX DataKonsult AB
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
2

bk@work.mysql.com's avatar
bk@work.mysql.com 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.
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
7

bk@work.mysql.com's avatar
bk@work.mysql.com 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.
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
12

bk@work.mysql.com's avatar
bk@work.mysql.com 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
23
*/
24

25
#include <my_global.h>
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>
tonu@hundin.mysql.fi's avatar
tonu@hundin.mysql.fi committed
32
#include <mysql_com.h>
33
#include <violite.h>
bk@work.mysql.com's avatar
bk@work.mysql.com 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"
43
#include <assert.h>
monty@donna.mysql.com's avatar
monty@donna.mysql.com committed
44

45
#if defined( OS2) && defined(MYSQL_SERVER)
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
46 47 48 49
#undef  ER
#define ER CER
#endif

monty@donna.mysql.com's avatar
monty@donna.mysql.com committed
50
extern "C" {					// Because of SCO 3.2V4.2
bk@work.mysql.com's avatar
bk@work.mysql.com committed
51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66
#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
67
#endif /*!defined(MSDOS) && !defined(__WIN__) */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
68 69 70 71 72 73
#ifdef HAVE_SYS_UN_H
#  include <sys/un.h>
#endif
#ifndef INADDR_NONE
#define INADDR_NONE	-1
#endif
monty@donna.mysql.com's avatar
monty@donna.mysql.com committed
74
}
bk@work.mysql.com's avatar
bk@work.mysql.com committed
75

76
static void mc_free_rows(MYSQL_DATA *cur);
77
void mc_end_server(MYSQL *mysql);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
78 79
static int mc_sock_connect(File s, const struct sockaddr *name, uint namelen, uint to);
static void mc_free_old_query(MYSQL *mysql);
80 81 82 83 84 85 86 87
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);

bk@work.mysql.com's avatar
bk@work.mysql.com committed
88 89


90 91 92
#define CLIENT_CAPABILITIES (CLIENT_LONG_PASSWORD | CLIENT_LONG_FLAG | \
                             CLIENT_LOCAL_FILES | CLIENT_SECURE_CONNECTION)

bk@work.mysql.com's avatar
bk@work.mysql.com committed
93 94 95 96

#if defined(MSDOS) || defined(__WIN__)
#define perror(A)
#else
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
97
#include <errno.h>
bk@work.mysql.com's avatar
bk@work.mysql.com committed
98 99 100 101 102 103 104 105 106 107 108
#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

109 110
extern ulong slave_net_timeout;

bk@work.mysql.com's avatar
bk@work.mysql.com committed
111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129
/*
** 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;

130
  sprintf(szPipeName, "\\\\%s\\pipe\\%s", host, unix_socket);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
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 183 184 185
  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
****************************************************************************/

186
MYSQL *mc_mysql_init(MYSQL *mysql)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
187 188 189 190 191 192 193 194 195 196 197 198 199 200
{
  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
201
  mysql->net.read_timeout = slave_net_timeout;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
202 203 204 205 206 207 208
  return mysql;
}

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

209
void
bk@work.mysql.com's avatar
bk@work.mysql.com committed
210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227
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)
228 229 230
    free_root(&mysql->field_alloc,MYF(0));
  else
    init_alloc_root(&mysql->field_alloc,8192,0); /* Assume rowlength < 8192 */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
231 232 233 234 235 236 237 238 239 240 241 242 243 244 245
  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>
*****************************************************************************/

246 247
static int mc_sock_connect(my_socket s, const struct sockaddr *name,
			   uint namelen, uint to)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
248
{
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
249
#if defined(__WIN__) || defined(OS2)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
250 251 252
  return connect(s, (struct sockaddr*) name, namelen);
#else
  int flags, res, s_err;
253
  SOCKOPT_OPTLEN_TYPE s_err_size = sizeof(uint);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
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
  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;
300
#ifdef HPUX10
bk@work.mysql.com's avatar
bk@work.mysql.com committed
301 302 303
  res = select(s+1, NULL, (int*) &sfds, NULL, &tv);
#else
  res = select(s+1, NULL, &sfds, NULL, &tv);
304
#endif /* HPUX10 */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
305 306 307 308 309 310 311 312 313 314 315 316 317
  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)
monty@donna.mysql.com's avatar
monty@donna.mysql.com committed
318
  {						// getsockopt() could succeed
bk@work.mysql.com's avatar
bk@work.mysql.com committed
319
    errno = s_err;
monty@donna.mysql.com's avatar
monty@donna.mysql.com committed
320
    return(-1);					// but return an error...
bk@work.mysql.com's avatar
bk@work.mysql.com committed
321 322 323 324 325 326 327 328 329 330
  }
  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
*****************************************************************************/

331
ulong
bk@work.mysql.com's avatar
bk@work.mysql.com committed
332 333 334
mc_net_safe_read(MYSQL *mysql)
{
  NET *net= &mysql->net;
335
  ulong len=0;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
336 337 338 339 340 341 342 343

  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));
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
344
    if (socket_errno != SOCKET_EINTR)
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
345 346
    {
      mc_end_server(mysql);
347
      if (net->last_errno != ER_NET_PACKET_TOO_LARGE)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
348
      {
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
349 350 351 352 353
	net->last_errno=CR_SERVER_LOST;
	strmov(net->last_error,ER(net->last_errno));
      }
      else
	strmov(net->last_error, "Packet too large - increase \
354
max_allowed_packet on this server");
355
    }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
356 357 358 359 360 361 362 363 364 365 366 367
    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;
368
	if (!net->last_errno)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391
	  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;
}


monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
392
char *mc_mysql_error(MYSQL *mysql)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
393 394 395 396
{
  return (mysql)->net.last_error;
}

397
int  mc_mysql_errno(MYSQL *mysql)
398 399 400 401
{
  return (mysql)->net.last_errno;
}

402 403

my_bool mc_mysql_reconnect(MYSQL *mysql)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
404 405 406 407
{
  MYSQL tmp_mysql;
  DBUG_ENTER("mc_mysql_reconnect");

408
  if (!mysql->reconnect)
409 410 411
  {
    mysql->net.last_errno=CR_SERVER_GONE_ERROR;
    strmov(mysql->net.last_error, ER(mysql->net.last_errno));
412
    DBUG_RETURN(1);
413
  }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
414 415 416
  mc_mysql_init(&tmp_mysql);
  tmp_mysql.options=mysql->options;
  if (!mc_mysql_connect(&tmp_mysql,mysql->host,mysql->user,mysql->passwd,
417 418
			mysql->db, mysql->port, mysql->unix_socket,
			mysql->client_flag, mysql->net.read_timeout))
419
  {
420 421
    mysql->net.last_errno= tmp_mysql.net.last_errno;
    strmov(mysql->net.last_error, tmp_mysql.net.last_error);
422 423
    DBUG_RETURN(1);
  }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
424 425 426 427 428 429 430 431 432 433 434 435
  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);
}



436
int
monty@donna.mysql.com's avatar
monty@donna.mysql.com committed
437 438
mc_simple_command(MYSQL *mysql,enum enum_server_command command,
		  const char *arg, uint length, my_bool skipp_check)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455
{
  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;
456
  mysql->net.report_error=0;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
457 458 459 460 461 462
  mysql->info=0;
  mysql->affected_rows= ~(my_ulonglong) 0;
  net_clear(net);			/* Clear receive buffer */
  if (!arg)
    arg="";

463
  if (net_write_command(net, (uchar) command, NullS, 0, arg, length))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
464
  {
465 466
    DBUG_PRINT("error",("Can't send command to server. Error: %d",
			socket_errno));
bk@work.mysql.com's avatar
bk@work.mysql.com committed
467
    mc_end_server(mysql);
468 469
    if (mc_mysql_reconnect(mysql))
      goto end;
470
    if (net_write_command(net,(uchar) command, NullS, 0, arg, length))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
471 472 473 474 475 476 477 478 479 480 481 482 483 484 485
    {
      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;
}


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

bk@work.mysql.com's avatar
bk@work.mysql.com committed
503 504 505 506 507 508
#ifdef __WIN__
  HANDLE	hPipe=INVALID_HANDLE_VALUE;
#endif
#ifdef HAVE_SYS_UN_H
  struct	sockaddr_un UNIXaddr;
#endif
509
  DBUG_ENTER("mc_mysql_connect");
510
  DBUG_PRINT("enter",("host: %s  db: %s  user: %s  connect_time_out: %u  read_timeout: %u",
bk@work.mysql.com's avatar
bk@work.mysql.com committed
511 512
		      host ? host : "(Null)",
		      db ? db : "(Null)",
513 514 515
		      user ? user : "(Null)",
		      net_read_timeout,
		      (uint) slave_net_timeout));
bk@work.mysql.com's avatar
bk@work.mysql.com committed
516 517 518 519 520 521 522 523
  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 */
524
  mysql->server_status=SERVER_STATUS_AUTOCOMMIT;
525 526
  if (!mysql->options.connect_timeout)
    mysql->options.connect_timeout= net_read_timeout;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
527 528 529 530 531 532

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

#if defined(HAVE_SYS_UN_H)
533
  if ((!host || !strcmp(host,LOCAL_HOST)) && unix_socket)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
534 535 536 537 538 539 540
  {
    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;
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
541
      sprintf(net->last_error,ER(net->last_errno),socket_errno);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
542 543 544 545 546 547 548
      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),
549
			mysql->options.connect_timeout) <0)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
550
    {
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
551
      DBUG_PRINT("error",("Got error %d on connect to local server",socket_errno));
bk@work.mysql.com's avatar
bk@work.mysql.com committed
552
      net->last_errno=CR_CONNECTION_ERROR;
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
553
      sprintf(net->last_error,ER(net->last_errno),unix_socket,socket_errno);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
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 595 596 597
      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));
598 599 600 601 602
    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)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
603 604
    {
      net->last_errno=CR_IPSOCK_ERROR;
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
605
      sprintf(net->last_error,ER(net->last_errno),socket_errno);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630
      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);
631
	my_gethostbyname_r_free();
bk@work.mysql.com's avatar
bk@work.mysql.com committed
632 633 634
	goto error;
      }
      memcpy(&sock_addr.sin_addr,hp->h_addr, (size_t) hp->h_length);
635
      my_gethostbyname_r_free();
bk@work.mysql.com's avatar
bk@work.mysql.com committed
636 637 638
    }
    sock_addr.sin_port = (ushort) htons((ushort) port);
    if (mc_sock_connect(sock,(struct sockaddr *) &sock_addr, sizeof(sock_addr),
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
639
			mysql->options.connect_timeout) <0)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
640
    {
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
641 642
      DBUG_PRINT("error",("Got error %d on connect to '%s'",
			  socket_errno,host));
bk@work.mysql.com's avatar
bk@work.mysql.com committed
643
      net->last_errno= CR_CONN_HOST_ERROR;
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
644
      sprintf(net->last_error ,ER(CR_CONN_HOST_ERROR), host, socket_errno);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
645 646 647 648 649 650 651
      goto error;
    }
  }

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

671
  /* Check if version of protocol matches current one */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688

  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);
689 690 691 692 693 694 695 696 697
  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);
  }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723

  /* 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;
724
  client_flag|=mysql->options.client_flag;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
725 726 727 728 729 730 731
  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
732 733 734 735
  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;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
736 737 738 739 740 741 742
  if (mysql->options.use_ssl)
    client_flag|=CLIENT_SSL;
#endif /* HAVE_OPENSSL */

  if (db)
    client_flag|=CLIENT_CONNECT_WITH_DB;
#ifdef HAVE_COMPRESS
743 744
  if ((mysql->server_capabilities & CLIENT_COMPRESS) &&
      (mysql->options.compress || (client_flag & CLIENT_COMPRESS)))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770
    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
771 772 773 774
  /*
    Oops.. are we careful enough to not send ANY information without
    encryption?
  */
tonu@x153.internalnet's avatar
tonu@x153.internalnet committed
775
  if (client_flag & CLIENT_SSL)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
776 777
  {
    if (my_net_write(net,buff,(uint) (2)) || net_flush(net))
778 779
    {
      net->last_errno= CR_SERVER_LOST;
780
      strmov(net->last_error,ER(net->last_errno));
tonu@x153.internalnet's avatar
tonu@x153.internalnet committed
781
      goto error;
782
    }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
783
    /* Do the SSL layering. */
tonu@x153.internalnet's avatar
tonu@x153.internalnet committed
784 785
    DBUG_PRINT("info", ("IO layer change in progress..."));
    DBUG_PRINT("info", ("IO context %p",((struct st_VioSSLConnectorFd*)mysql->connector_fd)->ssl_context_));
786
    sslconnect((struct st_VioSSLConnectorFd*)(mysql->connector_fd),mysql->net.vio, (long)(mysql->options.connect_timeout));
tonu@x153.internalnet's avatar
tonu@x153.internalnet committed
787 788
    DBUG_PRINT("info", ("IO layer change done!"));
  }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
789
#endif /* HAVE_OPENSSL */
790
  max_allowed_packet=mysql->net.max_packet_size;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
791
  int3store(buff+2,max_allowed_packet);
tonu@x153.internalnet's avatar
tonu@x153.internalnet committed
792

monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
793

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

  DBUG_PRINT("info",("user: %s",buff+5));
804

805 806 807 808 809 810 811 812
  /*
    We always start with old type handshake the only difference is message sent
    If server handles secure connection type we'll not send the real scramble
   */
  if (mysql->server_capabilities & CLIENT_SECURE_CONNECTION)
  {
    if (passwd[0])
    {
813 814 815 816 817 818
      /* Prepare false scramble */
      end=strend(buff+5)+1;
      bfill(end, SCRAMBLE_LENGTH, 'x');
      end+=SCRAMBLE_LENGTH;
      *end=0;
      end++;
819 820 821 822 823 824 825 826
    }
    else  /* For empty password*/
    {
      end=strend(buff+5)+1;
      *end=0; /* Store zero length scramble */
    }
  }
  else
827 828 829 830
    /*
     Real scramble is only sent to old servers. This can be blocked  
     by calling mysql_options(MYSQL *, MYSQL_SECURE_CONNECT, (char*) &1);
    */
831 832 833 834 835
    end=scramble(strend(buff+5)+1, mysql->scramble_buff, passwd,
                 (my_bool) (mysql->protocol_version == 9));

  /* Add database if needed */
  if (db && (mysql->server_capabilities & CLIENT_CONNECT_WITH_DB))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
836
  {
837
    end=strmake(end+1,db,NAME_LEN);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
838
    mysql->db=my_strdup(db,MYF(MY_WME));
839
    db=0;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
840
  }
841
  /* Write authentication package */
842 843 844
  if (my_net_write(net,buff,(ulong) (end-buff)) || net_flush(net))
  {
    net->last_errno= CR_SERVER_LOST;
845
    strmov(net->last_error,ER(net->last_errno));
846 847
    goto error;
  }
848 849 850 851

  /* We shall only query sever if it expect us to do so */

  if ( (pkt_length=mc_net_safe_read(mysql)) == packet_error)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
852
    goto error;
853 854 855

  if  (mysql->server_capabilities & CLIENT_SECURE_CONNECTION)
  {
856 857 858
    /* This should always happen with new server unless empty password */
    if (pkt_length==24 && net->read_pos[0]) 
    /* OK/Error message has zero as the first character */
859 860
    {
      /* Old passwords will have zero at the first byte of hash */
861
      if (net->read_pos[0] != '*')
862 863 864 865
      {
        /* Build full password hash as it is required to decode scramble */
        password_hash_stage1(buff, passwd);
        /* Store copy as we'll need it later */
peter@mysql.com's avatar
peter@mysql.com committed
866
        memcpy(password_hash,buff,SCRAMBLE41_LENGTH);
867 868 869
        /* Finally hash complete password using hash we got from server */
        password_hash_stage2(password_hash,(char*)net->read_pos);
        /* Decypt and store scramble 4 = hash for stage2 */
peter@mysql.com's avatar
peter@mysql.com committed
870 871 872
        password_crypt((char*)net->read_pos+4,mysql->scramble_buff,password_hash,
                       SCRAMBLE41_LENGTH);
        mysql->scramble_buff[SCRAMBLE41_LENGTH]=0;
873
        /* Encode scramble with password. Recycle buffer */
peter@mysql.com's avatar
peter@mysql.com committed
874
        password_crypt(mysql->scramble_buff,buff,buff,SCRAMBLE41_LENGTH);
875 876 877 878 879 880
      }
      else
      {
       /* Create password to decode scramble */
       create_key_from_old_password(passwd,password_hash);
       /* Decypt and store scramble 4 = hash for stage2 */
peter@mysql.com's avatar
peter@mysql.com committed
881 882 883
       password_crypt((char*)net->read_pos+4,mysql->scramble_buff,password_hash,
                      SCRAMBLE41_LENGTH);
       mysql->scramble_buff[SCRAMBLE41_LENGTH]=0;
884
       /* Finally scramble decoded scramble with password */
peter@mysql.com's avatar
peter@mysql.com committed
885
       scramble(buff, mysql->scramble_buff, passwd,0);
886 887
      }
      /* Write second package of authentication */
peter@mysql.com's avatar
peter@mysql.com committed
888
      if (my_net_write(net,buff,SCRAMBLE41_LENGTH) || net_flush(net))
889 890 891 892 893 894 895 896 897 898 899 900 901
      {
        net->last_errno= CR_SERVER_LOST;
        strmov(net->last_error,ER(net->last_errno));
        goto error;
      }
      /* Read What server thinks about out new auth message report */
      if (mc_net_safe_read(mysql) == packet_error)
          goto error;
    }
  }

   /* End of authentication part of handshake */

bk@work.mysql.com's avatar
bk@work.mysql.com committed
902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919
  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);
}

tonu@x153.internalnet's avatar
tonu@x153.internalnet committed
920 921 922 923 924 925 926 927

#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.
**************************************************************************
*/
928
int
tonu@x153.internalnet's avatar
tonu@x153.internalnet committed
929 930 931 932 933 934
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));
935
  my_free(mysql->options.ssl_cipher, MYF(MY_ALLOW_ZERO_PTR));
tonu@x153.internalnet's avatar
tonu@x153.internalnet committed
936 937 938 939
  mysql->options.ssl_key = 0;
  mysql->options.ssl_cert = 0;
  mysql->options.ssl_ca = 0;
  mysql->options.ssl_capath = 0;
940
  mysql->options.ssl_cipher= 0;
tonu@x153.internalnet's avatar
tonu@x153.internalnet committed
941 942 943 944 945 946 947
  mysql->options.use_ssl = FALSE;
  my_free(mysql->connector_fd,MYF(MY_ALLOW_ZERO_PTR));
  mysql->connector_fd = 0;
  return 0;
}
#endif /* HAVE_OPENSSL */

bk@work.mysql.com's avatar
bk@work.mysql.com committed
948 949 950 951 952
/*************************************************************************
** Send a QUIT to the server and close the connection
** If handle is alloced by mysql connect free it.
*************************************************************************/

953
void
bk@work.mysql.com's avatar
bk@work.mysql.com committed
954 955 956 957 958 959 960 961 962
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 */
963
      mysql->reconnect=0;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
964 965 966 967 968 969 970 971 972 973 974
      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
tonu@x153.internalnet's avatar
tonu@x153.internalnet committed
975
    mysql_ssl_clear(mysql);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
976 977 978 979 980 981
#endif /* HAVE_OPENSSL */
    if (mysql->free_me)
      my_free((gptr) mysql,MYF(0));
  }
  DBUG_VOID_RETURN;
}
982

monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
983
void mc_mysql_free_result(MYSQL_RES *result)
984 985 986 987 988 989 990 991 992 993
{
  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 (;;)
      {
994 995
	ulong pkt_len;
	if ((pkt_len=mc_net_safe_read(result->handle)) == packet_error)
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 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060
	  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);
}

1061
int mc_mysql_send_query(MYSQL* mysql, const char* query, uint length)
1062 1063 1064 1065
{
  return mc_simple_command(mysql, COM_QUERY, query, length, 1);
}

1066 1067

int mc_mysql_read_query_result(MYSQL *mysql)
1068 1069 1070 1071
{
  uchar *pos;
  ulong field_count;
  MYSQL_DATA *fields;
1072
  ulong length;
1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114
  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);
}

1115 1116

int mc_mysql_query(MYSQL *mysql, const char *query, uint length)
1117
{
1118
  DBUG_ENTER("mc_mysql_query");
1119 1120
  DBUG_PRINT("enter",("handle: %lx",mysql));
  DBUG_PRINT("query",("Query = \"%s\"",query));
1121
  DBUG_ASSERT(length == strlen(query));
1122 1123 1124 1125 1126
  if (mc_simple_command(mysql,COM_QUERY,query,length,1))
    DBUG_RETURN(-1);
  DBUG_RETURN(mc_mysql_read_query_result(mysql));
}

1127

1128 1129
static int mc_send_file_to_server(MYSQL *mysql, const char *filename)
{
1130 1131 1132
  int fd, readcount, result= -1;
  uint packet_length=MY_ALIGN(mysql->net.max_packet-16,IO_SIZE);
  char *buf, tmp_name[FN_REFLEN];
1133 1134
  DBUG_ENTER("send_file_to_server");

1135
  if (!(buf=my_malloc(packet_length,MYF(0))))
1136 1137 1138 1139
  {
    strmov(mysql->net.last_error, ER(mysql->net.last_errno=CR_OUT_OF_MEMORY));
    DBUG_RETURN(-1);
  }
1140 1141

  fn_format(tmp_name,filename,"","",4);		/* Convert to client format */
1142 1143
  if ((fd = my_open(tmp_name,O_RDONLY, MYF(0))) < 0)
  {
1144 1145
    my_net_write(&mysql->net,"",0);		// Server needs one packet
    net_flush(&mysql->net);
1146
    mysql->net.last_errno=EE_FILENOTFOUND;
1147 1148
    my_snprintf(mysql->net.last_error,sizeof(mysql->net.last_error)-1,
		EE(mysql->net.last_errno),tmp_name, errno);
1149
    goto err;
1150 1151
  }

1152
  while ((readcount = (int) my_read(fd,(byte*) buf,packet_length,MYF(0))) > 0)
1153 1154 1155
  {
    if (my_net_write(&mysql->net,buf,readcount))
    {
1156
      DBUG_PRINT("error",("Lost connection to MySQL server during LOAD DATA of local file"));
1157 1158
      mysql->net.last_errno=CR_SERVER_LOST;
      strmov(mysql->net.last_error,ER(mysql->net.last_errno));
1159
      goto err;
1160 1161 1162 1163 1164 1165 1166
    }
  }
  /* 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);
1167
    goto err;
1168 1169 1170 1171
  }
  if (readcount < 0)
  {
    mysql->net.last_errno=EE_READ; /* the errmsg for not entire file read */
1172 1173
    my_snprintf(mysql->net.last_error,sizeof(mysql->net.last_error)-1,
		tmp_name,errno);
1174
    goto err;
1175
  }
1176 1177 1178 1179 1180 1181 1182
  result=0;					// Ok

err:
  if (fd >= 0)
    (void) my_close(fd,MYF(0));
  my_free(buf,MYF(0));
  DBUG_RETURN(result);
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
/* 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)
{
1252 1253
  uint	field;
  ulong pkt_len;
1254 1255 1256 1257 1258 1259 1260 1261
  ulong len;
  uchar *cp;
  char	*to;
  MYSQL_DATA *result;
  MYSQL_ROWS **prev_ptr,*cur;
  NET *net = &mysql->net;
  DBUG_ENTER("mc_read_rows");

1262
  if ((pkt_len=mc_net_safe_read(mysql)) == packet_error)
1263 1264
    DBUG_RETURN(0);
  if (!(result=(MYSQL_DATA*) my_malloc(sizeof(MYSQL_DATA),
1265
				       MYF(MY_ZEROFILL))))
1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 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 1336 1337 1338
  {
    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;

1339
  if ((pkt_len=mc_net_safe_read(mysql)) == packet_error)
1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366
    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;
}

monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
1367
my_ulonglong mc_mysql_num_rows(MYSQL_RES *res)
1368 1369 1370 1371
{
  return res->row_count;
}

monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
1372
unsigned int mc_mysql_num_fields(MYSQL_RES *res)
1373 1374 1375 1376
{
  return res->field_count;
}

monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
1377
void mc_mysql_data_seek(MYSQL_RES *result, my_ulonglong row)
1378 1379 1380 1381 1382 1383 1384 1385 1386
{
  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;
}

monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
1387
MYSQL_ROW STDCALL mc_mysql_fetch_row(MYSQL_RES *res)
1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421
{
  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);
  }
}

monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
1422
int mc_mysql_select_db(MYSQL *mysql, const char *db)
1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435
{
  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);
}


1436
MYSQL_RES *mc_mysql_store_result(MYSQL *mysql)
1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451
{
  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,
1452
				      MYF(MY_ZEROFILL))))
1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474
  {
    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 */
}