protocol.cc 30.9 KB
Newer Older
unknown's avatar
unknown committed
1
/* Copyright (C) 2000-2003 MySQL AB
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21

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

   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
   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA */

/*
  Low level functions for storing data to be send to the MySQL client
  The actual communction is handled by the net_xxx functions in net_serv.cc
*/

22
#ifdef USE_PRAGMA_IMPLEMENTATION
23 24 25 26
#pragma implementation				// gcc: Class implementation
#endif

#include "mysql_priv.h"
27
#include "sp_rcontext.h"
28 29
#include <stdarg.h>

30 31
static const unsigned int PACKET_BUFFER_EXTRA_ALLOC= 1024;

unknown's avatar
SCRUM  
unknown committed
32 33
#ifndef EMBEDDED_LIBRARY
bool Protocol::net_store_data(const char *from, uint length)
unknown's avatar
SCRUM  
unknown committed
34 35 36
#else
bool Protocol_prep::net_store_data(const char *from, uint length)
#endif
unknown's avatar
SCRUM  
unknown committed
37 38
{
  ulong packet_length=packet->length();
unknown's avatar
unknown committed
39 40 41 42 43 44
  /* 
     The +9 comes from that strings of length longer than 16M require
     9 bytes to be stored (see net_store_length).
  */
  if (packet_length+9+length > packet->alloced_length() &&
      packet->realloc(packet_length+9+length))
unknown's avatar
SCRUM  
unknown committed
45 46 47 48 49 50 51 52 53
    return 1;
  char *to=(char*) net_store_length((char*) packet->ptr()+packet_length,
				    (ulonglong) length);
  memcpy(to,from,length);
  packet->length((uint) (to+length-packet->ptr()));
  return 0;
}


54 55
	/* Send a error string to client */

56
void net_send_error(THD *thd, uint sql_errno, const char *err)
57
{
58
#ifndef EMBEDDED_LIBRARY 
59
  uint length;
60
  char buff[MYSQL_ERRMSG_SIZE+2], *pos;
61
#endif
62
  NET *net= &thd->net;
unknown's avatar
unknown committed
63
  bool generate_warning= thd->killed != THD::KILL_CONNECTION;
64
  DBUG_ENTER("net_send_error");
65 66 67 68
  DBUG_PRINT("enter",("sql_errno: %d  err: %s", sql_errno,
		      err ? err : net->last_error[0] ?
		      net->last_error : "NULL"));

69 70 71 72 73 74
  if (net && net->no_send_error)
  {
    thd->clear_error();
    DBUG_PRINT("info", ("sending error messages prohibited"));
    DBUG_VOID_RETURN;
  }
unknown's avatar
unknown committed
75 76
  if (thd->spcont && thd->spcont->find_handler(sql_errno,
                                               MYSQL_ERROR::WARN_LEVEL_ERROR))
77 78 79
  {
    DBUG_VOID_RETURN;
  }
80 81 82 83 84 85 86 87
  thd->query_error=  1; // needed to catch query errors during replication
  if (!err)
  {
    if (sql_errno)
      err=ER(sql_errno);
    else
    {
      if ((err=net->last_error)[0])
88
      {
89
	sql_errno=net->last_errno;
90 91
        generate_warning= 0;            // This warning has already been given
      }
92 93 94 95 96 97
      else
      {
	sql_errno=ER_UNKNOWN_ERROR;
	err=ER(sql_errno);	 /* purecov: inspected */
      }
    }
98 99 100 101 102 103
  }

  if (generate_warning)
  {
    /* Error that we have not got with my_error() */
    push_warning(thd, MYSQL_ERROR::WARN_LEVEL_ERROR, sql_errno, err);
104
  }
unknown's avatar
unknown committed
105 106 107 108

#ifdef EMBEDDED_LIBRARY
  net->last_errno= sql_errno;
  strmake(net->last_error, err, sizeof(net->last_error)-1);
109
  strmov(net->sqlstate, mysql_errno_to_sqlstate(sql_errno));
unknown's avatar
unknown committed
110 111
#else

112 113 114 115 116 117 118 119 120 121 122 123 124
  if (net->vio == 0)
  {
    if (thd->bootstrap)
    {
      /* In bootstrap it's ok to print on stderr */
      fprintf(stderr,"ERROR: %d  %s\n",sql_errno,err);
    }
    DBUG_VOID_RETURN;
  }

  if (net->return_errno)
  {				// new client code; Add errno before message
    int2store(buff,sql_errno);
125 126 127 128
    pos= buff+2;
    if (thd->client_capabilities & CLIENT_PROTOCOL_41)
    {
      /* The first # is to make the protocol backward compatible */
129
      buff[2]= '#';
130
      pos= strmov(buff+3, mysql_errno_to_sqlstate(sql_errno));
131 132
    }
    length= (uint) (strmake(pos, err, MYSQL_ERRMSG_SIZE-1) - buff);
133 134 135 136 137 138 139 140
    err=buff;
  }
  else
  {
    length=(uint) strlen(err);
    set_if_smaller(length,MYSQL_ERRMSG_SIZE-1);
  }
  VOID(net_write_command(net,(uchar) 255, "", 0, (char*) err,length));
unknown's avatar
unknown committed
141
#endif  /* EMBEDDED_LIBRARY*/
142
  thd->is_fatal_error=0;			// Error message is given
143
  thd->net.report_error= 0;
144 145

  /* Abort multi-result sets */
146
  thd->server_status&= ~SERVER_MORE_RESULTS_EXISTS;
147 148 149 150 151 152 153 154 155 156
  DBUG_VOID_RETURN;
}

