client.c 135 KB
Newer Older
1
/* Copyright (c) 2003, 2016, Oracle and/or its affiliates.
2
   Copyright (c) 2009, 2017, MariaDB
unknown's avatar
unknown committed
3 4 5

   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
unknown's avatar
unknown committed
6
   the Free Software Foundation; version 2 of the License.
unknown's avatar
unknown committed
7 8 9 10 11 12 13 14

   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.

   You should have received a copy of the GNU General Public License
   along with this program; if not, write to the Free Software
15
   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA */
unknown's avatar
unknown committed
16

unknown's avatar
unknown committed
17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
/*
  This file is included by both libmysql.c (the MySQL client C API)
  and the mysqld server to connect to another MYSQL server.

  The differences for the two cases are:

  - Things that only works for the client:
  - Trying to automaticly determinate user name if not supplied to
    mysql_real_connect()
  - Support for reading local file with LOAD DATA LOCAL
  - SHARED memory handling
  - Prepared statements
  
  - Things that only works for the server
  - Alarm handling on connect
  
  In all other cases, the code should be idential for the client and
  server.
*/ 

unknown's avatar
unknown committed
37 38 39
#include <my_global.h>

#include "mysql.h"
unknown's avatar
SCRUM  
unknown committed
40

41 42 43 44
#ifndef __WIN__
#include <netdb.h>
#endif

unknown's avatar
unknown committed
45 46 47 48
/* Remove client convenience wrappers */
#undef max_allowed_packet
#undef net_buffer_length

unknown's avatar
SCRUM  
unknown committed
49 50 51 52 53 54 55 56
#ifdef EMBEDDED_LIBRARY

#undef MYSQL_SERVER

#ifndef MYSQL_CLIENT
#define MYSQL_CLIENT
#endif

57
#define CLI_MYSQL_REAL_CONNECT STDCALL cli_mysql_real_connect
unknown's avatar
SCRUM  
unknown committed
58 59 60 61 62

#undef net_flush
my_bool	net_flush(NET *net);

#else  /*EMBEDDED_LIBRARY*/
unknown's avatar
unknown committed
63
#define CLI_MYSQL_REAL_CONNECT STDCALL mysql_real_connect
unknown's avatar
SCRUM  
unknown committed
64
#endif /*EMBEDDED_LIBRARY*/
unknown's avatar
unknown committed
65 66 67 68 69 70 71 72
#include <my_sys.h>
#include <mysys_err.h>
#include <m_string.h>
#include <m_ctype.h>
#include "mysql_version.h"
#include "mysqld_error.h"
#include "errmsg.h"
#include <violite.h>
73
#if !defined(__WIN__)
unknown's avatar
unknown committed
74
#include <my_pthread.h>				/* because of signal()	*/
75
#endif /* !defined(__WIN__) */
unknown's avatar
unknown committed
76 77 78 79 80 81 82

#include <sys/stat.h>
#include <signal.h>
#include <time.h>
#ifdef	 HAVE_PWD_H
#include <pwd.h>
#endif
83
#if !defined(__WIN__)
unknown's avatar
unknown committed
84 85 86 87 88 89 90 91 92 93
#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
94
#endif /* !defined(__WIN__) */
unknown's avatar
unknown committed
95 96 97 98
#ifdef HAVE_SYS_UN_H
#  include <sys/un.h>
#endif

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

106 107 108 109 110 111
#ifdef __WIN__
#define CONNECT_TIMEOUT 20
#else
#define CONNECT_TIMEOUT 0
#endif

unknown's avatar
unknown committed
112 113
#include "client_settings.h"
#include <sql_common.h>
114
#include <mysql/client_plugin.h>
115 116
#include <my_context.h>
#include <mysql_async.h>
117 118 119

#define native_password_plugin_name "mysql_native_password"
#define old_password_plugin_name    "mysql_old_password"
unknown's avatar
unknown committed
120

121
uint            mariadb_deinitialize_ssl= 1;
122 123 124
uint		mysql_port=0;
char		*mysql_unix_port= 0;
const char	*unknown_sqlstate= "HY000";
unknown's avatar
unknown committed
125
const char	*not_error_sqlstate= "00000";
126
const char	*cant_connect_sqlstate= "08001";
127 128
#ifdef HAVE_SMEM
char		 *shared_memory_base_name= 0;
129
const char 	*def_shared_memory_base_name= default_shared_memory_base_name;
unknown's avatar
unknown committed
130 131
#endif

132 133
static void mysql_close_free_options(MYSQL *mysql);
static void mysql_close_free(MYSQL *mysql);
134
static void mysql_prune_stmt_list(MYSQL *mysql);
135
static int cli_report_progress(MYSQL *mysql, uchar *packet, uint length);
136

137
#if !defined(__WIN__)
unknown's avatar
unknown committed
138 139 140
static int wait_for_data(my_socket fd, uint timeout);
#endif

141 142
CHARSET_INFO *default_client_charset_info = &my_charset_latin1;

143 144 145
/* Server error code and message */
unsigned int mysql_server_last_errno;
char mysql_server_last_error[MYSQL_ERRMSG_SIZE];
146

unknown's avatar
SCRUM  
unknown committed
147 148 149 150 151 152 153 154 155
/****************************************************************************
  A modified version of connect().  my_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,
  my_connect() will behave exactly like connect().

  Base version coded by Steve Bernacki, Jr. <steve@navinet.net>
*****************************************************************************/

unknown's avatar
unknown committed
156 157
int my_connect(my_socket fd, const struct sockaddr *name, uint namelen,
	       uint timeout)
unknown's avatar
SCRUM  
unknown committed
158
{
159
#if defined(__WIN__)
160 161
  DBUG_ENTER("my_connect");
  DBUG_RETURN(connect(fd, (struct sockaddr*) name, namelen));
unknown's avatar
SCRUM  
unknown committed
162 163
#else
  int flags, res, s_err;
164 165
  DBUG_ENTER("my_connect");
  DBUG_PRINT("enter", ("fd: %d  timeout: %u", fd, timeout));
unknown's avatar
SCRUM  
unknown committed
166 167 168 169 170 171 172

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

  if (timeout == 0)
173
    DBUG_RETURN(connect(fd, (struct sockaddr*) name, namelen));
unknown's avatar
SCRUM  
unknown committed
174

unknown's avatar
unknown committed
175
  flags = fcntl(fd, F_GETFL, 0);	  /* Set socket to not block */
unknown's avatar
SCRUM  
unknown committed
176
#ifdef O_NONBLOCK
unknown's avatar
unknown committed
177
  fcntl(fd, F_SETFL, flags | O_NONBLOCK);  /* and save the flags..  */
unknown's avatar
SCRUM  
unknown committed
178 179
#endif

180
  DBUG_PRINT("info", ("connecting non-blocking"));
unknown's avatar
unknown committed
181
  res= connect(fd, (struct sockaddr*) name, namelen);
182
  DBUG_PRINT("info", ("connect result: %d  errno: %d", res, errno));
unknown's avatar
unknown committed
183 184
  s_err= errno;			/* Save the error... */
  fcntl(fd, F_SETFL, flags);
unknown's avatar
SCRUM  
unknown committed
185 186
  if ((res != 0) && (s_err != EINPROGRESS))
  {
unknown's avatar
unknown committed
187
    errno= s_err;			/* Restore it */
188
    DBUG_RETURN(-1);
unknown's avatar
SCRUM  
unknown committed
189 190
  }
  if (res == 0)				/* Connected quickly! */
191 192
    DBUG_RETURN(0);
  DBUG_RETURN(wait_for_data(fd, timeout));
unknown's avatar
unknown committed
193 194 195 196 197 198 199 200 201 202 203
#endif
}


/*
  Wait up to timeout seconds for a connection to be established.

  We prefer to do this with poll() as there is no limitations with this.
  If not, we will use select()
*/

204
#if !defined(__WIN__)
unknown's avatar
unknown committed
205 206 207 208 209 210

static int wait_for_data(my_socket fd, uint timeout)
{
#ifdef HAVE_POLL
  struct pollfd ufds;
  int res;
211
  DBUG_ENTER("wait_for_data");
unknown's avatar
unknown committed
212

213
  DBUG_PRINT("info", ("polling"));
unknown's avatar
unknown committed
214 215 216 217
  ufds.fd= fd;
  ufds.events= POLLIN | POLLPRI;
  if (!(res= poll(&ufds, 1, (int) timeout*1000)))
  {
218
    DBUG_PRINT("info", ("poll timed out"));
unknown's avatar
unknown committed
219
    errno= EINTR;
220
    DBUG_RETURN(-1);
unknown's avatar
unknown committed
221
  }
222 223 224
  DBUG_PRINT("info",
             ("poll result: %d  errno: %d  revents: 0x%02d  events: 0x%02d",
              res, errno, ufds.revents, ufds.events));
unknown's avatar
unknown committed
225
  if (res < 0 || !(ufds.revents & (POLLIN | POLLPRI)))
226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252
    DBUG_RETURN(-1);
  /*
    At this point, we know that something happened on the socket.
    But this does not means that everything is alright.
    The connect might have failed. We need to retrieve the error code
    from the socket layer. We must return success only if we are sure
    that it was really a success. Otherwise we might prevent the caller
    from trying another address to connect to.
  */
  {
    int         s_err;
    socklen_t   s_len= sizeof(s_err);

    DBUG_PRINT("info", ("Get SO_ERROR from non-blocked connected socket."));
    res= getsockopt(fd, SOL_SOCKET, SO_ERROR, &s_err, &s_len);
    DBUG_PRINT("info", ("getsockopt res: %d  s_err: %d", res, s_err));
    if (res)
      DBUG_RETURN(res);
    /* getsockopt() was successful, check the retrieved status value. */
    if (s_err)
    {
      errno= s_err;
      DBUG_RETURN(-1);
    }
    /* Status from connect() is zero. Socket is successfully connected. */
  }
  DBUG_RETURN(0);
unknown's avatar
unknown committed
253 254 255 256 257 258
#else
  SOCKOPT_OPTLEN_TYPE s_err_size = sizeof(uint);
  fd_set sfds;
  struct timeval tv;
  time_t start_time, now_time;
  int res, s_err;
259
  DBUG_ENTER("wait_for_data");
unknown's avatar
unknown committed
260 261

  if (fd >= FD_SETSIZE)				/* Check if wrong error */
262
    DBUG_RETURN(0);					/* Can't use timeout */
unknown's avatar
SCRUM  
unknown committed
263 264

  /*
unknown's avatar
unknown committed
265 266 267 268
    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
unknown's avatar
SCRUM  
unknown committed
269
    select() returns 1, then one of two conditions exist:
unknown's avatar
unknown committed
270
   
unknown's avatar
SCRUM  
unknown committed
271 272 273
    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.
unknown's avatar
unknown committed
274
   
unknown's avatar
SCRUM  
unknown committed
275 276 277 278 279 280
    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);
unknown's avatar
unknown committed
281
  FD_SET(fd, &sfds);
unknown's avatar
SCRUM  
unknown committed
282
  /*
unknown's avatar
unknown committed
283
    select could be interrupted by a signal, and if it is, 
unknown's avatar
SCRUM  
unknown committed
284
    the timeout should be adjusted and the select restarted
unknown's avatar
unknown committed
285
    to work around OSes that don't restart select and 
unknown's avatar
SCRUM  
unknown committed
286 287
    implementations of select that don't adjust tv upon
    failure to reflect the time remaining
unknown's avatar
unknown committed
288
   */
289
  start_time= my_time(0);
unknown's avatar
SCRUM  
unknown committed
290 291 292 293
  for (;;)
  {
    tv.tv_sec = (long) timeout;
    tv.tv_usec = 0;
294
#if defined(HPUX10)
unknown's avatar
unknown committed
295
    if ((res = select(fd+1, NULL, (int*) &sfds, NULL, &tv)) > 0)
unknown's avatar
SCRUM  
unknown committed
296 297
      break;
#else
unknown's avatar
unknown committed
298
    if ((res = select(fd+1, NULL, &sfds, NULL, &tv)) > 0)
unknown's avatar
SCRUM  
unknown committed
299 300 301
      break;
#endif
    if (res == 0)					/* timeout */
302
      DBUG_RETURN(-1);
303
    now_time= my_time(0);
unknown's avatar
SCRUM  
unknown committed
304 305
    timeout-= (uint) (now_time - start_time);
    if (errno != EINTR || (int) timeout <= 0)
306
      DBUG_RETURN(-1);
unknown's avatar
SCRUM  
unknown committed
307 308 309 310 311 312 313 314 315
  }

  /*
    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;
unknown's avatar
unknown committed
316
  if (getsockopt(fd, SOL_SOCKET, SO_ERROR, (char*) &s_err, &s_err_size) != 0)
317
    DBUG_RETURN(-1);
unknown's avatar
SCRUM  
unknown committed
318 319 320 321

  if (s_err)
  {						/* getsockopt could succeed */
    errno = s_err;
322
    DBUG_RETURN(-1);					/* but return an error... */
unknown's avatar
SCRUM  
unknown committed
323
  }
324
  DBUG_RETURN(0);					/* ok */
unknown's avatar
unknown committed
325
#endif /* HAVE_POLL */
unknown's avatar
SCRUM  
unknown committed
326
}
327
#endif /* !defined(__WIN__) */
unknown's avatar
unknown committed
328

329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344
/**
  Set the internal error message to mysql handler

  @param mysql    connection handle (client side)
  @param errcode  CR_ error code, passed to ER macro to get
                  error text
  @parma sqlstate SQL standard sqlstate
*/

void set_mysql_error(MYSQL *mysql, int errcode, const char *sqlstate)
{
  NET *net;
  DBUG_ENTER("set_mysql_error");
  DBUG_PRINT("enter", ("error :%d '%s'", errcode, ER(errcode)));
  DBUG_ASSERT(mysql != 0);

345 346 347
  if (mysql)
  {
    net= &mysql->net;
348 349
    net->last_errno= errcode;
    strmov(net->last_error, ER(errcode));
350 351 352 353 354 355 356
    strmov(net->sqlstate, sqlstate);
  }
  else
  {
    mysql_server_last_errno= errcode;
    strmov(mysql_server_last_error, ER(errcode));
  }
357 358 359 360 361 362 363 364 365 366 367
  DBUG_VOID_RETURN;
}

/**
  Clear possible error state of struct NET

  @param net  clear the state of the argument
*/

void net_clear_error(NET *net)
{
unknown's avatar
unknown committed
368 369
  net->last_errno= 0;
  net->last_error[0]= '\0';
370 371 372 373 374 375 376 377 378 379 380 381 382 383
  strmov(net->sqlstate, not_error_sqlstate);
}

/**
  Set an error message on the client.

  @param mysql     connection handle
  @param errcode   CR_* errcode, for client errors
  @param sqlstate  SQL standard sql state, unknown_sqlstate for the
                   majority of client errors.
  @param format    error message template, in sprintf format
  @param ...       variable number of arguments
*/

384
void set_mysql_extended_error(MYSQL *mysql, int errcode,
385 386 387 388 389 390 391 392 393 394
                                     const char *sqlstate,
                                     const char *format, ...)
{
  NET *net;
  va_list args;
  DBUG_ENTER("set_mysql_extended_error");
  DBUG_PRINT("enter", ("error :%d '%s'", errcode, format));
  DBUG_ASSERT(mysql != 0);

  net= &mysql->net;
unknown's avatar
unknown committed
395
  net->last_errno= errcode;
396
  va_start(args, format);
unknown's avatar
unknown committed
397
  my_vsnprintf(net->last_error, sizeof(net->last_error)-1,
398 399 400 401 402 403 404 405
               format, args);
  va_end(args);
  strmov(net->sqlstate, sqlstate);

  DBUG_VOID_RETURN;
}


unknown's avatar
SCRUM  
unknown committed
406 407 408 409 410 411 412

/*
  Create a named pipe connection
*/

#ifdef __WIN__

413
HANDLE create_named_pipe(MYSQL *mysql, uint connect_timeout, char **arg_host,
unknown's avatar
SCRUM  
unknown committed
414 415 416
			 char **arg_unix_socket)
{
  HANDLE hPipe=INVALID_HANDLE_VALUE;
unknown's avatar
unknown committed
417
  char pipe_name[1024];
unknown's avatar
SCRUM  
unknown committed
418 419 420 421 422 423 424 425 426 427
  DWORD dwMode;
  int i;
  my_bool testing_named_pipes=0;
  char *host= *arg_host, *unix_socket= *arg_unix_socket;

  if ( ! unix_socket || (unix_socket)[0] == 0x00)
    unix_socket = mysql_unix_port;
  if (!host || !strcmp(host,LOCAL_HOST))
    host=LOCAL_HOST_NAMEDPIPE;

unknown's avatar
unknown committed
428 429 430 431 432
  
  pipe_name[sizeof(pipe_name)-1]= 0;		/* Safety if too long string */
  strxnmov(pipe_name, sizeof(pipe_name)-1, "\\\\", host, "\\pipe\\",
	   unix_socket, NullS);
  DBUG_PRINT("info",("Server name: '%s'.  Named Pipe: %s", host, unix_socket));
unknown's avatar
SCRUM  
unknown committed
433 434 435

  for (i=0 ; i < 100 ; i++)			/* Don't retry forever */
  {
unknown's avatar
unknown committed
436
    if ((hPipe = CreateFile(pipe_name,
unknown's avatar
SCRUM  
unknown committed
437 438 439 440
			    GENERIC_READ | GENERIC_WRITE,
			    0,
			    NULL,
			    OPEN_EXISTING,
441
			    FILE_FLAG_OVERLAPPED,
unknown's avatar
SCRUM  
unknown committed
442 443 444 445
			    NULL )) != INVALID_HANDLE_VALUE)
      break;
    if (GetLastError() != ERROR_PIPE_BUSY)
    {
446 447 448
      set_mysql_extended_error(mysql, CR_NAMEDPIPEOPEN_ERROR,
                               unknown_sqlstate, ER(CR_NAMEDPIPEOPEN_ERROR),
                               host, unix_socket, (ulong) GetLastError());
unknown's avatar
SCRUM  
unknown committed
449 450 451
      return INVALID_HANDLE_VALUE;
    }
    /* wait for for an other instance */
unknown's avatar
unknown committed
452
    if (! WaitNamedPipe(pipe_name, connect_timeout*1000) )
unknown's avatar
SCRUM  
unknown committed
453
    {
454 455 456
      set_mysql_extended_error(mysql, CR_NAMEDPIPEWAIT_ERROR, unknown_sqlstate,
                               ER(CR_NAMEDPIPEWAIT_ERROR),
                               host, unix_socket, (ulong) GetLastError());
unknown's avatar
SCRUM  
unknown committed
457 458 459 460 461
      return INVALID_HANDLE_VALUE;
    }
  }
  if (hPipe == INVALID_HANDLE_VALUE)
  {
462 463 464
    set_mysql_extended_error(mysql, CR_NAMEDPIPEOPEN_ERROR, unknown_sqlstate,
                             ER(CR_NAMEDPIPEOPEN_ERROR), host, unix_socket,
                             (ulong) GetLastError());
unknown's avatar
SCRUM  
unknown committed
465 466 467 468 469 470
    return INVALID_HANDLE_VALUE;
  }
  dwMode = PIPE_READMODE_BYTE | PIPE_WAIT;
  if ( !SetNamedPipeHandleState(hPipe, &dwMode, NULL, NULL) )
  {
    CloseHandle( hPipe );
471 472 473
    set_mysql_extended_error(mysql, CR_NAMEDPIPESETSTATE_ERROR,
                             unknown_sqlstate, ER(CR_NAMEDPIPESETSTATE_ERROR),
                             host, unix_socket, (ulong) GetLastError());
unknown's avatar
SCRUM  
unknown committed
474 475 476 477 478 479 480
    return INVALID_HANDLE_VALUE;
  }
  *arg_host=host ; *arg_unix_socket=unix_socket;	/* connect arg */
  return (hPipe);
}
#endif

481

482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498
/*
  Create new shared memory connection, return handler of connection

  SYNOPSIS
    create_shared_memory()
    mysql		Pointer of mysql structure
    net			Pointer of net structure
    connect_timeout	Timeout of connection
*/

