mini_client.cc 41.4 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>
hf@deer.mysql.r18.ru's avatar
SCRUM  
hf@deer.mysql.r18.ru committed
26 27
#ifdef HAVE_EXTERNAL_CLIENT

28 29 30 31 32
/* 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>
33
#include <mysql_embed.h>
tonu@hundin.mysql.fi's avatar
tonu@hundin.mysql.fi committed
34
#include <mysql_com.h>
tonu@hundin.mysql.fi's avatar
tonu@hundin.mysql.fi committed
35
#include <violite.h>
bk@work.mysql.com's avatar
bk@work.mysql.com committed
36 37 38 39 40 41 42 43 44
#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"
45
#include <assert.h>
monty@donna.mysql.com's avatar
monty@donna.mysql.com committed
46

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

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

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


92 93 94
#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
95 96 97 98

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

111 112
extern ulong slave_net_timeout;

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

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

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

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

211
void
bk@work.mysql.com's avatar
bk@work.mysql.com committed
212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229
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)
230 231 232
    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
233 234 235 236 237 238 239 240 241 242 243 244 245 246 247
  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>
*****************************************************************************/

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

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

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

399
int  mc_mysql_errno(MYSQL *mysql)
sasha@mysql.sashanet.com's avatar
sasha@mysql.sashanet.com committed
400 401 402 403
{
  return (mysql)->net.last_errno;
}

404 405

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

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



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

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


488
MYSQL *
bk@work.mysql.com's avatar
bk@work.mysql.com committed
489
mc_mysql_connect(MYSQL *mysql,const char *host, const char *user,
490 491 492
		 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
493
{
494
  char		buff[NAME_LEN+USERNAME_LENGTH+100],*end,*host_info;
peter@mysql.com's avatar
peter@mysql.com committed
495
  char          password_hash[SCRAMBLE41_LENGTH];
monty@donna.mysql.com's avatar
monty@donna.mysql.com committed
496
  my_socket	sock;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
497 498
  ulong		ip_addr;
  struct	sockaddr_in sock_addr;
499
  ulong		pkt_length;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
500
  NET		*net= &mysql->net;
501
  thr_alarm_t   alarmed;
502 503
  ALARM		alarm_buff;
  ulong		max_allowed_packet;
504

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

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

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

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

678
  /* Check if version of protocol matches current one */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695

  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);
696 697 698 699 700 701 702 703 704
  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
705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730

  /* 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;
731
  client_flag|=mysql->options.client_flag;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
732 733 734 735 736 737 738
  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
739 740 741 742
  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
743 744 745 746 747 748 749
  if (mysql->options.use_ssl)
    client_flag|=CLIENT_SSL;
#endif /* HAVE_OPENSSL */

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

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

bk@work.mysql.com's avatar
bk@work.mysql.com committed
801 802 803
  if (user && user[0])
    strmake(buff+5,user,32);
  else
804 805 806 807 808
  {
    user = getenv("USER");
    if (!user) user = "mysql";
    strmov((char*) buff+5, user );
  }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
809 810

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

812 813 814 815 816 817 818 819
  /*
    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])
    {
820 821 822 823 824
      /* Prepare false scramble */
      end=strend(buff+5)+1;
      bfill(end, SCRAMBLE_LENGTH, 'x');
      end+=SCRAMBLE_LENGTH;
      *end=0;
825 826 827 828 829 830 831 832
    }
    else  /* For empty password*/
    {
      end=strend(buff+5)+1;
      *end=0; /* Store zero length scramble */
    }
  }
  else
833
  {
834
    /*
835 836
      Real scramble is only sent to old servers. This can be blocked  
      by calling mysql_options(MYSQL *, MYSQL_SECURE_CONNECT, (char*) &1);
837
    */
838 839 840
    end=scramble(strend(buff+5)+1, mysql->scramble_buff, passwd,
                 (my_bool) (mysql->protocol_version == 9));

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

  /* 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
860
    goto error;
861 862 863

  if  (mysql->server_capabilities & CLIENT_SECURE_CONNECTION)
  {
864 865 866
    /* 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 */
867 868
    {
      /* Old passwords will have zero at the first byte of hash */
869
      if (net->read_pos[0] != '*')
870 871 872 873
      {
        /* 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
874
        memcpy(password_hash,buff,SCRAMBLE41_LENGTH);
875 876 877
        /* 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
878 879 880
        password_crypt((char*)net->read_pos+4,mysql->scramble_buff,password_hash,
                       SCRAMBLE41_LENGTH);
        mysql->scramble_buff[SCRAMBLE41_LENGTH]=0;
881
        /* Encode scramble with password. Recycle buffer */
peter@mysql.com's avatar
peter@mysql.com committed
882
        password_crypt(mysql->scramble_buff,buff,buff,SCRAMBLE41_LENGTH);
883 884 885 886 887 888
      }
      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
889 890 891
       password_crypt((char*)net->read_pos+4,mysql->scramble_buff,password_hash,
                      SCRAMBLE41_LENGTH);
       mysql->scramble_buff[SCRAMBLE41_LENGTH]=0;
892
       /* Finally scramble decoded scramble with password */
peter@mysql.com's avatar
peter@mysql.com committed
893
       scramble(buff, mysql->scramble_buff, passwd,0);
894 895
      }
      /* Write second package of authentication */
peter@mysql.com's avatar
peter@mysql.com committed
896
      if (my_net_write(net,buff,SCRAMBLE41_LENGTH) || net_flush(net))
897 898 899 900 901 902 903 904 905 906 907 908 909
      {
        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
910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927
  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
928 929 930 931 932 933 934 935

#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.
**************************************************************************
*/
936
int
tonu@x153.internalnet's avatar
tonu@x153.internalnet committed
937 938 939 940 941 942
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));
943
  my_free(mysql->options.ssl_cipher, MYF(MY_ALLOW_ZERO_PTR));