/*
   Write error package and flush to client
   It's a little too low level, but I don't want to use another buffer for
   this
*/

void
157
net_printf_error(THD *thd, uint errcode, ...)
158 159 160
{
  va_list args;
  uint length,offset;
unknown's avatar
unknown committed
161 162 163
  const char *format;
#ifndef EMBEDDED_LIBRARY
  const char *text_pos;
unknown's avatar
unknown committed
164
  int head_length= NET_HEADER_SIZE;
unknown's avatar
unknown committed
165
#else
166
  char text_pos[1024];
unknown's avatar
unknown committed
167
#endif
168
  NET *net= &thd->net;
unknown's avatar
unknown committed
169

170
  DBUG_ENTER("net_printf_error");
171 172
  DBUG_PRINT("enter",("message: %u",errcode));

173 174 175 176 177 178 179
  if (net && net->no_send_error)
  {
    thd->clear_error();
    DBUG_PRINT("info", ("sending error messages prohibited"));
    DBUG_VOID_RETURN;
  }

unknown's avatar
unknown committed
180 181
  if (thd->spcont && thd->spcont->find_handler(errcode,
                                               MYSQL_ERROR::WARN_LEVEL_ERROR))
182 183 184
  {
    DBUG_VOID_RETURN;
  }
185
  thd->query_error=  1; // needed to catch query errors during replication
unknown's avatar
unknown committed
186
#ifndef EMBEDDED_LIBRARY
187
  query_cache_abort(net);	// Safety
unknown's avatar
unknown committed
188
#endif
189 190
  va_start(args,errcode);
  /*
191 192
    The following is needed to make net_printf_error() work with 0 argument
    for errorcode and use the argument after that as the format string. This
193 194 195 196 197 198 199 200 201 202
    is useful for rare errors that are not worth the hassle to put in
    errmsg.sys, but at the same time, the message is not fixed text
  */
  if (errcode)
    format= ER(errcode);
  else
  {
    format=va_arg(args,char*);
    errcode= ER_UNKNOWN_ERROR;
  }
203 204 205
  offset= (net->return_errno ?
	   ((thd->client_capabilities & CLIENT_PROTOCOL_41) ?
	    2+SQLSTATE_LENGTH+1 : 2) : 0);
unknown's avatar
unknown committed
206
#ifndef EMBEDDED_LIBRARY
207
  text_pos=(char*) net->buff + head_length + offset + 1;
unknown's avatar
unknown committed
208
  length= (uint) ((char*)net->buff_end - text_pos);
unknown's avatar
unknown committed
209 210
#else
  length=sizeof(text_pos)-1;
unknown's avatar
unknown committed
211
#endif
unknown's avatar
unknown committed
212 213
  length=my_vsnprintf(my_const_cast(char*) (text_pos),
                      min(length, sizeof(net->last_error)),
unknown's avatar
unknown committed
214
                      format,args);
215 216
  va_end(args);

unknown's avatar
unknown committed
217 218 219 220
  /* Replication slave relies on net->last_* to see if there was error */
  net->last_errno= errcode;
  strmake(net->last_error, text_pos, sizeof(net->last_error)-1);

unknown's avatar
unknown committed
221
#ifndef EMBEDDED_LIBRARY
222 223 224 225
  if (net->vio == 0)
  {
    if (thd->bootstrap)
    {
unknown's avatar
unknown committed
226 227 228 229
      /*
	In bootstrap it's ok to print on stderr
	This may also happen when we get an error from a slave thread
      */
230
      fprintf(stderr,"ERROR: %d  %s\n",errcode,text_pos);
231
      thd->fatal_error();
232 233 234 235 236 237 238 239
    }
    DBUG_VOID_RETURN;
  }

  int3store(net->buff,length+1+offset);
  net->buff[3]= (net->compress) ? 0 : (uchar) (net->pkt_nr++);
  net->buff[head_length]=(uchar) 255;		// Error package
  if (offset)
240 241 242 243 244
  {
    uchar *pos= net->buff+head_length+1;
    int2store(pos, errcode);
    if (thd->client_capabilities & CLIENT_PROTOCOL_41)
    {
245 246
      pos[2]= '#';      /* To make the protocol backward compatible */
      memcpy(pos+3, mysql_errno_to_sqlstate(errcode), SQLSTATE_LENGTH);
247 248
    }
  }
249
  VOID(net_real_write(net,(char*) net->buff,length+head_length+1+offset));
unknown's avatar
unknown committed
250 251 252
#else
  net->last_errno= errcode;
  strmake(net->last_error, text_pos, length);
253
  strmake(net->sqlstate, mysql_errno_to_sqlstate(errcode), SQLSTATE_LENGTH);
unknown's avatar
unknown committed
254
#endif
unknown's avatar
unknown committed
255
  if (thd->killed != THD::KILL_CONNECTION)
unknown's avatar
unknown committed
256 257
    push_warning(thd, MYSQL_ERROR::WARN_LEVEL_ERROR, errcode,
                 text_pos ? text_pos : ER(errcode));
258
  thd->is_fatal_error=0;			// Error message is given
259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287
  DBUG_VOID_RETURN;
}

/*
  Return ok to the client.

  SYNOPSIS
    send_ok()
    thd			Thread handler
    affected_rows	Number of rows changed by statement
    id			Auto_increment id for first row (if used)
    message		Message to send to the client (Used by mysql_status)

  DESCRIPTION
    The ok packet has the following structure

    0			Marker (1 byte)
    affected_rows	Stored in 1-9 bytes
    id			Stored in 1-9 bytes
    server_status	Copy of thd->server_status;  Can be used by client
			to check if we are inside an transaction
			New in 4.0 protocol
    warning_count	Stored in 2 bytes; New in 4.1 protocol
    message		Stored as packed length (1-9 bytes) + message
			Is not stored if no message

   If net->no_send_ok return without sending packet
*/    