#ifdef HAVE_SMEM
HANDLE create_shared_memory(MYSQL *mysql,NET *net, uint connect_timeout)
{
  ulong smem_buffer_length = shared_memory_buffer_length + 4;
  /*
    event_connect_request is event object for start connection actions
    event_connect_answer is event object for confirm, that server put data
499 500
    handle_connect_file_map is file-mapping object, use for create shared
    memory
501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518
    handle_connect_map is pointer on shared memory
    handle_map is pointer on shared memory for client
    event_server_wrote,
    event_server_read,
    event_client_wrote,
    event_client_read are events for transfer data between server and client
    handle_file_map is file-mapping object, use for create shared memory
  */
  HANDLE event_connect_request = NULL;
  HANDLE event_connect_answer = NULL;
  HANDLE handle_connect_file_map = NULL;
  char *handle_connect_map = NULL;

  char *handle_map = NULL;
  HANDLE event_server_wrote = NULL;
  HANDLE event_server_read = NULL;
  HANDLE event_client_wrote = NULL;
  HANDLE event_client_read = NULL;
unknown's avatar
unknown committed
519
  HANDLE event_conn_closed = NULL;
520 521 522
  HANDLE handle_file_map = NULL;
  ulong connect_number;
  char connect_number_char[22], *p;
523
  char *tmp= NULL;
524 525 526
  char *suffix_pos;
  DWORD error_allow = 0;
  DWORD error_code = 0;
527
  DWORD event_access_rights= SYNCHRONIZE | EVENT_MODIFY_STATE;
528
  char *shared_memory_base_name = mysql->options.shared_memory_base_name;
529 530 531
  static const char *name_prefixes[] = {"","Global\\"};
  const char *prefix;
  int i;
532

533 534 535 536 537 538 539 540 541
  /*
    If this is NULL, somebody freed the MYSQL* options.  mysql_close()
    is a good candidate.  We don't just silently (re)set it to
    def_shared_memory_base_name as that would create really confusing/buggy
    behavior if the user passed in a different name on the command-line or
    in a my.cnf.
  */
  DBUG_ASSERT(shared_memory_base_name != NULL);

542 543 544 545 546 547
  /*
     get enough space base-name + '_' + longest suffix we might ever send
   */
  if (!(tmp= (char *)my_malloc(strlen(shared_memory_base_name) + 32L, MYF(MY_FAE))))
    goto err;

548 549
  /*
    The name of event and file-mapping events create agree next rule:
unknown's avatar
unknown committed
550
    shared_memory_base_name+unique_part
551
    Where:
unknown's avatar
unknown committed
552 553
    shared_memory_base_name is unique value for each server
    unique_part is uniquel value for each object (events and file-mapping)
554
  */
555 556 557 558 559 560 561 562 563 564 565 566
  for (i = 0; i< array_elements(name_prefixes); i++)
  {
    prefix= name_prefixes[i];
    suffix_pos = strxmov(tmp, prefix , shared_memory_base_name, "_", NullS);
    strmov(suffix_pos, "CONNECT_REQUEST");
    event_connect_request= OpenEvent(event_access_rights, FALSE, tmp);
    if (event_connect_request)
    {
      break;
    }
  }
  if (!event_connect_request)
567 568 569 570 571
  {
    error_allow = CR_SHARED_MEMORY_CONNECT_REQUEST_ERROR;
    goto err;
  }
  strmov(suffix_pos, "CONNECT_ANSWER");
572
  if (!(event_connect_answer= OpenEvent(event_access_rights,FALSE,tmp)))
573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588
  {
    error_allow = CR_SHARED_MEMORY_CONNECT_ANSWER_ERROR;
    goto err;
  }
  strmov(suffix_pos, "CONNECT_DATA");
  if (!(handle_connect_file_map= OpenFileMapping(FILE_MAP_WRITE,FALSE,tmp)))
  {
    error_allow = CR_SHARED_MEMORY_CONNECT_FILE_MAP_ERROR;
    goto err;
  }
  if (!(handle_connect_map= MapViewOfFile(handle_connect_file_map,
					  FILE_MAP_WRITE,0,0,sizeof(DWORD))))
  {
    error_allow = CR_SHARED_MEMORY_CONNECT_MAP_ERROR;
    goto err;
  }
unknown's avatar
unknown committed
589 590

  /* Send to server request of connection */
591 592 593 594 595
  if (!SetEvent(event_connect_request))
  {
    error_allow = CR_SHARED_MEMORY_CONNECT_SET_ERROR;
    goto err;
  }
unknown's avatar
unknown committed
596 597

  /* Wait of answer from server */
598 599 600
  if (WaitForSingleObject(event_connect_answer,connect_timeout*1000) !=
      WAIT_OBJECT_0)
  {
unknown's avatar
unknown committed
601
    error_allow = CR_SHARED_MEMORY_CONNECT_ABANDONED_ERROR;
602 603
    goto err;
  }
unknown's avatar
unknown committed
604 605

  /* Get number of connection */
606
  connect_number = uint4korr(handle_connect_map);/*WAX2*/
607
  p= int10_to_str(connect_number, connect_number_char, 10);
608 609 610 611

  /*
    The name of event and file-mapping events create agree next rule:
    shared_memory_base_name+unique_part+number_of_connection
unknown's avatar
unknown committed
612

613
    Where:
unknown's avatar
unknown committed
614 615 616
    shared_memory_base_name is uniquel value for each server
    unique_part is uniquel value for each object (events and file-mapping)
    number_of_connection is number of connection between server and client
617
  */
618
  suffix_pos = strxmov(tmp, prefix , shared_memory_base_name, "_", connect_number_char,
619
		       "_", NullS);
620 621 622 623 624 625 626 627 628 629 630 631 632 633
  strmov(suffix_pos, "DATA");
  if ((handle_file_map = OpenFileMapping(FILE_MAP_WRITE,FALSE,tmp)) == NULL)
  {
    error_allow = CR_SHARED_MEMORY_FILE_MAP_ERROR;
    goto err2;
  }
  if ((handle_map = MapViewOfFile(handle_file_map,FILE_MAP_WRITE,0,0,
				  smem_buffer_length)) == NULL)
  {
    error_allow = CR_SHARED_MEMORY_MAP_ERROR;
    goto err2;
  }

  strmov(suffix_pos, "SERVER_WROTE");
634
  if ((event_server_wrote = OpenEvent(event_access_rights,FALSE,tmp)) == NULL)
635 636 637 638 639 640
  {
    error_allow = CR_SHARED_MEMORY_EVENT_ERROR;
    goto err2;
  }

  strmov(suffix_pos, "SERVER_READ");
641
  if ((event_server_read = OpenEvent(event_access_rights,FALSE,tmp)) == NULL)
642 643 644 645 646 647
  {
    error_allow = CR_SHARED_MEMORY_EVENT_ERROR;
    goto err2;
  }

  strmov(suffix_pos, "CLIENT_WROTE");
648
  if ((event_client_wrote = OpenEvent(event_access_rights,FALSE,tmp)) == NULL)
649 650 651 652 653 654
  {
    error_allow = CR_SHARED_MEMORY_EVENT_ERROR;
    goto err2;
  }

  strmov(suffix_pos, "CLIENT_READ");
655
  if ((event_client_read = OpenEvent(event_access_rights,FALSE,tmp)) == NULL)
656 657 658 659
  {
    error_allow = CR_SHARED_MEMORY_EVENT_ERROR;
    goto err2;
  }
unknown's avatar
unknown committed
660 661

  strmov(suffix_pos, "CONNECTION_CLOSED");
662
  if ((event_conn_closed = OpenEvent(event_access_rights,FALSE,tmp)) == NULL)
unknown's avatar
unknown committed
663 664 665 666
  {
    error_allow = CR_SHARED_MEMORY_EVENT_ERROR;
    goto err2;
  }
667 668 669 670 671 672 673 674
  /*
    Set event that server should send data
  */
  SetEvent(event_server_read);

err2:
  if (error_allow == 0)
  {
675
    net->vio= vio_new_win32shared_memory(handle_file_map,handle_map,
unknown's avatar
unknown committed
676
                                         event_server_wrote,
677
                                         event_server_read,event_client_wrote,
unknown's avatar
unknown committed
678
                                         event_client_read,event_conn_closed);
679 680 681 682 683 684 685 686 687 688 689 690
  }
  else
  {
    error_code = GetLastError();
    if (event_server_read)
      CloseHandle(event_server_read);
    if (event_server_wrote)
      CloseHandle(event_server_wrote);
    if (event_client_read)
      CloseHandle(event_client_read);
    if (event_client_wrote)
      CloseHandle(event_client_wrote);
unknown's avatar
unknown committed
691 692
    if (event_conn_closed)
      CloseHandle(event_conn_closed);
693 694 695 696 697 698
    if (handle_map)
      UnmapViewOfFile(handle_map);
    if (handle_file_map)
      CloseHandle(handle_file_map);
  }
err:
699
  my_free(tmp);
700 701 702 703 704 705 706 707 708 709 710 711 712
  if (error_allow)
    error_code = GetLastError();
  if (event_connect_request)
    CloseHandle(event_connect_request);
  if (event_connect_answer)
    CloseHandle(event_connect_answer);
  if (handle_connect_map)
    UnmapViewOfFile(handle_connect_map);
  if (handle_connect_file_map)
    CloseHandle(handle_connect_file_map);
  if (error_allow)
  {
    if (error_allow == CR_SHARED_MEMORY_EVENT_ERROR)
713 714
      set_mysql_extended_error(mysql, error_allow, unknown_sqlstate,
                               ER(error_allow), suffix_pos, error_code);
715
    else
716 717
      set_mysql_extended_error(mysql, error_allow, unknown_sqlstate,
                               ER(error_allow), error_code);
718 719 720 721 722 723
    return(INVALID_HANDLE_VALUE);
  }
  return(handle_map);
}
#endif

724
/**
unknown's avatar
SCRUM  
unknown committed
725 726
  Read a packet from server. Give error message if socket was down
  or packet is an error message
727 728 729 730 731

  @retval  packet_error    An error occurred during reading.
                           Error message is set.
  @retval  
*/
unknown's avatar
SCRUM  
unknown committed
732 733

ulong
734
cli_safe_read(MYSQL *mysql)
unknown's avatar
SCRUM  
unknown committed
735 736 737 738
{
  NET *net= &mysql->net;
  ulong len=0;

739
restart:
unknown's avatar
SCRUM  
unknown committed
740 741 742 743 744
  if (net->vio != 0)
    len=my_net_read(net);

  if (len == packet_error || len == 0)
  {
unknown's avatar
unknown committed
745
    DBUG_PRINT("error",("Wrong connection or packet. fd: %s  len: %lu",
unknown's avatar
SCRUM  
unknown committed
746
			vio_description(net->vio),len));
unknown's avatar
unknown committed
747
#ifdef MYSQL_SERVER
748
    if (net->vio && vio_was_interrupted(net->vio))
unknown's avatar
unknown committed
749 750
      return (packet_error);
#endif /*MYSQL_SERVER*/
unknown's avatar
SCRUM  
unknown committed
751
    end_server(mysql);
unknown's avatar
unknown committed
752
    set_mysql_error(mysql, net->last_errno == ER_NET_PACKET_TOO_LARGE ?
753
                    CR_NET_PACKET_TOO_LARGE: CR_SERVER_LOST, unknown_sqlstate);
unknown's avatar
SCRUM  
unknown committed
754 755 756 757 758 759
    return (packet_error);
  }
  if (net->read_pos[0] == 255)
  {
    if (len > 3)
    {
760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775
      uchar *pos= net->read_pos+1;
      uint last_errno=uint2korr(pos);

      if (last_errno == 65535 &&
          (mysql->server_capabilities & CLIENT_PROGRESS))
      {
        if (cli_report_progress(mysql, pos+2, (uint) (len-3)))
        {
          /* Wrong packet */
          set_mysql_error(mysql,  CR_MALFORMED_PACKET, unknown_sqlstate);
          return (packet_error);
        }
        goto restart;
      }
      net->last_errno= last_errno;
      
unknown's avatar
SCRUM  
unknown committed
776 777
      pos+=2;
      len-=2;
778
      if (protocol_41(mysql) && (char) pos[0] == '#')
unknown's avatar
unknown committed
779
      {
780
	strmake_buf(net->sqlstate, (char*) pos+1);
unknown's avatar
unknown committed
781 782
	pos+= SQLSTATE_LENGTH+1;
      }
783 784 785 786 787 788 789 790 791 792
      else
      {
        /*
          The SQL state hasn't been received -- it should be reset to HY000
          (unknown error sql state).
        */

        strmov(net->sqlstate, unknown_sqlstate);
      }

unknown's avatar
unknown committed
793 794
      (void) strmake(net->last_error,(char*) pos,
		     min((uint) len,(uint) sizeof(net->last_error)-1));
unknown's avatar
SCRUM  
unknown committed
795 796
    }
    else
797
      set_mysql_error(mysql, CR_UNKNOWN_ERROR, unknown_sqlstate);
798 799 800 801 802 803 804 805 806 807
    /*
      Cover a protocol design error: error packet does not
      contain the server status. Therefore, the client has no way
      to find out whether there are more result sets of
      a multiple-result-set statement pending. Luckily, in 5.0 an
      error always aborts execution of a statement, wherever it is
      a multi-statement or a stored procedure, so it should be
      safe to unconditionally turn off the flag here.
    */
    mysql->server_status&= ~SERVER_MORE_RESULTS_EXISTS;
808

unknown's avatar
unknown committed
809
    DBUG_PRINT("error",("Got error: %d/%s (%s)",
unknown's avatar
unknown committed
810
                        net->last_errno,
811
                        net->sqlstate,
unknown's avatar
unknown committed
812
                        net->last_error));
unknown's avatar
SCRUM  
unknown committed
813 814 815 816 817
    return(packet_error);
  }
  return len;
}

unknown's avatar
unknown committed
818
void free_rows(MYSQL_DATA *cur)
unknown's avatar
SCRUM  
unknown committed
819 820 821 822
{
  if (cur)
  {
    free_root(&cur->alloc,MYF(0));
823
    my_free(cur);
unknown's avatar
SCRUM  
unknown committed
824 825 826
  }
}

unknown's avatar
unknown committed
827
my_bool
unknown's avatar
SCRUM  
unknown committed
828
cli_advanced_command(MYSQL *mysql, enum enum_server_command command,
829 830
		     const uchar *header, ulong header_length,
		     const uchar *arg, ulong arg_length, my_bool skip_check,
831
                     MYSQL_STMT *stmt)
unknown's avatar
SCRUM  
unknown committed
832 833 834
{
  NET *net= &mysql->net;
  my_bool result= 1;
835
  my_bool stmt_skip= stmt ? stmt->state != MYSQL_STMT_INIT_DONE : FALSE;
836
  DBUG_ENTER("cli_advanced_command");
unknown's avatar
SCRUM  
unknown committed
837 838 839

  if (mysql->net.vio == 0)
  {						/* Do reconnect if possible */
840
    if (mysql_reconnect(mysql) || stmt_skip)
841
      DBUG_RETURN(1);
unknown's avatar
SCRUM  
unknown committed
842
  }
843 844
  if (mysql->status != MYSQL_STATUS_READY ||
      mysql->server_status & SERVER_MORE_RESULTS_EXISTS)
unknown's avatar
SCRUM  
unknown committed
845
  {
unknown's avatar
unknown committed
846
    DBUG_PRINT("error",("state: %d", mysql->status));
847
    set_mysql_error(mysql, CR_COMMANDS_OUT_OF_SYNC, unknown_sqlstate);
848
    DBUG_RETURN(1);
unknown's avatar
SCRUM  
unknown committed
849 850
  }

851
  net_clear_error(net);
unknown's avatar
SCRUM  
unknown committed
852 853
  mysql->info=0;
  mysql->affected_rows= ~(my_ulonglong) 0;
854
  /*
855
    We don't want to clear the protocol buffer on COM_QUIT, because if
856 857 858
    the previous command was a shutdown command, we may have the
    response for the COM_QUIT already in the communication buffer
  */
859
  net_clear(&mysql->net, (command != COM_QUIT));
unknown's avatar
SCRUM  
unknown committed
860 861 862 863 864 865

  if (net_write_command(net,(uchar) command, header, header_length,
			arg, arg_length))
  {
    DBUG_PRINT("error",("Can't send command to server. Error: %d",
			socket_errno));
unknown's avatar
unknown committed
866
    if (net->last_errno == ER_NET_PACKET_TOO_LARGE)
unknown's avatar
SCRUM  
unknown committed
867
    {
868
      set_mysql_error(mysql, CR_NET_PACKET_TOO_LARGE, unknown_sqlstate);
unknown's avatar
SCRUM  
unknown committed
869 870 871
      goto end;
    }
    end_server(mysql);
872
    if (mysql_reconnect(mysql) || stmt_skip)
unknown's avatar
SCRUM  
unknown committed
873 874 875 876
      goto end;
    if (net_write_command(net,(uchar) command, header, header_length,
			  arg, arg_length))
    {
877
      set_mysql_error(mysql, CR_SERVER_GONE_ERROR, unknown_sqlstate);
unknown's avatar
SCRUM  
unknown committed
878 879 880 881 882
      goto end;
    }
  }
  result=0;
  if (!skip_check)
883
    result= ((mysql->packet_length=cli_safe_read(mysql)) == packet_error ?
unknown's avatar
SCRUM  
unknown committed
884
	     1 : 0);
unknown's avatar
unknown committed
885
end:
886 887
  DBUG_PRINT("exit",("result: %d", result));
  DBUG_RETURN(result);
unknown's avatar
SCRUM  
unknown committed
888 889
}

unknown's avatar
unknown committed
890
void free_old_query(MYSQL *mysql)
unknown's avatar
SCRUM  
unknown committed
891 892 893 894
{
  DBUG_ENTER("free_old_query");
  if (mysql->fields)
    free_root(&mysql->field_alloc,MYF(0));
895
  init_alloc_root(&mysql->field_alloc,8192,0); /* Assume rowlength < 8192 */
896 897
  mysql->fields= 0;
  mysql->field_count= 0;			/* For API */
898
  mysql->warning_count= 0;
899
  mysql->info= 0;
unknown's avatar
SCRUM  
unknown committed
900 901 902
  DBUG_VOID_RETURN;
}

903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988

/**
  Finish reading of a partial result set from the server.
  Get the EOF packet, and update mysql->status
  and mysql->warning_count.

  @return  TRUE if a communication or protocol error, an error
           is set in this case, FALSE otherwise.
*/

my_bool flush_one_result(MYSQL *mysql)
{
  ulong packet_length;

  DBUG_ASSERT(mysql->status != MYSQL_STATUS_READY);

  do
  {
    packet_length= cli_safe_read(mysql);
    /*
      There is an error reading from the connection,
      or (sic!) there were no error and no
      data in the stream, i.e. no more data from the server.
      Since we know our position in the stream (somewhere in
      the middle of a result set), this latter case is an error too
      -- each result set must end with a EOF packet.
      cli_safe_read() has set an error for us, just return.
    */
    if (packet_length == packet_error)
      return TRUE;
  }
  while (packet_length > 8 || mysql->net.read_pos[0] != 254);

  /* Analyze EOF packet of the result set. */

  if (protocol_41(mysql))
  {
    char *pos= (char*) mysql->net.read_pos + 1;
    mysql->warning_count=uint2korr(pos);
    pos+=2;
    mysql->server_status=uint2korr(pos);
    pos+=2;
  }
  return FALSE;
}


/**
  Read a packet from network. If it's an OK packet, flush it.

  @return  TRUE if error, FALSE otherwise. In case of 
           success, is_ok_packet is set to TRUE or FALSE,
           based on what we got from network.
*/

my_bool opt_flush_ok_packet(MYSQL *mysql, my_bool *is_ok_packet)
{
  ulong packet_length= cli_safe_read(mysql);

  if (packet_length == packet_error)
    return TRUE;

  /* cli_safe_read always reads a non-empty packet. */
  DBUG_ASSERT(packet_length);

  *is_ok_packet= mysql->net.read_pos[0] == 0;
  if (*is_ok_packet)
  {
    uchar *pos= mysql->net.read_pos + 1;

    net_field_length_ll(&pos); /* affected rows */
    net_field_length_ll(&pos); /* insert id */

    mysql->server_status=uint2korr(pos);
    pos+=2;

    if (protocol_41(mysql))
    {
      mysql->warning_count=uint2korr(pos);
      pos+=2;
    }
  }
  return FALSE;
}


989 990 991 992
/*
  Flush result set sent from server
*/