tonu@x153.internalnet's avatar
tonu@x153.internalnet committed
944 945 946 947
  mysql->options.ssl_key = 0;
  mysql->options.ssl_cert = 0;
  mysql->options.ssl_ca = 0;
  mysql->options.ssl_capath = 0;
948
  mysql->options.ssl_cipher= 0;
tonu@x153.internalnet's avatar
tonu@x153.internalnet committed
949 950 951 952 953 954 955
  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
956 957 958 959 960
/*************************************************************************
** Send a QUIT to the server and close the connection
** If handle is alloced by mysql connect free it.
*************************************************************************/

961
void
bk@work.mysql.com's avatar
bk@work.mysql.com committed
962 963 964 965 966 967 968 969 970
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 */
971
      mysql->reconnect=0;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
972 973 974 975 976 977 978 979 980 981 982
      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
983
    mysql_ssl_clear(mysql);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
984 985 986 987 988 989
#endif /* HAVE_OPENSSL */
    if (mysql->free_me)
      my_free((gptr) mysql,MYF(0));
  }
  DBUG_VOID_RETURN;
}
990

monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
991
void mc_mysql_free_result(MYSQL_RES *result)
992 993 994 995 996 997 998 999 1000 1001
{
  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 (;;)
      {
1002 1003
	ulong pkt_len;
	if ((pkt_len=mc_net_safe_read(result->handle)) == packet_error)
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 1061 1062 1063 1064 1065 1066 1067 1068
	  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);
}

1069
int mc_mysql_send_query(MYSQL* mysql, const char* query, uint length)
1070 1071 1072 1073
{
  return mc_simple_command(mysql, COM_QUERY, query, length, 1);
}

1074 1075

int mc_mysql_read_query_result(MYSQL *mysql)
1076 1077 1078 1079
{
  uchar *pos;
  ulong field_count;
  MYSQL_DATA *fields;
1080
  ulong length;
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 1115 1116 1117 1118 1119 1120 1121 1122
  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);
}

1123 1124

int mc_mysql_query(MYSQL *mysql, const char *query, uint length)
1125
{
1126
  DBUG_ENTER("mc_mysql_query");
1127 1128
  DBUG_PRINT("enter",("handle: %lx",mysql));
  DBUG_PRINT("query",("Query = \"%s\"",query));
1129
  DBUG_ASSERT(length == strlen(query));
1130 1131 1132 1133 1134
  if (mc_simple_command(mysql,COM_QUERY,query,length,1))
    DBUG_RETURN(-1);
  DBUG_RETURN(mc_mysql_read_query_result(mysql));
}

1135

1136 1137
static int mc_send_file_to_server(MYSQL *mysql, const char *filename)
{
1138 1139 1140
  int fd, readcount, result= -1;
  uint packet_length=MY_ALIGN(mysql->net.max_packet-16,IO_SIZE);
  char *buf, tmp_name[FN_REFLEN];
1141 1142
  DBUG_ENTER("send_file_to_server");

1143
  if (!(buf=my_malloc(packet_length,MYF(0))))
1144 1145 1146 1147
  {
    strmov(mysql->net.last_error, ER(mysql->net.last_errno=CR_OUT_OF_MEMORY));
    DBUG_RETURN(-1);
  }
1148 1149

  fn_format(tmp_name,filename,"","",4);		/* Convert to client format */
1150 1151
  if ((fd = my_open(tmp_name,O_RDONLY, MYF(0))) < 0)
  {
1152 1153
    my_net_write(&mysql->net,"",0);		// Server needs one packet
    net_flush(&mysql->net);
1154
    mysql->net.last_errno=EE_FILENOTFOUND;
1155 1156
    my_snprintf(mysql->net.last_error,sizeof(mysql->net.last_error)-1,
		EE(mysql->net.last_errno),tmp_name, errno);
1157
    goto err;
1158 1159
  }

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

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

1270
  if ((pkt_len=mc_net_safe_read(mysql)) == packet_error)
1271 1272
    DBUG_RETURN(0);
  if (!(result=(MYSQL_DATA*) my_malloc(sizeof(MYSQL_DATA),
1273
				       MYF(MY_ZEROFILL))))
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 1339 1340 1341 1342 1343 1344 1345 1346
  {
    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;

1347
  if ((pkt_len=mc_net_safe_read(mysql)) == packet_error)
1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374
    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
1375
my_ulonglong mc_mysql_num_rows(MYSQL_RES *res)
1376 1377 1378 1379
{
  return res->row_count;
}

monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
1380
unsigned int mc_mysql_num_fields(MYSQL_RES *res)
1381 1382 1383 1384
{
  return res->field_count;
}

monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
1385
void mc_mysql_data_seek(MYSQL_RES *result, my_ulonglong row)
1386 1387 1388 1389 1390 1391 1392 1393 1394
{
  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
1395
MYSQL_ROW STDCALL mc_mysql_fetch_row(MYSQL_RES *res)
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 1422 1423 1424 1425 1426 1427 1428 1429
{
  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
1430
int mc_mysql_select_db(MYSQL *mysql, const char *db)
1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443
{
  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);
}


1444
MYSQL_RES *mc_mysql_store_result(MYSQL *mysql)
1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459
{
  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,
1460
				      MYF(MY_ZEROFILL))))
1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482
  {
    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 */
}
1483

hf@deer.mysql.r18.ru's avatar
SCRUM  
hf@deer.mysql.r18.ru committed
1484
#endif /* HAVE_EXTERNAL_CLIENT */