288
#ifndef EMBEDDED_LIBRARY
289 290 291 292 293 294
void
send_ok(THD *thd, ha_rows affected_rows, ulonglong id, const char *message)
{
  NET *net= &thd->net;
  char buff[MYSQL_ERRMSG_SIZE+10],*pos;
  DBUG_ENTER("send_ok");
295 296

  if (net->no_send_ok || !net->vio)	// hack for re-parsing queries
297 298 299 300
  {
    DBUG_PRINT("info", ("no send ok: %s, vio present: %s",
                        (net->no_send_ok ? "YES" : "NO"),
                        (net->vio ? "YES" : "NO")));
301
    DBUG_VOID_RETURN;
302
  }
303

304 305 306 307 308
  buff[0]=0;					// No fields
  pos=net_store_length(buff+1,(ulonglong) affected_rows);
  pos=net_store_length(pos, (ulonglong) id);
  if (thd->client_capabilities & CLIENT_PROTOCOL_41)
  {
309 310 311 312 313 314
    DBUG_PRINT("info",
	       ("affected_rows: %lu  id: %lu  status: %u  warning_count: %u",
		(ulong) affected_rows,		
		(ulong) id,
		(uint) (thd->server_status & 0xffff),
		(uint) thd->total_warn_count));
315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331
    int2store(pos,thd->server_status);
    pos+=2;

    /* We can only return up to 65535 warnings in two bytes */
    uint tmp= min(thd->total_warn_count, 65535);
    int2store(pos, tmp);
    pos+= 2;
  }
  else if (net->return_status)			// For 4.0 protocol
  {
    int2store(pos,thd->server_status);
    pos+=2;
  }
  if (message)
    pos=net_store_data((char*) pos, message, strlen(message));
  VOID(my_net_write(net,buff,(uint) (pos-buff)));
  VOID(net_flush(net));
unknown's avatar
unknown committed
332 333
  /* We can't anymore send an error to the client */
  thd->net.report_error= 0;
334
  thd->net.no_send_error= 1;
335
  DBUG_PRINT("info", ("OK sent, so no more error sending allowed"));
336

337 338 339
  DBUG_VOID_RETURN;
}

340
static char eof_buff[1]= { (char) 254 };        /* Marker for end of fields */
341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368

/*
  Send eof (= end of result set) to the client

  SYNOPSIS
    send_eof()
    thd			Thread handler
    no_flush		Set to 1 if there will be more data to the client,
			like in send_fields().

  DESCRIPTION
    The eof packet has the following structure

    254			Marker (1 byte)
    warning_count	Stored in 2 bytes; New in 4.1 protocol
    status_flag		Stored in 2 bytes;
			For flags like SERVER_STATUS_MORE_RESULTS

    Note that the warning count will not be sent if 'no_flush' is set as
    we don't want to report the warning count until all data is sent to the
    client.
*/    

void
send_eof(THD *thd, bool no_flush)
{
  NET *net= &thd->net;
  DBUG_ENTER("send_eof");
369
  if (net->vio != 0 && !net->no_send_eof)
370
  {
371
    if (thd->client_capabilities & CLIENT_PROTOCOL_41)
372 373
    {
      uchar buff[5];
374 375 376
      /* Don't send warn count during SP execution, as the warn_list
         is cleared between substatements, and mysqltest gets confused */
      uint tmp= (thd->spcont ? 0 : min(thd->total_warn_count, 65535));
377 378
      buff[0]=254;
      int2store(buff+1, tmp);
379 380 381 382 383 384
      /*
	The following test should never be true, but it's better to do it
	because if 'is_fatal_error' is set the server is not going to execute
	other queries (see the if test in dispatch_command / COM_QUERY)
      */
      if (thd->is_fatal_error)
385
	thd->server_status&= ~SERVER_MORE_RESULTS_EXISTS;
386
      int2store(buff+3, thd->server_status);
387 388 389 390 391 392 393 394 395
      VOID(my_net_write(net,(char*) buff,5));
      VOID(net_flush(net));
    }
    else
    {
      VOID(my_net_write(net,eof_buff,1));
      if (!no_flush)
	VOID(net_flush(net));
    }
396
    thd->net.no_send_error= 1;
397
    DBUG_PRINT("info", ("EOF sent, so no more error sending allowed"));
398 399 400
  }
  DBUG_VOID_RETURN;
}
401 402 403 404 405 406 407 408 409 410 411 412 413 414 415

/*
    Please client to send scrambled_password in old format.
  SYNOPSYS
    send_old_password_request()
    thd thread handle
     
  RETURN VALUE
    0  ok
   !0  error
*/

bool send_old_password_request(THD *thd)
{
  NET *net= &thd->net;
416
  return my_net_write(net, eof_buff, 1) || net_flush(net);
417 418
}

unknown's avatar
unknown committed
419
#endif /* EMBEDDED_LIBRARY */
420 421

/*
422 423 424 425 426 427 428
  Faster net_store_length when we know that length is less than 65536.
  We keep a separate version for that range because it's widely used in
  libmysql.
  uint is used as agrument type because of MySQL type conventions:
  uint for 0..65536
  ulong for 0..4294967296
  ulonglong for bigger numbers.
429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485
*/