993
static void cli_flush_use_result(MYSQL *mysql, my_bool flush_all_results)
994 995
{
  /* Clear the current execution status */
996
  DBUG_ENTER("cli_flush_use_result");
997
  DBUG_PRINT("warning",("Not all packets read, clearing them"));
998 999 1000 1001 1002 1003 1004 1005

  if (flush_one_result(mysql))
    DBUG_VOID_RETURN;                           /* An error occurred */

  if (! flush_all_results)
    DBUG_VOID_RETURN;

  while (mysql->server_status & SERVER_MORE_RESULTS_EXISTS)
1006
  {
1007 1008 1009 1010
    my_bool is_ok_packet;
    if (opt_flush_ok_packet(mysql, &is_ok_packet))
      DBUG_VOID_RETURN;                         /* An error occurred. */
    if (is_ok_packet)
1011
    {
1012 1013 1014 1015 1016 1017
      /*
        Indeed what we got from network was an OK packet, and we
        know that OK is the last one in a multi-result-set, so
        just return.
      */
      DBUG_VOID_RETURN;
1018
    }
1019 1020 1021 1022 1023 1024 1025 1026
    /*
      It's a result set, not an OK packet. A result set contains
      of two result set subsequences: field metadata, terminated
      with EOF packet, and result set data, again terminated with
      EOF packet. Read and flush them.
    */
    if (flush_one_result(mysql) || flush_one_result(mysql))
      DBUG_VOID_RETURN;                         /* An error occurred. */
1027
  }
1028

1029
  DBUG_VOID_RETURN;
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
/*
  Report progress to the client

  RETURN VALUES
    0  ok
    1  error
*/

static int cli_report_progress(MYSQL *mysql, uchar *packet, uint length)
{
  uint stage, max_stage, proc_length;
  double progress;
  uchar *start= packet;

  if (length < 5)
    return 1;                         /* Wrong packet */

  if (!(mysql->options.extension && mysql->options.extension->report_progress))
    return 0;                         /* No callback, ignore packet */

  packet++;                           /* Ignore number of strings */
  stage= (uint) *packet++;
  max_stage= (uint) *packet++;
  progress= uint3korr(packet)/1000.0;
  packet+= 3;
  proc_length= net_field_length(&packet);
  if (packet + proc_length > start + length)
    return 1;                         /* Wrong packet */
  (*mysql->options.extension->report_progress)(mysql, stage, max_stage,
                                               progress, (char*) packet,
                                               proc_length);
  return 0;
}

unknown's avatar
SCRUM  
unknown committed
1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080
#ifdef __WIN__
static my_bool is_NT(void)
{
  char *os=getenv("OS");
  return (os && !strcmp(os, "Windows_NT")) ? 1 : 0;
}
#endif

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

void end_server(MYSQL *mysql)
{
unknown's avatar
unknown committed
1081
  int save_errno= errno;
unknown's avatar
SCRUM  
unknown committed
1082 1083 1084 1085
  DBUG_ENTER("end_server");
  if (mysql->net.vio != 0)
  {
    DBUG_PRINT("info",("Net: %s", vio_description(mysql->net.vio)));
1086 1087 1088
#ifdef MYSQL_SERVER
    slave_io_thread_detach_vio();
#endif
unknown's avatar
SCRUM  
unknown committed
1089 1090
    vio_delete(mysql->net.vio);
    mysql->net.vio= 0;          /* Marker */
1091
    mysql_prune_stmt_list(mysql);
unknown's avatar
SCRUM  
unknown committed
1092 1093 1094
  }
  net_end(&mysql->net);
  free_old_query(mysql);
unknown's avatar
unknown committed
1095
  errno= save_errno;
unknown's avatar
SCRUM  
unknown committed
1096 1097 1098
  DBUG_VOID_RETURN;
}

1099

unknown's avatar
SCRUM  
unknown committed
1100 1101 1102 1103
void STDCALL
mysql_free_result(MYSQL_RES *result)
{
  DBUG_ENTER("mysql_free_result");
unknown's avatar
unknown committed
1104
  DBUG_PRINT("enter",("mysql_res: 0x%lx", (long) result));
unknown's avatar
SCRUM  
unknown committed
1105 1106
  if (result)
  {
1107 1108
    MYSQL *mysql= result->handle;
    if (mysql)
unknown's avatar
SCRUM  
unknown committed
1109
    {
1110 1111 1112
      if (mysql->unbuffered_fetch_owner == &result->unbuffered_fetch_cancelled)
        mysql->unbuffered_fetch_owner= 0;
      if (mysql->status == MYSQL_STATUS_USE_RESULT)
unknown's avatar
SCRUM  
unknown committed
1113
      {
1114
        (*mysql->methods->flush_use_result)(mysql, FALSE);
1115
        mysql->status=MYSQL_STATUS_READY;
1116 1117
        if (mysql->unbuffered_fetch_owner)
          *mysql->unbuffered_fetch_owner= TRUE;
unknown's avatar
SCRUM  
unknown committed
1118 1119 1120 1121 1122
      }
    }
    free_rows(result->data);
    if (result->fields)
      free_root(&result->field_alloc,MYF(0));
1123 1124
    my_free(result->row);
    my_free(result);
unknown's avatar
SCRUM  
unknown committed
1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139
  }
  DBUG_VOID_RETURN;
}

/****************************************************************************
  Get options from my.cnf
****************************************************************************/

static const char *default_options[]=
{
  "port","socket","compress","password","pipe", "timeout", "user",
  "init-command", "host", "database", "debug", "return-found-rows",
  "ssl-key" ,"ssl-cert" ,"ssl-ca" ,"ssl-capath",
  "character-sets-dir", "default-character-set", "interactive-timeout",
  "connect-timeout", "local-infile", "disable-local-infile",
unknown's avatar
unknown committed
1140
  "ssl-cipher", "max-allowed-packet", "protocol", "shared-memory-base-name",
unknown's avatar
unknown committed
1141
  "multi-results", "multi-statements", "multi-queries", "secure-auth",
1142
  "report-data-truncation", "plugin-dir", "default-auth",
1143
  "enable-cleartext-plugin",
unknown's avatar
SCRUM  
unknown committed
1144 1145
  NullS
};
1146 1147 1148 1149 1150 1151 1152 1153 1154
enum option_id {
  OPT_port=1, OPT_socket, OPT_compress, OPT_password, OPT_pipe, OPT_timeout, OPT_user, 
  OPT_init_command, OPT_host, OPT_database, OPT_debug, OPT_return_found_rows, 
  OPT_ssl_key, OPT_ssl_cert, OPT_ssl_ca, OPT_ssl_capath, 
  OPT_character_sets_dir, OPT_default_character_set, OPT_interactive_timeout, 
  OPT_connect_timeout, OPT_local_infile, OPT_disable_local_infile, 
  OPT_ssl_cipher, OPT_max_allowed_packet, OPT_protocol, OPT_shared_memory_base_name, 
  OPT_multi_results, OPT_multi_statements, OPT_multi_queries, OPT_secure_auth, 
  OPT_report_data_truncation, OPT_plugin_dir, OPT_default_auth, 
1155
  OPT_enable_cleartext_plugin,
Guilhem Bichot's avatar
Guilhem Bichot committed
1156
  OPT_keep_this_one_last
1157
};
unknown's avatar
SCRUM  
unknown committed
1158 1159

static TYPELIB option_types={array_elements(default_options)-1,
unknown's avatar
unknown committed
1160
			     "options",default_options, NULL};
unknown's avatar
SCRUM  
unknown committed
1161

1162 1163 1164
const char *sql_protocol_names_lib[] =
{ "TCP", "SOCKET", "PIPE", "MEMORY", NullS };
TYPELIB sql_protocol_typelib = {array_elements(sql_protocol_names_lib)-1,"",
unknown's avatar
unknown committed
1165
				sql_protocol_names_lib, NULL};
1166

unknown's avatar
SCRUM  
unknown committed
1167 1168 1169 1170 1171 1172 1173 1174
static int add_init_command(struct st_mysql_options *options, const char *cmd)
{
  char *tmp;

  if (!options->init_commands)
  {
    options->init_commands= (DYNAMIC_ARRAY*)my_malloc(sizeof(DYNAMIC_ARRAY),
						      MYF(MY_WME));
Sergei Golubchik's avatar
Sergei Golubchik committed
1175
    init_dynamic_array(options->init_commands,sizeof(char*),5,5);
unknown's avatar
SCRUM  
unknown committed
1176 1177 1178
  }

  if (!(tmp= my_strdup(cmd,MYF(MY_WME))) ||
1179
      insert_dynamic(options->init_commands, (uchar*)&tmp))
unknown's avatar
SCRUM  
unknown committed
1180
  {
1181
    my_free(tmp);
unknown's avatar
SCRUM  
unknown committed
1182 1183 1184 1185 1186 1187
    return 1;
  }

  return 0;
}

Sergei Golubchik's avatar
Sergei Golubchik committed
1188
#define EXTENSION_SET(OPTS, X, VAL)                              \
1189
    if (!(OPTS)->extension)                                      \
1190 1191 1192
      (OPTS)->extension= (struct st_mysql_options_extention *)   \
        my_malloc(sizeof(struct st_mysql_options_extention),     \
                  MYF(MY_WME | MY_ZEROFILL));                    \
1193 1194
    (OPTS)->extension->X= VAL;

Sergei Golubchik's avatar
Sergei Golubchik committed
1195
#define EXTENSION_SET_STRING(OPTS, X, STR)                       \
1196
    if ((OPTS)->extension)                                       \
Sergei Golubchik's avatar
Sergei Golubchik committed
1197 1198
      my_free((OPTS)->extension->X);                             \
    EXTENSION_SET(OPTS, X, my_strdup((STR), MYF(MY_WME)));
1199

1200 1201 1202 1203 1204 1205
#if defined(HAVE_OPENSSL) && !defined(EMBEDDED_LIBRARY)
static char *set_ssl_option_unpack_path(const char *arg)
{
  char *opt_var= NULL;
  if (arg)
  {
1206
    char buff[FN_REFLEN + 1];
1207 1208 1209 1210 1211 1212 1213
    unpack_filename(buff, (char *)arg);
    opt_var= my_strdup(buff, MYF(MY_WME));
  }
  return opt_var;
}
#endif /* HAVE_OPENSSL && !EMBEDDED_LIBRARY */

unknown's avatar
SCRUM  
unknown committed
1214 1215
void mysql_read_default_options(struct st_mysql_options *options,
				const char *filename,const char *group)
unknown's avatar
SCRUM  
unknown committed
1216 1217 1218
{
  int argc;
  char *argv_buff[1],**argv;
1219
  const char *groups[5];
unknown's avatar
SCRUM  
unknown committed
1220 1221 1222
  DBUG_ENTER("mysql_read_default_options");
  DBUG_PRINT("enter",("file: %s  group: %s",filename,group ? group :"NULL"));

Guilhem Bichot's avatar
Guilhem Bichot committed
1223 1224 1225
  compile_time_assert(OPT_keep_this_one_last ==
                      array_elements(default_options));

unknown's avatar
SCRUM  
unknown committed
1226
  argc=1; argv=argv_buff; argv_buff[0]= (char*) "client";
1227 1228 1229 1230 1231
  groups[0]= (char*) "client";
  groups[1]= (char*) "client-server";
  groups[2]= (char*) "client-mariadb";
  groups[3]= (char*) group;
  groups[4]=0;
unknown's avatar
SCRUM  
unknown committed
1232

1233
  my_load_defaults(filename, groups, &argc, &argv, NULL);
unknown's avatar
SCRUM  
unknown committed
1234 1235 1236 1237 1238
  if (argc != 1)				/* If some default option */
  {
    char **option=argv;
    while (*++option)
    {
1239
      if (my_getopt_is_args_separator(option[0]))          /* skip arguments separator */
1240
        continue;
unknown's avatar
SCRUM  
unknown committed
1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253
      /* DBUG_PRINT("info",("option: %s",option[0])); */
      if (option[0][0] == '-' && option[0][1] == '-')
      {
	char *end=strcend(*option,'=');
	char *opt_arg=0;
	if (*end)
	{
	  opt_arg=end+1;
	  *end=0;				/* Remove '=' */
	}
	/* Change all '_' in variable name to '-' */
	for (end= *option ; *(end= strcend(end,'_')) ; )
	  *end= '-';
Guilhem Bichot's avatar
Guilhem Bichot committed
1254
	switch (find_type(*option + 2, &option_types, FIND_TYPE_BASIC)) {
1255
	case OPT_port:
unknown's avatar
SCRUM  
unknown committed
1256 1257 1258
	  if (opt_arg)
	    options->port=atoi(opt_arg);
	  break;
1259
	case OPT_socket:
unknown's avatar
SCRUM  
unknown committed
1260 1261
	  if (opt_arg)
	  {
1262
	    my_free(options->unix_socket);
unknown's avatar
SCRUM  
unknown committed
1263 1264 1265
	    options->unix_socket=my_strdup(opt_arg,MYF(MY_WME));
	  }
	  break;
1266
	case OPT_compress:
unknown's avatar
SCRUM  
unknown committed
1267 1268 1269
	  options->compress=1;
	  options->client_flag|= CLIENT_COMPRESS;
	  break;
1270
        case OPT_password:
unknown's avatar
SCRUM  
unknown committed
1271 1272
	  if (opt_arg)
	  {
1273
	    my_free(options->password);
unknown's avatar
SCRUM  
unknown committed
1274 1275 1276
	    options->password=my_strdup(opt_arg,MYF(MY_WME));
	  }
	  break;
1277
        case OPT_pipe:
unknown's avatar
SCRUM  
unknown committed
1278
          options->protocol = MYSQL_PROTOCOL_PIPE;
1279
          break;
1280 1281
        case OPT_connect_timeout: 
	case OPT_timeout:
unknown's avatar
SCRUM  
unknown committed
1282 1283 1284
	  if (opt_arg)
	    options->connect_timeout=atoi(opt_arg);
	  break;
1285
	case OPT_user:
unknown's avatar
SCRUM  
unknown committed
1286 1287
	  if (opt_arg)
	  {
1288
	    my_free(options->user);
unknown's avatar
SCRUM  
unknown committed
1289 1290 1291
	    options->user=my_strdup(opt_arg,MYF(MY_WME));
	  }
	  break;
1292
	case OPT_init_command:
unknown's avatar
SCRUM  
unknown committed
1293 1294
	  add_init_command(options,opt_arg);
	  break;
1295
	case OPT_host:
unknown's avatar
SCRUM  
unknown committed
1296 1297
	  if (opt_arg)
	  {
1298
	    my_free(options->host);
unknown's avatar
SCRUM  
unknown committed
1299 1300 1301
	    options->host=my_strdup(opt_arg,MYF(MY_WME));
	  }
	  break;
1302
        case OPT_database:
unknown's avatar
SCRUM  
unknown committed
1303 1304
	  if (opt_arg)
	  {
1305
	    my_free(options->db);
unknown's avatar
SCRUM  
unknown committed
1306 1307 1308
	    options->db=my_strdup(opt_arg,MYF(MY_WME));
	  }
	  break;
1309
	case OPT_debug:
1310
#ifdef MYSQL_CLIENT
unknown's avatar
SCRUM  
unknown committed
1311 1312
	  mysql_debug(opt_arg ? opt_arg : "d:t:o,/tmp/client.trace");
	  break;
unknown's avatar
unknown committed
1313
#endif
1314
	case OPT_return_found_rows:
unknown's avatar
SCRUM  
unknown committed
1315 1316
	  options->client_flag|=CLIENT_FOUND_ROWS;
	  break;
Konstantin Osipov's avatar
Konstantin Osipov committed
1317
#if defined(HAVE_OPENSSL) && !defined(EMBEDDED_LIBRARY)
1318
	case OPT_ssl_key:
1319
	  my_free(options->ssl_key);
unknown's avatar
SCRUM  
unknown committed
1320 1321
          options->ssl_key = my_strdup(opt_arg, MYF(MY_WME));
          break;
1322
	case OPT_ssl_cert:
1323
	  my_free(options->ssl_cert);
unknown's avatar
SCRUM  
unknown committed
1324 1325
          options->ssl_cert = my_strdup(opt_arg, MYF(MY_WME));
          break;
1326
	case OPT_ssl_ca:
1327
	  my_free(options->ssl_ca);
unknown's avatar
SCRUM  
unknown committed
1328 1329
          options->ssl_ca = my_strdup(opt_arg, MYF(MY_WME));
          break;
1330
	case OPT_ssl_capath:
1331
	  my_free(options->ssl_capath);
unknown's avatar
SCRUM  
unknown committed
1332 1333
          options->ssl_capath = my_strdup(opt_arg, MYF(MY_WME));
          break;
1334
        case OPT_ssl_cipher:
1335
          my_free(options->ssl_cipher);
1336 1337
          options->ssl_cipher= my_strdup(opt_arg, MYF(MY_WME));
          break;
unknown's avatar
SCRUM  
unknown committed
1338
#else
1339 1340 1341 1342 1343
	case OPT_ssl_key:
	case OPT_ssl_cert:
	case OPT_ssl_ca:
	case OPT_ssl_capath:
        case OPT_ssl_cipher:
unknown's avatar
SCRUM  
unknown committed
1344
	  break;
Konstantin Osipov's avatar
Konstantin Osipov committed
1345
#endif /* HAVE_OPENSSL && !EMBEDDED_LIBRARY */
1346
	case OPT_character_sets_dir:
1347
	  my_free(options->charset_dir);
unknown's avatar
SCRUM  
unknown committed
1348 1349
          options->charset_dir = my_strdup(opt_arg, MYF(MY_WME));
	  break;
1350
	case OPT_default_character_set:
1351
	  my_free(options->charset_name);
unknown's avatar
SCRUM  
unknown committed
1352 1353
          options->charset_name = my_strdup(opt_arg, MYF(MY_WME));
	  break;
1354
        case OPT_interactive_timeout:
unknown's avatar
SCRUM  
unknown committed
1355 1356
	  options->client_flag|= CLIENT_INTERACTIVE;
	  break;
1357
        case OPT_local_infile:
unknown's avatar
SCRUM  
unknown committed
1358 1359 1360 1361 1362
	  if (!opt_arg || atoi(opt_arg) != 0)
	    options->client_flag|= CLIENT_LOCAL_FILES;
	  else
	    options->client_flag&= ~CLIENT_LOCAL_FILES;
	  break;
1363
        case OPT_disable_local_infile:
unknown's avatar
unknown committed
1364
	  options->client_flag&= ~CLIENT_LOCAL_FILES;
unknown's avatar
SCRUM  
unknown committed
1365
          break;
1366
	case OPT_max_allowed_packet:
unknown's avatar
unknown committed
1367 1368
          if (opt_arg)
	    options->max_allowed_packet= atoi(opt_arg);
unknown's avatar
SCRUM  
unknown committed
1369
	  break;
1370
        case OPT_protocol:
Guilhem Bichot's avatar
Guilhem Bichot committed
1371 1372
          if ((options->protocol= find_type(opt_arg, &sql_protocol_typelib,
                                            FIND_TYPE_BASIC)) <= 0)
unknown's avatar
SCRUM  
unknown committed
1373 1374 1375 1376 1377
          {
            fprintf(stderr, "Unknown option to protocol: %s\n", opt_arg);
            exit(1);
          }
          break;
1378
        case OPT_shared_memory_base_name:
unknown's avatar
SCRUM  
unknown committed
1379 1380
#ifdef HAVE_SMEM
          if (options->shared_memory_base_name != def_shared_memory_base_name)
1381
            my_free(options->shared_memory_base_name);
unknown's avatar
SCRUM  
unknown committed
1382 1383 1384
          options->shared_memory_base_name=my_strdup(opt_arg,MYF(MY_WME));
#endif
          break;
1385
        case OPT_multi_results:
unknown's avatar
unknown committed
1386 1387
	  options->client_flag|= CLIENT_MULTI_RESULTS;
	  break;
1388 1389
        case OPT_multi_statements:
        case OPT_multi_queries:
1390
	  options->client_flag|= CLIENT_MULTI_STATEMENTS | CLIENT_MULTI_RESULTS;
unknown's avatar
unknown committed
1391
	  break;
1392
        case OPT_secure_auth:
unknown's avatar
unknown committed
1393 1394
          options->secure_auth= TRUE;
          break;
1395
        case OPT_report_data_truncation:
1396 1397
          options->report_data_truncation= opt_arg ? test(atoi(opt_arg)) : 1;
          break;
1398
        case OPT_plugin_dir:
1399 1400 1401 1402 1403 1404 1405 1406 1407 1408
          {
            char buff[FN_REFLEN], buff2[FN_REFLEN];
            if (strlen(opt_arg) >= FN_REFLEN)
              opt_arg[FN_REFLEN]= '\0';
            if (my_realpath(buff, opt_arg, 0))
            {
              DBUG_PRINT("warning",("failed to normalize the plugin path: %s",
                                    opt_arg));
              break;
            }
1409
            convert_dirname(buff2, buff, NULL);
1410 1411
            EXTENSION_SET_STRING(options, plugin_dir, buff2);
          }
1412 1413
          break;
        case OPT_default_auth:
1414
          EXTENSION_SET_STRING(options, default_auth, opt_arg);
1415
          break;
1416 1417
        case OPT_enable_cleartext_plugin:
          break;
unknown's avatar
SCRUM  
unknown committed
1418 1419 1420 1421 1422 1423 1424 1425 1426 1427
	default:
	  DBUG_PRINT("warning",("unknown option: %s",option[0]));
	}
      }
    }
  }
  free_defaults(argv);
  DBUG_VOID_RETURN;
}

1428

unknown's avatar
SCRUM  
unknown committed
1429 1430 1431 1432 1433 1434
/**************************************************************************
  Get column lengths of the current row
  If one uses mysql_use_result, res->lengths contains the length information,
  else the lengths are calculated from the offset between pointers.
**************************************************************************/

unknown's avatar
unknown committed
1435
static void cli_fetch_lengths(ulong *to, MYSQL_ROW column,
unknown's avatar
unknown committed
1436
			      unsigned int field_count)
unknown's avatar
SCRUM  
unknown committed
1437
{ 
1438
  ulong *prev_length;
1439
  char *start=0;
unknown's avatar
SCRUM  
unknown committed
1440
  MYSQL_ROW end;
1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454

  prev_length=0;				/* Keep gcc happy */
  for (end=column + field_count + 1 ; column != end ; column++, to++)
  {
    if (!*column)
    {
      *to= 0;					/* Null */
      continue;
    }
    if (start)					/* Found end of prev string */
      *prev_length= (ulong) (*column-start-1);
    start= *column;
    prev_length= to;
  }
unknown's avatar
SCRUM  
unknown committed
1455 1456 1457 1458 1459 1460
}

/***************************************************************************
  Change field rows to field structs
***************************************************************************/

unknown's avatar
unknown committed
1461
MYSQL_FIELD *
1462
unpack_fields(MYSQL *mysql, MYSQL_DATA *data,MEM_ROOT *alloc,uint fields,
unknown's avatar
SCRUM  
unknown committed
1463 1464 1465 1466
	      my_bool default_value, uint server_capabilities)
{
  MYSQL_ROWS	*row;
  MYSQL_FIELD	*field,*result;
unknown's avatar
unknown committed
1467
  ulong lengths[9];				/* Max of fields */
unknown's avatar
SCRUM  
unknown committed
1468 1469
  DBUG_ENTER("unpack_fields");

1470 1471
  field= result= (MYSQL_FIELD*) alloc_root(alloc,
					   (uint) sizeof(*field)*fields);
unknown's avatar
SCRUM  
unknown committed
1472 1473 1474
  if (!result)
  {
    free_rows(data);				/* Free old data */
1475
    set_mysql_error(mysql, CR_OUT_OF_MEMORY, unknown_sqlstate);
unknown's avatar
SCRUM  
unknown committed
1476 1477 1478 1479 1480 1481 1482 1483 1484
    DBUG_RETURN(0);
  }
  bzero((char*) field, (uint) sizeof(MYSQL_FIELD)*fields);
  if (server_capabilities & CLIENT_PROTOCOL_41)
  {
    /* server is 4.1, and returns the new field result format */
    for (row=data->data; row ; row = row->next,field++)
    {
      uchar *pos;
1485
      /* fields count may be wrong */
1486
      DBUG_ASSERT((uint) (field - result) < fields);
1487
      cli_fetch_lengths(&lengths[0], row->data, default_value ? 8 : 7);
1488 1489 1490 1491 1492 1493
      field->catalog=   strmake_root(alloc,(char*) row->data[0], lengths[0]);
      field->db=        strmake_root(alloc,(char*) row->data[1], lengths[1]);
      field->table=     strmake_root(alloc,(char*) row->data[2], lengths[2]);
      field->org_table= strmake_root(alloc,(char*) row->data[3], lengths[3]);
      field->name=      strmake_root(alloc,(char*) row->data[4], lengths[4]);
      field->org_name=  strmake_root(alloc,(char*) row->data[5], lengths[5]);
unknown's avatar
unknown committed
1494 1495 1496 1497 1498 1499 1500

      field->catalog_length=	lengths[0];
      field->db_length=		lengths[1];
      field->table_length=	lengths[2];
      field->org_table_length=	lengths[3];
      field->name_length=	lengths[4];
      field->org_name_length=	lengths[5];
unknown's avatar
SCRUM  
unknown committed
1501 1502

      /* Unpack fixed length parts */
1503 1504 1505 1506 1507 1508 1509 1510
      if (lengths[6] != 12)
      {
        /* malformed packet. signal an error. */
        free_rows(data);			/* Free old data */
        set_mysql_error(mysql, CR_MALFORMED_PACKET, unknown_sqlstate);
        DBUG_RETURN(0);
      }

unknown's avatar
unknown committed
1511
      pos= (uchar*) row->data[6];
unknown's avatar
SCRUM  
unknown committed
1512
      field->charsetnr= uint2korr(pos);
unknown's avatar
unknown committed
1513 1514 1515 1516
      field->length=	(uint) uint4korr(pos+2);
      field->type=	(enum enum_field_types) pos[6];
      field->flags=	uint2korr(pos+7);
      field->decimals=  (uint) pos[9];
unknown's avatar
SCRUM  
unknown committed
1517

1518
      if (IS_NUM(field->type))
unknown's avatar
SCRUM  
unknown committed
1519
        field->flags|= NUM_FLAG;
unknown's avatar
unknown committed
1520
      if (default_value && row->data[7])
unknown's avatar
SCRUM  
unknown committed
1521
      {
1522
        field->def=strmake_root(alloc,(char*) row->data[7], lengths[7]);
unknown's avatar
unknown committed
1523
	field->def_length= lengths[7];
unknown's avatar
SCRUM  
unknown committed
1524 1525 1526 1527 1528 1529 1530 1531
      }
      else
        field->def=0;
      field->max_length= 0;
    }
  }
#ifndef DELETE_SUPPORT_OF_4_0_PROTOCOL
  else
1532 1533 1534 1535
  {
    /* old protocol, for backward compatibility */
    for (row=data->data; row ; row = row->next,field++)
    {
1536
      cli_fetch_lengths(&lengths[0], row->data, default_value ? 6 : 5);
1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558
      field->org_table= 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];

      field->catalog=(char*)  "";
      field->db=     (char*)  "";
      field->catalog_length= 0;
      field->db_length= 0;
      field->org_table_length=	field->table_length=	lengths[0];
      field->name_length=	lengths[1];

      if (server_capabilities & CLIENT_LONG_FLAG)
      {
        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];
      }
1559
      if (IS_NUM(field->type))
1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570
        field->flags|= NUM_FLAG;
      if (default_value && row->data[5])
      {
        field->def=strdup_root(alloc,(char*) row->data[5]);
	field->def_length= lengths[5];
      }
      else
        field->def=0;
      field->max_length= 0;
    }
  }
unknown's avatar
SCRUM  
unknown committed
1571 1572 1573 1574 1575 1576 1577
#endif /* DELETE_SUPPORT_OF_4_0_PROTOCOL */
  free_rows(data);				/* Free old data */
  DBUG_RETURN(result);
}

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

unknown's avatar
unknown committed
1578 1579
MYSQL_DATA *cli_read_rows(MYSQL *mysql,MYSQL_FIELD *mysql_fields,
			  unsigned int fields)