char *net_store_length(char *pkg, uint length)
{
  uchar *packet=(uchar*) pkg;
  if (length < 251)
  {
    *packet=(uchar) length;
    return (char*) packet+1;
  }
  *packet++=252;
  int2store(packet,(uint) length);
  return (char*) packet+2;
}


/****************************************************************************
  Functions used by the protocol functions (like send_ok) to store strings
  and numbers in the header result packet.
****************************************************************************/

/* The following will only be used for short strings < 65K */

char *net_store_data(char *to,const char *from, uint length)
{
  to=net_store_length(to,length);
  memcpy(to,from,length);
  return to+length;
}

char *net_store_data(char *to,int32 from)
{
  char buff[20];
  uint length=(uint) (int10_to_str(from,buff,10)-buff);
  to=net_store_length(to,length);
  memcpy(to,buff,length);
  return to+length;
}

char *net_store_data(char *to,longlong from)
{
  char buff[22];
  uint length=(uint) (longlong10_to_str(from,buff,10)-buff);
  to=net_store_length(to,length);
  memcpy(to,buff,length);
  return to+length;
}


/*****************************************************************************
  Default Protocol functions
*****************************************************************************/

void Protocol::init(THD *thd_arg)
{
  thd=thd_arg;
  packet= &thd->packet;
486
  convert= &thd->convert_buffer;
487 488 489 490 491
#ifndef DEBUG_OFF
  field_types= 0;
#endif
}

492

493 494 495 496 497 498 499 500 501
bool Protocol::flush()
{
#ifndef EMBEDDED_LIBRARY
  return net_flush(&thd->net);
#else
  return 0;
#endif
}

502 503 504 505 506 507 508 509 510 511
/*
  Send name and type of result to client.

  SYNOPSIS
    send_fields()
    THD		Thread data object
    list	List of items to send to client
    flag	Bit mask with the following functions:
		1 send number of rows
		2 send default values
512
                4 don't write eof packet
513 514 515 516 517 518 519 520 521

  DESCRIPTION
    Sum fields has table name empty and field_name.

  RETURN VALUES
    0	ok
    1	Error  (Note that in this case the error is not sent to the client)
*/

unknown's avatar
unknown committed
522
#ifndef EMBEDDED_LIBRARY
unknown's avatar
unknown committed
523
bool Protocol::send_fields(List<Item> *list, uint flags)
524 525 526 527
{
  List_iterator_fast<Item> it(*list);
  Item *item;
  char buff[80];
unknown's avatar
unknown committed
528
  String tmp((char*) buff,sizeof(buff),&my_charset_bin);
529
  Protocol_simple prot(thd);
530
  String *local_packet= prot.storage_packet();
531
  CHARSET_INFO *thd_charset= thd->variables.character_set_results;
532 533
  DBUG_ENTER("send_fields");

534
  if (flags & SEND_NUM_ROWS)
535 536 537 538 539 540 541 542 543 544 545 546 547 548
  {				// Packet with number of elements
    char *pos=net_store_length(buff, (uint) list->elements);
    (void) my_net_write(&thd->net, buff,(uint) (pos-buff));
  }

#ifndef DEBUG_OFF
  field_types= (enum_field_types*) thd->alloc(sizeof(field_types) *
					      list->elements);
  uint count= 0;
#endif

  while ((item=it++))
  {
    char *pos;
549
    CHARSET_INFO *cs= system_charset_info;
550 551
    Send_field field;
    item->make_field(&field);
552 553 554 555 556

    /* Keep things compatible for old clients */
    if (field.type == MYSQL_TYPE_VARCHAR)
      field.type= MYSQL_TYPE_VAR_STRING;

557 558 559 560
    prot.prepare_for_resend();

    if (thd->client_capabilities & CLIENT_PROTOCOL_41)
    {
561
      if (prot.store("def", 3, cs, thd_charset) ||
562 563
	  prot.store(field.db_name, (uint) strlen(field.db_name),
		     cs, thd_charset) ||
564
	  prot.store(field.table_name, (uint) strlen(field.table_name),
565
		     cs, thd_charset) ||
566
	  prot.store(field.org_table_name, (uint) strlen(field.org_table_name),
567
		     cs, thd_charset) ||
568
	  prot.store(field.col_name, (uint) strlen(field.col_name),
569
		     cs, thd_charset) ||
570
	  prot.store(field.org_col_name, (uint) strlen(field.org_col_name),
571
		     cs, thd_charset) ||
572
	  local_packet->realloc(local_packet->length()+12))
573
	goto err;
574
      /* Store fixed length fields */
575
      pos= (char*) local_packet->ptr()+local_packet->length();
576
      *pos++= 12;				// Length of packed fields
unknown's avatar
unknown committed
577
      if (item->collation.collation == &my_charset_bin || thd_charset == NULL)
578 579
      {
        /* No conversion */
unknown's avatar
unknown committed
580
        int2store(pos, field.charsetnr);
581 582
        int4store(pos+2, field.length);
      }
unknown's avatar
unknown committed
583
      else
584 585 586 587 588 589
      {
        /* With conversion */
        int2store(pos, thd_charset->number);
        uint char_len= field.length / item->collation.collation->mbmaxlen;
        int4store(pos+2, char_len * thd_charset->mbmaxlen);
      }
590 591 592
      pos[6]= field.type;
      int2store(pos+7,field.flags);
      pos[9]= (char) field.decimals;
593
      pos[10]= 0;				// For the future
594 595
      pos[11]= 0;				// For the future
      pos+= 12;
596 597 598
    }
    else
    {
599
      if (prot.store(field.table_name, (uint) strlen(field.table_name),
600
		     cs, thd_charset) ||
601
	  prot.store(field.col_name, (uint) strlen(field.col_name),
602
		     cs, thd_charset) ||
603
	  local_packet->realloc(local_packet->length()+10))
604
	goto err;
605
      pos= (char*) local_packet->ptr()+local_packet->length();
606 607

#ifdef TO_BE_DELETED_IN_6
608 609 610 611 612 613 614 615 616 617 618 619
      if (!(thd->client_capabilities & CLIENT_LONG_FLAG))
      {
	pos[0]=3;
	int3store(pos+1,field.length);
	pos[4]=1;
	pos[5]=field.type;
	pos[6]=2;
	pos[7]= (char) field.flags;
	pos[8]= (char) field.decimals;
	pos+= 9;
      }
      else
620
#endif
621 622 623 624 625 626 627 628 629 630
      {
	pos[0]=3;
	int3store(pos+1,field.length);
	pos[4]=1;
	pos[5]=field.type;
	pos[6]=3;
	int2store(pos+7,field.flags);
	pos[9]= (char) field.decimals;
	pos+= 10;
      }
631
    }
632
    local_packet->length((uint) (pos - local_packet->ptr()));
633
    if (flags & SEND_DEFAULTS)
634 635 636 637 638 639 640 641
      item->send(&prot, &tmp);			// Send default value
    if (prot.write())
      break;					/* purecov: inspected */
#ifndef DEBUG_OFF
    field_types[count++]= field.type;
#endif
  }

642 643
  if (flags & SEND_EOF)
    my_net_write(&thd->net, eof_buff, 1);
644 645 646
  DBUG_RETURN(prepare_for_send(list));

err:
unknown's avatar
unknown committed
647 648
  my_message(ER_OUT_OF_RESOURCES, ER(ER_OUT_OF_RESOURCES),
             MYF(0));	/* purecov: inspected */
649 650 651
  DBUG_RETURN(1);				/* purecov: inspected */
}

652

653 654 655
bool Protocol::write()
{
  DBUG_ENTER("Protocol::write");
unknown's avatar
SCRUM  
unknown committed
656
  DBUG_RETURN(my_net_write(&thd->net, packet->ptr(), packet->length()));
657
}
unknown's avatar
SCRUM  
unknown committed
658 659 660
#endif /* EMBEDDED_LIBRARY */


661 662 663 664 665 666 667 668 669 670 671 672 673 674 675
/*
  Send \0 end terminated string

  SYNOPSIS
    store()
    from	NullS or \0 terminated string

  NOTES
    In most cases one should use store(from, length) instead of this function

  RETURN VALUES
    0		ok
    1		error
*/

676
bool Protocol::store(const char *from, CHARSET_INFO *cs)
677 678 679 680
{
  if (!from)
    return store_null();
  uint length= strlen(from);
681
  return store(from, length, cs);
682 683 684 685 686 687 688 689 690 691
}


/*
  Send a set of strings as one long string with ',' in between
*/

bool Protocol::store(I_List<i_string>* str_list)
{
  char buf[256];
unknown's avatar
unknown committed
692
  String tmp(buf, sizeof(buf), &my_charset_bin);
693
  uint32 len;
694 695 696
  I_List_iterator<i_string> it(*str_list);
  i_string* s;

697
  tmp.length(0);
698 699 700
  while ((s=it++))
  {
    tmp.append(s->ptr);
701
    tmp.append(',');
702
  }
703 704
  if ((len= tmp.length()))
    len--;					// Remove last ','
705
  return store((char*) tmp.ptr(), len,  tmp.charset());
706 707 708 709 710 711 712 713 714 715 716
}


/****************************************************************************
  Functions to handle the simple (default) protocol where everything is
  This protocol is the one that is used by default between the MySQL server
  and client when you are not using prepared statements.

  All data are sent as 'packed-string-length' followed by 'string-data'
****************************************************************************/

unknown's avatar
SCRUM  
unknown committed
717
#ifndef EMBEDDED_LIBRARY
718 719 720 721 722 723 724 725 726 727 728 729 730 731
void Protocol_simple::prepare_for_resend()
{
  packet->length(0);
#ifndef DEBUG_OFF
  field_pos= 0;
#endif
}

bool Protocol_simple::store_null()
{
#ifndef DEBUG_OFF
  field_pos++;
#endif
  char buff[1];
unknown's avatar
unknown committed
732
  buff[0]= (char)251;
733
  return packet->append(buff, sizeof(buff), PACKET_BUFFER_EXTRA_ALLOC);
734
}
unknown's avatar
SCRUM  
unknown committed
735
#endif
736

737

738 739 740 741 742 743 744 745 746 747 748 749 750
/*
  Auxilary function to convert string to the given character set
  and store in network buffer.
*/

bool Protocol::store_string_aux(const char *from, uint length,
                                CHARSET_INFO *fromcs, CHARSET_INFO *tocs)
{
  /* 'tocs' is set 0 when client issues SET character_set_results=NULL */
  if (tocs && !my_charset_same(fromcs, tocs) &&
      fromcs != &my_charset_bin &&
      tocs != &my_charset_bin)
  {
751 752
    uint dummy_errors;
    return convert->copy(from, length, fromcs, tocs, &dummy_errors) ||
753 754 755 756 757 758
           net_store_data(convert->ptr(), convert->length());
  }
  return net_store_data(from, length);
}


759 760
bool Protocol_simple::store(const char *from, uint length,
			    CHARSET_INFO *fromcs, CHARSET_INFO *tocs)