unknown's avatar
SCRUM  
unknown committed
1580 1581 1582 1583 1584 1585 1586 1587 1588
{
  uint	field;
  ulong pkt_len;
  ulong len;
  uchar *cp;
  char	*to, *end_to;
  MYSQL_DATA *result;
  MYSQL_ROWS **prev_ptr,*cur;
  NET *net = &mysql->net;
unknown's avatar
SCRUM  
unknown committed
1589
  DBUG_ENTER("cli_read_rows");
unknown's avatar
SCRUM  
unknown committed
1590

1591
  if ((pkt_len= cli_safe_read(mysql)) == packet_error)
unknown's avatar
SCRUM  
unknown committed
1592 1593 1594 1595
    DBUG_RETURN(0);
  if (!(result=(MYSQL_DATA*) my_malloc(sizeof(MYSQL_DATA),
				       MYF(MY_WME | MY_ZEROFILL))))
  {
1596
    set_mysql_error(mysql, CR_OUT_OF_MEMORY, unknown_sqlstate);
unknown's avatar
SCRUM  
unknown committed
1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622
    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;

  /*
    The last EOF packet is either a single 254 character or (in MySQL 4.1)
    254 followed by 1-7 status bytes.

    This doesn't conflict with normal usage of 254 which stands for a
    string where the length of the string is 8 bytes. (see net_field_length())
  */

  while (*(cp=net->read_pos) != 254 || pkt_len >= 8)
  {
    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))))
    {
      free_rows(result);
1623
      set_mysql_error(mysql, CR_OUT_OF_MEMORY, unknown_sqlstate);
unknown's avatar
SCRUM  
unknown committed
1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638
      DBUG_RETURN(0);
    }
    *prev_ptr=cur;
    prev_ptr= &cur->next;
    to= (char*) (cur->data+fields+1);
    end_to=to+pkt_len-1;
    for (field=0 ; field < fields ; field++)
    {
      if ((len=(ulong) net_field_length(&cp)) == NULL_LENGTH)
      {						/* null field */
	cur->data[field] = 0;
      }
      else
      {
	cur->data[field] = to;
1639
        if (unlikely(len > (ulong)(end_to-to) || to > end_to))
unknown's avatar
SCRUM  
unknown committed
1640 1641
        {
          free_rows(result);
1642
          set_mysql_error(mysql, CR_MALFORMED_PACKET, unknown_sqlstate);
unknown's avatar
SCRUM  
unknown committed
1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655
          DBUG_RETURN(0);
        }
	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 */
1656
    if ((pkt_len=cli_safe_read(mysql)) == packet_error)
unknown's avatar
SCRUM  
unknown committed
1657 1658 1659 1660 1661 1662 1663 1664 1665
    {
      free_rows(result);
      DBUG_RETURN(0);
    }
  }
  *prev_ptr=0;					/* last pointer is null */
  if (pkt_len > 1)				/* MySQL 4.1 protocol */
  {
    mysql->warning_count= uint2korr(cp+1);
1666
    mysql->server_status= uint2korr(cp+3);
1667 1668
    DBUG_PRINT("info",("status: %u  warning_count:  %u",
		       mysql->server_status, mysql->warning_count));
unknown's avatar
SCRUM  
unknown committed
1669
  }
unknown's avatar
unknown committed
1670
  DBUG_PRINT("exit", ("Got %lu rows", (ulong) result->rows));
unknown's avatar
SCRUM  
unknown committed
1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684
  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
read_one_row(MYSQL *mysql,uint fields,MYSQL_ROW row, ulong *lengths)
{
  uint field;
  ulong pkt_len,len;
unknown's avatar
unknown committed
1685 1686
  uchar *pos, *prev_pos, *end_pos;
  NET *net= &mysql->net;
unknown's avatar
SCRUM  
unknown committed
1687

1688
  if ((pkt_len=cli_safe_read(mysql)) == packet_error)
unknown's avatar
SCRUM  
unknown committed
1689
    return -1;
unknown's avatar
unknown committed
1690
  if (pkt_len <= 8 && net->read_pos[0] == 254)
unknown's avatar
SCRUM  
unknown committed
1691 1692
  {
    if (pkt_len > 1)				/* MySQL 4.1 protocol */
1693
    {
unknown's avatar
unknown committed
1694
      mysql->warning_count= uint2korr(net->read_pos+1);
1695 1696
      mysql->server_status= uint2korr(net->read_pos+3);
    }
unknown's avatar
SCRUM  
unknown committed
1697 1698 1699
    return 1;				/* End of data */
  }
  prev_pos= 0;				/* allowed to write at packet[-1] */
unknown's avatar
unknown committed
1700
  pos=net->read_pos;
unknown's avatar
SCRUM  
unknown committed
1701 1702 1703 1704 1705 1706 1707 1708 1709 1710
  end_pos=pos+pkt_len;
  for (field=0 ; field < fields ; field++)
  {
    if ((len=(ulong) net_field_length(&pos)) == NULL_LENGTH)
    {						/* null field */
      row[field] = 0;
      *lengths++=0;
    }
    else
    {
1711
      if (unlikely(len > (ulong)(end_pos - pos) || pos > end_pos))
unknown's avatar
SCRUM  
unknown committed
1712
      {
1713
        set_mysql_error(mysql, CR_UNKNOWN_ERROR, unknown_sqlstate);
unknown's avatar
SCRUM  
unknown committed
1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736
        return -1;
      }
      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;
}


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

MYSQL * STDCALL
mysql_init(MYSQL *mysql)
{
1737 1738
  if (mysql_server_init(0, NULL, NULL))
    return 0;
unknown's avatar
SCRUM  
unknown committed
1739 1740 1741
  if (!mysql)
  {
    if (!(mysql=(MYSQL*) my_malloc(sizeof(*mysql),MYF(MY_WME | MY_ZEROFILL))))
1742 1743
    {
      set_mysql_error(NULL, CR_OUT_OF_MEMORY, unknown_sqlstate);
unknown's avatar
SCRUM  
unknown committed
1744
      return 0;
1745
    }
unknown's avatar
SCRUM  
unknown committed
1746 1747 1748
    mysql->free_me=1;
  }
  else
1749
    bzero((char*) (mysql), sizeof(*(mysql)));
1750
  mysql->options.connect_timeout= CONNECT_TIMEOUT;
1751
  mysql->charset=default_client_charset_info;
unknown's avatar
unknown committed
1752
  strmov(mysql->net.sqlstate, not_error_sqlstate);
unknown's avatar
SCRUM  
unknown committed
1753

1754 1755 1756 1757
  /*
    Only enable LOAD DATA INFILE by default if configured with
    --enable-local-infile
  */
1758

1759
#if defined(ENABLED_LOCAL_INFILE) && !defined(MYSQL_SERVER)
unknown's avatar
SCRUM  
unknown committed
1760 1761
  mysql->options.client_flag|= CLIENT_LOCAL_FILES;
#endif
1762

unknown's avatar
SCRUM  
unknown committed
1763
#ifdef HAVE_SMEM
1764
  mysql->options.shared_memory_base_name= (char*) def_shared_memory_base_name;
unknown's avatar
SCRUM  
unknown committed
1765
#endif
1766

unknown's avatar
SCRUM  
unknown committed
1767
  mysql->options.methods_to_use= MYSQL_OPT_GUESS_CONNECTION;
1768
  mysql->options.report_data_truncation= TRUE;  /* default */
1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786

  /*
    By default we don't reconnect because it could silently corrupt data (after
    reconnection you potentially lose table locks, user variables, session
    variables (transactions but they are specifically dealt with in
    mysql_reconnect()).
    This is a change: < 5.0.3 mysql->reconnect was set to 1 by default.
    How this change impacts existing apps:
    - existing apps which relyed on the default will see a behaviour change;
    they will have to set reconnect=1 after mysql_real_connect().
    - existing apps which explicitely asked for reconnection (the only way they
    could do it was by setting mysql.reconnect to 1 after mysql_real_connect())
    will not see a behaviour change.
    - existing apps which explicitely asked for no reconnection
    (mysql.reconnect=0) will not see a behaviour change.
  */
  mysql->reconnect= 0;

1787
  DBUG_PRINT("mysql",("mysql: 0x%lx", (long) mysql));
unknown's avatar
SCRUM  
unknown committed
1788 1789 1790 1791 1792
  return mysql;
}


/*
1793 1794
  Fill in SSL part of MYSQL structure and set 'use_ssl' flag.
  NB! Errors are not reported until you do mysql_real_connect.
unknown's avatar
SCRUM  
unknown committed
1795 1796
*/

1797 1798 1799 1800 1801 1802 1803 1804 1805
#define strdup_if_not_null(A) (A) == 0 ? 0 : my_strdup((A),MYF(MY_WME))

my_bool STDCALL
mysql_ssl_set(MYSQL *mysql __attribute__((unused)) ,
	      const char *key __attribute__((unused)),
	      const char *cert __attribute__((unused)),
	      const char *ca __attribute__((unused)),
	      const char *capath __attribute__((unused)),
	      const char *cipher __attribute__((unused)))
unknown's avatar
SCRUM  
unknown committed
1806
{
1807
  DBUG_ENTER("mysql_ssl_set");
unknown's avatar
unknown committed
1808
#if defined(HAVE_OPENSSL) && !defined(EMBEDDED_LIBRARY)
1809 1810 1811 1812 1813
  my_free(mysql->options.ssl_key);
  my_free(mysql->options.ssl_cert);
  my_free(mysql->options.ssl_ca);
  my_free(mysql->options.ssl_capath);
  my_free(mysql->options.ssl_cipher);
1814 1815 1816 1817
  mysql->options.ssl_key=    set_ssl_option_unpack_path(key);
  mysql->options.ssl_cert=   set_ssl_option_unpack_path(cert);
  mysql->options.ssl_ca=     set_ssl_option_unpack_path(ca);
  mysql->options.ssl_capath= set_ssl_option_unpack_path(capath);
1818
  mysql->options.ssl_cipher= strdup_if_not_null(cipher);
Konstantin Osipov's avatar
Konstantin Osipov committed
1819
#endif /* HAVE_OPENSSL && !EMBEDDED_LIBRARY */
1820
  mysql->options.use_ssl= TRUE;
1821
  DBUG_RETURN(0);
1822
}
unknown's avatar
SCRUM  
unknown committed
1823 1824


1825 1826 1827 1828 1829
/*
  Free strings in the SSL structure and clear 'use_ssl' flag.
  NB! Errors are not reported until you do mysql_real_connect.
*/

Konstantin Osipov's avatar
Konstantin Osipov committed
1830
#if defined(HAVE_OPENSSL) && !defined(EMBEDDED_LIBRARY)
unknown's avatar
unknown committed
1831

1832 1833 1834
static void
mysql_ssl_free(MYSQL *mysql __attribute__((unused)))
{
unknown's avatar
unknown committed
1835
  struct st_VioSSLFd *ssl_fd= (struct st_VioSSLFd*) mysql->connector_fd;
1836
  DBUG_ENTER("mysql_ssl_free");
1837

1838 1839 1840 1841 1842
  my_free(mysql->options.ssl_key);
  my_free(mysql->options.ssl_cert);
  my_free(mysql->options.ssl_ca);
  my_free(mysql->options.ssl_capath);
  my_free(mysql->options.ssl_cipher);
unknown's avatar
unknown committed
1843 1844
  if (ssl_fd)
    SSL_CTX_free(ssl_fd->ssl_context);
1845
  my_free(mysql->connector_fd);
1846 1847 1848 1849 1850 1851 1852
  mysql->options.ssl_key = 0;
  mysql->options.ssl_cert = 0;
  mysql->options.ssl_ca = 0;
  mysql->options.ssl_capath = 0;
  mysql->options.ssl_cipher= 0;
  mysql->options.use_ssl = FALSE;
  mysql->connector_fd = 0;
1853
  DBUG_VOID_RETURN;
unknown's avatar
SCRUM  
unknown committed
1854
}
1855

Konstantin Osipov's avatar
Konstantin Osipov committed
1856
#endif /* HAVE_OPENSSL && !EMBEDDED_LIBRARY */
1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868

/*
  Return the SSL cipher (if any) used for current
  connection to the server.

  SYNOPSYS
    mysql_get_ssl_cipher()
      mysql pointer to the mysql connection

*/

const char * STDCALL
1869
mysql_get_ssl_cipher(MYSQL *mysql __attribute__((unused)))
1870 1871
{
  DBUG_ENTER("mysql_get_ssl_cipher");
Konstantin Osipov's avatar
Konstantin Osipov committed
1872
#if defined(HAVE_OPENSSL) && !defined(EMBEDDED_LIBRARY)
1873
  if (mysql->net.vio && mysql->net.vio->ssl_arg)
1874
    DBUG_RETURN(SSL_get_cipher_name((SSL*)mysql->net.vio->ssl_arg));
Konstantin Osipov's avatar
Konstantin Osipov committed
1875
#endif /* HAVE_OPENSSL && !EMBEDDED_LIBRARY */
1876 1877 1878
  DBUG_RETURN(NULL);
}

1879

1880 1881 1882 1883 1884 1885 1886 1887
/*
  Check the server's (subject) Common Name against the
  hostname we connected to

  SYNOPSIS
  ssl_verify_server_cert()
    vio              pointer to a SSL connected vio
    server_hostname  name of the server that we connected to
1888 1889
    errptr           if we fail, we'll return (a pointer to a string
                     describing) the reason here
1890 1891 1892 1893 1894 1895

  RETURN VALUES
   0 Success
   1 Failed to validate server

 */
unknown's avatar
unknown committed
1896

1897
#if defined(HAVE_OPENSSL)
unknown's avatar
unknown committed
1898

1899
static int ssl_verify_server_cert(Vio *vio, const char* server_hostname, const char **errptr)
1900 1901
{
  SSL *ssl;
1902 1903 1904 1905 1906 1907 1908 1909
  X509 *server_cert= NULL;
  char *cn= NULL;
  int cn_loc= -1;
  ASN1_STRING *cn_asn1= NULL;
  X509_NAME_ENTRY *cn_entry= NULL;
  X509_NAME *subject= NULL;
  int ret_validation= 1;

1910 1911 1912 1913 1914
  DBUG_ENTER("ssl_verify_server_cert");
  DBUG_PRINT("enter", ("server_hostname: %s", server_hostname));

  if (!(ssl= (SSL*)vio->ssl_arg))
  {
1915
    *errptr= "No SSL pointer found";
1916
    goto error;
1917 1918 1919 1920
  }

  if (!server_hostname)
  {
1921
    *errptr= "No server hostname supplied";
1922
    goto error;
1923 1924 1925 1926
  }

  if (!(server_cert= SSL_get_peer_certificate(ssl)))
  {
1927
    *errptr= "Could not get server certificate";
1928
    goto error;
1929 1930
  }

1931 1932 1933
  if (X509_V_OK != SSL_get_verify_result(ssl))
  {
    *errptr= "Failed to verify the server certificate";
1934
    goto error;
1935
  }
1936 1937 1938 1939 1940 1941
  /*
    We already know that the certificate exchanged was valid; the SSL library
    handled that. Now we need to verify that the contents of the certificate
    are what we expect.
  */

1942 1943 1944 1945 1946 1947 1948
  /*
   Some notes for future development
   We should check host name in alternative name first and then if needed check in common name.
   Currently yssl doesn't support alternative name.
   openssl 1.0.2 support X509_check_host method for host name validation, we may need to start using
   X509_check_host in the future.
  */
1949

1950
  subject= X509_get_subject_name(server_cert);
1951 1952
  cn_loc= X509_NAME_get_index_by_NID(subject, NID_commonName, -1);
  if (cn_loc < 0)
1953
  {
1954 1955 1956
    *errptr= "Failed to get CN location in the certificate subject";
    goto error;
  }
1957

1958 1959 1960 1961 1962
  cn_entry= X509_NAME_get_entry(subject, cn_loc);
  if (cn_entry == NULL)
  {
    *errptr= "Failed to get CN entry using CN location";
    goto error;
1963
  }
1964

1965 1966 1967 1968 1969 1970
  cn_asn1 = X509_NAME_ENTRY_get_data(cn_entry);
  if (cn_asn1 == NULL)
  {
    *errptr= "Failed to get CN from CN entry";
    goto error;
  }
1971

1972
  cn= (char *) ASN1_STRING_data(cn_asn1);
1973

1974 1975 1976 1977 1978
  if ((size_t)ASN1_STRING_length(cn_asn1) != strlen(cn))
  {
    *errptr= "NULL embedded in the certificate CN";
    goto error;
  }
1979

1980 1981 1982 1983 1984 1985
  DBUG_PRINT("info", ("Server hostname in cert: %s", cn));
  if (!strcmp(cn, server_hostname))
  {
    /* Success */
    ret_validation= 0;
  }
1986

1987
  *errptr= "SSL certificate validation failure";
1988 1989 1990 1991 1992

error:
  if (server_cert != NULL)
    X509_free (server_cert);
  DBUG_RETURN(ret_validation);
1993 1994
}

1995
#endif /* HAVE_OPENSSL */
unknown's avatar
SCRUM  
unknown committed
1996 1997 1998 1999 2000 2001 2002


/*
  Note that the mysql argument must be initialized with mysql_init()
  before calling mysql_real_connect !
*/

2003 2004
static my_bool cli_read_query_result(MYSQL *mysql);
static MYSQL_RES *cli_use_result(MYSQL *mysql);
unknown's avatar
SCRUM  
unknown committed
2005

2006 2007 2008 2009 2010
int cli_read_change_user_result(MYSQL *mysql)
{
  return cli_safe_read(mysql);
}

unknown's avatar
SCRUM  
unknown committed
2011 2012
static MYSQL_METHODS client_methods=
{
2013 2014 2015 2016 2017
  cli_read_query_result,                       /* read_query_result */
  cli_advanced_command,                        /* advanced_command */
  cli_read_rows,                               /* read_rows */
  cli_use_result,                              /* use_result */
  cli_fetch_lengths,                           /* fetch_lengths */
2018 2019
  cli_flush_use_result,                        /* flush_use_result */
  cli_read_change_user_result                  /* read_change_user_result */
unknown's avatar
SCRUM  
unknown committed
2020
#ifndef MYSQL_SERVER
2021 2022 2023 2024 2025 2026 2027 2028 2029
  ,cli_list_fields,                            /* list_fields */
  cli_read_prepare_result,                     /* read_prepare_result */
  cli_stmt_execute,                            /* stmt_execute */
  cli_read_binary_rows,                        /* read_binary_rows */
  cli_unbuffered_fetch,                        /* unbuffered_fetch */
  NULL,                                        /* free_embedded_thd */
  cli_read_statistics,                         /* read_statistics */
  cli_read_query_result,                       /* next_result */
  cli_read_binary_rows                         /* read_rows_from_cursor */
unknown's avatar
SCRUM  
unknown committed
2030
#endif
unknown's avatar
SCRUM  
unknown committed
2031 2032
};

2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085


typedef enum my_cs_match_type_enum
{
  /* MySQL and OS charsets are fully compatible */
  my_cs_exact,
  /* MySQL charset is very close to OS charset  */
  my_cs_approx,
  /*
    MySQL knows this charset, but it is not supported as client character set.
  */
  my_cs_unsupp
} my_cs_match_type;


typedef struct str2str_st
{
  const char *os_name;
  const char *my_name;
  my_cs_match_type param;
} MY_CSET_OS_NAME;

const MY_CSET_OS_NAME charsets[]=
{
#ifdef __WIN__
  {"cp437",          "cp850",    my_cs_approx},
  {"cp850",          "cp850",    my_cs_exact},
  {"cp852",          "cp852",    my_cs_exact},
  {"cp858",          "cp850",    my_cs_approx},
  {"cp866",          "cp866",    my_cs_exact},
  {"cp874",          "tis620",   my_cs_approx},
  {"cp932",          "cp932",    my_cs_exact},
  {"cp936",          "gbk",      my_cs_approx},
  {"cp949",          "euckr",    my_cs_approx},
  {"cp950",          "big5",     my_cs_exact},
  {"cp1200",         "utf16le",  my_cs_unsupp},
  {"cp1201",         "utf16",    my_cs_unsupp},
  {"cp1250",         "cp1250",   my_cs_exact},
  {"cp1251",         "cp1251",   my_cs_exact},
  {"cp1252",         "latin1",   my_cs_exact},
  {"cp1253",         "greek",    my_cs_exact},
  {"cp1254",         "latin5",   my_cs_exact},
  {"cp1255",         "hebrew",   my_cs_approx},
  {"cp1256",         "cp1256",   my_cs_exact},
  {"cp1257",         "cp1257",   my_cs_exact},
  {"cp10000",        "macroman", my_cs_exact},
  {"cp10001",        "sjis",     my_cs_approx},
  {"cp10002",        "big5",     my_cs_approx},
  {"cp10008",        "gb2312",   my_cs_approx},
  {"cp10021",        "tis620",   my_cs_approx},
  {"cp10029",        "macce",    my_cs_exact},
  {"cp12001",        "utf32",    my_cs_unsupp},
  {"cp20107",        "swe7",     my_cs_exact},
2086
  {"cp20127",        "latin1",   my_cs_approx},
2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113
  {"cp20866",        "koi8r",    my_cs_exact},
  {"cp20932",        "ujis",     my_cs_exact},
  {"cp20936",        "gb2312",   my_cs_approx},
  {"cp20949",        "euckr",    my_cs_approx},
  {"cp21866",        "koi8u",    my_cs_exact},
  {"cp28591",        "latin1",   my_cs_approx},
  {"cp28592",        "latin2",   my_cs_exact},
  {"cp28597",        "greek",    my_cs_exact},
  {"cp28598",        "hebrew",   my_cs_exact},
  {"cp28599",        "latin5",   my_cs_exact},
  {"cp28603",        "latin7",   my_cs_exact},
#ifdef UNCOMMENT_THIS_WHEN_WL_4579_IS_DONE
  {"cp28605",        "latin9",   my_cs_exact},
#endif
  {"cp38598",        "hebrew",   my_cs_exact},
  {"cp51932",        "ujis",     my_cs_exact},
  {"cp51936",        "gb2312",   my_cs_exact},
  {"cp51949",        "euckr",    my_cs_exact},
  {"cp51950",        "big5",     my_cs_exact},
#ifdef UNCOMMENT_THIS_WHEN_WL_WL_4024_IS_DONE
  {"cp54936",        "gb18030",  my_cs_exact},
#endif
  {"cp65001",        "utf8",     my_cs_exact},

#else /* not Windows */

  {"646",            "latin1",   my_cs_approx}, /* Default on Solaris */
2114
  {"ANSI_X3.4-1968", "latin1",   my_cs_approx},
2115 2116 2117
  {"ansi1251",       "cp1251",   my_cs_exact},
  {"armscii8",       "armscii8", my_cs_exact},
  {"armscii-8",      "armscii8", my_cs_exact},
2118
  {"ASCII",          "latin1",   my_cs_approx},
2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190
  {"Big5",           "big5",     my_cs_exact},
  {"cp1251",         "cp1251",   my_cs_exact},
  {"cp1255",         "hebrew",   my_cs_approx},
  {"CP866",          "cp866",    my_cs_exact},
  {"eucCN",          "gb2312",   my_cs_exact},
  {"euc-CN",         "gb2312",   my_cs_exact},
  {"eucJP",          "ujis",     my_cs_exact},
  {"euc-JP",         "ujis",     my_cs_exact},
  {"eucKR",          "euckr",    my_cs_exact},
  {"euc-KR",         "euckr",    my_cs_exact},
#ifdef UNCOMMENT_THIS_WHEN_WL_WL_4024_IS_DONE
  {"gb18030",        "gb18030",  my_cs_exact},
#endif
  {"gb2312",         "gb2312",   my_cs_exact},
  {"gbk",            "gbk",      my_cs_exact},
  {"georgianps",     "geostd8",  my_cs_exact},
  {"georgian-ps",    "geostd8",  my_cs_exact},
  {"IBM-1252",       "cp1252",   my_cs_exact},

  {"iso88591",       "latin1",   my_cs_approx},
  {"ISO_8859-1",     "latin1",   my_cs_approx},
  {"ISO8859-1",      "latin1",   my_cs_approx},
  {"ISO-8859-1",     "latin1",   my_cs_approx},

  {"iso885913",      "latin7",   my_cs_exact},
  {"ISO_8859-13",    "latin7",   my_cs_exact},
  {"ISO8859-13",     "latin7",   my_cs_exact},
  {"ISO-8859-13",    "latin7",   my_cs_exact},

#ifdef UNCOMMENT_THIS_WHEN_WL_4579_IS_DONE
  {"iso885915",      "latin9",   my_cs_exact},
  {"ISO_8859-15",    "latin9",   my_cs_exact},
  {"ISO8859-15",     "latin9",   my_cs_exact},
  {"ISO-8859-15",    "latin9",   my_cs_exact},
#endif

  {"iso88592",       "latin2",   my_cs_exact},
  {"ISO_8859-2",     "latin2",   my_cs_exact},
  {"ISO8859-2",      "latin2",   my_cs_exact},
  {"ISO-8859-2",     "latin2",   my_cs_exact},

  {"iso88597",       "greek",    my_cs_exact},
  {"ISO_8859-7",     "greek",    my_cs_exact},
  {"ISO8859-7",      "greek",    my_cs_exact},
  {"ISO-8859-7",     "greek",    my_cs_exact},

  {"iso88598",       "hebrew",   my_cs_exact},
  {"ISO_8859-8",     "hebrew",   my_cs_exact},
  {"ISO8859-8",      "hebrew",   my_cs_exact},
  {"ISO-8859-8",     "hebrew",   my_cs_exact},

  {"iso88599",       "latin5",   my_cs_exact},
  {"ISO_8859-9",     "latin5",   my_cs_exact},
  {"ISO8859-9",      "latin5",   my_cs_exact},
  {"ISO-8859-9",     "latin5",   my_cs_exact},

  {"koi8r",          "koi8r",    my_cs_exact},
  {"KOI8-R",         "koi8r",    my_cs_exact},
  {"koi8u",          "koi8u",    my_cs_exact},
  {"KOI8-U",         "koi8u",    my_cs_exact},

  {"roman8",         "hp8",      my_cs_exact}, /* Default on HP UX */

  {"Shift_JIS",      "sjis",     my_cs_exact},
  {"SJIS",           "sjis",     my_cs_exact},
  {"shiftjisx0213",  "sjis",     my_cs_exact},
  
  {"tis620",         "tis620",   my_cs_exact},
  {"tis-620",        "tis620",   my_cs_exact},

  {"ujis",           "ujis",     my_cs_exact},

2191
  {"US-ASCII",       "latin1",   my_cs_approx},
2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261

  {"utf8",           "utf8",     my_cs_exact},
  {"utf-8",          "utf8",     my_cs_exact},
#endif
  {NULL,             NULL,       0}
};


static const char *
my_os_charset_to_mysql_charset(const char *csname)
{
  const MY_CSET_OS_NAME *csp;
  for (csp= charsets; csp->os_name; csp++)
  {
    if (!my_strcasecmp(&my_charset_latin1, csp->os_name, csname))
    {
      switch (csp->param)
      {
      case my_cs_exact:
        return csp->my_name;

      case my_cs_approx:
        /*
          Maybe we should print a warning eventually:
          character set correspondence is not exact.
        */
        return csp->my_name;

      default:
        my_printf_error(ER_UNKNOWN_ERROR,
                        "OS character set '%s'"
                        " is not supported by MySQL client",
                         MYF(0), csp->my_name);
        goto def;
      }
    }
  }

  my_printf_error(ER_UNKNOWN_ERROR,
                  "Unknown OS character set '%s'.",
                  MYF(0), csname);

def:
  csname= MYSQL_DEFAULT_CHARSET_NAME;
  my_printf_error(ER_UNKNOWN_ERROR,
                  "Switching to the default character set '%s'.",
                  MYF(0), csname);
  return csname;
}


#ifndef __WIN__
#include <stdlib.h> /* for getenv() */
#ifdef HAVE_LANGINFO_H
#include <langinfo.h>
#endif
#ifdef HAVE_LOCALE_H
#include <locale.h>
#endif
#endif /* __WIN__ */


static int
mysql_autodetect_character_set(MYSQL *mysql)
{
  const char *csname= MYSQL_DEFAULT_CHARSET_NAME;

#ifdef __WIN__
  char cpbuf[64];
  {
2262 2263 2264 2265
    UINT cp= GetConsoleCP();
    if (cp == 0)
      cp= GetACP();
    my_snprintf(cpbuf, sizeof(cpbuf), "cp%d", (int)cp);
2266 2267 2268 2269 2270 2271 2272 2273 2274
    csname= my_os_charset_to_mysql_charset(cpbuf);
  }
#elif defined(HAVE_SETLOCALE) && defined(HAVE_NL_LANGINFO)
  {
    if (setlocale(LC_CTYPE, "") && (csname= nl_langinfo(CODESET)))
      csname= my_os_charset_to_mysql_charset(csname);
  }
#endif

2275 2276
  if (mysql->options.charset_name)
    my_free(mysql->options.charset_name);
2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313
  if (!(mysql->options.charset_name= my_strdup(csname, MYF(MY_WME))))
    return 1;
  return 0;
}


static void
mysql_set_character_set_with_default_collation(MYSQL *mysql)
{
  const char *save= charsets_dir;
  if (mysql->options.charset_dir)
    charsets_dir=mysql->options.charset_dir;

  if ((mysql->charset= get_charset_by_csname(mysql->options.charset_name,
                                             MY_CS_PRIMARY, MYF(MY_WME))))
  {
    /* Try to set compiled default collation when it's possible. */
    CHARSET_INFO *collation;
    if ((collation= 
         get_charset_by_name(MYSQL_DEFAULT_COLLATION_NAME, MYF(MY_WME))) &&
                             my_charset_same(mysql->charset, collation))
    {
      mysql->charset= collation;
    }
    else
    {
      /*
        Default compiled collation not found, or is not applicable
        to the requested character set.
        Continue with the default collation of the character set.
      */
    }
  }
  charsets_dir= save;
}


2314 2315 2316 2317
C_MODE_START
int mysql_init_character_set(MYSQL *mysql)
{
  /* Set character set */
2318 2319 2320
  if (!mysql->options.charset_name)
  {
    if (!(mysql->options.charset_name= 
2321
       my_strdup(MYSQL_DEFAULT_CHARSET_NAME,MYF(MY_WME))))
2322
      return 1;
2323
  }
2324 2325 2326 2327 2328 2329
  else if (!strcmp(mysql->options.charset_name,
                   MYSQL_AUTODETECT_CHARSET_NAME) &&
            mysql_autodetect_character_set(mysql))
    return 1;

  mysql_set_character_set_with_default_collation(mysql);
2330

2331 2332 2333
  if (!mysql->charset)
  {
    if (mysql->options.charset_dir)
2334 2335 2336 2337
      set_mysql_extended_error(mysql, CR_CANT_READ_CHARSET, unknown_sqlstate,
                               ER(CR_CANT_READ_CHARSET),
                               mysql->options.charset_name,
                               mysql->options.charset_dir);
2338 2339 2340 2341
    else
    {
      char cs_dir_name[FN_REFLEN];
      get_charsets_dir(cs_dir_name);
2342 2343 2344 2345
      set_mysql_extended_error(mysql, CR_CANT_READ_CHARSET, unknown_sqlstate,
                               ER(CR_CANT_READ_CHARSET),
                               mysql->options.charset_name,
                               cs_dir_name);
2346 2347 2348 2349 2350 2351 2352
    }
    return 1;
  }
  return 0;
}
C_MODE_END

2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367
/*********** client side authentication support **************************/

typedef struct st_mysql_client_plugin_AUTHENTICATION auth_plugin_t;
static int client_mpvio_write_packet(struct st_plugin_vio*, const uchar*, int);
static int native_password_auth_client(MYSQL_PLUGIN_VIO *vio, MYSQL *mysql);
static int old_password_auth_client(MYSQL_PLUGIN_VIO *vio, MYSQL *mysql);

static auth_plugin_t native_password_client_plugin=
{
  MYSQL_CLIENT_AUTHENTICATION_PLUGIN,
  MYSQL_CLIENT_AUTHENTICATION_PLUGIN_INTERFACE_VERSION,
  native_password_plugin_name,
  "R.J.Silk, Sergei Golubchik",
  "Native MySQL authentication",
  {1, 0, 0},
2368 2369 2370
  "GPL",
  NULL,
  NULL,
2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383
  NULL,
  NULL,
  native_password_auth_client
};

static auth_plugin_t old_password_client_plugin=
{
  MYSQL_CLIENT_AUTHENTICATION_PLUGIN,
  MYSQL_CLIENT_AUTHENTICATION_PLUGIN_INTERFACE_VERSION,
  old_password_plugin_name,
  "R.J.Silk, Sergei Golubchik",
  "Old MySQL-3.23 authentication",
  {1, 0, 0},
2384 2385 2386
  "GPL",
  NULL,
  NULL,
2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405
  NULL,
  NULL,
  old_password_auth_client
};

struct st_mysql_client_plugin *mysql_client_builtins[]=
{
  (struct st_mysql_client_plugin *)&native_password_client_plugin,
  (struct st_mysql_client_plugin *)&old_password_client_plugin,
  0
};

/* this is a "superset" of MYSQL_PLUGIN_VIO, in C++ I use inheritance */
typedef struct {
  int (*read_packet)(struct st_plugin_vio *vio, uchar **buf);
  int (*write_packet)(struct st_plugin_vio *vio, const uchar *pkt, int pkt_len);
  void (*info)(struct st_plugin_vio *vio, struct st_plugin_vio_info *info);
  /* -= end of MYSQL_PLUGIN_VIO =- */
  MYSQL *mysql;
2406
  auth_plugin_t *plugin;            /**< what plugin we're under */
2407 2408
  const char *db;
  struct {
2409
    uchar *pkt;                     /**< pointer into NET::buff */
2410 2411
    uint pkt_len;
  } cached_server_reply;
2412 2413 2414
  int packets_read, packets_written; /**< counters for send/received packets */
  int mysql_change_user;            /**< if it's mysql_change_user() */
  int last_read_packet_len;         /**< the length of the last *read* packet */
2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442
} MCPVIO_EXT;

/**
  sends a COM_CHANGE_USER command with a caller provided payload

  Packet format:
   
    Bytes       Content
    -----       ----
    n           user name - \0-terminated string
    n           password
                  3.23 scramble - \0-terminated string (9 bytes)
                  otherwise - length (1 byte) coded
    n           database name - \0-terminated string
    2           character set number (if the server >= 4.1.x)
    n           client auth plugin name - \0-terminated string,
                  (if the server supports plugin auth)

  @retval 0 ok
  @retval 1 error
*/
static int send_change_user_packet(MCPVIO_EXT *mpvio,
                                   const uchar *data, int data_len)
{
  MYSQL *mysql= mpvio->mysql;
  char *buff, *end;
  int res= 1;

2443
  buff= my_alloca(USERNAME_LENGTH+1 + data_len+1 + NAME_LEN+1 + 2 + NAME_LEN+1);
2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534

  end= strmake(buff, mysql->user, USERNAME_LENGTH) + 1;

  if (!data_len)
    *end++= 0;
  else
  {
    if (mysql->client_flag & CLIENT_SECURE_CONNECTION)
    {
      DBUG_ASSERT(data_len <= 255);
      if (data_len > 255)
      {
        set_mysql_error(mysql, CR_MALFORMED_PACKET, unknown_sqlstate);
        goto error;
      }
      *end++= data_len;
    }
    else
    {
      DBUG_ASSERT(data_len == SCRAMBLE_LENGTH_323 + 1);
      DBUG_ASSERT(data[SCRAMBLE_LENGTH_323] == 0);
    }
    memcpy(end, data, data_len);
    end+= data_len;
  }
  end= strmake(end, mpvio->db ? mpvio->db : "", NAME_LEN) + 1;

  if (mysql->server_capabilities & CLIENT_PROTOCOL_41)
  {
    int2store(end, (ushort) mysql->charset->number);
    end+= 2;
  }

  if (mysql->server_capabilities & CLIENT_PLUGIN_AUTH)
    end= strmake(end, mpvio->plugin->name, NAME_LEN) + 1;

  res= simple_command(mysql, COM_CHANGE_USER,
                      (uchar*)buff, (ulong)(end-buff), 1);

error:
  my_afree(buff);
  return res;
}


/**
  sends a client authentication packet (second packet in the 3-way handshake)

  Packet format (when the server is 4.0 or earlier):
   
    Bytes       Content
    -----       ----
    2           client capabilities
    3           max packet size
    n           user name, \0-terminated
    9           scramble_323, \0-terminated

  Packet format (when the server is 4.1 or newer):
   
    Bytes       Content
    -----       ----
    4           client capabilities
    4           max packet size
    1           charset number
    23          reserved (always 0)
    n           user name, \0-terminated
    n           plugin auth data (e.g. scramble), length (1 byte) coded
    n           database name, \0-terminated
                (if CLIENT_CONNECT_WITH_DB is set in the capabilities)
    n           client auth plugin name - \0-terminated string,
                (if CLIENT_PLUGIN_AUTH is set in the capabilities)

  @retval 0 ok
  @retval 1 error
*/
static int send_client_reply_packet(MCPVIO_EXT *mpvio,
                                    const uchar *data, int data_len)
{
  MYSQL *mysql= mpvio->mysql;
  NET *net= &mysql->net;
  char *buff, *end;

  /* see end= buff+32 below, fixed size of the packet is 32 bytes */
  buff= my_alloca(33 + USERNAME_LENGTH + data_len + NAME_LEN + NAME_LEN);
  
  mysql->client_flag|= mysql->options.client_flag;
  mysql->client_flag|= CLIENT_CAPABILITIES;

  if (mysql->client_flag & CLIENT_MULTI_STATEMENTS)
    mysql->client_flag|= CLIENT_MULTI_RESULTS;

2535
#ifdef HAVE_OPENSSL
2536 2537
  if (mysql->options.use_ssl)
    mysql->client_flag|= CLIENT_SSL;
2538
#endif /* HAVE_OPENSSL */
2539

2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566
  if (mpvio->db)
    mysql->client_flag|= CLIENT_CONNECT_WITH_DB;

  /* Remove options that server doesn't support */
  mysql->client_flag= mysql->client_flag &
                       (~(CLIENT_COMPRESS | CLIENT_SSL | CLIENT_PROTOCOL_41) 
                       | mysql->server_capabilities);

#ifndef HAVE_COMPRESS
  mysql->client_flag&= ~CLIENT_COMPRESS;
#endif

  if (mysql->client_flag & CLIENT_PROTOCOL_41)
  {
    /* 4.1 server and 4.1 client has a 32 byte option flag */
    int4store(buff,mysql->client_flag);
    int4store(buff+4, net->max_packet_size);
    buff[8]= (char) mysql->charset->number;
    bzero(buff+9, 32-9);
    end= buff+32;
  }
  else
  {
    int2store(buff, mysql->client_flag);
    int3store(buff+2, net->max_packet_size);
    end= buff+5;
  }
2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583

  /*
     If client uses ssl and client also has to verify the server
     certificate, a ssl connection is required.
     If the server does not support ssl, we abort the connection.
  */
  if (mysql->options.use_ssl &&
      (mysql->client_flag & CLIENT_SSL_VERIFY_SERVER_CERT) &&
      !(mysql->server_capabilities & CLIENT_SSL))
  {
    set_mysql_extended_error(mysql, CR_SSL_CONNECTION_ERROR, unknown_sqlstate,
                             ER(CR_SSL_CONNECTION_ERROR),
                             "SSL is required, but the server does not "
                             "support it");
    goto error;
  }

2584
#ifdef HAVE_OPENSSL
2585 2586 2587 2588 2589
  if (mysql->client_flag & CLIENT_SSL)
  {
    /* Do the SSL layering. */
    struct st_mysql_options *options= &mysql->options;
    struct st_VioSSLFd *ssl_fd;
2590 2591 2592
    enum enum_ssl_init_error ssl_init_error;
    const char *cert_error;
    unsigned long ssl_error;
2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611

    /*
      Send mysql->client_flag, max_packet_size - unencrypted otherwise
      the server does not know we want to do SSL
    */
    if (my_net_write(net, (uchar*)buff, (size_t) (end-buff)) || net_flush(net))
    {
      set_mysql_extended_error(mysql, CR_SERVER_LOST, unknown_sqlstate,
                               ER(CR_SERVER_LOST_EXTENDED),
                               "sending connection information to server",
                               errno);
      goto error;
    }

    /* Create the VioSSLConnectorFd - init SSL and load certs */
    if (!(ssl_fd= new_VioSSLConnectorFd(options->ssl_key,
                                        options->ssl_cert,
                                        options->ssl_ca,
                                        options->ssl_capath,
2612 2613
                                        options->ssl_cipher,
                                        &ssl_init_error)))
2614
    {
2615 2616
      set_mysql_extended_error(mysql, CR_SSL_CONNECTION_ERROR, unknown_sqlstate,
                               ER(CR_SSL_CONNECTION_ERROR), sslGetErrString(ssl_init_error));
2617 2618
      goto error;
    }
2619
    mysql->connector_fd= (unsigned char *) ssl_fd;
2620 2621 2622 2623

    /* Connect to the server */
    DBUG_PRINT("info", ("IO layer change in progress..."));
    if (sslconnect(ssl_fd, net->vio,
2624
                   (long) (mysql->options.connect_timeout), &ssl_error))
2625
    {    
2626 2627 2628 2629 2630 2631
      char buf[512];
      ERR_error_string_n(ssl_error, buf, 512);
      buf[511]= 0;
      set_mysql_extended_error(mysql, CR_SSL_CONNECTION_ERROR, unknown_sqlstate,
                               ER(CR_SSL_CONNECTION_ERROR),
                               buf);
2632 2633 2634 2635 2636 2637
      goto error;
    }
    DBUG_PRINT("info", ("IO layer change done!"));

    /* Verify server cert */
    if ((mysql->client_flag & CLIENT_SSL_VERIFY_SERVER_CERT) &&
2638
        ssl_verify_server_cert(net->vio, mysql->host, &cert_error))
2639
    {
2640 2641
      set_mysql_extended_error(mysql, CR_SSL_CONNECTION_ERROR, unknown_sqlstate,
                               ER(CR_SSL_CONNECTION_ERROR), cert_error);
2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823
      goto error;
    }
  }
#endif /* HAVE_OPENSSL */

  DBUG_PRINT("info",("Server version = '%s'  capabilites: %lu  status: %u  client_flag: %lu",
		     mysql->server_version, mysql->server_capabilities,
		     mysql->server_status, mysql->client_flag));

  /* This needs to be changed as it's not useful with big packets */
  if (mysql->user[0])
    strmake(end, mysql->user, USERNAME_LENGTH);
  else
    read_user_name(end);

  /* We have to handle different version of handshake here */
  DBUG_PRINT("info",("user: %s",end));
  end= strend(end) + 1;
  if (data_len)
  {
    if (mysql->server_capabilities & CLIENT_SECURE_CONNECTION)
    {
      *end++= data_len;
      memcpy(end, data, data_len);
      end+= data_len;
    }
    else
    {
      DBUG_ASSERT(data_len == SCRAMBLE_LENGTH_323 + 1); /* incl. \0 at the end */
      memcpy(end, data, data_len);
      end+= data_len;
    }
  }
  else
    *end++= 0;

  /* Add database if needed */
  if (mpvio->db && (mysql->server_capabilities & CLIENT_CONNECT_WITH_DB))
  {
    end= strmake(end, mpvio->db, NAME_LEN) + 1;
    mysql->db= my_strdup(mpvio->db, MYF(MY_WME));
  }

  if (mysql->server_capabilities & CLIENT_PLUGIN_AUTH)
    end= strmake(end, mpvio->plugin->name, NAME_LEN) + 1;

  /* Write authentication package */
  if (my_net_write(net, (uchar*) buff, (size_t) (end-buff)) || net_flush(net))
  {
    set_mysql_extended_error(mysql, CR_SERVER_LOST, unknown_sqlstate,
                             ER(CR_SERVER_LOST_EXTENDED),
                             "sending authentication information",
                             errno);
    goto error;
  }
  my_afree(buff);
  return 0;
  
error:
  my_afree(buff);
  return 1;
}


/**
  vio->read_packet() callback method for client authentication plugins

  This function is called by a client authentication plugin, when it wants
  to read data from the server.
*/
static int client_mpvio_read_packet(struct st_plugin_vio *mpv, uchar **buf)
{
  MCPVIO_EXT *mpvio= (MCPVIO_EXT*)mpv;
  MYSQL *mysql= mpvio->mysql;
  ulong  pkt_len;

  /* there are cached data left, feed it to a plugin */
  if (mpvio->cached_server_reply.pkt)
  {
    *buf= mpvio->cached_server_reply.pkt;
    mpvio->cached_server_reply.pkt= 0;
    mpvio->packets_read++;
    return mpvio->cached_server_reply.pkt_len;
  }

  if (mpvio->packets_read == 0)
  {
    /*
      the server handshake packet came from the wrong plugin,
      or it's mysql_change_user(). Either way, there is no data
      for a plugin to read. send a dummy packet to the server
      to initiate a dialog.
    */
    if (client_mpvio_write_packet(mpv, 0, 0))
      return (int)packet_error;
  }

  /* otherwise read the data */
  pkt_len= (*mysql->methods->read_change_user_result)(mysql);
  mpvio->last_read_packet_len= pkt_len;
  *buf= mysql->net.read_pos;

  /* was it a request to change plugins ? */
  if (**buf == 254)
    return (int)packet_error; /* if yes, this plugin shan't continue */

  /*
    the server sends \1\255 or \1\254 instead of just \255 or \254 -
    for us to not confuse it with an error or "change plugin" packets.
    We remove this escaping \1 here.

    See also server_mpvio_write_packet() where the escaping is done.
  */
  if (pkt_len && **buf == 1)
  {
    (*buf)++;
    pkt_len--;
  }
  mpvio->packets_read++;
  return pkt_len;
}


/**
  vio->write_packet() callback method for client authentication plugins

  This function is called by a client authentication plugin, when it wants
  to send data to the server.

  It transparently wraps the data into a change user or authentication
  handshake packet, if neccessary.
*/
static int client_mpvio_write_packet(struct st_plugin_vio *mpv,
                                     const uchar *pkt, int pkt_len)
{
  int res;
  MCPVIO_EXT *mpvio= (MCPVIO_EXT*)mpv;

  if (mpvio->packets_written == 0)
  {
    if (mpvio->mysql_change_user)
      res= send_change_user_packet(mpvio, pkt, pkt_len);
    else
      res= send_client_reply_packet(mpvio, pkt, pkt_len);
  }
  else
  {
    NET *net= &mpvio->mysql->net;
    if (mpvio->mysql->thd)
      res= 1; /* no chit-chat in embedded */
    else
      res= my_net_write(net, pkt, pkt_len) || net_flush(net);
    if (res)
      set_mysql_extended_error(mpvio->mysql, CR_SERVER_LOST, unknown_sqlstate,
                               ER(CR_SERVER_LOST_EXTENDED),
                               "sending authentication information",
                               errno);
  }
  mpvio->packets_written++;
  return res;
}


/**
  fills MYSQL_PLUGIN_VIO_INFO structure with the information about the
  connection
*/
void mpvio_info(Vio *vio, MYSQL_PLUGIN_VIO_INFO *info)
{
  bzero(info, sizeof(*info));
  switch (vio->type) {
  case VIO_TYPE_TCPIP:
    info->protocol= MYSQL_VIO_TCP;
    info->socket= vio->sd;
    return;
  case VIO_TYPE_SOCKET:
    info->protocol= MYSQL_VIO_SOCKET;
    info->socket= vio->sd;
    return;
  case VIO_TYPE_SSL:
    {
      struct sockaddr addr;
Sergei Golubchik's avatar
Sergei Golubchik committed
2824
      SOCKET_SIZE_TYPE addrlen= sizeof(addr);
2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838
      if (getsockname(vio->sd, &addr, &addrlen))
        return;
      info->protocol= addr.sa_family == AF_UNIX ?
        MYSQL_VIO_SOCKET : MYSQL_VIO_TCP;
      info->socket= vio->sd;
      return;
    }
#ifdef _WIN32
  case VIO_TYPE_NAMEDPIPE:
    info->protocol= MYSQL_VIO_PIPE;
    info->handle= vio->hPipe;
    return;
  case VIO_TYPE_SHARED_MEMORY:
    info->protocol= MYSQL_VIO_MEMORY;
Sergei Golubchik's avatar
Sergei Golubchik committed
2839
#ifdef HAVE_SMEM
Sergei Golubchik's avatar
Sergei Golubchik committed
2840
    info->handle= vio->handle_file_map; /* or what ? */
2841
#endif
2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873
    return;
#endif
  default: DBUG_ASSERT(0);
  }
}


static void client_mpvio_info(MYSQL_PLUGIN_VIO *vio,
                              MYSQL_PLUGIN_VIO_INFO *info)
{
  MCPVIO_EXT *mpvio= (MCPVIO_EXT*)vio;
  mpvio_info(mpvio->mysql->net.vio, info);
}


/**
  Client side of the plugin driver authentication.

  @note this is used by both the mysql_real_connect and mysql_change_user

  @param mysql       mysql
  @param data        pointer to the plugin auth data (scramble) in the
                     handshake packet
  @param data_len    the length of the data
  @param data_plugin a plugin that data were prepared for
                     or 0 if it's mysql_change_user()
  @param db          initial db to use, can be 0

  @retval 0 ok
  @retval 1 error
*/
int run_plugin_auth(MYSQL *mysql, char *data, uint data_len,
Michael Widenius's avatar
Michael Widenius committed
2874
                    const char *data_plugin, const char *db)
2875 2876 2877 2878 2879 2880 2881
{
  const char    *auth_plugin_name;
  auth_plugin_t *auth_plugin;
  MCPVIO_EXT    mpvio;
  ulong		pkt_length;
  int           res;

2882
  DBUG_ENTER ("run_plugin_auth");
2883 2884 2885 2886 2887 2888 2889
  /* determine the default/initial plugin to use */
  if (mysql->options.extension && mysql->options.extension->default_auth &&
      mysql->server_capabilities & CLIENT_PLUGIN_AUTH)
  {
    auth_plugin_name= mysql->options.extension->default_auth;
    if (!(auth_plugin= (auth_plugin_t*) mysql_client_find_plugin(mysql,
                       auth_plugin_name, MYSQL_CLIENT_AUTHENTICATION_PLUGIN)))
2890
      DBUG_RETURN (1); /* oops, not found */
2891 2892 2893 2894 2895 2896 2897 2898
  }
  else
  {
    auth_plugin= mysql->server_capabilities & CLIENT_PROTOCOL_41 ?
      &native_password_client_plugin : &old_password_client_plugin;
    auth_plugin_name= auth_plugin->name;
  }

2899 2900
  DBUG_PRINT ("info", ("using plugin %s", auth_plugin_name));

2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921
  mysql->net.last_errno= 0; /* just in case */

  if (data_plugin && strcmp(data_plugin, auth_plugin_name))
  {
    /* data was prepared for a different plugin, don't show it to this one */
    data= 0;
    data_len= 0;
  }

  mpvio.mysql_change_user= data_plugin == 0;
  mpvio.cached_server_reply.pkt= (uchar*)data;
  mpvio.cached_server_reply.pkt_len= data_len;
  mpvio.read_packet= client_mpvio_read_packet;
  mpvio.write_packet= client_mpvio_write_packet;
  mpvio.info= client_mpvio_info;
  mpvio.mysql= mysql;
  mpvio.packets_read= mpvio.packets_written= 0;
  mpvio.db= db;
  mpvio.plugin= auth_plugin;

  res= auth_plugin->authenticate_user((struct st_plugin_vio *)&mpvio, mysql);
2922 2923 2924 2925 2926
  DBUG_PRINT ("info", ("authenticate_user returned %s", 
                       res == CR_OK ? "CR_OK" : 
                       res == CR_ERROR ? "CR_ERROR" :
                       res == CR_OK_HANDSHAKE_COMPLETE ? 
                         "CR_OK_HANDSHAKE_COMPLETE" : "error"));
2927 2928 2929 2930 2931 2932 2933 2934 2935 2936

  compile_time_assert(CR_OK == -1);
  compile_time_assert(CR_ERROR == 0);
  if (res > CR_OK && mysql->net.read_pos[0] != 254)
  {
    /*
      the plugin returned an error. write it down in mysql,
      unless the error code is CR_ERROR and mysql->net.last_errno
      is already set (the plugin has done it)
    */
2937
    DBUG_PRINT ("info", ("res=%d", res));
2938 2939 2940 2941 2942
    if (res > CR_ERROR)
      set_mysql_error(mysql, res, unknown_sqlstate);
    else
      if (!mysql->net.last_errno)
        set_mysql_error(mysql, CR_UNKNOWN_ERROR, unknown_sqlstate);
2943
    DBUG_RETURN (1);
2944 2945 2946 2947 2948 2949 2950 2951
  }

  /* read the OK packet (or use the cached value in mysql->net.read_pos */
  if (res == CR_OK)
    pkt_length= (*mysql->methods->read_change_user_result)(mysql);
  else /* res == CR_OK_HANDSHAKE_COMPLETE */
    pkt_length= mpvio.last_read_packet_len;

2952
  DBUG_PRINT ("info", ("OK packet length=%lu", pkt_length));
2953 2954 2955 2956 2957 2958 2959
  if (pkt_length == packet_error)
  {
    if (mysql->net.last_errno == CR_SERVER_LOST)
      set_mysql_extended_error(mysql, CR_SERVER_LOST, unknown_sqlstate,
                               ER(CR_SERVER_LOST_EXTENDED),
                               "reading authorization packet",
                               errno);
2960
    DBUG_RETURN (1);
2961 2962 2963 2964 2965 2966 2967 2968
  }

  if (mysql->net.read_pos[0] == 254)
  {
    /* The server asked to use a different authentication plugin */
    if (pkt_length == 1)
    {
      /* old "use short scramble" packet */
2969
      DBUG_PRINT ("info", ("old use short scramble packet from server"));
2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981
      auth_plugin_name= old_password_plugin_name;
      mpvio.cached_server_reply.pkt= (uchar*)mysql->scramble;
      mpvio.cached_server_reply.pkt_len= SCRAMBLE_LENGTH + 1;
    }
    else
    {
      /* new "use different plugin" packet */
      uint len;
      auth_plugin_name= (char*)mysql->net.read_pos + 1;
      len= strlen(auth_plugin_name); /* safe as my_net_read always appends \0 */
      mpvio.cached_server_reply.pkt_len= pkt_length - len - 2;
      mpvio.cached_server_reply.pkt= mysql->net.read_pos + len + 2;
2982 2983
      DBUG_PRINT ("info", ("change plugin packet from server for plugin %s",
                           auth_plugin_name));
2984 2985 2986 2987
    }

    if (!(auth_plugin= (auth_plugin_t *) mysql_client_find_plugin(mysql,
                         auth_plugin_name, MYSQL_CLIENT_AUTHENTICATION_PLUGIN)))
2988
      DBUG_RETURN (1);
2989 2990 2991 2992

    mpvio.plugin= auth_plugin;
    res= auth_plugin->authenticate_user((struct st_plugin_vio *)&mpvio, mysql);

2993 2994 2995 2996 2997
    DBUG_PRINT ("info", ("second authenticate_user returned %s", 
                         res == CR_OK ? "CR_OK" : 
                         res == CR_ERROR ? "CR_ERROR" :
                         res == CR_OK_HANDSHAKE_COMPLETE ? 
                         "CR_OK_HANDSHAKE_COMPLETE" : "error"));
2998 2999 3000 3001 3002 3003 3004
    if (res > CR_OK)
    {
      if (res > CR_ERROR)
        set_mysql_error(mysql, res, unknown_sqlstate);
      else
        if (!mysql->net.last_errno)
          set_mysql_error(mysql, CR_UNKNOWN_ERROR, unknown_sqlstate);
3005
      DBUG_RETURN (1);
3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017
    }

    if (res != CR_OK_HANDSHAKE_COMPLETE)
    {
      /* Read what server thinks about out new auth message report */
      if (cli_safe_read(mysql) == packet_error)
      {
        if (mysql->net.last_errno == CR_SERVER_LOST)
          set_mysql_extended_error(mysql, CR_SERVER_LOST, unknown_sqlstate,
                                   ER(CR_SERVER_LOST_EXTENDED),
                                   "reading final connect information",
                                   errno);
3018
        DBUG_RETURN (1);
3019 3020 3021 3022 3023 3024 3025
      }
    }
  }
  /*
    net->read_pos[0] should always be 0 here if the server implements
    the protocol correctly
  */
3026
  DBUG_RETURN (mysql->net.read_pos[0] != 0);
3027 3028
}

3029

3030 3031 3032 3033
static int
connect_sync_or_async(MYSQL *mysql, NET *net, my_socket fd,
                      const struct sockaddr *name, uint namelen)
{
3034 3035
  if (mysql->options.extension && mysql->options.extension->async_context &&
      mysql->options.extension->async_context->active)
3036 3037 3038
  {
    my_bool old_mode;
    vio_blocking(net->vio, FALSE, &old_mode);
3039 3040
    return my_connect_async(mysql->options.extension->async_context, fd,
                            name, namelen, mysql->options.connect_timeout);
3041
  }
3042 3043

  return my_connect(fd, name, namelen, mysql->options.connect_timeout);
3044 3045
}

unknown's avatar
SCRUM  
unknown committed
3046 3047 3048 3049
MYSQL * STDCALL 
CLI_MYSQL_REAL_CONNECT(MYSQL *mysql,const char *host, const char *user,
		       const char *passwd, const char *db,
		       uint port, const char *unix_socket,ulong client_flag)
unknown's avatar
SCRUM  
unknown committed
3050
{
unknown's avatar
unknown committed
3051
  char		buff[NAME_LEN+USERNAME_LENGTH+100];
3052
  int           scramble_data_len, pkt_scramble_len= 0;
3053
  char          *end,*host_info= 0, *server_version_end, *pkt_end;
Michael Widenius's avatar
Michael Widenius committed
3054 3055
  char          *scramble_data;
  const char    *scramble_plugin;
unknown's avatar
SCRUM  
unknown committed
3056 3057 3058 3059 3060 3061 3062 3063 3064
  ulong		pkt_length;
  NET		*net= &mysql->net;
#ifdef __WIN__
  HANDLE	hPipe=INVALID_HANDLE_VALUE;
#endif
#ifdef HAVE_SYS_UN_H
  struct	sockaddr_un UNIXaddr;
#endif
  DBUG_ENTER("mysql_real_connect");
3065
  LINT_INIT(pkt_scramble_len);
unknown's avatar
SCRUM  
unknown committed
3066

3067
  DBUG_PRINT("enter",("host: %s  db: %s  user: %s (client)",
unknown's avatar
SCRUM  
unknown committed
3068 3069 3070 3071
		      host ? host : "(Null)",
		      db ? db : "(Null)",
		      user ? user : "(Null)"));

3072 3073 3074 3075 3076 3077 3078
  /* Test whether we're already connected */
  if (net->vio)
  {
    set_mysql_error(mysql, CR_ALREADY_CONNECTED, unknown_sqlstate);
    DBUG_RETURN(0);
  }

3079
  mysql->methods= &client_methods;
unknown's avatar
SCRUM  
unknown committed
3080
  net->vio = 0;				/* If something goes wrong */
unknown's avatar
unknown committed
3081
  mysql->client_flag=0;			/* For handshake */
unknown's avatar
SCRUM  
unknown committed
3082 3083 3084 3085 3086 3087 3088 3089

  /* use default options */
  if (mysql->options.my_cnf_file || mysql->options.my_cnf_group)
  {
    mysql_read_default_options(&mysql->options,
			       (mysql->options.my_cnf_file ?
				mysql->options.my_cnf_file : "my"),
			       mysql->options.my_cnf_group);
3090 3091
    my_free(mysql->options.my_cnf_file);
    my_free(mysql->options.my_cnf_group);
unknown's avatar
SCRUM  
unknown committed
3092 3093 3094 3095 3096 3097 3098
    mysql->options.my_cnf_file=mysql->options.my_cnf_group=0;
  }

  /* Some empty-string-tests are done because of ODBC */
  if (!host || !host[0])
    host=mysql->options.host;
  if (!user || !user[0])
unknown's avatar
unknown committed
3099
  {
unknown's avatar
SCRUM  
unknown committed
3100
    user=mysql->options.user;
unknown's avatar
unknown committed
3101 3102 3103
    if (!user)
      user= "";
  }
unknown's avatar
SCRUM  
unknown committed
3104 3105 3106
  if (!passwd)
  {
    passwd=mysql->options.password;
3107
#if !defined(DONT_USE_MYSQL_PWD) && !defined(MYSQL_SERVER)
unknown's avatar
SCRUM  
unknown committed
3108 3109 3110
    if (!passwd)
      passwd=getenv("MYSQL_PWD");		/* get it from environment */
#endif
unknown's avatar
unknown committed
3111 3112
    if (!passwd)
      passwd= "";
unknown's avatar
SCRUM  
unknown committed
3113 3114 3115 3116 3117 3118 3119 3120 3121
  }
  if (!db || !db[0])
    db=mysql->options.db;
  if (!port)
    port=mysql->options.port;
  if (!unix_socket)
    unix_socket=mysql->options.unix_socket;

  mysql->server_status=SERVER_STATUS_AUTOCOMMIT;
3122
  DBUG_PRINT("info", ("Connecting"));
unknown's avatar
SCRUM  
unknown committed
3123 3124

  /*
3125
    Part 0: Grab a socket and connect it to the server
unknown's avatar
SCRUM  
unknown committed
3126
  */
3127
#if defined(HAVE_SMEM)
unknown's avatar
SCRUM  
unknown committed
3128 3129
  if ((!mysql->options.protocol ||
       mysql->options.protocol == MYSQL_PROTOCOL_MEMORY) &&
3130 3131
      (!host || !strcmp(host,LOCAL_HOST)) &&
      mysql->options.shared_memory_base_name)
unknown's avatar
SCRUM  
unknown committed
3132
  {
3133
    DBUG_PRINT("info", ("Using shared memory"));
unknown's avatar
SCRUM  
unknown committed
3134 3135 3136 3137 3138 3139 3140
    if ((create_shared_memory(mysql,net, mysql->options.connect_timeout)) ==
	INVALID_HANDLE_VALUE)
    {
      DBUG_PRINT("error",
		 ("host: '%s'  socket: '%s'  shared memory: %s  have_tcpip: %d",
		  host ? host : "<null>",
		  unix_socket ? unix_socket : "<null>",
3141
		  mysql->options.shared_memory_base_name,
unknown's avatar
SCRUM  
unknown committed
3142 3143 3144
		  (int) have_tcpip));
      if (mysql->options.protocol == MYSQL_PROTOCOL_MEMORY)
	goto error;
3145 3146 3147 3148 3149 3150 3151

      /*
        Try also with PIPE or TCP/IP. Clear the error from
        create_shared_memory().
      */

      net_clear_error(net);
unknown's avatar
SCRUM  
unknown committed
3152 3153 3154 3155 3156 3157
    }
    else
    {
      mysql->options.protocol=MYSQL_PROTOCOL_MEMORY;
      unix_socket = 0;
      host=mysql->options.shared_memory_base_name;
3158 3159
      my_snprintf(host_info=buff, sizeof(buff)-1,
                  ER(CR_SHARED_MEMORY_CONNECTION), host);
unknown's avatar
SCRUM  
unknown committed
3160
    }
3161
  }
unknown's avatar
SCRUM  
unknown committed
3162 3163
#endif /* HAVE_SMEM */
#if defined(HAVE_SYS_UN_H)
3164 3165 3166 3167 3168 3169
  if (!net->vio &&
      (!mysql->options.protocol ||
       mysql->options.protocol == MYSQL_PROTOCOL_SOCKET) &&
      (unix_socket || mysql_unix_port) &&
      (!host || !strcmp(host,LOCAL_HOST)))
  {
3170
    my_socket sock= socket(AF_UNIX, SOCK_STREAM, 0);
Joerg Bruehe's avatar
Joerg Bruehe committed
3171
    DBUG_PRINT("info", ("Using socket"));
3172
    if (sock == SOCKET_ERROR)
unknown's avatar
SCRUM  
unknown committed
3173
    {
3174 3175 3176 3177
      set_mysql_extended_error(mysql, CR_SOCKET_CREATE_ERROR,
                               unknown_sqlstate,
                               ER(CR_SOCKET_CREATE_ERROR),
                               socket_errno);
3178 3179
      goto error;
    }
3180

3181 3182
    net->vio= vio_new(sock, VIO_TYPE_SOCKET,
                      VIO_LOCALHOST | VIO_BUFFERED_READ);
3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198
    if (!net->vio)
    {
      DBUG_PRINT("error",("Unknow protocol %d ", mysql->options.protocol));
      set_mysql_error(mysql, CR_CONN_UNKNOW_PROTOCOL, unknown_sqlstate);
      closesocket(sock);
      goto error;
    }

    host= LOCAL_HOST;
    if (!unix_socket)
      unix_socket= mysql_unix_port;
    host_info= (char*) ER(CR_LOCALHOST_CONNECTION);
    DBUG_PRINT("info", ("Using UNIX sock '%s'", unix_socket));

    bzero((char*) &UNIXaddr, sizeof(UNIXaddr));
    UNIXaddr.sun_family= AF_UNIX;
3199
    strmake_buf(UNIXaddr.sun_path, unix_socket);
3200 3201
    if (connect_sync_or_async(mysql, net, sock,
                              (struct sockaddr *) &UNIXaddr, sizeof(UNIXaddr)))
3202 3203 3204
    {
      DBUG_PRINT("error",("Got error %d on connect to local server",
			  socket_errno));
3205 3206 3207 3208
      set_mysql_extended_error(mysql, CR_CONNECTION_ERROR,
                               unknown_sqlstate,
                               ER(CR_CONNECTION_ERROR),
                               unix_socket, socket_errno);
3209 3210
      vio_delete(net->vio);
      net->vio= 0;
3211 3212 3213 3214 3215 3216 3217 3218 3219 3220
      goto error;
    }
    mysql->options.protocol=MYSQL_PROTOCOL_SOCKET;
  }
#elif defined(__WIN__)
  if (!net->vio &&
      (mysql->options.protocol == MYSQL_PROTOCOL_PIPE ||
       (host && !strcmp(host,LOCAL_HOST_NAMEDPIPE)) ||
       (! have_tcpip && (unix_socket || !host && is_NT()))))
  {
3221 3222
    if ((hPipe= create_named_pipe(mysql, mysql->options.connect_timeout,
                                  (char**) &host, (char**) &unix_socket)) ==
3223 3224 3225 3226 3227 3228 3229 3230 3231 3232
	INVALID_HANDLE_VALUE)
    {
      DBUG_PRINT("error",
		 ("host: '%s'  socket: '%s'  have_tcpip: %d",
		  host ? host : "<null>",
		  unix_socket ? unix_socket : "<null>",
		  (int) have_tcpip));
      if (mysql->options.protocol == MYSQL_PROTOCOL_PIPE ||
	  (host && !strcmp(host,LOCAL_HOST_NAMEDPIPE)) ||
	  (unix_socket && !strcmp(unix_socket,MYSQL_NAMEDPIPE)))
unknown's avatar
SCRUM  
unknown committed
3233
	goto error;
3234
      /* Try also with TCP/IP */
unknown's avatar
SCRUM  
unknown committed
3235 3236 3237
    }
    else
    {
3238
      net->vio= vio_new_win32pipe(hPipe);
3239 3240
      my_snprintf(host_info=buff, sizeof(buff)-1,
                  ER(CR_NAMEDPIPE_CONNECTION), unix_socket);
unknown's avatar
SCRUM  
unknown committed
3241
    }
3242
  }
unknown's avatar
SCRUM  
unknown committed
3243
#endif
3244 3245
  DBUG_PRINT("info", ("net->vio: %p  protocol: %d",
                      net->vio, mysql->options.protocol));
3246 3247 3248
  if (!net->vio &&
      (!mysql->options.protocol ||
       mysql->options.protocol == MYSQL_PROTOCOL_TCP))
unknown's avatar
SCRUM  
unknown committed
3249
  {
3250 3251 3252 3253
    struct addrinfo *res_lst, hints, *t_res;
    int gai_errno;
    char port_buf[NI_MAXSERV];
    my_socket sock= SOCKET_ERROR;
3254
    int saved_error= 0, status= -1;
3255

unknown's avatar
SCRUM  
unknown committed
3256
    unix_socket=0;				/* This is not used */
3257

unknown's avatar
SCRUM  
unknown committed
3258
    if (!port)
3259 3260
      port= mysql_port;

unknown's avatar
SCRUM  
unknown committed
3261
    if (!host)
3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286
      host= LOCAL_HOST;

    my_snprintf(host_info=buff, sizeof(buff)-1, ER(CR_TCP_CONNECTION), host);
    DBUG_PRINT("info",("Server name: '%s'.  TCP sock: %d", host, port));
    DBUG_PRINT("info",("IP '%s'", "client"));

    memset(&hints, 0, sizeof(hints));
    hints.ai_socktype= SOCK_STREAM;
    hints.ai_protocol= IPPROTO_TCP;
    hints.ai_family= AF_UNSPEC;

    DBUG_PRINT("info",("IPV6 getaddrinfo %s", host));
    my_snprintf(port_buf, NI_MAXSERV, "%d", port);
    gai_errno= getaddrinfo(host, port_buf, &hints, &res_lst);

    if (gai_errno != 0) 
    { 
      /* 
        For DBUG we are keeping the right message but for client we default to
        historical error message.
      */
      DBUG_PRINT("info",("IPV6 getaddrinfo error %d", gai_errno));
      set_mysql_extended_error(mysql, CR_UNKNOWN_HOST, unknown_sqlstate,
                               ER(CR_UNKNOWN_HOST), host, errno);

unknown's avatar
SCRUM  
unknown committed
3287 3288 3289 3290
      goto error;
    }

    /*
3291 3292
      A hostname might map to multiple IP addresses (IPv4/IPv6). Go over the
      list of IP addresses until a successful connection can be established.
unknown's avatar
SCRUM  
unknown committed
3293
    */
3294 3295
    DBUG_PRINT("info", ("Try connect on all addresses for host."));
    for (t_res= res_lst; t_res; t_res= t_res->ai_next)
unknown's avatar
SCRUM  
unknown committed
3296
    {
3297 3298 3299 3300 3301 3302 3303 3304 3305
      DBUG_PRINT("info", ("Create socket, family: %d  type: %d  proto: %d",
                          t_res->ai_family, t_res->ai_socktype,
                          t_res->ai_protocol));
      sock= socket(t_res->ai_family, t_res->ai_socktype, t_res->ai_protocol);
      if (sock == SOCKET_ERROR)
      {
        saved_error= socket_errno;
        continue;
      }
3306

3307 3308
      net->vio= vio_new(sock, VIO_TYPE_TCPIP, VIO_BUFFERED_READ);
      if (!net->vio)
3309
      {
3310 3311 3312 3313
        set_mysql_error(mysql, CR_OUT_OF_MEMORY, unknown_sqlstate);
        closesocket(sock);
        freeaddrinfo(res_lst);
        goto error;
3314 3315
      }

3316
      DBUG_PRINT("info", ("Connect socket"));
3317 3318
      status= connect_sync_or_async(mysql, net, sock,
                                    t_res->ai_addr, t_res->ai_addrlen);
3319
      /*
3320 3321 3322
        Here we rely on my_connect() to return success only if the
        connect attempt was really successful. Otherwise we would stop
        trying another address, believing we were successful.
3323
      */
3324 3325
      if (!status)
        break;
3326

3327 3328 3329 3330 3331
      /*
        Save value as socket errno might be overwritten due to
        calling a socket function below.
      */
      saved_error= socket_errno;
3332

3333
      DBUG_PRINT("info", ("No success, close socket, try next address."));
3334 3335
      vio_delete(mysql->net.vio);
      mysql->net.vio= 0;
3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347
    }
    DBUG_PRINT("info",
               ("End of connect attempts, sock: %d  status: %d  error: %d",
                sock, status, saved_error));

    freeaddrinfo(res_lst);

    if (sock == SOCKET_ERROR)
    {
      set_mysql_extended_error(mysql, CR_IPSOCK_ERROR, unknown_sqlstate,
                                ER(CR_IPSOCK_ERROR), saved_error);
      goto error;
unknown's avatar
SCRUM  
unknown committed
3348
    }
3349 3350

    if (status)
unknown's avatar
SCRUM  
unknown committed
3351
    {
3352
      DBUG_PRINT("error",("Got error %d on connect to '%s'", saved_error, host));
3353
      set_mysql_extended_error(mysql, CR_CONN_HOST_ERROR, unknown_sqlstate,
3354 3355 3356
                                ER(CR_CONN_HOST_ERROR), host, saved_error);
      goto error;
    }
unknown's avatar
SCRUM  
unknown committed
3357
  }
3358 3359

  DBUG_PRINT("info", ("net->vio: %p", net->vio));
3360
  if (!net->vio)
unknown's avatar
SCRUM  
unknown committed
3361 3362
  {
    DBUG_PRINT("error",("Unknow protocol %d ",mysql->options.protocol));
3363
    set_mysql_error(mysql, CR_CONN_UNKNOW_PROTOCOL, unknown_sqlstate);
unknown's avatar
SCRUM  
unknown committed
3364 3365
    goto error;
  }
3366

3367
  if (mysql->options.extension && mysql->options.extension->async_context)
3368
    net->vio->async_context= mysql->options.extension->async_context;
3369

3370
  if (my_net_init(net, net->vio))
unknown's avatar
SCRUM  
unknown committed
3371 3372 3373
  {
    vio_delete(net->vio);
    net->vio = 0;
3374
    set_mysql_error(mysql, CR_OUT_OF_MEMORY, unknown_sqlstate);
unknown's avatar
SCRUM  
unknown committed
3375 3376 3377
    goto error;
  }
  vio_keepalive(net->vio,TRUE);
3378 3379

  /* If user set read_timeout, let it override the default */
3380
  if (mysql->options.read_timeout)
3381
    my_net_set_read_timeout(net, mysql->options.read_timeout);
3382 3383

  /* If user set write_timeout, let it override the default */
3384
  if (mysql->options.write_timeout)
3385
    my_net_set_write_timeout(net, mysql->options.write_timeout);
3386

3387 3388 3389
  if (mysql->options.max_allowed_packet)
    net->max_packet_size= mysql->options.max_allowed_packet;

unknown's avatar
SCRUM  
unknown committed
3390 3391 3392 3393 3394
  /* Get version info */
  mysql->protocol_version= PROTOCOL_VERSION;	/* Assume this */
  if (mysql->options.connect_timeout &&
      vio_poll_read(net->vio, mysql->options.connect_timeout))
  {
unknown's avatar
unknown committed
3395 3396 3397 3398
    set_mysql_extended_error(mysql, CR_SERVER_LOST, unknown_sqlstate,
                             ER(CR_SERVER_LOST_EXTENDED),
                             "waiting for initial communication packet",
                             errno);
unknown's avatar
SCRUM  
unknown committed
3399 3400
    goto error;
  }
3401 3402 3403 3404

  /*
    Part 1: Connection established, read and parse first packet
  */
3405
  DBUG_PRINT("info", ("Read first packet."));
3406

3407
  if ((pkt_length=cli_safe_read(mysql)) == packet_error)
unknown's avatar
unknown committed
3408
  {
unknown's avatar
unknown committed
3409
    if (mysql->net.last_errno == CR_SERVER_LOST)
unknown's avatar
unknown committed
3410 3411 3412 3413
      set_mysql_extended_error(mysql, CR_SERVER_LOST, unknown_sqlstate,
                               ER(CR_SERVER_LOST_EXTENDED),
                               "reading initial communication packet",
                               errno);
unknown's avatar
SCRUM  
unknown committed
3414
    goto error;
unknown's avatar
unknown committed
3415
  }
3416
  pkt_end= (char*)net->read_pos + pkt_length;
unknown's avatar
SCRUM  
unknown committed
3417 3418
  /* Check if version of protocol matches current one */
  mysql->protocol_version= net->read_pos[0];
unknown's avatar
unknown committed
3419
  DBUG_DUMP("packet",(uchar*) net->read_pos,10);
unknown's avatar
SCRUM  
unknown committed
3420 3421
  DBUG_PRINT("info",("mysql protocol version %d, server=%d",
		     PROTOCOL_VERSION, mysql->protocol_version));
3422
  if (mysql->protocol_version != PROTOCOL_VERSION)
unknown's avatar
SCRUM  
unknown committed
3423
  {
3424 3425 3426
    set_mysql_extended_error(mysql, CR_VERSION_ERROR, unknown_sqlstate,
                             ER(CR_VERSION_ERROR), mysql->protocol_version,
                             PROTOCOL_VERSION);
unknown's avatar
SCRUM  
unknown committed
3427 3428
    goto error;
  }
3429
  server_version_end= end= strend((char*) net->read_pos+1);
unknown's avatar
SCRUM  
unknown committed
3430 3431
  mysql->thread_id=uint4korr(end+1);
  end+=5;
3432
  /* 
3433
    Scramble is split into two parts because old clients do not understand
3434 3435
    long scrambles; here goes the first part.
  */
3436 3437 3438 3439
  scramble_data= end;
  scramble_data_len= SCRAMBLE_LENGTH_323 + 1;
  scramble_plugin= old_password_plugin_name;
  end+= scramble_data_len;
3440

3441
  if (pkt_end >= end + 1)
unknown's avatar
SCRUM  
unknown committed
3442
    mysql->server_capabilities=uint2korr(end);
3443
  if (pkt_end >= end + 18)
unknown's avatar
SCRUM  
unknown committed
3444 3445 3446 3447
  {
    /* New protocol with 16 bytes to describe server characteristics */
    mysql->server_language=end[2];
    mysql->server_status=uint2korr(end+3);
3448 3449
    mysql->server_capabilities|= uint2korr(end+5) << 16;
    pkt_scramble_len= end[7];
3450 3451 3452 3453 3454 3455
    if (pkt_scramble_len < 0)
    {
      set_mysql_error(mysql, CR_MALFORMED_PACKET,
                      unknown_sqlstate);        /* purecov: inspected */
      goto error;
    }
unknown's avatar
SCRUM  
unknown committed
3456
  }
3457
  end+= 18;
unknown's avatar
SCRUM  
unknown committed
3458

unknown's avatar
unknown committed
3459 3460 3461
  if (mysql->options.secure_auth && passwd[0] &&
      !(mysql->server_capabilities & CLIENT_SECURE_CONNECTION))
  {
3462
    set_mysql_error(mysql, CR_SECURE_AUTH, unknown_sqlstate);
unknown's avatar
unknown committed
3463 3464 3465
    goto error;
  }

3466
  if (mysql_init_character_set(mysql))
unknown's avatar
unknown committed
3467
    goto error;
unknown's avatar
SCRUM  
unknown committed
3468 3469 3470 3471 3472 3473 3474 3475

  /* Save connection information */
  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,
3476
		       (uint) (server_version_end - (char*) net->read_pos + 1),
unknown's avatar
SCRUM  
unknown committed
3477 3478 3479 3480
		       NullS) ||
      !(mysql->user=my_strdup(user,MYF(0))) ||
      !(mysql->passwd=my_strdup(passwd,MYF(0))))
  {
3481
    set_mysql_error(mysql, CR_OUT_OF_MEMORY, unknown_sqlstate);
unknown's avatar
SCRUM  
unknown committed
3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492
    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;

3493 3494 3495 3496 3497
  /*
    remove the rpl hack from the version string,
    see RPL_VERSION_HACK comment
  */
  if ((mysql->server_capabilities & CLIENT_PLUGIN_AUTH) &&
3498 3499 3500 3501
      strncmp(mysql->server_version, RPL_VERSION_HACK,
              sizeof(RPL_VERSION_HACK) - 1) == 0)
    mysql->server_version+= sizeof(RPL_VERSION_HACK) - 1;

3502
  if (pkt_end >= end + SCRAMBLE_LENGTH - SCRAMBLE_LENGTH_323 + 1)
unknown's avatar
SCRUM  
unknown committed
3503
  {
unknown's avatar
unknown committed
3504
    /*
3505 3506 3507
     move the first scramble part - directly in the NET buffer -
     to get a full continuous scramble. We've read all the header,
     and can overwrite it now.
unknown's avatar
unknown committed
3508
    */
3509 3510 3511 3512
    memmove(end - SCRAMBLE_LENGTH_323, scramble_data,
            SCRAMBLE_LENGTH_323);
    scramble_data= end - SCRAMBLE_LENGTH_323;
    if (mysql->server_capabilities & CLIENT_PLUGIN_AUTH)
unknown's avatar
SCRUM  
unknown committed
3513
    {
3514 3515 3516 3517
      scramble_data_len= pkt_scramble_len;
      scramble_plugin= scramble_data + scramble_data_len;
      if (scramble_data + scramble_data_len > pkt_end)
        scramble_data_len= pkt_end - scramble_data;
unknown's avatar
SCRUM  
unknown committed
3518
    }
unknown's avatar
unknown committed
3519
    else
unknown's avatar
SCRUM  
unknown committed
3520
    {
3521 3522
      scramble_data_len= pkt_end - scramble_data;
      scramble_plugin= native_password_plugin_name;
unknown's avatar
SCRUM  
unknown committed
3523 3524 3525
    }
  }
  else
3526 3527 3528
    mysql->server_capabilities&= ~CLIENT_SECURE_CONNECTION;

  mysql->client_flag= client_flag;
3529 3530

  /*
3531
    Part 2: invoke the plugin to send the authentication data to the server
3532
  */
unknown's avatar
SCRUM  
unknown committed
3533

3534 3535
  if (run_plugin_auth(mysql, scramble_data, scramble_data_len,
                      scramble_plugin, db))
unknown's avatar
SCRUM  
unknown committed
3536 3537
    goto error;

3538 3539 3540
  /*
    Part 3: authenticated, finish the initialization of the connection
  */
3541

3542
  if (mysql->client_flag & CLIENT_COMPRESS)      /* We will use compression */
unknown's avatar
SCRUM  
unknown committed
3543 3544
    net->compress=1;

3545
  if (db && !mysql->db && mysql_select_db(mysql, db))
unknown's avatar
unknown committed
3546
  {
unknown's avatar
unknown committed
3547
    if (mysql->net.last_errno == CR_SERVER_LOST)
unknown's avatar
unknown committed
3548 3549 3550 3551
        set_mysql_extended_error(mysql, CR_SERVER_LOST, unknown_sqlstate,
                                 ER(CR_SERVER_LOST_EXTENDED),
                                 "Setting intital database",
                                 errno);
unknown's avatar
SCRUM  
unknown committed
3552
    goto error;
unknown's avatar
unknown committed
3553
  }
unknown's avatar
SCRUM  
unknown committed
3554

3555 3556 3557 3558 3559
  /*
     Using init_commands is not supported when connecting from within the
     server.
  */
#ifndef MYSQL_SERVER
unknown's avatar
SCRUM  
unknown committed
3560 3561 3562 3563
  if (mysql->options.init_commands)
  {
    DYNAMIC_ARRAY *init_commands= mysql->options.init_commands;
    char **ptr= (char**)init_commands->buffer;
3564
    char **end_command= ptr + init_commands->elements;
unknown's avatar
SCRUM  
unknown committed
3565 3566 3567 3568

    my_bool reconnect=mysql->reconnect;
    mysql->reconnect=0;

3569
    for (; ptr < end_command; ptr++)
unknown's avatar
SCRUM  
unknown committed
3570
    {
3571 3572
      int status;

3573
      if (mysql_real_query(mysql,*ptr, (ulong) strlen(*ptr)))
unknown's avatar
SCRUM  
unknown committed
3574
	goto error;
3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586

      do {
        if (mysql->fields)
        {
          MYSQL_RES *res;
          if (!(res= cli_use_result(mysql)))
            goto error;
          mysql_free_result(res);
        }
        if ((status= mysql_next_result(mysql)) > 0)
          goto error;
      } while (status == 0);
unknown's avatar
SCRUM  
unknown committed
3587 3588 3589
    }
    mysql->reconnect=reconnect;
  }
3590
#endif
unknown's avatar
SCRUM  
unknown committed
3591

unknown's avatar
unknown committed
3592
  DBUG_PRINT("exit", ("Mysql handler: 0x%lx", (long) mysql));
unknown's avatar
SCRUM  
unknown committed
3593 3594 3595
  DBUG_RETURN(mysql);

error:
unknown's avatar
unknown committed
3596
  DBUG_PRINT("error",("message: %u/%s (%s)",
unknown's avatar
unknown committed
3597
                      net->last_errno,
3598
                      net->sqlstate,
unknown's avatar
unknown committed
3599
                      net->last_error));
unknown's avatar
SCRUM  
unknown committed
3600 3601 3602
  {
    /* Free alloced memory */
    end_server(mysql);
3603
    mysql_close_free(mysql);
unknown's avatar
SCRUM  
unknown committed
3604 3605 3606 3607
  }
  DBUG_RETURN(0);
}

3608

3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631
struct my_hook_data {
  MYSQL *orig_mysql;
  MYSQL *new_mysql;
  /* This is always NULL currently, but restoring does not hurt just in case. */
  Vio *orig_vio;
};
/*
  Callback hook to make the new VIO accessible via the old MYSQL to calling
  application when suspending a non-blocking call during automatic reconnect.
*/
static void
my_suspend_hook(my_bool suspend, void *data)
{
  struct my_hook_data *hook_data= (struct my_hook_data *)data;
  if (suspend)
  {
    hook_data->orig_vio= hook_data->orig_mysql->net.vio;
    hook_data->orig_mysql->net.vio= hook_data->new_mysql->net.vio;
  }
  else
    hook_data->orig_mysql->net.vio= hook_data->orig_vio;
}

unknown's avatar
SCRUM  
unknown committed
3632 3633 3634
my_bool mysql_reconnect(MYSQL *mysql)
{
  MYSQL tmp_mysql;
3635 3636
  struct my_hook_data hook_data;
  struct mysql_async_context *ctxt= NULL;
unknown's avatar
SCRUM  
unknown committed
3637
  DBUG_ENTER("mysql_reconnect");
3638 3639
  DBUG_ASSERT(mysql);
  DBUG_PRINT("enter", ("mysql->reconnect: %d", mysql->reconnect));
unknown's avatar
SCRUM  
unknown committed
3640

unknown's avatar
unknown committed
3641 3642
  if (!mysql->reconnect ||
      (mysql->server_status & SERVER_STATUS_IN_TRANS) || !mysql->host_info)
unknown's avatar
SCRUM  
unknown committed
3643
  {
unknown's avatar
unknown committed
3644
    /* Allow reconnect next time */
unknown's avatar
SCRUM  
unknown committed
3645
    mysql->server_status&= ~SERVER_STATUS_IN_TRANS;
3646
    set_mysql_error(mysql, CR_SERVER_GONE_ERROR, unknown_sqlstate);
unknown's avatar
SCRUM  
unknown committed
3647 3648 3649
    DBUG_RETURN(1);
  }
  mysql_init(&tmp_mysql);
3650
  tmp_mysql.options= mysql->options;
3651
  tmp_mysql.options.my_cnf_file= tmp_mysql.options.my_cnf_group= 0;
Konstantin Osipov's avatar
Konstantin Osipov committed
3652

3653 3654 3655 3656 3657 3658 3659 3660 3661 3662
  /*
    If we are automatically re-connecting inside a non-blocking API call, we
    may need to suspend and yield to the user application during the reconnect.
    If so, the user application will need access to the new VIO already then
    so that it can correctly wait for I/O to become ready.
    To achieve this, we temporarily install a hook that will temporarily put in
    the VIO while we are suspended.
    (The vio will be put in the original MYSQL permanently once we successfully
    reconnect, or be discarded if we fail to reconnect.)
  */
3663 3664 3665
  if (mysql->options.extension &&
      (ctxt= mysql->options.extension->async_context) &&
      mysql->options.extension->async_context->active)
3666 3667 3668 3669 3670 3671
  {
    hook_data.orig_mysql= mysql;
    hook_data.new_mysql= &tmp_mysql;
    hook_data.orig_vio= mysql->net.vio;
    my_context_install_suspend_resume_hook(ctxt, my_suspend_hook, &hook_data);
  }
unknown's avatar
SCRUM  
unknown committed
3672 3673
  if (!mysql_real_connect(&tmp_mysql,mysql->host,mysql->user,mysql->passwd,
			  mysql->db, mysql->port, mysql->unix_socket,
3674
			  mysql->client_flag))
unknown's avatar
SCRUM  
unknown committed
3675
  {
3676 3677
    if (ctxt)
      my_context_install_suspend_resume_hook(ctxt, NULL, NULL);
unknown's avatar
unknown committed
3678 3679
    mysql->net.last_errno= tmp_mysql.net.last_errno;
    strmov(mysql->net.last_error, tmp_mysql.net.last_error);
3680
    strmov(mysql->net.sqlstate, tmp_mysql.net.sqlstate);
unknown's avatar
SCRUM  
unknown committed
3681 3682
    DBUG_RETURN(1);
  }
unknown's avatar
unknown committed
3683 3684
  if (mysql_set_character_set(&tmp_mysql, mysql->charset->csname))
  {
3685 3686
    DBUG_PRINT("error", ("mysql_set_character_set() failed"));
    bzero((char*) &tmp_mysql.options,sizeof(tmp_mysql.options));
unknown's avatar
unknown committed
3687
    mysql_close(&tmp_mysql);
3688 3689
    if (ctxt)
      my_context_install_suspend_resume_hook(ctxt, NULL, NULL);
unknown's avatar
unknown committed
3690 3691
    mysql->net.last_errno= tmp_mysql.net.last_errno;
    strmov(mysql->net.last_error, tmp_mysql.net.last_error);
unknown's avatar
unknown committed
3692 3693 3694
    strmov(mysql->net.sqlstate, tmp_mysql.net.sqlstate);
    DBUG_RETURN(1);
  }
3695 3696
  if (ctxt)
    my_context_install_suspend_resume_hook(ctxt, NULL, NULL);
unknown's avatar
unknown committed
3697

3698
  DBUG_PRINT("info", ("reconnect succeded"));
3699
  tmp_mysql.reconnect= 1;
unknown's avatar
unknown committed
3700
  tmp_mysql.free_me= mysql->free_me;
3701

3702 3703 3704
  /* Move prepared statements (if any) over to the new mysql object */
  tmp_mysql.stmts= mysql->stmts;
  mysql->stmts= 0;
3705

unknown's avatar
unknown committed
3706 3707
  /* Don't free options as these are now used in tmp_mysql */
  bzero((char*) &mysql->options,sizeof(mysql->options));
unknown's avatar
SCRUM  
unknown committed
3708 3709 3710
  mysql->free_me=0;
  mysql_close(mysql);
  *mysql=tmp_mysql;
3711
  net_clear(&mysql->net, 1);
unknown's avatar
SCRUM  
unknown committed
3712 3713 3714 3715
  mysql->affected_rows= ~(my_ulonglong) 0;
  DBUG_RETURN(0);
}

3716

unknown's avatar
SCRUM  
unknown committed
3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727
/**************************************************************************
  Set current database
**************************************************************************/

int STDCALL
mysql_select_db(MYSQL *mysql, const char *db)
{
  int error;
  DBUG_ENTER("mysql_select_db");
  DBUG_PRINT("enter",("db: '%s'",db));

3728 3729
  if ((error=simple_command(mysql,COM_INIT_DB, (const uchar*) db,
                            (ulong) strlen(db),0)))
unknown's avatar
SCRUM  
unknown committed
3730
    DBUG_RETURN(error);
3731
  my_free(mysql->db);
unknown's avatar
SCRUM  
unknown committed
3732 3733 3734 3735 3736 3737 3738 3739 3740 3741
  mysql->db=my_strdup(db,MYF(MY_WME));
  DBUG_RETURN(0);
}


/*************************************************************************
  Send a QUIT to the server and close the connection
  If handle is alloced by mysql connect free it.
*************************************************************************/

3742 3743
static void mysql_close_free_options(MYSQL *mysql)
{
3744 3745
  DBUG_ENTER("mysql_close_free_options");

3746 3747 3748 3749 3750 3751 3752 3753 3754 3755
  my_free(mysql->options.user);
  my_free(mysql->options.host);
  my_free(mysql->options.password);
  my_free(mysql->options.unix_socket);
  my_free(mysql->options.db);
  my_free(mysql->options.my_cnf_file);
  my_free(mysql->options.my_cnf_group);
  my_free(mysql->options.charset_dir);
  my_free(mysql->options.charset_name);
  my_free(mysql->options.client_ip);
3756 3757 3758 3759 3760 3761
  if (mysql->options.init_commands)
  {
    DYNAMIC_ARRAY *init_commands= mysql->options.init_commands;
    char **ptr= (char**)init_commands->buffer;
    char **end= ptr + init_commands->elements;
    for (; ptr<end; ptr++)
3762
      my_free(*ptr);
3763
    delete_dynamic(init_commands);
3764
    my_free(init_commands);
3765
  }
Konstantin Osipov's avatar
Konstantin Osipov committed
3766
#if defined(HAVE_OPENSSL) && !defined(EMBEDDED_LIBRARY)
3767
  mysql_ssl_free(mysql);
Konstantin Osipov's avatar
Konstantin Osipov committed
3768
#endif /* HAVE_OPENSSL && !EMBEDDED_LIBRARY */
3769 3770
#ifdef HAVE_SMEM
  if (mysql->options.shared_memory_base_name != def_shared_memory_base_name)
3771
    my_free(mysql->options.shared_memory_base_name);
3772
#endif /* HAVE_SMEM */
3773 3774
  if (mysql->options.extension)
  {
3775
    struct mysql_async_context *ctxt= mysql->options.extension->async_context;
3776 3777
    my_free(mysql->options.extension->plugin_dir);
    my_free(mysql->options.extension->default_auth);
3778 3779 3780
    if (ctxt)
    {
      my_context_destroy(&ctxt->async_context);
3781
      my_free(ctxt);
3782
    }
3783
    my_free(mysql->options.extension);
3784
  }
unknown's avatar
unknown committed
3785
  bzero((char*) &mysql->options,sizeof(mysql->options));
3786
  DBUG_VOID_RETURN;
3787 3788 3789 3790 3791
}


static void mysql_close_free(MYSQL *mysql)
{
3792 3793 3794 3795
  my_free(mysql->host_info);
  my_free(mysql->user);
  my_free(mysql->passwd);
  my_free(mysql->db);
3796
#if defined(EMBEDDED_LIBRARY) || MYSQL_VERSION_ID >= 50100
3797
  my_free(mysql->info_buffer);
3798 3799
  mysql->info_buffer= 0;
#endif
unknown's avatar
unknown committed
3800
  /* Clear pointers for better safety */
3801
  mysql->host_info= mysql->user= mysql->passwd= mysql->db= 0;
3802 3803 3804
}


3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819
/**
  For use when the connection to the server has been lost (in which case 
  the server has discarded all information about prepared statements
  associated with the connection).

  Mark all statements in mysql->stmts by setting stmt->mysql= 0 if the
  statement has transitioned beyond the MYSQL_STMT_INIT_DONE state, and
  unlink the statement from the mysql->stmts list.

  The remaining pruned list of statements (if any) is kept in mysql->stmts.

  @param mysql       pointer to the MYSQL object

  @return none
*/
3820
static void mysql_prune_stmt_list(MYSQL *mysql)
3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831
{
  LIST *element= mysql->stmts;
  for (; element; element= element->next)
  {
    MYSQL_STMT *stmt= (MYSQL_STMT *) element->data;
    if (stmt->state != MYSQL_STMT_INIT_DONE)
    {
      stmt->mysql= 0;
      stmt->last_errno= CR_SERVER_LOST;
      strmov(stmt->last_error, ER(CR_SERVER_LOST));
      strmov(stmt->sqlstate, unknown_sqlstate);
3832
      mysql->stmts= list_delete(mysql->stmts, element);
3833 3834 3835 3836 3837
    }
  }
}


3838 3839 3840 3841 3842 3843 3844 3845
/*
  Clear connection pointer of every statement: this is necessary
  to give error on attempt to use a prepared statement of closed
  connection.

  SYNOPSYS
    mysql_detach_stmt_list()
      stmt_list  pointer to mysql->stmts
3846
      func_name  name of calling function
3847 3848 3849 3850

  NOTE
    There is similar code in mysql_reconnect(), so changes here
    should also be reflected there.
3851 3852
*/

3853
void mysql_detach_stmt_list(LIST **stmt_list __attribute__((unused)),
3854
                            const char *func_name __attribute__((unused)))
3855 3856 3857 3858
{
#ifdef MYSQL_CLIENT
  /* Reset connection handle in all prepared statements. */
  LIST *element= *stmt_list;
3859 3860 3861 3862
  char buff[MYSQL_ERRMSG_SIZE];
  DBUG_ENTER("mysql_detach_stmt_list");

  my_snprintf(buff, sizeof(buff)-1, ER(CR_STMT_CLOSED), func_name);
3863 3864 3865
  for (; element; element= element->next)
  {
    MYSQL_STMT *stmt= (MYSQL_STMT *) element->data;
3866
    set_stmt_error(stmt, CR_STMT_CLOSED, unknown_sqlstate, buff);
3867 3868 3869 3870
    stmt->mysql= 0;
    /* No need to call list_delete for statement here */
  }
  *stmt_list= 0;
3871
  DBUG_VOID_RETURN;
3872 3873 3874 3875
#endif /* MYSQL_CLIENT */
}


3876 3877 3878 3879 3880 3881 3882
/*
  Close a MySQL connection and free all resources attached to it.

  This function is coded in such that it can be called multiple times
  (As some clients call this after mysql_real_connect() fails)
*/

3883 3884 3885 3886 3887 3888 3889 3890
/*
  mysql_close() can actually block, at least in theory, if the socket buffer
  is full when sending the COM_QUIT command.

  On the other hand, the latter part of mysql_close() needs to free the stack
  used for non-blocking operation of blocking stuff, so that later part can
  _not_ be done non-blocking.

3891 3892 3893 3894
  Therefore, mysql_close_slow_part() is used to run the parts of mysql_close()
  that may block. It can be called before mysql_close(), and in that case
  mysql_close() is guaranteed not to need to block.  */
void STDCALL mysql_close_slow_part(MYSQL *mysql)
3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906
{
  /* If connection is still up, send a QUIT message */
  if (mysql->net.vio != 0)
  {
    free_old_query(mysql);
    mysql->status=MYSQL_STATUS_READY; /* Force command */
    mysql->reconnect=0;
    simple_command(mysql,COM_QUIT,(uchar*) 0,0,1);
    end_server(mysql);			/* Sets mysql->net.vio= 0 */
  }
}

unknown's avatar
unknown committed
3907
void STDCALL mysql_close(MYSQL *mysql)
unknown's avatar
SCRUM  
unknown committed
3908 3909
{
  DBUG_ENTER("mysql_close");
3910 3911
  DBUG_PRINT("enter", ("mysql: 0x%lx", (long) mysql));

unknown's avatar
SCRUM  
unknown committed
3912 3913
  if (mysql)					/* Some simple safety */
  {
3914
    mysql_close_slow_part(mysql);
3915 3916
    mysql_close_free_options(mysql);
    mysql_close_free(mysql);
3917
    mysql_detach_stmt_list(&mysql->stmts, "mysql_close");
unknown's avatar
SCRUM  
unknown committed
3918 3919
#ifndef MYSQL_SERVER
    if (mysql->thd)
3920
    {
unknown's avatar
SCRUM  
unknown committed
3921
      (*mysql->methods->free_embedded_thd)(mysql);
3922 3923
      mysql->thd= 0;
    }
unknown's avatar
SCRUM  
unknown committed
3924
#endif
unknown's avatar
SCRUM  
unknown committed
3925
    if (mysql->free_me)
3926
      my_free(mysql);
unknown's avatar
SCRUM  
unknown committed
3927 3928 3929 3930
  }
  DBUG_VOID_RETURN;
}

unknown's avatar
unknown committed
3931

3932
static my_bool cli_read_query_result(MYSQL *mysql)
unknown's avatar
SCRUM  
unknown committed
3933 3934 3935 3936 3937
{
  uchar *pos;
  ulong field_count;
  MYSQL_DATA *fields;
  ulong length;
3938
  DBUG_ENTER("cli_read_query_result");
unknown's avatar
SCRUM  
unknown committed
3939

3940
  if ((length = cli_safe_read(mysql)) == packet_error)
unknown's avatar
SCRUM  
unknown committed
3941
    DBUG_RETURN(1);
3942 3943
  free_old_query(mysql);		/* Free old result */
#ifdef MYSQL_CLIENT			/* Avoid warn of unused labels*/
unknown's avatar
SCRUM  
unknown committed
3944
get_info:
unknown's avatar
unknown committed
3945
#endif
unknown's avatar
SCRUM  
unknown committed
3946 3947 3948 3949 3950
  pos=(uchar*) mysql->net.read_pos;
  if ((field_count= net_field_length(&pos)) == 0)
  {
    mysql->affected_rows= net_field_length_ll(&pos);
    mysql->insert_id=	  net_field_length_ll(&pos);
3951 3952 3953
    DBUG_PRINT("info",("affected_rows: %lu  insert_id: %lu",
		       (ulong) mysql->affected_rows,
		       (ulong) mysql->insert_id));
unknown's avatar
SCRUM  
unknown committed
3954 3955 3956 3957 3958
    if (protocol_41(mysql))
    {
      mysql->server_status=uint2korr(pos); pos+=2;
      mysql->warning_count=uint2korr(pos); pos+=2;
    }
unknown's avatar
unknown committed
3959
    else if (mysql->server_capabilities & CLIENT_TRANSACTIONS)
unknown's avatar
SCRUM  
unknown committed
3960
    {
3961
      /* MySQL 4.0 protocol */
unknown's avatar
SCRUM  
unknown committed
3962 3963 3964
      mysql->server_status=uint2korr(pos); pos+=2;
      mysql->warning_count= 0;
    }
3965
    DBUG_PRINT("info",("status: %u  warning_count: %u",
unknown's avatar
SCRUM  
unknown committed
3966 3967 3968 3969 3970
		       mysql->server_status, mysql->warning_count));
    if (pos < mysql->net.read_pos+length && net_field_length(&pos))
      mysql->info=(char*) pos;
    DBUG_RETURN(0);
  }
unknown's avatar
unknown committed
3971
#ifdef MYSQL_CLIENT
unknown's avatar
SCRUM  
unknown committed
3972 3973
  if (field_count == NULL_LENGTH)		/* LOAD DATA LOCAL INFILE */
  {
unknown's avatar
unknown committed
3974 3975 3976 3977 3978 3979 3980 3981 3982
    int error;

    if (!(mysql->options.client_flag & CLIENT_LOCAL_FILES))
    {
      set_mysql_error(mysql, CR_MALFORMED_PACKET, unknown_sqlstate);
      DBUG_RETURN(1);
    }   

    error= handle_local_infile(mysql,(char*) pos);
3983
    if ((length= cli_safe_read(mysql)) == packet_error || error)
unknown's avatar
SCRUM  
unknown committed
3984 3985 3986
      DBUG_RETURN(1);
    goto get_info;				/* Get info packet */
  }
unknown's avatar
unknown committed
3987
#endif
unknown's avatar
SCRUM  
unknown committed
3988 3989 3990
  if (!(mysql->server_status & SERVER_STATUS_AUTOCOMMIT))
    mysql->server_status|= SERVER_STATUS_IN_TRANS;

3991
  if (!(fields=cli_read_rows(mysql,(MYSQL_FIELD*)0, protocol_41(mysql) ? 7:5)))
unknown's avatar
SCRUM  
unknown committed
3992
    DBUG_RETURN(1);
3993
  if (!(mysql->fields=unpack_fields(mysql, fields,&mysql->field_alloc,
unknown's avatar
SCRUM  
unknown committed
3994 3995 3996 3997 3998
				    (uint) field_count,0,
				    mysql->server_capabilities)))
    DBUG_RETURN(1);
  mysql->status= MYSQL_STATUS_GET_RESULT;
  mysql->field_count= (uint) field_count;
3999
  DBUG_PRINT("exit",("ok"));
unknown's avatar
SCRUM  
unknown committed
4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013
  DBUG_RETURN(0);
}


/*
  Send the query and return so we can do something else.
  Needs to be followed by mysql_read_query_result() when we want to
  finish processing it.
*/

int STDCALL
mysql_send_query(MYSQL* mysql, const char* query, ulong length)
{
  DBUG_ENTER("mysql_send_query");
4014
  DBUG_RETURN(simple_command(mysql, COM_QUERY, (uchar*) query, length, 1));
unknown's avatar
SCRUM  
unknown committed
4015 4016 4017 4018 4019 4020 4021
}


int STDCALL
mysql_real_query(MYSQL *mysql, const char *query, ulong length)
{
  DBUG_ENTER("mysql_real_query");
unknown's avatar
unknown committed
4022
  DBUG_PRINT("enter",("handle: 0x%lx", (long) mysql));
unknown's avatar
SCRUM  
unknown committed
4023 4024 4025 4026
  DBUG_PRINT("query",("Query = '%-.4096s'",query));

  if (mysql_send_query(mysql,query,length))
    DBUG_RETURN(1);
unknown's avatar
unknown committed
4027
  DBUG_RETURN((int) (*mysql->methods->read_query_result)(mysql));
unknown's avatar
SCRUM  
unknown committed
4028 4029
}

4030

unknown's avatar
SCRUM  
unknown committed
4031 4032 4033 4034 4035
/**************************************************************************
  Alloc result struct for buffered results. All rows are read to buffer.
  mysql_data_seek may be used.
**************************************************************************/

unknown's avatar
SCRUM  
unknown committed
4036
MYSQL_RES * STDCALL mysql_store_result(MYSQL *mysql)
unknown's avatar
SCRUM  
unknown committed
4037 4038 4039
{
  MYSQL_RES *result;
  DBUG_ENTER("mysql_store_result");
Konstantin Osipov's avatar
Konstantin Osipov committed
4040

unknown's avatar
SCRUM  
unknown committed
4041 4042 4043 4044
  if (!mysql->fields)
    DBUG_RETURN(0);
  if (mysql->status != MYSQL_STATUS_GET_RESULT)
  {
4045
    set_mysql_error(mysql, CR_COMMANDS_OUT_OF_SYNC, unknown_sqlstate);
unknown's avatar
SCRUM  
unknown committed
4046 4047 4048 4049 4050 4051 4052 4053
    DBUG_RETURN(0);
  }
  mysql->status=MYSQL_STATUS_READY;		/* server is ready */
  if (!(result=(MYSQL_RES*) my_malloc((uint) (sizeof(MYSQL_RES)+
					      sizeof(ulong) *
					      mysql->field_count),
				      MYF(MY_WME | MY_ZEROFILL))))
  {
4054
    set_mysql_error(mysql, CR_OUT_OF_MEMORY, unknown_sqlstate);
unknown's avatar
SCRUM  
unknown committed
4055 4056
    DBUG_RETURN(0);
  }
4057
  result->methods= mysql->methods;
unknown's avatar
SCRUM  
unknown committed
4058 4059
  result->eof=1;				/* Marker for buffered */
  result->lengths=(ulong*) (result+1);
unknown's avatar
SCRUM  
unknown committed
4060 4061
  if (!(result->data=
	(*mysql->methods->read_rows)(mysql,mysql->fields,mysql->field_count)))
unknown's avatar
SCRUM  
unknown committed
4062
  {
4063
    my_free(result);
unknown's avatar
SCRUM  
unknown committed
4064 4065 4066 4067 4068 4069 4070
    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;
4071
  /* The rest of result members is bzeroed in malloc */
unknown's avatar
SCRUM  
unknown committed
4072
  mysql->fields=0;				/* fields is now in result */
4073
  clear_alloc_root(&mysql->field_alloc);
4074 4075
  /* just in case this was mistakenly called after mysql_stmt_execute() */
  mysql->unbuffered_fetch_owner= 0;
unknown's avatar
SCRUM  
unknown committed
4076 4077 4078
  DBUG_RETURN(result);				/* Data fetched */
}

4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089

/**************************************************************************
  Alloc struct for use with unbuffered reads. Data is fetched by domand
  when calling to mysql_fetch_row.
  mysql_data_seek is a noop.

  No other queries may be specified with the same MYSQL handle.
  There shouldn't be much processing per row because mysql server shouldn't
  have to wait for the client (and will not wait more than 30 sec/packet).
**************************************************************************/

4090
static MYSQL_RES * cli_use_result(MYSQL *mysql)
4091 4092
{
  MYSQL_RES *result;
4093
  DBUG_ENTER("cli_use_result");
4094 4095 4096 4097 4098

  if (!mysql->fields)
    DBUG_RETURN(0);
  if (mysql->status != MYSQL_STATUS_GET_RESULT)
  {
4099
    set_mysql_error(mysql, CR_COMMANDS_OUT_OF_SYNC, unknown_sqlstate);
4100 4101 4102 4103 4104 4105 4106
    DBUG_RETURN(0);
  }
  if (!(result=(MYSQL_RES*) my_malloc(sizeof(*result)+
				      sizeof(ulong)*mysql->field_count,
				      MYF(MY_WME | MY_ZEROFILL))))
    DBUG_RETURN(0);
  result->lengths=(ulong*) (result+1);
4107
  result->methods= mysql->methods;
4108 4109 4110
  if (!(result->row=(MYSQL_ROW)
	my_malloc(sizeof(result->row[0])*(mysql->field_count+1), MYF(MY_WME))))
  {					/* Ptrs: to one row */
4111
    my_free(result);
4112 4113 4114 4115 4116 4117 4118 4119 4120
    DBUG_RETURN(0);
  }
  result->fields=	mysql->fields;
  result->field_alloc=	mysql->field_alloc;
  result->field_count=	mysql->field_count;
  result->current_field=0;
  result->handle=	mysql;
  result->current_row=	0;
  mysql->fields=0;			/* fields is now in result */
4121
  clear_alloc_root(&mysql->field_alloc);
4122
  mysql->status=MYSQL_STATUS_USE_RESULT;
4123
  mysql->unbuffered_fetch_owner= &result->unbuffered_fetch_cancelled;
4124 4125 4126 4127
  DBUG_RETURN(result);			/* Data is read to be fetched */
}


unknown's avatar
SCRUM  
unknown committed
4128
/**************************************************************************
4129
  Return next row of the query results
unknown's avatar
SCRUM  
unknown committed
4130 4131 4132 4133 4134 4135 4136 4137 4138 4139
**************************************************************************/

MYSQL_ROW STDCALL
mysql_fetch_row(MYSQL_RES *res)
{
  DBUG_ENTER("mysql_fetch_row");
  if (!res->data)
  {						/* Unbufferred fetch */
    if (!res->eof)
    {
4140 4141
      MYSQL *mysql= res->handle;
      if (mysql->status != MYSQL_STATUS_USE_RESULT)
unknown's avatar
SCRUM  
unknown committed
4142
      {
4143 4144
        set_mysql_error(mysql,
                        res->unbuffered_fetch_cancelled ? 
unknown's avatar
unknown committed
4145
                        CR_FETCH_CANCELED : CR_COMMANDS_OUT_OF_SYNC,
4146
                        unknown_sqlstate);
unknown's avatar
SCRUM  
unknown committed
4147
      }
4148
      else if (!(read_one_row(mysql, res->field_count, res->row, res->lengths)))
unknown's avatar
SCRUM  
unknown committed
4149
      {
4150 4151
	res->row_count++;
	DBUG_RETURN(res->current_row=res->row);
unknown's avatar
SCRUM  
unknown committed
4152
      }
4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163
      DBUG_PRINT("info",("end of data"));
      res->eof=1;
      mysql->status=MYSQL_STATUS_READY;
      /*
        Reset only if owner points to us: there is a chance that somebody
        started new query after mysql_stmt_close():
      */
      if (mysql->unbuffered_fetch_owner == &res->unbuffered_fetch_cancelled)
        mysql->unbuffered_fetch_owner= 0;
      /* Don't clear handle in mysql_free_result */
      res->handle=0;
unknown's avatar
SCRUM  
unknown committed
4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180
    }
    DBUG_RETURN((MYSQL_ROW) NULL);
  }
  {
    MYSQL_ROW tmp;
    if (!res->data_cursor)
    {
      DBUG_PRINT("info",("end of data"));
      DBUG_RETURN(res->current_row=(MYSQL_ROW) NULL);
    }
    tmp = res->data_cursor->data;
    res->data_cursor = res->data_cursor->next;
    DBUG_RETURN(res->current_row=tmp);
  }
}


unknown's avatar
unknown committed
4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199
/**************************************************************************
  Get column lengths of the current row
  If one uses mysql_use_result, res->lengths contains the length information,
  else the lengths are calculated from the offset between pointers.
**************************************************************************/

ulong * STDCALL
mysql_fetch_lengths(MYSQL_RES *res)
{
  MYSQL_ROW column;

  if (!(column=res->current_row))
    return 0;					/* Something is wrong */
  if (res->data)
    (*res->methods->fetch_lengths)(res->lengths, column, res->field_count);
  return res->lengths;
}


4200 4201
#define ASYNC_CONTEXT_DEFAULT_STACK_SIZE (4096*15)

unknown's avatar
unknown committed
4202
int STDCALL
4203
mysql_options(MYSQL *mysql,enum mysql_option option, const void *arg)
unknown's avatar
unknown committed
4204
{
4205 4206 4207
  struct mysql_async_context *ctxt;
  size_t stacksize;

4208
  DBUG_ENTER("mysql_options");
unknown's avatar
unknown committed
4209 4210 4211 4212 4213
  DBUG_PRINT("enter",("option: %d",(int) option));
  switch (option) {
  case MYSQL_OPT_CONNECT_TIMEOUT:
    mysql->options.connect_timeout= *(uint*) arg;
    break;
4214 4215 4216 4217 4218 4219
  case MYSQL_OPT_READ_TIMEOUT:
    mysql->options.read_timeout= *(uint*) arg;
    break;
  case MYSQL_OPT_WRITE_TIMEOUT:
    mysql->options.write_timeout= *(uint*) arg;
    break;
unknown's avatar
unknown committed
4220 4221 4222 4223
  case MYSQL_OPT_COMPRESS:
    mysql->options.compress= 1;			/* Remember for connect */
    mysql->options.client_flag|= CLIENT_COMPRESS;
    break;
4224
  case MYSQL_OPT_NAMED_PIPE:			/* This option is depricated */
unknown's avatar
unknown committed
4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236
    mysql->options.protocol=MYSQL_PROTOCOL_PIPE; /* Force named pipe */
    break;
  case MYSQL_OPT_LOCAL_INFILE:			/* Allow LOAD DATA LOCAL ?*/
    if (!arg || test(*(uint*) arg))
      mysql->options.client_flag|= CLIENT_LOCAL_FILES;
    else
      mysql->options.client_flag&= ~CLIENT_LOCAL_FILES;
    break;
  case MYSQL_INIT_COMMAND:
    add_init_command(&mysql->options,arg);
    break;
  case MYSQL_READ_DEFAULT_FILE:
4237
    my_free(mysql->options.my_cnf_file);
unknown's avatar
unknown committed
4238 4239 4240
    mysql->options.my_cnf_file=my_strdup(arg,MYF(MY_WME));
    break;
  case MYSQL_READ_DEFAULT_GROUP:
4241
    my_free(mysql->options.my_cnf_group);
unknown's avatar
unknown committed
4242 4243 4244
    mysql->options.my_cnf_group=my_strdup(arg,MYF(MY_WME));
    break;
  case MYSQL_SET_CHARSET_DIR:
4245
    my_free(mysql->options.charset_dir);
unknown's avatar
unknown committed
4246 4247 4248
    mysql->options.charset_dir=my_strdup(arg,MYF(MY_WME));
    break;
  case MYSQL_SET_CHARSET_NAME:
4249
    my_free(mysql->options.charset_name);
unknown's avatar
unknown committed
4250 4251 4252 4253 4254 4255 4256 4257
    mysql->options.charset_name=my_strdup(arg,MYF(MY_WME));
    break;
  case MYSQL_OPT_PROTOCOL:
    mysql->options.protocol= *(uint*) arg;
    break;
  case MYSQL_SHARED_MEMORY_BASE_NAME:
#ifdef HAVE_SMEM
    if (mysql->options.shared_memory_base_name != def_shared_memory_base_name)
4258
      my_free(mysql->options.shared_memory_base_name);
unknown's avatar
unknown committed
4259 4260
    mysql->options.shared_memory_base_name=my_strdup(arg,MYF(MY_WME));
#endif
unknown's avatar
fix:  
unknown committed
4261
    break;
unknown's avatar
SCRUM  
unknown committed
4262 4263 4264 4265
  case MYSQL_OPT_USE_REMOTE_CONNECTION:
  case MYSQL_OPT_USE_EMBEDDED_CONNECTION:
  case MYSQL_OPT_GUESS_CONNECTION:
    mysql->options.methods_to_use= option;
unknown's avatar
unknown committed
4266
    break;
unknown's avatar
unknown committed
4267
  case MYSQL_SET_CLIENT_IP:
4268
    my_free(mysql->options.client_ip);
unknown's avatar
unknown committed
4269
    mysql->options.client_ip= my_strdup(arg, MYF(MY_WME));
4270
    break;
unknown's avatar
unknown committed
4271 4272
  case MYSQL_SECURE_AUTH:
    mysql->options.secure_auth= *(my_bool *) arg;
unknown's avatar
fix:  
unknown committed
4273
    break;
4274 4275 4276
  case MYSQL_REPORT_DATA_TRUNCATION:
    mysql->options.report_data_truncation= test(*(my_bool *) arg);
    break;
4277 4278 4279
  case MYSQL_OPT_RECONNECT:
    mysql->reconnect= *(my_bool *) arg;
    break;
4280
  case MYSQL_OPT_SSL_VERIFY_SERVER_CERT:
4281
    if (*(my_bool*) arg)
4282 4283 4284
      mysql->options.client_flag|= CLIENT_SSL_VERIFY_SERVER_CERT;
    else
      mysql->options.client_flag&= ~CLIENT_SSL_VERIFY_SERVER_CERT;
4285
    break;
4286
  case MYSQL_PLUGIN_DIR:
4287
    EXTENSION_SET_STRING(&mysql->options, plugin_dir, arg);
4288 4289
    break;
  case MYSQL_DEFAULT_AUTH:
4290
    EXTENSION_SET_STRING(&mysql->options, default_auth, arg);
4291
    break;
4292 4293
  case MYSQL_ENABLE_CLEARTEXT_PLUGIN:
    break;
4294 4295 4296 4297 4298 4299 4300 4301 4302
  case MYSQL_PROGRESS_CALLBACK:
    if (!mysql->options.extension)
      mysql->options.extension= (struct st_mysql_options_extention *)
        my_malloc(sizeof(struct st_mysql_options_extention),
                  MYF(MY_WME | MY_ZEROFILL));
    if (mysql->options.extension)
      mysql->options.extension->report_progress= 
        (void (*)(const MYSQL *, uint, uint, double, const char *, uint)) arg;
    break;
4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313
  case MYSQL_OPT_NONBLOCK:
    if (mysql->options.extension &&
        (ctxt = mysql->options.extension->async_context) != 0)
    {
      /*
        We must not allow changing the stack size while a non-blocking call is
        suspended (as the stack is then in use).
      */
      if (ctxt->suspended)
        DBUG_RETURN(1);
      my_context_destroy(&ctxt->async_context);
4314
      my_free(ctxt);
4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328
    }
    if (!(ctxt= (struct mysql_async_context *)
          my_malloc(sizeof(*ctxt), MYF(MY_ZEROFILL))))
    {
      set_mysql_error(mysql, CR_OUT_OF_MEMORY, unknown_sqlstate);
      DBUG_RETURN(1);
    }
    stacksize= 0;
    if (arg)
      stacksize= *(const size_t *)arg;
    if (!stacksize)
      stacksize= ASYNC_CONTEXT_DEFAULT_STACK_SIZE;
    if (my_context_init(&ctxt->async_context, stacksize))
    {
4329
      set_mysql_error(mysql, CR_OUT_OF_MEMORY, unknown_sqlstate);
4330
      my_free(ctxt);
4331 4332
      DBUG_RETURN(1);
    }
4333
    EXTENSION_SET(&(mysql->options), async_context, ctxt)
4334 4335 4336
    if (mysql->net.vio)
      mysql->net.vio->async_context= ctxt;
    break;
unknown's avatar
unknown committed
4337 4338 4339 4340 4341 4342 4343
  default:
    DBUG_RETURN(1);
  }
  DBUG_RETURN(0);
}


unknown's avatar
SCRUM  
unknown committed
4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361
/****************************************************************************
  Functions to get information from the MySQL structure
  These are functions to make shared libraries more usable.
****************************************************************************/

/* MYSQL_RES */
my_ulonglong STDCALL mysql_num_rows(MYSQL_RES *res)
{
  return res->row_count;
}

unsigned int STDCALL mysql_num_fields(MYSQL_RES *res)
{
  return res->field_count;
}

uint STDCALL mysql_errno(MYSQL *mysql)
{
4362
  return mysql ? mysql->net.last_errno : mysql_server_last_errno;
unknown's avatar
SCRUM  
unknown committed
4363 4364
}

4365

unknown's avatar
SCRUM  
unknown committed
4366 4367
const char * STDCALL mysql_error(MYSQL *mysql)
{
4368
  return mysql ? mysql->net.last_error : mysql_server_last_error;
unknown's avatar
SCRUM  
unknown committed
4369
}
4370

4371 4372 4373 4374 4375 4376 4377 4378 4379

/*
  Get version number for server in a form easy to test on

  SYNOPSIS
    mysql_get_server_version()
    mysql		Connection

  EXAMPLE
4380
    MariaDB-4.1.0-alfa ->  40100
4381 4382 4383 4384 4385 4386
  
  NOTES
    We will ensure that a newer server always has a bigger number.

  RETURN
   Signed number > 323000
4387
   Zero if there is no connection
4388 4389 4390 4391 4392
*/

ulong STDCALL
mysql_get_server_version(MYSQL *mysql)
{
4393 4394 4395 4396
  ulong major= 0, minor= 0, version= 0;

  if (mysql->server_version)
  {
Sergei Golubchik's avatar
Sergei Golubchik committed
4397 4398 4399 4400 4401
    const char *pos= mysql->server_version;
    char *end_pos;
    /* Skip possible prefix */
    while (*pos && !my_isdigit(&my_charset_latin1, *pos))
      pos++;
4402 4403 4404 4405 4406 4407 4408 4409 4410 4411
    major=   strtoul(pos, &end_pos, 10);	pos=end_pos+1;
    minor=   strtoul(pos, &end_pos, 10);	pos=end_pos+1;
    version= strtoul(pos, &end_pos, 10);
  }
  else
  {
    set_mysql_error(mysql, CR_COMMANDS_OUT_OF_SYNC, unknown_sqlstate);
  }

  return major*10000 + minor*100 + version;
4412 4413 4414
}


4415 4416 4417 4418 4419 4420 4421 4422
/* 
   mysql_set_character_set function sends SET NAMES cs_name to
   the server (which changes character_set_client, character_set_result
   and character_set_connection) and updates mysql->charset so other
   functions like mysql_real_escape will work correctly.
*/
int STDCALL mysql_set_character_set(MYSQL *mysql, const char *cs_name)
{
4423
  CHARSET_INFO *cs;
4424 4425 4426 4427 4428 4429 4430 4431 4432 4433
  const char *save_csdir= charsets_dir;

  if (mysql->options.charset_dir)
    charsets_dir= mysql->options.charset_dir;

  if (strlen(cs_name) < MY_CS_NAME_SIZE &&
     (cs= get_charset_by_csname(cs_name, MY_CS_PRIMARY, MYF(0))))
  {
    char buff[MY_CS_NAME_SIZE + 10];
    charsets_dir= save_csdir;
unknown's avatar
unknown committed
4434 4435 4436
    /* Skip execution of "SET NAMES" for pre-4.1 servers */
    if (mysql_get_server_version(mysql) < 40100)
      return 0;
4437
    sprintf(buff, "SET NAMES %s", cs_name);
4438
    if (!mysql_real_query(mysql, buff, (uint) strlen(buff)))
4439 4440 4441 4442 4443 4444 4445 4446
    {
      mysql->charset= cs;
    }
  }
  else
  {
    char cs_dir_name[FN_REFLEN];
    get_charsets_dir(cs_dir_name);
4447 4448
    set_mysql_extended_error(mysql, CR_CANT_READ_CHARSET, unknown_sqlstate,
                             ER(CR_CANT_READ_CHARSET), cs_name, cs_dir_name);
4449 4450
  }
  charsets_dir= save_csdir;
unknown's avatar
unknown committed
4451
  return mysql->net.last_errno;
4452 4453
}

4454 4455 4456 4457 4458 4459 4460 4461 4462
/**
  client authentication plugin that does native MySQL authentication
  using a 20-byte (4.1+) scramble
*/
static int native_password_auth_client(MYSQL_PLUGIN_VIO *vio, MYSQL *mysql)
{
  int pkt_len;
  uchar *pkt;

4463
  DBUG_ENTER("native_password_auth_client");
4464 4465 4466 4467 4468 4469 4470 4471 4472 4473 4474 4475 4476 4477 4478


  if (((MCPVIO_EXT *)vio)->mysql_change_user)
  {
    /*
      in mysql_change_user() the client sends the first packet.
      we use the old scramble.
    */
    pkt= (uchar*)mysql->scramble;
    pkt_len= SCRAMBLE_LENGTH + 1;
  }
  else
  {
    /* read the scramble */
    if ((pkt_len= vio->read_packet(vio, &pkt)) < 0)
4479
      DBUG_RETURN(CR_ERROR);
4480 4481

    if (pkt_len != SCRAMBLE_LENGTH + 1)
4482
      DBUG_RETURN(CR_SERVER_HANDSHAKE_ERR);
4483 4484 4485 4486 4487 4488 4489 4490 4491

    /* save it in MYSQL */
    memcpy(mysql->scramble, pkt, SCRAMBLE_LENGTH);
    mysql->scramble[SCRAMBLE_LENGTH] = 0;
  }

  if (mysql->passwd[0])
  {
    char scrambled[SCRAMBLE_LENGTH + 1];
4492
    DBUG_PRINT("info", ("sending scramble"));
4493 4494
    scramble(scrambled, (char*)pkt, mysql->passwd);
    if (vio->write_packet(vio, (uchar*)scrambled, SCRAMBLE_LENGTH))
4495
      DBUG_RETURN(CR_ERROR);
4496 4497 4498
  }
  else
  {
4499
    DBUG_PRINT("info", ("no password"));
4500
    if (vio->write_packet(vio, 0, 0)) /* no password */
4501
      DBUG_RETURN(CR_ERROR);
4502 4503
  }

4504
  DBUG_RETURN(CR_OK);
4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515
}

/**
  client authentication plugin that does old MySQL authentication
  using an 8-byte (4.0-) scramble
*/
static int old_password_auth_client(MYSQL_PLUGIN_VIO *vio, MYSQL *mysql)
{
  uchar *pkt;
  int pkt_len;

4516
  DBUG_ENTER("old_password_auth_client");
4517 4518 4519 4520 4521 4522 4523 4524 4525 4526 4527 4528 4529 4530

  if (((MCPVIO_EXT *)vio)->mysql_change_user)
  {
    /*
      in mysql_change_user() the client sends the first packet.
      we use the old scramble.
    */
    pkt= (uchar*)mysql->scramble;
    pkt_len= SCRAMBLE_LENGTH_323 + 1;
  }
  else
  {
    /* read the scramble */
    if ((pkt_len= vio->read_packet(vio, &pkt)) < 0)
4531
      DBUG_RETURN(CR_ERROR);
4532 4533 4534

    if (pkt_len != SCRAMBLE_LENGTH_323 + 1 &&
        pkt_len != SCRAMBLE_LENGTH + 1)
4535
        DBUG_RETURN(CR_SERVER_HANDSHAKE_ERR);
4536

4537
    /* save it in MYSQL */
Sergei Golubchik's avatar
Sergei Golubchik committed
4538
    memmove(mysql->scramble, pkt, pkt_len - 1);
4539
    mysql->scramble[pkt_len - 1] = 0;
4540 4541 4542 4543 4544 4545 4546
  }

  if (mysql->passwd[0])
  {
    char scrambled[SCRAMBLE_LENGTH_323 + 1];
    scramble_323(scrambled, (char*)pkt, mysql->passwd);
    if (vio->write_packet(vio, (uchar*)scrambled, SCRAMBLE_LENGTH_323 + 1))
4547
      DBUG_RETURN(CR_ERROR);
4548 4549 4550
  }
  else
    if (vio->write_packet(vio, 0, 0)) /* no password */
4551
      DBUG_RETURN(CR_ERROR);
4552

4553
  DBUG_RETURN(CR_OK);
4554
}
4555

4556 4557 4558 4559 4560 4561

my_socket STDCALL
mysql_get_socket(const MYSQL *mysql)
{
  if (mysql->net.vio)
    return mysql->net.vio->sd;
4562
  return INVALID_SOCKET;
4563
}