761 762 763
{
#ifndef DEBUG_OFF
  DBUG_ASSERT(field_types == 0 ||
764
	      field_types[field_pos] == MYSQL_TYPE_DECIMAL ||
unknown's avatar
unknown committed
765
              field_types[field_pos] == MYSQL_TYPE_BIT ||
unknown's avatar
unknown committed
766
              field_types[field_pos] == MYSQL_TYPE_NEWDECIMAL ||
767 768
	      (field_types[field_pos] >= MYSQL_TYPE_ENUM &&
	       field_types[field_pos] <= MYSQL_TYPE_GEOMETRY));
769 770
  field_pos++;
#endif
771
  return store_string_aux(from, length, fromcs, tocs);
772 773 774 775 776 777
}


bool Protocol_simple::store(const char *from, uint length,
			    CHARSET_INFO *fromcs)
{
778
  CHARSET_INFO *tocs= this->thd->variables.character_set_results;
779 780 781
#ifndef DEBUG_OFF
  DBUG_ASSERT(field_types == 0 ||
	      field_types[field_pos] == MYSQL_TYPE_DECIMAL ||
unknown's avatar
unknown committed
782
              field_types[field_pos] == MYSQL_TYPE_BIT ||
unknown's avatar
unknown committed
783
              field_types[field_pos] == MYSQL_TYPE_NEWDECIMAL ||
784 785 786 787
	      (field_types[field_pos] >= MYSQL_TYPE_ENUM &&
	       field_types[field_pos] <= MYSQL_TYPE_GEOMETRY));
  field_pos++;
#endif
788
  return store_string_aux(from, length, fromcs, tocs);
789 790 791 792 793 794
}


bool Protocol_simple::store_tiny(longlong from)
{
#ifndef DEBUG_OFF
unknown's avatar
unknown committed
795 796
  DBUG_ASSERT(field_types == 0 || field_types[field_pos] == MYSQL_TYPE_TINY);
  field_pos++;
797 798
#endif
  char buff[20];
unknown's avatar
SCRUM  
unknown committed
799
  return net_store_data((char*) buff,
800 801 802
			(uint) (int10_to_str((int) from,buff, -10)-buff));
}

803

804 805 806 807
bool Protocol_simple::store_short(longlong from)
{
#ifndef DEBUG_OFF
  DBUG_ASSERT(field_types == 0 ||
unknown's avatar
unknown committed
808
	      field_types[field_pos] == MYSQL_TYPE_YEAR ||
unknown's avatar
unknown committed
809 810
	      field_types[field_pos] == MYSQL_TYPE_SHORT);
  field_pos++;
811 812
#endif
  char buff[20];
unknown's avatar
SCRUM  
unknown committed
813
  return net_store_data((char*) buff,
814 815 816
			(uint) (int10_to_str((int) from,buff, -10)-buff));
}

817

818 819 820
bool Protocol_simple::store_long(longlong from)
{
#ifndef DEBUG_OFF
unknown's avatar
unknown committed
821 822 823 824
  DBUG_ASSERT(field_types == 0 ||
              field_types[field_pos] == MYSQL_TYPE_INT24 ||
              field_types[field_pos] == MYSQL_TYPE_LONG);
  field_pos++;
825 826
#endif
  char buff[20];
unknown's avatar
SCRUM  
unknown committed
827
  return net_store_data((char*) buff,
828
			(uint) (int10_to_str((long int)from,buff, (from <0)?-10:10)-buff));
829 830 831 832 833 834 835
}


bool Protocol_simple::store_longlong(longlong from, bool unsigned_flag)
{
#ifndef DEBUG_OFF
  DBUG_ASSERT(field_types == 0 ||
unknown's avatar
unknown committed
836 837
	      field_types[field_pos] == MYSQL_TYPE_LONGLONG);
  field_pos++;
838 839
#endif
  char buff[22];
unknown's avatar
SCRUM  
unknown committed
840
  return net_store_data((char*) buff,
841 842 843 844 845 846
			(uint) (longlong10_to_str(from,buff,
						  unsigned_flag ? 10 : -10)-
				buff));
}


unknown's avatar
unknown committed
847 848 849 850 851 852 853
bool Protocol_simple::store_decimal(const my_decimal *d)
{
#ifndef DEBUG_OFF
  DBUG_ASSERT(field_types == 0 ||
              field_types[field_pos] == MYSQL_TYPE_NEWDECIMAL);
  field_pos++;
#endif
854 855 856
  char buff[DECIMAL_MAX_STR_LENGTH];
  String str(buff, sizeof(buff), &my_charset_bin);
  (void) my_decimal2string(E_DEC_FATAL_ERROR, d, 0, 0, 0, &str);
unknown's avatar
unknown committed
857 858 859 860
  return net_store_data(str.ptr(), str.length());
}


861 862 863 864
bool Protocol_simple::store(float from, uint32 decimals, String *buffer)
{
#ifndef DEBUG_OFF
  DBUG_ASSERT(field_types == 0 ||
unknown's avatar
unknown committed
865 866
	      field_types[field_pos] == MYSQL_TYPE_FLOAT);
  field_pos++;
867
#endif
868
  buffer->set((double) from, decimals, thd->charset());
unknown's avatar
SCRUM  
unknown committed
869
  return net_store_data((char*) buffer->ptr(), buffer->length());
870 871
}

872

873 874 875 876
bool Protocol_simple::store(double from, uint32 decimals, String *buffer)
{
#ifndef DEBUG_OFF
  DBUG_ASSERT(field_types == 0 ||
unknown's avatar
unknown committed
877 878
	      field_types[field_pos] == MYSQL_TYPE_DOUBLE);
  field_pos++;
879
#endif
880
  buffer->set(from, decimals, thd->charset());
unknown's avatar
SCRUM  
unknown committed
881
  return net_store_data((char*) buffer->ptr(), buffer->length());
882 883 884 885 886
}


bool Protocol_simple::store(Field *field)
{
887 888
  if (field->is_null())
    return store_null();
889 890 891 892
#ifndef DEBUG_OFF
  field_pos++;
#endif
  char buff[MAX_FIELD_WIDTH];
893
  String str(buff,sizeof(buff), &my_charset_bin);
894 895
  CHARSET_INFO *tocs= this->thd->variables.character_set_results;

896
  field->val_str(&str);
897
  return store_string_aux(str.ptr(), str.length(), str.charset(), tocs);
898 899 900
}


unknown's avatar
unknown committed
901 902 903 904 905 906 907
/*
   TODO:
        Second_part format ("%06") needs to change when 
        we support 0-6 decimals for time.
*/


908 909 910 911
bool Protocol_simple::store(TIME *tm)
{
#ifndef DEBUG_OFF
  DBUG_ASSERT(field_types == 0 ||
912 913 914
	      field_types[field_pos] == MYSQL_TYPE_DATETIME ||
	      field_types[field_pos] == MYSQL_TYPE_TIMESTAMP);
  field_pos++;
915 916
#endif
  char buff[40];
917 918 919 920 921 922 923 924 925 926 927
  uint length;
  length= my_sprintf(buff,(buff, "%04d-%02d-%02d %02d:%02d:%02d",
			   (int) tm->year,
			   (int) tm->month,
			   (int) tm->day,
			   (int) tm->hour,
			   (int) tm->minute,
			   (int) tm->second));
  if (tm->second_part)
    length+= my_sprintf(buff+length,(buff+length, ".%06d", (int)tm->second_part));
  return net_store_data((char*) buff, length);
928 929 930 931 932 933 934
}


bool Protocol_simple::store_date(TIME *tm)
{
#ifndef DEBUG_OFF
  DBUG_ASSERT(field_types == 0 ||
unknown's avatar
unknown committed
935 936
	      field_types[field_pos] == MYSQL_TYPE_DATE);
  field_pos++;
937
#endif
938 939 940
  char buff[MAX_DATE_STRING_REP_LENGTH];
  int length= my_date_to_str(tm, buff);
  return net_store_data(buff, (uint) length);
941 942 943
}


unknown's avatar
unknown committed
944 945 946 947 948 949
/*
   TODO:
        Second_part format ("%06") needs to change when 
        we support 0-6 decimals for time.
*/

950 951 952 953
bool Protocol_simple::store_time(TIME *tm)
{
#ifndef DEBUG_OFF
  DBUG_ASSERT(field_types == 0 ||
unknown's avatar
unknown committed
954 955
	      field_types[field_pos] == MYSQL_TYPE_TIME);
  field_pos++;
956 957
#endif
  char buff[40];
958
  uint length;
959
  uint day= (tm->year || tm->month) ? 0 : tm->day;
960 961 962 963 964 965 966 967
  length= my_sprintf(buff,(buff, "%s%02ld:%02d:%02d",
			   tm->neg ? "-" : "",
			   (long) day*24L+(long) tm->hour,
			   (int) tm->minute,
			   (int) tm->second));
  if (tm->second_part)
    length+= my_sprintf(buff+length,(buff+length, ".%06d", (int)tm->second_part));
  return net_store_data((char*) buff, length);
968 969 970 971 972
}


/****************************************************************************
  Functions to handle the binary protocol used with prepared statements
unknown's avatar
unknown committed
973 974 975

  Data format:

976 977 978 979 980 981 982 983 984 985 986 987
   [ok:1]                            reserved ok packet
   [null_field:(field_count+7+2)/8]  reserved to send null data. The size is
                                     calculated using:
                                     bit_fields= (field_count+7+2)/8; 
                                     2 bits are reserved for identifying type
				     of package.
   [[length]data]                    data field (the length applies only for 
                                     string/binary/time/timestamp fields and 
                                     rest of them are not sent as they have 
                                     the default length that client understands
                                     based on the field type
   [..]..[[length]data]              data
988 989 990 991
****************************************************************************/

bool Protocol_prep::prepare_for_send(List<Item> *item_list)
{
unknown's avatar
SCRUM  
unknown committed
992
  Protocol::prepare_for_send(item_list);
unknown's avatar
unknown committed
993 994
  bit_fields= (field_count+9)/8;
  if (packet->alloc(bit_fields+1))
995 996 997 998 999 1000 1001 1002
    return 1;
  /* prepare_for_resend will be called after this one */
  return 0;
}


void Protocol_prep::prepare_for_resend()
{
unknown's avatar
unknown committed
1003 1004
  packet->length(bit_fields+1);
  bzero((char*) packet->ptr(), 1+bit_fields);
1005 1006 1007 1008
  field_pos=0;
}


1009
bool Protocol_prep::store(const char *from, uint length, CHARSET_INFO *fromcs)
1010
{
1011
  CHARSET_INFO *tocs= thd->variables.character_set_results;
1012
  field_pos++;
1013
  return store_string_aux(from, length, fromcs, tocs);
1014 1015
}

1016 1017 1018 1019
bool Protocol_prep::store(const char *from,uint length,
			  CHARSET_INFO *fromcs, CHARSET_INFO *tocs)
{
  field_pos++;
1020
  return store_string_aux(from, length, fromcs, tocs);
1021 1022
}

1023 1024
bool Protocol_prep::store_null()
{
unknown's avatar
unknown committed
1025
  uint offset= (field_pos+2)/8+1, bit= (1 << ((field_pos+2) & 7));
1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038
  /* Room for this as it's allocated in prepare_for_send */
  char *to= (char*) packet->ptr()+offset;
  *to= (char) ((uchar) *to | (uchar) bit);
  field_pos++;
  return 0;
}


bool Protocol_prep::store_tiny(longlong from)
{
  char buff[1];
  field_pos++;
  buff[0]= (uchar) from;
1039
  return packet->append(buff, sizeof(buff), PACKET_BUFFER_EXTRA_ALLOC);
1040 1041 1042 1043 1044 1045
}


bool Protocol_prep::store_short(longlong from)
{
  field_pos++;
1046
  char *to= packet->prep_append(2, PACKET_BUFFER_EXTRA_ALLOC);
1047 1048 1049 1050 1051 1052 1053 1054 1055 1056
  if (!to)
    return 1;
  int2store(to, (int) from);
  return 0;
}


bool Protocol_prep::store_long(longlong from)
{
  field_pos++;
1057
  char *to= packet->prep_append(4, PACKET_BUFFER_EXTRA_ALLOC);
1058 1059 1060 1061 1062 1063 1064 1065 1066 1067
  if (!to)
    return 1;
  int4store(to, from);
  return 0;
}


bool Protocol_prep::store_longlong(longlong from, bool unsigned_flag)
{
  field_pos++;
1068
  char *to= packet->prep_append(8, PACKET_BUFFER_EXTRA_ALLOC);
1069 1070 1071 1072 1073 1074
  if (!to)
    return 1;
  int8store(to, from);
  return 0;
}

unknown's avatar
unknown committed
1075 1076 1077 1078 1079 1080 1081
bool Protocol_prep::store_decimal(const my_decimal *d)
{
#ifndef DEBUG_OFF
  DBUG_ASSERT(field_types == 0 ||
              field_types[field_pos] == MYSQL_TYPE_NEWDECIMAL);
  field_pos++;
#endif
1082 1083 1084
  char buff[DECIMAL_MAX_STR_LENGTH];
  String str(buff, sizeof(buff), &my_charset_bin);
  (void) my_decimal2string(E_DEC_FATAL_ERROR, d, 0, 0, 0, &str);
unknown's avatar
unknown committed
1085 1086
  return store(str.ptr(), str.length(), str.charset());
}
1087 1088 1089 1090

bool Protocol_prep::store(float from, uint32 decimals, String *buffer)
{
  field_pos++;
1091
  char *to= packet->prep_append(4, PACKET_BUFFER_EXTRA_ALLOC);
1092 1093 1094 1095 1096 1097 1098 1099 1100 1101
  if (!to)
    return 1;
  float4store(to, from);
  return 0;
}


bool Protocol_prep::store(double from, uint32 decimals, String *buffer)
{
  field_pos++;
1102
  char *to= packet->prep_append(8, PACKET_BUFFER_EXTRA_ALLOC);
1103 1104 1105 1106 1107 1108 1109 1110 1111 1112
  if (!to)
    return 1;
  float8store(to, from);
  return 0;
}


bool Protocol_prep::store(Field *field)
{
  /*
1113
    We should not increment field_pos here as send_binary() will call another
1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127
    protocol function to do this for us
  */
  if (field->is_null())
    return store_null();
  return field->send_binary(this);
}


bool Protocol_prep::store(TIME *tm)
{
  char buff[12],*pos;
  uint length;
  field_pos++;
  pos= buff+1;
unknown's avatar
unknown committed
1128

1129
  int2store(pos, tm->year);
1130 1131 1132 1133 1134
  pos[2]= (uchar) tm->month;
  pos[3]= (uchar) tm->day;
  pos[4]= (uchar) tm->hour;
  pos[5]= (uchar) tm->minute;
  pos[6]= (uchar) tm->second;
1135 1136 1137 1138 1139 1140 1141 1142 1143 1144
  int4store(pos+7, tm->second_part);
  if (tm->second_part)
    length=11;
  else if (tm->hour || tm->minute || tm->second)
    length=7;
  else if (tm->year || tm->month || tm->day)
    length=4;
  else
    length=0;
  buff[0]=(char) length;			// Length is stored first
1145
  return packet->append(buff, length+1, PACKET_BUFFER_EXTRA_ALLOC);
1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157
}

bool Protocol_prep::store_date(TIME *tm)
{
  tm->hour= tm->minute= tm->second=0;
  tm->second_part= 0;
  return Protocol_prep::store(tm);
}


bool Protocol_prep::store_time(TIME *tm)
{
1158
  char buff[13], *pos;
1159 1160 1161 1162
  uint length;
  field_pos++;
  pos= buff+1;
  pos[0]= tm->neg ? 1 : 0;
1163 1164 1165 1166 1167 1168 1169
  if (tm->hour >= 24)
  {
    /* Fix if we come from Item::send */
    uint days= tm->hour/24;
    tm->hour-= days*24;
    tm->day+= days;
  }
unknown's avatar
unknown committed
1170
  int4store(pos+1, tm->day);
1171 1172 1173 1174
  pos[5]= (uchar) tm->hour;
  pos[6]= (uchar) tm->minute;
  pos[7]= (uchar) tm->second;
  int4store(pos+8, tm->second_part);
1175
  if (tm->second_part)
1176
    length=12;
1177
  else if (tm->hour || tm->minute || tm->second || tm->day)
1178
    length=8;
1179 1180 1181
  else
    length=0;
  buff[0]=(char) length;			// Length is stored first
1182
  return packet->append(buff, length+1, PACKET_BUFFER_EXTRA_ALLOC);
1183
}