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

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

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

unknown's avatar
unknown committed
13 14 15 16 17 18 19
   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 */


/* This file defines all string functions
** Warning: Some string functions doesn't always put and end-null on a String
20
** (This shouldn't be needed)
unknown's avatar
unknown committed
21 22
*/

23
#ifdef USE_PRAGMA_IMPLEMENTATION
unknown's avatar
unknown committed
24 25 26 27 28
#pragma implementation				// gcc: Class implementation
#endif

#include "mysql_priv.h"
#include <m_ctype.h>
29 30 31
#ifdef HAVE_OPENSSL
#include <openssl/des.h>
#endif /* HAVE_OPENSSL */
unknown's avatar
unknown committed
32
#include "md5.h"
33 34
#include "sha1.h"
#include "my_aes.h"
unknown's avatar
unknown committed
35
C_MODE_START
36
#include "../mysys/my_static.h"			// For soundex_map
unknown's avatar
unknown committed
37
C_MODE_END
unknown's avatar
unknown committed
38

unknown's avatar
SCRUM  
unknown committed
39
String my_empty_string("",default_charset_info);
unknown's avatar
unknown committed
40

unknown's avatar
unknown committed
41 42
static void my_coll_agg_error(DTCollation &c1, DTCollation &c2,
                              const char *fname)
43
{
44 45 46 47
  my_error(ER_CANT_AGGREGATE_2COLLATIONS, MYF(0),
           c1.collation->name, c1.derivation_name(),
           c2.collation->name, c2.derivation_name(),
           fname);
48 49
}

50

51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82
String *Item_str_func::check_well_formed_result(String *str)
{
  /* Check whether we got a well-formed string */
  CHARSET_INFO *cs= str->charset();
  int well_formed_error;
  uint wlen= cs->cset->well_formed_len(cs,
                                       str->ptr(), str->ptr() + str->length(),
                                       str->length(), &well_formed_error);
  if (wlen < str->length())
  {
    THD *thd= current_thd;
    char hexbuf[7];
    enum MYSQL_ERROR::enum_warning_level level;
    uint diff= str->length() - wlen;
    set_if_smaller(diff, 3);
    octet2hex(hexbuf, str->ptr() + wlen, diff);
    if (thd->variables.sql_mode &
        (MODE_STRICT_TRANS_TABLES | MODE_STRICT_ALL_TABLES))
    {
      level= MYSQL_ERROR::WARN_LEVEL_ERROR;
      null_value= 1;
      str= 0;
    }
    else
      level= MYSQL_ERROR::WARN_LEVEL_WARN;
    push_warning_printf(thd, level, ER_INVALID_CHARACTER_STRING,
                        ER(ER_INVALID_CHARACTER_STRING), cs->csname, hexbuf);
  }
  return str;
}


unknown's avatar
unknown committed
83 84 85 86 87 88 89 90 91 92 93 94 95 96
bool Item_str_func::fix_fields(THD *thd, Item **ref)
{
  bool res= Item_func::fix_fields(thd, ref);
  /*
    In Item_str_func::check_well_formed_result() we may set null_value
    flag on the same condition as in test() below.
  */
  maybe_null= (maybe_null ||
               test(thd->variables.sql_mode &
                    (MODE_STRICT_TRANS_TABLES | MODE_STRICT_ALL_TABLES)));
  return res;
}


97 98 99 100 101 102 103 104 105 106 107 108 109 110
my_decimal *Item_str_func::val_decimal(my_decimal *decimal_value)
{
  DBUG_ASSERT(fixed == 1);
  char buff[64];
  String *res, tmp(buff,sizeof(buff), &my_charset_bin);
  res= val_str(&tmp);
  if (!res)
    return 0;
  (void)str2my_decimal(E_DEC_FATAL_ERROR, (char*) res->ptr(),
                       res->length(), res->charset(), decimal_value);
  return decimal_value;
}


111
double Item_str_func::val_real()
unknown's avatar
unknown committed
112
{
113
  DBUG_ASSERT(fixed == 1);
114 115
  int err_not_used;
  char *end_not_used, buff[64];
unknown's avatar
unknown committed
116 117
  String *res, tmp(buff,sizeof(buff), &my_charset_bin);
  res= val_str(&tmp);
118 119
  return res ? my_strntod(res->charset(), (char*) res->ptr(), res->length(),
			  &end_not_used, &err_not_used) : 0.0;
unknown's avatar
unknown committed
120 121
}

122

unknown's avatar
unknown committed
123 124
longlong Item_str_func::val_int()
{
125
  DBUG_ASSERT(fixed == 1);
126
  int err;
unknown's avatar
unknown committed
127 128 129
  char buff[22];
  String *res, tmp(buff,sizeof(buff), &my_charset_bin);
  res= val_str(&tmp);
unknown's avatar
unknown committed
130 131 132 133
  return (res ?
	  my_strntoll(res->charset(), res->ptr(), res->length(), 10, NULL,
		      &err) :
	  (longlong) 0);
unknown's avatar
unknown committed
134 135 136 137 138
}


String *Item_func_md5::val_str(String *str)
{
139
  DBUG_ASSERT(fixed == 1);
unknown's avatar
unknown committed
140
  String * sptr= args[0]->val_str(str);
141
  str->set_charset(&my_charset_bin);
unknown's avatar
unknown committed
142 143
  if (sptr)
  {
144
    my_MD5_CTX context;
unknown's avatar
unknown committed
145
    uchar digest[16];
unknown's avatar
unknown committed
146 147

    null_value=0;
148
    my_MD5Init (&context);
unknown's avatar
unknown committed
149
    my_MD5Update (&context,(uchar *) sptr->ptr(), sptr->length());
150
    my_MD5Final (digest, &context);
unknown's avatar
unknown committed
151 152 153 154 155
    if (str->alloc(32))				// Ensure that memory is free
    {
      null_value=1;
      return 0;
    }
unknown's avatar
unknown committed
156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171
    sprintf((char *) str->ptr(),
	    "%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
	    digest[0], digest[1], digest[2], digest[3],
	    digest[4], digest[5], digest[6], digest[7],
	    digest[8], digest[9], digest[10], digest[11],
	    digest[12], digest[13], digest[14], digest[15]);
    str->length((uint) 32);
    return str;
  }
  null_value=1;
  return 0;
}


void Item_func_md5::fix_length_and_dec()
{
172 173 174 175 176 177 178 179 180
  max_length=32;
  /*
    The MD5() function treats its parameter as being a case sensitive. Thus
    we set binary collation on it so different instances of MD5() will be
    compared properly.
  */
  args[0]->collation.set(
      get_charset_by_csname(args[0]->collation.collation->csname,
                            MY_CS_BINSORT,MYF(0)), DERIVATION_COERCIBLE);
unknown's avatar
unknown committed
181 182
}

183 184 185

String *Item_func_sha::val_str(String *str)
{
186
  DBUG_ASSERT(fixed == 1);
187
  String * sptr= args[0]->val_str(str);
188
  str->set_charset(&my_charset_bin);
189 190 191
  if (sptr)  /* If we got value different from NULL */
  {
    SHA1_CONTEXT context;  /* Context used to generate SHA1 hash */
192
    /* Temporary buffer to store 160bit digest */
unknown's avatar
unknown committed
193
    uint8 digest[SHA1_HASH_SIZE];
194
    mysql_sha1_reset(&context);  /* We do not have to check for error here */
195
    /* No need to check error as the only case would be too long message */
196
    mysql_sha1_input(&context,
unknown's avatar
unknown committed
197
                     (const uchar *) sptr->ptr(), sptr->length());
198
    /* Ensure that memory is free and we got result */
199 200
    if (!( str->alloc(SHA1_HASH_SIZE*2) ||
           (mysql_sha1_result(&context,digest))))
201
    {
202 203
      sprintf((char *) str->ptr(),
      "%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x\
204 205 206 207 208 209
%02x%02x%02x%02x%02x%02x%02x%02x",
           digest[0], digest[1], digest[2], digest[3],
           digest[4], digest[5], digest[6], digest[7],
           digest[8], digest[9], digest[10], digest[11],
           digest[12], digest[13], digest[14], digest[15],
           digest[16], digest[17], digest[18], digest[19]);
210

211 212 213 214
      str->length((uint)  SHA1_HASH_SIZE*2);
      null_value=0;
      return str;
    }
215
  }
216 217 218 219 220 221
  null_value=1;
  return 0;
}

void Item_func_sha::fix_length_and_dec()
{
222 223 224 225 226 227 228 229 230
  max_length=SHA1_HASH_SIZE*2; // size of hex representation of hash
  /*
    The SHA() function treats its parameter as being a case sensitive. Thus
    we set binary collation on it so different instances of MD5() will be
    compared properly.
  */
  args[0]->collation.set(
      get_charset_by_csname(args[0]->collation.collation->csname,
                            MY_CS_BINSORT,MYF(0)), DERIVATION_COERCIBLE);
231
}
232 233 234 235


/* Implementation of AES encryption routines */

236 237
String *Item_func_aes_encrypt::val_str(String *str)
{
238
  DBUG_ASSERT(fixed == 1);
239
  char key_buff[80];
240
  String tmp_key_value(key_buff, sizeof(key_buff), system_charset_info);
241 242
  String *sptr= args[0]->val_str(str);			// String to encrypt
  String *key=  args[1]->val_str(&tmp_key_value);	// key
243 244 245 246
  int aes_length;
  if (sptr && key) // we need both arguments to be not NULL
  {
    null_value=0;
247
    aes_length=my_aes_get_size(sptr->length()); // Calculate result length
248

249
    if (!str_value.alloc(aes_length))		// Ensure that memory is free
250 251
    {
      // finally encrypt directly to allocated buffer.
252
      if (my_aes_encrypt(sptr->ptr(),sptr->length(), (char*) str_value.ptr(),
253
			 key->ptr(), key->length()) == aes_length)
254
      {
255
	// We got the expected result length
256 257
	str_value.length((uint) aes_length);
	return &str_value;
258 259 260 261 262 263 264
      }
    }
  }
  null_value=1;
  return 0;
}

265

266 267
void Item_func_aes_encrypt::fix_length_and_dec()
{
268
  max_length=my_aes_get_size(args[0]->max_length);
269 270 271 272 273
}


String *Item_func_aes_decrypt::val_str(String *str)
{
274
  DBUG_ASSERT(fixed == 1);
275
  char key_buff[80];
276 277
  String tmp_key_value(key_buff, sizeof(key_buff), system_charset_info);
  String *sptr, *key;
278 279 280 281 282
  DBUG_ENTER("Item_func_aes_decrypt::val_str");

  sptr= args[0]->val_str(str);			// String to decrypt
  key=  args[1]->val_str(&tmp_key_value);	// Key
  if (sptr && key)  			// Need to have both arguments not NULL
283 284
  {
    null_value=0;
285
    if (!str_value.alloc(sptr->length()))  // Ensure that memory is free
286
    {
287
      // finally decrypt directly to allocated buffer.
288 289 290
      int length;
      length=my_aes_decrypt(sptr->ptr(), sptr->length(),
			    (char*) str_value.ptr(),
291 292
                            key->ptr(), key->length());
      if (length >= 0)  // if we got correct data data
293
      {
294 295
        str_value.length((uint) length);
        DBUG_RETURN(&str_value);
296
      }
297 298 299 300
    }
  }
  // Bad parameters. No memory or bad data will all go here
  null_value=1;
301
  DBUG_RETURN(0);
302 303
}

304

305 306 307
void Item_func_aes_decrypt::fix_length_and_dec()
{
   max_length=args[0]->max_length;
unknown's avatar
unknown committed
308
   maybe_null= 1;
309
}
310 311


unknown's avatar
unknown committed
312
/*
313 314 315
  Concatenate args with the following premises:
  If only one arg (which is ok), return value of arg
  Don't reallocate val_str() if not absolute necessary.
unknown's avatar
unknown committed
316 317 318 319
*/

String *Item_func_concat::val_str(String *str)
{
320
  DBUG_ASSERT(fixed == 1);
unknown's avatar
unknown committed
321 322
  String *res,*res2,*use_as_buff;
  uint i;
323
  bool is_const= 0;
unknown's avatar
unknown committed
324 325 326 327 328

  null_value=0;
  if (!(res=args[0]->val_str(str)))
    goto null;
  use_as_buff= &tmp_value;
unknown's avatar
unknown committed
329 330
  /* Item_subselect in --ps-protocol mode will state it as a non-const */
  is_const= args[0]->const_item() || !args[0]->used_tables();
unknown's avatar
unknown committed
331 332 333 334 335 336 337 338 339 340 341 342 343
  for (i=1 ; i < arg_count ; i++)
  {
    if (res->length() == 0)
    {
      if (!(res=args[i]->val_str(str)))
	goto null;
    }
    else
    {
      if (!(res2=args[i]->val_str(use_as_buff)))
	goto null;
      if (res2->length() == 0)
	continue;
unknown's avatar
unknown committed
344 345
      if (res->length()+res2->length() >
	  current_thd->variables.max_allowed_packet)
346 347 348
      {
	push_warning_printf(current_thd, MYSQL_ERROR::WARN_LEVEL_WARN,
			    ER_WARN_ALLOWED_PACKET_OVERFLOWED,
349 350
			    ER(ER_WARN_ALLOWED_PACKET_OVERFLOWED), func_name(),
			    current_thd->variables.max_allowed_packet);
351 352
	goto null;
      }
353
      if (!is_const && res->alloced_length() >= res->length()+res2->length())
unknown's avatar
unknown committed
354 355 356 357 358 359 360 361 362 363 364 365
      {						// Use old buffer
	res->append(*res2);
      }
      else if (str->alloced_length() >= res->length()+res2->length())
      {
	if (str == res2)
	  str->replace(0,0,*res);
	else
	{
	  str->copy(*res);
	  str->append(*res2);
	}
366 367
        res= str;
        use_as_buff= &tmp_value;
unknown's avatar
unknown committed
368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407
      }
      else if (res == &tmp_value)
      {
	if (res->append(*res2))			// Must be a blob
	  goto null;
      }
      else if (res2 == &tmp_value)
      {						// This can happend only 1 time
	if (tmp_value.replace(0,0,*res))
	  goto null;
	res= &tmp_value;
	use_as_buff=str;			// Put next arg here
      }
      else if (tmp_value.is_alloced() && res2->ptr() >= tmp_value.ptr() &&
	       res2->ptr() <= tmp_value.ptr() + tmp_value.alloced_length())
      {
	/*
	  This happens really seldom:
	  In this case res2 is sub string of tmp_value.  We will
	  now work in place in tmp_value to set it to res | res2
	*/
	/* Chop the last characters in tmp_value that isn't in res2 */
	tmp_value.length((uint32) (res2->ptr() - tmp_value.ptr()) +
			 res2->length());
	/* Place res2 at start of tmp_value, remove chars before res2 */
	if (tmp_value.replace(0,(uint32) (res2->ptr() - tmp_value.ptr()),
			      *res))
	  goto null;
	res= &tmp_value;
	use_as_buff=str;			// Put next arg here
      }
      else
      {						// Two big const strings
	if (tmp_value.alloc(max_length) ||
	    tmp_value.copy(*res) ||
	    tmp_value.append(*res2))
	  goto null;
	res= &tmp_value;
	use_as_buff=str;
      }
408
      is_const= 0;
unknown's avatar
unknown committed
409 410
    }
  }
411
  res->set_charset(collation.collation);
unknown's avatar
unknown committed
412 413 414 415 416 417 418 419 420 421
  return res;

null:
  null_value=1;
  return 0;
}


void Item_func_concat::fix_length_and_dec()
{
422
  ulonglong max_result_length= 0;
423

424
  if (agg_arg_charsets(collation, args, arg_count, MY_COLL_ALLOW_CONV, 1))
unknown's avatar
unknown committed
425 426
    return;

unknown's avatar
unknown committed
427
  for (uint i=0 ; i < arg_count ; i++)
428 429 430 431 432 433 434 435
  {
    if (args[i]->collation.collation->mbmaxlen != collation.collation->mbmaxlen)
      max_result_length+= (args[i]->max_length /
                           args[i]->collation.collation->mbmaxlen) *
                           collation.collation->mbmaxlen;
    else
      max_result_length+= args[i]->max_length;
  }
436

437
  if (max_result_length >= MAX_BLOB_WIDTH)
unknown's avatar
unknown committed
438
  {
439 440
    max_result_length= MAX_BLOB_WIDTH;
    maybe_null= 1;
unknown's avatar
unknown committed
441
  }
442
  max_length= (ulong) max_result_length;
unknown's avatar
unknown committed
443 444
}

445
/*
unknown's avatar
unknown committed
446 447
  Function des_encrypt() by tonu@spam.ee & monty
  Works only if compiled with OpenSSL library support.
448
  This returns a binary string where first character is CHAR(128 | key-number).
unknown's avatar
unknown committed
449
  If one uses a string key key_number is 127.
450
  Encryption result is longer than original by formula:
unknown's avatar
unknown committed
451
  new_length= org_length + (8-(org_length % 8))+1
452 453
*/

454 455
String *Item_func_des_encrypt::val_str(String *str)
{
456
  DBUG_ASSERT(fixed == 1);
457
#ifdef HAVE_OPENSSL
458
  uint code= ER_WRONG_PARAMETERS_TO_PROCEDURE;
459
  DES_cblock ivec;
unknown's avatar
unknown committed
460 461
  struct st_des_keyblock keyblock;
  struct st_des_keyschedule keyschedule;
unknown's avatar
unknown committed
462 463
  const char *append_str="********";
  uint key_number, res_length, tail;
unknown's avatar
unknown committed
464
  String *res= args[0]->val_str(str);
465

unknown's avatar
unknown committed
466 467
  if ((null_value= args[0]->null_value))
    return 0;                                   // ENCRYPT(NULL) == NULL
unknown's avatar
unknown committed
468
  if ((res_length=res->length()) == 0)
unknown's avatar
SCRUM  
unknown committed
469
    return &my_empty_string;
unknown's avatar
unknown committed
470

unknown's avatar
unknown committed
471
  if (arg_count == 1)
unknown's avatar
unknown committed
472 473 474 475 476 477
  {
    /* Protect against someone doing FLUSH DES_KEY_FILE */
    VOID(pthread_mutex_lock(&LOCK_des_key_file));
    keyschedule= des_keyschedule[key_number=des_default_key];
    VOID(pthread_mutex_unlock(&LOCK_des_key_file));
  }
unknown's avatar
unknown committed
478
  else if (args[1]->result_type() == INT_RESULT)
unknown's avatar
unknown committed
479 480 481 482
  {
    key_number= (uint) args[1]->val_int();
    if (key_number > 9)
      goto error;
unknown's avatar
unknown committed
483 484 485
    VOID(pthread_mutex_lock(&LOCK_des_key_file));
    keyschedule= des_keyschedule[key_number];
    VOID(pthread_mutex_unlock(&LOCK_des_key_file));
486
  }
unknown's avatar
unknown committed
487 488 489 490 491
  else
  {
    String *keystr=args[1]->val_str(&tmp_value);
    if (!keystr)
      goto error;
unknown's avatar
unknown committed
492
    key_number=127;				// User key string
unknown's avatar
unknown committed
493 494

    /* We make good 24-byte (168 bit) key from given plaintext key with MD5 */
unknown's avatar
unknown committed
495
    bzero((char*) &ivec,sizeof(ivec));
unknown's avatar
unknown committed
496 497 498
    EVP_BytesToKey(EVP_des_ede3_cbc(),EVP_md5(),NULL,
		   (uchar*) keystr->ptr(), (int) keystr->length(),
		   1, (uchar*) &keyblock,ivec);
499 500 501
    DES_set_key_unchecked(&keyblock.key1,&keyschedule.ks1);
    DES_set_key_unchecked(&keyblock.key2,&keyschedule.ks2);
    DES_set_key_unchecked(&keyblock.key3,&keyschedule.ks3);
unknown's avatar
unknown committed
502 503
  }

504
  /*
unknown's avatar
unknown committed
505
     The problem: DES algorithm requires original data to be in 8-bytes
506 507
     chunks. Missing bytes get filled with '*'s and result of encryption
     can be up to 8 bytes longer than original string. When decrypted,
unknown's avatar
unknown committed
508
     we do not know the size of original string :(
unknown's avatar
unknown committed
509 510
     We add one byte with value 0x1..0x8 as the last byte of the padded
     string marking change of string length.
unknown's avatar
unknown committed
511 512
  */

unknown's avatar
unknown committed
513 514
  tail=  (8-(res_length) % 8);			// 1..8 marking extra length
  res_length+=tail;
515
  code= ER_OUT_OF_RESOURCES;
unknown's avatar
unknown committed
516
  if (tail && res->append(append_str, tail) || tmp_value.alloc(res_length+1))
unknown's avatar
unknown committed
517
    goto error;
unknown's avatar
unknown committed
518 519 520
  (*res)[res_length-1]=tail;			// save extra length
  tmp_value.length(res_length+1);
  tmp_value[0]=(char) (128 | key_number);
unknown's avatar
unknown committed
521
  // Real encryption
unknown's avatar
unknown committed
522
  bzero((char*) &ivec,sizeof(ivec));
523
  DES_ede3_cbc_encrypt((const uchar*) (res->ptr()),
unknown's avatar
unknown committed
524
		       (uchar*) (tmp_value.ptr()+1),
unknown's avatar
unknown committed
525
		       res_length,
526 527 528
		       &keyschedule.ks1,
		       &keyschedule.ks2,
		       &keyschedule.ks3,
unknown's avatar
unknown committed
529 530 531 532
		       &ivec, TRUE);
  return &tmp_value;

error:
533 534 535 536 537 538 539
  push_warning_printf(current_thd,MYSQL_ERROR::WARN_LEVEL_ERROR,
                          code, ER(code),
                          "des_encrypt");
#else
  push_warning_printf(current_thd,MYSQL_ERROR::WARN_LEVEL_ERROR,
                      ER_FEATURE_DISABLED, ER(ER_FEATURE_DISABLED),
                      "des_encrypt","--with-openssl");
unknown's avatar
unknown committed
540
#endif	/* HAVE_OPENSSL */
541 542 543 544
  null_value=1;
  return 0;
}

unknown's avatar
unknown committed
545

546 547
String *Item_func_des_decrypt::val_str(String *str)
{
548
  DBUG_ASSERT(fixed == 1);
549
#ifdef HAVE_OPENSSL
550
  uint code= ER_WRONG_PARAMETERS_TO_PROCEDURE;
551
  DES_cblock ivec;
unknown's avatar
unknown committed
552 553
  struct st_des_keyblock keyblock;
  struct st_des_keyschedule keyschedule;
unknown's avatar
unknown committed
554
  String *res= args[0]->val_str(str);
555
  uint length,tail;
556

557
  if ((null_value= args[0]->null_value))
unknown's avatar
unknown committed
558
    return 0;
559
  length= res->length();
unknown's avatar
unknown committed
560
  if (length < 9 || (length % 8) != 1 || !((*res)[0] & 128))
unknown's avatar
unknown committed
561
    return res;				// Skip decryption if not encrypted
unknown's avatar
unknown committed
562

unknown's avatar
unknown committed
563
  if (arg_count == 1)			// If automatic uncompression
564
  {
unknown's avatar
unknown committed
565
    uint key_number=(uint) (*res)[0] & 127;
unknown's avatar
unknown committed
566
    // Check if automatic key and that we have privilege to uncompress using it
567 568
    if (!(current_thd->security_ctx->master_access & SUPER_ACL) ||
        key_number > 9)
unknown's avatar
unknown committed
569
      goto error;
570

unknown's avatar
unknown committed
571 572 573
    VOID(pthread_mutex_lock(&LOCK_des_key_file));
    keyschedule= des_keyschedule[key_number];
    VOID(pthread_mutex_unlock(&LOCK_des_key_file));
574
  }
unknown's avatar
unknown committed
575 576 577 578
  else
  {
    // We make good 24-byte (168 bit) key from given plaintext key with MD5
    String *keystr=args[1]->val_str(&tmp_value);
unknown's avatar
unknown committed
579
    if (!keystr)
unknown's avatar
unknown committed
580
      goto error;
unknown's avatar
unknown committed
581

unknown's avatar
unknown committed
582
    bzero((char*) &ivec,sizeof(ivec));
unknown's avatar
unknown committed
583 584 585 586
    EVP_BytesToKey(EVP_des_ede3_cbc(),EVP_md5(),NULL,
		   (uchar*) keystr->ptr(),(int) keystr->length(),
		   1,(uchar*) &keyblock,ivec);
    // Here we set all 64-bit keys (56 effective) one by one
587 588
    DES_set_key_unchecked(&keyblock.key1,&keyschedule.ks1);
    DES_set_key_unchecked(&keyblock.key2,&keyschedule.ks2);
unknown's avatar
unknown committed
589
    DES_set_key_unchecked(&keyblock.key3,&keyschedule.ks3);
unknown's avatar
unknown committed
590
  }
591
  code= ER_OUT_OF_RESOURCES;
unknown's avatar
unknown committed
592
  if (tmp_value.alloc(length-1))
unknown's avatar
unknown committed
593
    goto error;
unknown's avatar
unknown committed
594 595

  bzero((char*) &ivec,sizeof(ivec));
596
  DES_ede3_cbc_encrypt((const uchar*) res->ptr()+1,
unknown's avatar
unknown committed
597
		       (uchar*) (tmp_value.ptr()),
unknown's avatar
unknown committed
598
		       length-1,
599 600 601
		       &keyschedule.ks1,
		       &keyschedule.ks2,
		       &keyschedule.ks3,
unknown's avatar
unknown committed
602
		       &ivec, FALSE);
unknown's avatar
unknown committed
603 604
  /* Restore old length of key */
  if ((tail=(uint) (uchar) tmp_value[length-2]) > 8)
605
    goto wrong_key;				     // Wrong key
unknown's avatar
unknown committed
606
  tmp_value.length(length-1-tail);
unknown's avatar
unknown committed
607 608 609
  return &tmp_value;

error:
610 611 612 613 614 615 616 617
  push_warning_printf(current_thd,MYSQL_ERROR::WARN_LEVEL_ERROR,
                          code, ER(code),
                          "des_decrypt");
wrong_key:
#else
  push_warning_printf(current_thd,MYSQL_ERROR::WARN_LEVEL_ERROR,
                      ER_FEATURE_DISABLED, ER(ER_FEATURE_DISABLED),
                      "des_decrypt","--with-openssl");
unknown's avatar
unknown committed
618
#endif	/* HAVE_OPENSSL */
619 620 621 622 623
  null_value=1;
  return 0;
}


624
/*
unknown's avatar
unknown committed
625 626
  concat with separator. First arg is the separator
  concat_ws takes at least two arguments.
unknown's avatar
unknown committed
627 628 629 630
*/

String *Item_func_concat_ws::val_str(String *str)
{
631
  DBUG_ASSERT(fixed == 1);
unknown's avatar
unknown committed
632
  char tmp_str_buff[10];
633
  String tmp_sep_str(tmp_str_buff, sizeof(tmp_str_buff),default_charset_info),
unknown's avatar
unknown committed
634 635 636 637
         *sep_str, *res, *res2,*use_as_buff;
  uint i;

  null_value=0;
638
  if (!(sep_str= args[0]->val_str(&tmp_sep_str)))
unknown's avatar
unknown committed
639 640 641
    goto null;

  use_as_buff= &tmp_value;
unknown's avatar
unknown committed
642
  str->length(0);				// QQ; Should be removed
unknown's avatar
unknown committed
643 644
  res=str;

645
  // Skip until non-null argument is found.
unknown's avatar
unknown committed
646
  // If not, return the empty string
647
  for (i=1; i < arg_count; i++)
648
    if ((res= args[i]->val_str(str)))
649
      break;
unknown's avatar
unknown committed
650
  if (i ==  arg_count)
unknown's avatar
SCRUM  
unknown committed
651
    return &my_empty_string;
unknown's avatar
unknown committed
652 653 654

  for (i++; i < arg_count ; i++)
  {
655 656
    if (!(res2= args[i]->val_str(use_as_buff)))
      continue;					// Skip NULL
unknown's avatar
unknown committed
657 658

    if (res->length() + sep_str->length() + res2->length() >
unknown's avatar
unknown committed
659
	current_thd->variables.max_allowed_packet)
660 661 662
    {
      push_warning_printf(current_thd, MYSQL_ERROR::WARN_LEVEL_WARN,
			  ER_WARN_ALLOWED_PACKET_OVERFLOWED,
663 664
			  ER(ER_WARN_ALLOWED_PACKET_OVERFLOWED), func_name(),
			  current_thd->variables.max_allowed_packet);
665 666
      goto null;
    }
unknown's avatar
unknown committed
667 668 669 670 671 672 673 674
    if (res->alloced_length() >=
	res->length() + sep_str->length() + res2->length())
    {						// Use old buffer
      res->append(*sep_str);			// res->length() > 0 always
      res->append(*res2);
    }
    else if (str->alloced_length() >=
	     res->length() + sep_str->length() + res2->length())
unknown's avatar
unknown committed
675
    {
676 677 678 679 680 681 682 683 684 685 686 687
      /* We have room in str;  We can't get any errors here */
      if (str == res2)
      {						// This is quote uncommon!
	str->replace(0,0,*sep_str);
	str->replace(0,0,*res);
      }
      else
      {
	str->copy(*res);
	str->append(*sep_str);
	str->append(*res2);
      }
unknown's avatar
unknown committed
688 689 690 691 692
      res=str;
      use_as_buff= &tmp_value;
    }
    else if (res == &tmp_value)
    {
693
      if (res->append(*sep_str) || res->append(*res2))
unknown's avatar
unknown committed
694 695
	goto null; // Must be a blob
    }
696 697 698 699 700 701 702
    else if (res2 == &tmp_value)
    {						// This can happend only 1 time
      if (tmp_value.replace(0,0,*sep_str) || tmp_value.replace(0,0,*res))
	goto null;
      res= &tmp_value;
      use_as_buff=str;				// Put next arg here
    }
unknown's avatar
unknown committed
703
    else if (tmp_value.is_alloced() && res2->ptr() >= tmp_value.ptr() &&
704
	     res2->ptr() < tmp_value.ptr() + tmp_value.alloced_length())
unknown's avatar
unknown committed
705 706 707 708
    {
      /*
	This happens really seldom:
	In this case res2 is sub string of tmp_value.  We will
709
	now work in place in tmp_value to set it to res | sep_str | res2
unknown's avatar
unknown committed
710 711 712 713 714 715
      */
      /* Chop the last characters in tmp_value that isn't in res2 */
      tmp_value.length((uint32) (res2->ptr() - tmp_value.ptr()) +
		       res2->length());
      /* Place res2 at start of tmp_value, remove chars before res2 */
      if (tmp_value.replace(0,(uint32) (res2->ptr() - tmp_value.ptr()),
716 717
			    *res) ||
	  tmp_value.replace(res->length(),0, *sep_str))
unknown's avatar
unknown committed
718 719 720 721 722 723 724 725 726 727 728 729 730
	goto null;
      res= &tmp_value;
      use_as_buff=str;			// Put next arg here
    }
    else
    {						// Two big const strings
      if (tmp_value.alloc(max_length) ||
	  tmp_value.copy(*res) ||
	  tmp_value.append(*sep_str) ||
	  tmp_value.append(*res2))
	goto null;
      res= &tmp_value;
      use_as_buff=str;
unknown's avatar
unknown committed
731 732
    }
  }
733
  res->set_charset(collation.collation);
unknown's avatar
unknown committed
734 735 736 737 738 739 740 741 742 743
  return res;

null:
  null_value=1;
  return 0;
}


void Item_func_concat_ws::fix_length_and_dec()
{
744
  ulonglong max_result_length;
745

746
  if (agg_arg_charsets(collation, args, arg_count, MY_COLL_ALLOW_CONV, 1))
747 748
    return;

unknown's avatar
unknown committed
749 750 751 752 753
  /*
     arg_count cannot be less than 2,
     it is done on parser level in sql_yacc.yy
     so, (arg_count - 2) is safe here.
  */
754
  max_result_length= (ulonglong) args[0]->max_length * (arg_count - 2);
755
  for (uint i=1 ; i < arg_count ; i++)
756
    max_result_length+=args[i]->max_length;
757

758
  if (max_result_length >= MAX_BLOB_WIDTH)
unknown's avatar
unknown committed
759
  {
760 761
    max_result_length= MAX_BLOB_WIDTH;
    maybe_null= 1;
unknown's avatar
unknown committed
762
  }
763
  max_length= (ulong) max_result_length;
unknown's avatar
unknown committed
764 765
}

unknown's avatar
unknown committed
766 767 768

String *Item_func_reverse::val_str(String *str)
{
769
  DBUG_ASSERT(fixed == 1);
unknown's avatar
unknown committed
770
  String *res = args[0]->val_str(str);
unknown's avatar
unknown committed
771
  char *ptr, *end, *tmp;
unknown's avatar
unknown committed
772 773 774 775 776

  if ((null_value=args[0]->null_value))
    return 0;
  /* An empty string is a special case as the string pointer may be null */
  if (!res->length())
unknown's avatar
SCRUM  
unknown committed
777
    return &my_empty_string;
unknown's avatar
unknown committed
778 779 780 781 782 783 784 785 786 787 788
  if (tmp_value.alloced_length() < res->length() &&
      tmp_value.realloc(res->length()))
  {
    null_value= 1;
    return 0;
  }
  tmp_value.length(res->length());
  tmp_value.set_charset(res->charset());
  ptr= (char *) res->ptr();
  end= ptr + res->length();
  tmp= (char *) tmp_value.ptr() + tmp_value.length();
unknown's avatar
unknown committed
789
#ifdef USE_MB
790
  if (use_mb(res->charset()))
unknown's avatar
unknown committed
791 792 793 794
  {
    register uint32 l;
    while (ptr < end)
    {
unknown's avatar
unknown committed
795 796 797 798 799 800
      if ((l= my_ismbchar(res->charset(),ptr,end)))
      {
        tmp-= l;
        memcpy(tmp,ptr,l);
        ptr+= l;
      }
unknown's avatar
unknown committed
801
      else
unknown's avatar
unknown committed
802
        *--tmp= *ptr++;
unknown's avatar
unknown committed
803 804 805 806 807 808
    }
  }
  else
#endif /* USE_MB */
  {
    while (ptr < end)
unknown's avatar
unknown committed
809
      *--tmp= *ptr++;
unknown's avatar
unknown committed
810
  }
unknown's avatar
unknown committed
811
  return &tmp_value;
unknown's avatar
unknown committed
812 813 814 815 816
}


void Item_func_reverse::fix_length_and_dec()
{
817
  collation.set(args[0]->collation);
unknown's avatar
unknown committed
818 819 820 821 822
  max_length = args[0]->max_length;
}

/*
** Replace all occurences of string2 in string1 with string3.
823
** Don't reallocate val_str() if not needed
unknown's avatar
unknown committed
824 825 826 827 828 829
*/

/* TODO: Fix that this works with binary strings when using USE_MB */

String *Item_func_replace::val_str(String *str)
{
830
  DBUG_ASSERT(fixed == 1);
unknown's avatar
unknown committed
831
  String *res,*res2,*res3;
unknown's avatar
unknown committed
832
  int offset;
unknown's avatar
unknown committed
833 834 835 836 837
  uint from_length,to_length;
  bool alloced=0;
#ifdef USE_MB
  const char *ptr,*end,*strend,*search,*search_end;
  register uint32 l;
838
  bool binary_cmp;
unknown's avatar
unknown committed
839 840 841 842 843 844 845 846 847 848
#endif

  null_value=0;
  res=args[0]->val_str(str);
  if (args[0]->null_value)
    goto null;
  res2=args[1]->val_str(&tmp_value);
  if (args[1]->null_value)
    goto null;

849 850
  res->set_charset(collation.collation);

851
#ifdef USE_MB
852
  binary_cmp = ((res->charset()->state & MY_CS_BINSORT) || !use_mb(res->charset()));
853 854
#endif

unknown's avatar
unknown committed
855 856 857 858 859 860
  if (res2->length() == 0)
    return res;
#ifndef USE_MB
  if ((offset=res->strstr(*res2)) < 0)
    return res;
#else
unknown's avatar
unknown committed
861
  offset=0;
862
  if (binary_cmp && (offset=res->strstr(*res2)) < 0)
unknown's avatar
unknown committed
863 864 865 866 867 868 869 870
    return res;
#endif
  if (!(res3=args[2]->val_str(&tmp_value2)))
    goto null;
  from_length= res2->length();
  to_length=   res3->length();

#ifdef USE_MB
871
  if (!binary_cmp)
unknown's avatar
unknown committed
872 873 874 875 876 877 878 879 880 881 882 883 884 885
  {
    search=res2->ptr();
    search_end=search+from_length;
redo:
    ptr=res->ptr()+offset;
    strend=res->ptr()+res->length();
    end=strend-from_length+1;
    while (ptr < end)
    {
        if (*ptr == *search)
        {
          register char *i,*j;
          i=(char*) ptr+1; j=(char*) search+1;
          while (j != search_end)
886
            if (*i++ != *j++) goto skip;
unknown's avatar
unknown committed
887
          offset= (int) (ptr-res->ptr());
unknown's avatar
unknown committed
888 889
          if (res->length()-from_length + to_length >
	      current_thd->variables.max_allowed_packet)
890 891 892 893
	  {
	    push_warning_printf(current_thd, MYSQL_ERROR::WARN_LEVEL_WARN,
				ER_WARN_ALLOWED_PACKET_OVERFLOWED,
				ER(ER_WARN_ALLOWED_PACKET_OVERFLOWED),
894 895
				func_name(),
				current_thd->variables.max_allowed_packet);
896

unknown's avatar
unknown committed
897
            goto null;
898
	  }
unknown's avatar
unknown committed
899 900 901 902 903 904
          if (!alloced)
          {
            alloced=1;
            res=copy_if_not_alloced(str,res,res->length()+to_length);
          }
          res->replace((uint) offset,from_length,*res3);
unknown's avatar
unknown committed
905
	  offset+=(int) to_length;
unknown's avatar
unknown committed
906 907
          goto redo;
        }
908
skip:
909
        if ((l=my_ismbchar(res->charset(), ptr,strend))) ptr+=l;
unknown's avatar
unknown committed
910 911 912 913 914 915 916
        else ++ptr;
    }
  }
  else
#endif /* USE_MB */
    do
    {
unknown's avatar
unknown committed
917 918
      if (res->length()-from_length + to_length >
	  current_thd->variables.max_allowed_packet)
919 920 921
      {
	push_warning_printf(current_thd, MYSQL_ERROR::WARN_LEVEL_WARN,
			    ER_WARN_ALLOWED_PACKET_OVERFLOWED,
922 923
			    ER(ER_WARN_ALLOWED_PACKET_OVERFLOWED), func_name(),
			    current_thd->variables.max_allowed_packet);
unknown's avatar
unknown committed
924
        goto null;
925
      }
unknown's avatar
unknown committed
926 927 928 929 930 931 932 933
      if (!alloced)
      {
        alloced=1;
        res=copy_if_not_alloced(str,res,res->length()+to_length);
      }
      res->replace((uint) offset,from_length,*res3);
      offset+=(int) to_length;
    }
934
    while ((offset=res->strstr(*res2,(uint) offset)) >= 0);
unknown's avatar
unknown committed
935 936 937 938 939 940 941 942 943 944
  return res;

null:
  null_value=1;
  return 0;
}


void Item_func_replace::fix_length_and_dec()
{
945
  ulonglong max_result_length= args[0]->max_length;
unknown's avatar
unknown committed
946 947 948
  int diff=(int) (args[2]->max_length - args[1]->max_length);
  if (diff > 0 && args[1]->max_length)
  {						// Calculate of maxreplaces
949 950
    ulonglong max_substrs= max_result_length/args[1]->max_length;
    max_result_length+= max_substrs * (uint) diff;
unknown's avatar
unknown committed
951
  }
952
  if (max_result_length >= MAX_BLOB_WIDTH)
unknown's avatar
unknown committed
953
  {
954 955
    max_result_length= MAX_BLOB_WIDTH;
    maybe_null= 1;
unknown's avatar
unknown committed
956
  }
957
  max_length= (ulong) max_result_length;
958
  
959
  if (agg_arg_charsets(collation, args, 3, MY_COLL_CMP_CONV, 1))
unknown's avatar
unknown committed
960
    return;
unknown's avatar
unknown committed
961 962 963 964 965
}


String *Item_func_insert::val_str(String *str)
{
966
  DBUG_ASSERT(fixed == 1);
unknown's avatar
unknown committed
967
  String *res,*res2;
968
  longlong start, length;  /* must be longlong to avoid truncation */
unknown's avatar
unknown committed
969 970 971 972

  null_value=0;
  res=args[0]->val_str(str);
  res2=args[3]->val_str(&tmp_value);
973 974 975
  start= args[1]->val_int() - 1;
  length= args[2]->val_int();

unknown's avatar
unknown committed
976 977 978
  if (args[0]->null_value || args[1]->null_value || args[2]->null_value ||
      args[3]->null_value)
    goto null; /* purecov: inspected */
979 980 981 982 983 984 985

  if ((start < 0) || (start > res->length() + 1))
    return res;                                 // Wrong param; skip insert
  if ((length < 0) || (length > res->length() + 1))
    length= res->length() + 1;

  /* start and length are now sufficiently valid to pass to charpos function */
986 987
   start= res->charpos((int) start);
   length= res->charpos((int) length, (uint32) start);
988 989 990 991 992 993 994

  /* Re-testing with corrected params */
  if (start > res->length() + 1)
    return res;                                 // Wrong param; skip insert
  if (length > res->length() - start)
    length= res->length() - start;

unknown's avatar
unknown committed
995 996
  if ((ulonglong) (res->length() - length + res2->length()) >
      (ulonglong) current_thd->variables.max_allowed_packet)
997 998 999
  {
    push_warning_printf(current_thd, MYSQL_ERROR::WARN_LEVEL_WARN,
			ER_WARN_ALLOWED_PACKET_OVERFLOWED,
1000 1001
			ER(ER_WARN_ALLOWED_PACKET_OVERFLOWED),
			func_name(), current_thd->variables.max_allowed_packet);
1002 1003
    goto null;
  }
unknown's avatar
unknown committed
1004
  res=copy_if_not_alloced(str,res,res->length());
1005
  res->replace((uint32) start,(uint32) length,*res2);
unknown's avatar
unknown committed
1006 1007 1008 1009 1010 1011 1012 1013 1014
  return res;
null:
  null_value=1;
  return 0;
}


void Item_func_insert::fix_length_and_dec()
{
1015 1016
  ulonglong max_result_length;

1017 1018
  // Handle character set for args[0] and args[3].
  if (agg_arg_charsets(collation, &args[0], 2, MY_COLL_ALLOW_CONV, 3))
unknown's avatar
unknown committed
1019
    return;
1020 1021 1022
  max_result_length= ((ulonglong) args[0]->max_length+
                      (ulonglong) args[3]->max_length);
  if (max_result_length >= MAX_BLOB_WIDTH)
unknown's avatar
unknown committed
1023
  {
1024 1025
    max_result_length= MAX_BLOB_WIDTH;
    maybe_null= 1;
unknown's avatar
unknown committed
1026
  }
1027
  max_length= (ulong) max_result_length;
unknown's avatar
unknown committed
1028 1029 1030
}


1031
String *Item_str_conv::val_str(String *str)
unknown's avatar
unknown committed
1032
{
1033
  DBUG_ASSERT(fixed == 1);
unknown's avatar
unknown committed
1034 1035 1036 1037 1038 1039 1040
  String *res;
  if (!(res=args[0]->val_str(str)))
  {
    null_value=1; /* purecov: inspected */
    return 0; /* purecov: inspected */
  }
  null_value=0;
1041
  if (multiply == 1)
unknown's avatar
unknown committed
1042
  {
1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058
    uint len;
    res= copy_if_not_alloced(str,res,res->length());
    len= converter(collation.collation, (char*) res->ptr(), res->length(),
                                        (char*) res->ptr(), res->length());
    DBUG_ASSERT(len <= res->length());
    res->length(len);
  }
  else
  {
    uint len= res->length() * multiply;
    tmp_value.alloc(len);
    tmp_value.set_charset(collation.collation);
    len= converter(collation.collation, (char*) res->ptr(), res->length(),
                                        (char*) tmp_value.ptr(), len);
    tmp_value.length(len);
    res= &tmp_value;
unknown's avatar
unknown committed
1059 1060 1061 1062 1063 1064 1065
  }
  return res;
}


String *Item_func_left::val_str(String *str)
{
1066
  DBUG_ASSERT(fixed == 1);
1067 1068 1069 1070
  String *res= args[0]->val_str(str);

  /* must be longlong to avoid truncation */
  longlong length= args[1]->val_int();
1071
  uint char_pos;
unknown's avatar
unknown committed
1072

unknown's avatar
unknown committed
1073
  if ((null_value=(args[0]->null_value || args[1]->null_value)))
unknown's avatar
unknown committed
1074
    return 0;
1075 1076 1077

  /* if "unsigned_flag" is set, we have a *huge* positive number. */
  if ((length <= 0) && (!args[1]->unsigned_flag))
unknown's avatar
SCRUM  
unknown committed
1078
    return &my_empty_string;
1079 1080

  if ((res->length() <= (ulonglong) length) ||
1081
      (res->length() <= (char_pos= res->charpos((int) length))))
unknown's avatar
a fix  
unknown committed
1082
    return res;
1083 1084 1085

  tmp_value.set(*res, 0, char_pos);
  return &tmp_value;
unknown's avatar
unknown committed
1086 1087 1088 1089 1090 1091 1092 1093
}


void Item_str_func::left_right_max_length()
{
  max_length=args[0]->max_length;
  if (args[1]->const_item())
  {
1094
    int length=(int) args[1]->val_int()*collation.collation->mbmaxlen;
unknown's avatar
unknown committed
1095 1096 1097 1098 1099 1100 1101 1102 1103 1104
    if (length <= 0)
      max_length=0;
    else
      set_if_smaller(max_length,(uint) length);
  }
}


void Item_func_left::fix_length_and_dec()
{
1105
  collation.set(args[0]->collation);
unknown's avatar
unknown committed
1106 1107 1108 1109 1110 1111
  left_right_max_length();
}


String *Item_func_right::val_str(String *str)
{
1112
  DBUG_ASSERT(fixed == 1);
1113 1114 1115
  String *res= args[0]->val_str(str);
  /* must be longlong to avoid truncation */
  longlong length= args[1]->val_int();
unknown's avatar
unknown committed
1116

unknown's avatar
unknown committed
1117
  if ((null_value=(args[0]->null_value || args[1]->null_value)))
unknown's avatar
unknown committed
1118
    return 0; /* purecov: inspected */
1119 1120 1121

  /* if "unsigned_flag" is set, we have a *huge* positive number. */
  if ((length <= 0) && (!args[1]->unsigned_flag))
unknown's avatar
SCRUM  
unknown committed
1122
    return &my_empty_string; /* purecov: inspected */
1123 1124

  if (res->length() <= (ulonglong) length)
unknown's avatar
unknown committed
1125
    return res; /* purecov: inspected */
unknown's avatar
unknown committed
1126

unknown's avatar
unknown committed
1127 1128
  uint start=res->numchars();
  if (start <= (uint) length)
unknown's avatar
unknown committed
1129
    return res;
unknown's avatar
unknown committed
1130
  start=res->charpos(start - (uint) length);
unknown's avatar
unknown committed
1131
  tmp_value.set(*res,start,res->length()-start);
unknown's avatar
unknown committed
1132 1133 1134 1135 1136 1137
  return &tmp_value;
}


void Item_func_right::fix_length_and_dec()
{
1138
  collation.set(args[0]->collation);
unknown's avatar
unknown committed
1139 1140 1141 1142 1143 1144
  left_right_max_length();
}


String *Item_func_substr::val_str(String *str)
{
1145
  DBUG_ASSERT(fixed == 1);
unknown's avatar
unknown committed
1146
  String *res  = args[0]->val_str(str);
1147 1148 1149 1150 1151 1152
  /* must be longlong to avoid truncation */
  longlong start= args[1]->val_int();
  /* Assumes that the maximum length of a String is < INT_MAX32. */
  /* Limit so that code sees out-of-bound value properly. */
  longlong length= arg_count == 3 ? args[2]->val_int() : INT_MAX32;
  longlong tmp_length;
unknown's avatar
unknown committed
1153 1154 1155 1156

  if ((null_value=(args[0]->null_value || args[1]->null_value ||
		   (arg_count == 3 && args[2]->null_value))))
    return 0; /* purecov: inspected */
1157 1158 1159

  /* Negative length, will return empty string. */
  if ((arg_count == 3) && (length <= 0) && !args[2]->unsigned_flag)
unknown's avatar
SCRUM  
unknown committed
1160
    return &my_empty_string;
unknown's avatar
unknown committed
1161

1162 1163 1164 1165 1166 1167 1168
  /* Assumes that the maximum length of a String is < INT_MAX32. */
  /* Set here so that rest of code sees out-of-bound value as such. */
  if ((length <= 0) || (length > INT_MAX32))
    length= INT_MAX32;

  /* if "unsigned_flag" is set, we have a *huge* positive number. */
  /* Assumes that the maximum length of a String is < INT_MAX32. */
1169 1170
  if ((!args[1]->unsigned_flag && (start < INT_MIN32 || start > INT_MAX32)) ||
      (args[1]->unsigned_flag && ((ulonglong) start > INT_MAX32)))
1171
    return &my_empty_string;
unknown's avatar
unknown committed
1172

1173
  start= ((start < 0) ? res->numchars() + start : start - 1);
1174
  start= res->charpos((int) start);
1175 1176 1177
  if ((start < 0) || ((uint) start + 1 > res->length()))
    return &my_empty_string;

1178
  length= res->charpos((int) length, (uint32) start);
1179 1180 1181
  tmp_length= res->length() - start;
  length= min(length, tmp_length);

1182
  if (!start && (longlong) res->length() == length)
unknown's avatar
unknown committed
1183
    return res;
1184
  tmp_value.set(*res, (uint32) start, (uint32) length);
unknown's avatar
unknown committed
1185 1186 1187 1188 1189 1190 1191 1192
  return &tmp_value;
}


void Item_func_substr::fix_length_and_dec()
{
  max_length=args[0]->max_length;

1193
  collation.set(args[0]->collation);
unknown's avatar
unknown committed
1194 1195
  if (args[1]->const_item())
  {
1196 1197
    int32 start= (int32) args[1]->val_int();
    start= (int32)((start < 0) ? max_length + start : start - 1);
unknown's avatar
unknown committed
1198 1199 1200 1201 1202 1203 1204
    if (start < 0 || start >= (int32) max_length)
      max_length=0; /* purecov: inspected */
    else
      max_length-= (uint) start;
  }
  if (arg_count == 3 && args[2]->const_item())
  {
1205
    int32 length= (int32) args[2]->val_int();
unknown's avatar
unknown committed
1206 1207 1208 1209 1210
    if (length <= 0)
      max_length=0; /* purecov: inspected */
    else
      set_if_smaller(max_length,(uint) length);
  }
1211
  max_length*= collation.collation->mbmaxlen;
unknown's avatar
unknown committed
1212 1213 1214
}


1215 1216 1217
void Item_func_substr_index::fix_length_and_dec()
{ 
  max_length= args[0]->max_length;
unknown's avatar
unknown committed
1218

1219
  if (agg_arg_charsets(collation, args, 2, MY_COLL_CMP_CONV, 1))
unknown's avatar
unknown committed
1220
    return;
1221 1222 1223
}


unknown's avatar
unknown committed
1224 1225
String *Item_func_substr_index::val_str(String *str)
{
1226
  DBUG_ASSERT(fixed == 1);
1227 1228 1229
  String *res= args[0]->val_str(str);
  String *delimiter= args[1]->val_str(&tmp_value);
  int32 count= (int32) args[2]->val_int();
unknown's avatar
unknown committed
1230 1231 1232 1233 1234 1235 1236 1237
  uint offset;

  if (args[0]->null_value || args[1]->null_value || args[2]->null_value)
  {					// string and/or delim are null
    null_value=1;
    return 0;
  }
  null_value=0;
1238 1239
  uint delimiter_length= delimiter->length();
  if (!res->length() || !delimiter_length || !count)
unknown's avatar
SCRUM  
unknown committed
1240
    return &my_empty_string;		// Wrong parameters
unknown's avatar
unknown committed
1241

1242 1243
  res->set_charset(collation.collation);

unknown's avatar
unknown committed
1244
#ifdef USE_MB
1245
  if (use_mb(res->charset()))
unknown's avatar
unknown committed
1246
  {
1247 1248 1249 1250 1251
    const char *ptr= res->ptr();
    const char *strend= ptr+res->length();
    const char *end= strend-delimiter_length+1;
    const char *search= delimiter->ptr();
    const char *search_end= search+delimiter_length;
unknown's avatar
unknown committed
1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262
    int32 n=0,c=count,pass;
    register uint32 l;
    for (pass=(count>0);pass<2;++pass)
    {
      while (ptr < end)
      {
        if (*ptr == *search)
        {
	  register char *i,*j;
	  i=(char*) ptr+1; j=(char*) search+1;
	  while (j != search_end)
1263
	    if (*i++ != *j++) goto skip;
unknown's avatar
unknown committed
1264 1265
	  if (pass==0) ++n;
	  else if (!--c) break;
1266
	  ptr+= delimiter_length;
unknown's avatar
unknown committed
1267 1268
	  continue;
	}
1269
    skip:
1270
        if ((l=my_ismbchar(res->charset(), ptr,strend))) ptr+=l;
unknown's avatar
unknown committed
1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283
        else ++ptr;
      } /* either not found or got total number when count<0 */
      if (pass == 0) /* count<0 */
      {
        c+=n+1;
        if (c<=0) return res; /* not found, return original string */
        ptr=res->ptr();
      }
      else
      {
        if (c) return res; /* Not found, return original string */
        if (count>0) /* return left part */
        {
unknown's avatar
unknown committed
1284
	  tmp_value.set(*res,0,(ulong) (ptr-res->ptr()));
unknown's avatar
unknown committed
1285 1286 1287
        }
        else /* return right part */
        {
1288
	  ptr+= delimiter_length;
unknown's avatar
unknown committed
1289
	  tmp_value.set(*res,(ulong) (ptr-res->ptr()), (ulong) (strend-ptr));
unknown's avatar
unknown committed
1290 1291 1292 1293 1294 1295 1296 1297 1298
        }
      }
    }
  }
  else
#endif /* USE_MB */
  {
    if (count > 0)
    {					// start counting from the beginning
1299
      for (offset=0; ; offset+= delimiter_length)
unknown's avatar
unknown committed
1300
      {
1301
	if ((int) (offset= res->strstr(*delimiter, offset)) < 0)
unknown's avatar
unknown committed
1302 1303 1304 1305 1306 1307 1308 1309 1310
	  return res;			// Didn't find, return org string
	if (!--count)
	{
	  tmp_value.set(*res,0,offset);
	  break;
	}
      }
    }
    else
1311
    {
unknown's avatar
unknown committed
1312 1313 1314 1315
      /*
        Negative index, start counting at the end
      */
      for (offset=res->length(); offset ;)
unknown's avatar
unknown committed
1316
      {
unknown's avatar
unknown committed
1317 1318 1319 1320 1321
        /* 
          this call will result in finding the position pointing to one 
          address space less than where the found substring is located
          in res
        */
1322
	if ((int) (offset= res->strrstr(*delimiter, offset)) < 0)
unknown's avatar
unknown committed
1323
	  return res;			// Didn't find, return org string
unknown's avatar
unknown committed
1324 1325 1326 1327
        /*
          At this point, we've searched for the substring
          the number of times as supplied by the index value
        */
unknown's avatar
unknown committed
1328 1329
	if (!++count)
	{
1330
	  offset+= delimiter_length;
unknown's avatar
unknown committed
1331 1332 1333 1334 1335 1336
	  tmp_value.set(*res,offset,res->length()- offset);
	  break;
	}
      }
    }
  }
1337 1338 1339 1340 1341 1342
  /*
    We always mark tmp_value as const so that if val_str() is called again
    on this object, we don't disrupt the contents of tmp_value when it was
    derived from another String.
  */
  tmp_value.mark_as_const();
unknown's avatar
unknown committed
1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355
  return (&tmp_value);
}

/*
** The trim functions are extension to ANSI SQL because they trim substrings
** They ltrim() and rtrim() functions are optimized for 1 byte strings
** They also return the original string if possible, else they return
** a substring that points at the original string.
*/


String *Item_func_ltrim::val_str(String *str)
{
1356
  DBUG_ASSERT(fixed == 1);
1357 1358 1359
  char buff[MAX_FIELD_WIDTH], *ptr, *end;
  String tmp(buff,sizeof(buff),system_charset_info);
  String *res, *remove_str;
unknown's avatar
unknown committed
1360 1361 1362
  uint remove_length;
  LINT_INIT(remove_length);

1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374
  res= args[0]->val_str(str);
  if ((null_value=args[0]->null_value))
    return 0;
  remove_str= &remove;                          /* Default value. */
  if (arg_count == 2)
  {
    remove_str= args[1]->val_str(&tmp);
    if ((null_value= args[1]->null_value))
      return 0;
  }

  if ((remove_length= remove_str->length()) == 0 ||
unknown's avatar
unknown committed
1375 1376 1377
      remove_length > res->length())
    return res;

1378 1379
  ptr= (char*) res->ptr();
  end= ptr+res->length();
unknown's avatar
unknown committed
1380 1381 1382 1383 1384 1385 1386 1387 1388 1389
  if (remove_length == 1)
  {
    char chr=(*remove_str)[0];
    while (ptr != end && *ptr == chr)
      ptr++;
  }
  else
  {
    const char *r_ptr=remove_str->ptr();
    end-=remove_length;
1390
    while (ptr <= end && !memcmp(ptr, r_ptr, remove_length))
unknown's avatar
unknown committed
1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402
      ptr+=remove_length;
    end+=remove_length;
  }
  if (ptr == res->ptr())
    return res;
  tmp_value.set(*res,(uint) (ptr - res->ptr()),(uint) (end-ptr));
  return &tmp_value;
}


String *Item_func_rtrim::val_str(String *str)
{
1403
  DBUG_ASSERT(fixed == 1);
1404 1405 1406
  char buff[MAX_FIELD_WIDTH], *ptr, *end;
  String tmp(buff, sizeof(buff), system_charset_info);
  String *res, *remove_str;
unknown's avatar
unknown committed
1407 1408 1409
  uint remove_length;
  LINT_INIT(remove_length);

1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421
  res= args[0]->val_str(str);
  if ((null_value=args[0]->null_value))
    return 0;
  remove_str= &remove;                          /* Default value. */
  if (arg_count == 2)
  {
    remove_str= args[1]->val_str(&tmp);
    if ((null_value= args[1]->null_value))
      return 0;
  }

  if ((remove_length= remove_str->length()) == 0 ||
unknown's avatar
unknown committed
1422 1423 1424
      remove_length > res->length())
    return res;

1425 1426
  ptr= (char*) res->ptr();
  end= ptr+res->length();
unknown's avatar
unknown committed
1427 1428 1429 1430 1431 1432 1433 1434
#ifdef USE_MB
  char *p=ptr;
  register uint32 l;
#endif
  if (remove_length == 1)
  {
    char chr=(*remove_str)[0];
#ifdef USE_MB
1435
    if (use_mb(res->charset()))
unknown's avatar
unknown committed
1436 1437 1438
    {
      while (ptr < end)
      {
1439
	if ((l=my_ismbchar(res->charset(), ptr,end))) ptr+=l,p=ptr;
unknown's avatar
unknown committed
1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451
	else ++ptr;
      }
      ptr=p;
    }
#endif
    while (ptr != end  && end[-1] == chr)
      end--;
  }
  else
  {
    const char *r_ptr=remove_str->ptr();
#ifdef USE_MB
1452
    if (use_mb(res->charset()))
unknown's avatar
unknown committed
1453 1454 1455 1456
    {
  loop:
      while (ptr + remove_length < end)
      {
1457
	if ((l=my_ismbchar(res->charset(), ptr,end))) ptr+=l;
unknown's avatar
unknown committed
1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469
	else ++ptr;
      }
      if (ptr + remove_length == end && !memcmp(ptr,r_ptr,remove_length))
      {
	end-=remove_length;
	ptr=p;
	goto loop;
      }
    }
    else
#endif /* USE_MB */
    {
1470 1471
      while (ptr + remove_length <= end &&
	     !memcmp(end-remove_length, r_ptr, remove_length))
unknown's avatar
unknown committed
1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483
	end-=remove_length;
    }
  }
  if (end == res->ptr()+res->length())
    return res;
  tmp_value.set(*res,0,(uint) (end-res->ptr()));
  return &tmp_value;
}


String *Item_func_trim::val_str(String *str)
{
1484
  DBUG_ASSERT(fixed == 1);
1485 1486 1487 1488
  char buff[MAX_FIELD_WIDTH], *ptr, *end;
  const char *r_ptr;
  String tmp(buff, sizeof(buff), system_charset_info);
  String *res, *remove_str;
unknown's avatar
unknown committed
1489 1490
  uint remove_length;
  LINT_INIT(remove_length);
unknown's avatar
unknown committed
1491

1492 1493 1494 1495
  res= args[0]->val_str(str);
  if ((null_value=args[0]->null_value))
    return 0;
  remove_str= &remove;                          /* Default value. */
unknown's avatar
unknown committed
1496 1497 1498 1499 1500 1501
  if (arg_count == 2)
  {
    remove_str= args[1]->val_str(&tmp);
    if ((null_value= args[1]->null_value))
      return 0;
  }
unknown's avatar
unknown committed
1502

1503
  if ((remove_length= remove_str->length()) == 0 ||
unknown's avatar
unknown committed
1504 1505 1506
      remove_length > res->length())
    return res;

1507 1508 1509
  ptr= (char*) res->ptr();
  end= ptr+res->length();
  r_ptr= remove_str->ptr();
unknown's avatar
unknown committed
1510
  while (ptr+remove_length <= end && !memcmp(ptr,r_ptr,remove_length))
unknown's avatar
unknown committed
1511 1512
    ptr+=remove_length;
#ifdef USE_MB
1513
  if (use_mb(res->charset()))
unknown's avatar
unknown committed
1514 1515 1516 1517 1518 1519
  {
    char *p=ptr;
    register uint32 l;
 loop:
    while (ptr + remove_length < end)
    {
1520
      if ((l=my_ismbchar(res->charset(), ptr,end))) ptr+=l;
unknown's avatar
unknown committed
1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533
      else ++ptr;
    }
    if (ptr + remove_length == end && !memcmp(ptr,r_ptr,remove_length))
    {
      end-=remove_length;
      ptr=p;
      goto loop;
    }
    ptr=p;
  }
  else
#endif /* USE_MB */
  {
unknown's avatar
unknown committed
1534
    while (ptr + remove_length <= end &&
unknown's avatar
unknown committed
1535 1536 1537 1538 1539 1540 1541 1542 1543
	   !memcmp(end-remove_length,r_ptr,remove_length))
      end-=remove_length;
  }
  if (ptr == res->ptr() && end == ptr+res->length())
    return res;
  tmp_value.set(*res,(uint) (ptr - res->ptr()),(uint) (end-ptr));
  return &tmp_value;
}

1544 1545 1546 1547 1548
void Item_func_trim::fix_length_and_dec()
{
  max_length= args[0]->max_length;
  if (arg_count == 1)
  {
1549
    collation.set(args[0]->collation);
1550
    remove.set_charset(collation.collation);
1551 1552 1553 1554
    remove.set_ascii(" ",1);
  }
  else
  {
1555 1556 1557
    // Handle character set for args[1] and args[0].
    // Note that we pass args[1] as the first item, and args[0] as the second.
    if (agg_arg_charsets(collation, &args[1], 2, MY_COLL_CMP_CONV, -1))
unknown's avatar
unknown committed
1558
      return;
1559 1560 1561
  }
}

1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573
void Item_func_trim::print(String *str)
{
  if (arg_count == 1)
  {
    Item_func::print(str);
    return;
  }
  str->append(Item_func_trim::func_name());
  str->append('(');
  str->append(mode_name());
  str->append(' ');
  args[1]->print(str);
1574
  str->append(STRING_WITH_LEN(" from "));
1575 1576 1577 1578
  args[0]->print(str);
  str->append(')');
}

1579

1580
/* Item_func_password */
unknown's avatar
unknown committed
1581 1582 1583

String *Item_func_password::val_str(String *str)
{
1584
  DBUG_ASSERT(fixed == 1);
1585
  String *res= args[0]->val_str(str); 
unknown's avatar
unknown committed
1586 1587
  if ((null_value=args[0]->null_value))
    return 0;
1588
  if (res->length() == 0)
unknown's avatar
SCRUM  
unknown committed
1589
    return &my_empty_string;
1590 1591 1592
  make_scrambled_password(tmp_value, res->c_ptr());
  str->set(tmp_value, SCRAMBLED_PASSWORD_CHAR_LENGTH, res->charset());
  return str;
unknown's avatar
unknown committed
1593 1594
}

unknown's avatar
unknown committed
1595 1596 1597 1598 1599 1600 1601 1602
char *Item_func_password::alloc(THD *thd, const char *password)
{
  char *buff= (char *) thd->alloc(SCRAMBLED_PASSWORD_CHAR_LENGTH+1);
  if (buff)
    make_scrambled_password(buff, password);
  return buff;
}

1603 1604
/* Item_func_old_password */

1605 1606
String *Item_func_old_password::val_str(String *str)
{
1607
  DBUG_ASSERT(fixed == 1);
1608
  String *res= args[0]->val_str(str);
1609 1610 1611
  if ((null_value=args[0]->null_value))
    return 0;
  if (res->length() == 0)
unknown's avatar
SCRUM  
unknown committed
1612
    return &my_empty_string;
1613 1614
  make_scrambled_password_323(tmp_value, res->c_ptr());
  str->set(tmp_value, SCRAMBLED_PASSWORD_CHAR_LENGTH_323, res->charset());
1615 1616 1617
  return str;
}

unknown's avatar
unknown committed
1618 1619 1620 1621 1622 1623 1624
char *Item_func_old_password::alloc(THD *thd, const char *password)
{
  char *buff= (char *) thd->alloc(SCRAMBLED_PASSWORD_CHAR_LENGTH_323+1);
  if (buff)
    make_scrambled_password_323(buff, password);
  return buff;
}
1625 1626


unknown's avatar
unknown committed
1627
#define bin_to_ascii(c) ((c)>=38?((c)-38+'a'):(c)>=12?((c)-12+'A'):(c)+'.')
unknown's avatar
unknown committed
1628 1629 1630

String *Item_func_encrypt::val_str(String *str)
{
1631
  DBUG_ASSERT(fixed == 1);
unknown's avatar
unknown committed
1632 1633 1634 1635 1636 1637 1638
  String *res  =args[0]->val_str(str);

#ifdef HAVE_CRYPT
  char salt[3],*salt_ptr;
  if ((null_value=args[0]->null_value))
    return 0;
  if (res->length() == 0)
unknown's avatar
SCRUM  
unknown committed
1639
    return &my_empty_string;
unknown's avatar
unknown committed
1640 1641 1642 1643

  if (arg_count == 1)
  {					// generate random salt
    time_t timestamp=current_thd->query_start();
unknown's avatar
unknown committed
1644 1645
    salt[0] = bin_to_ascii( (ulong) timestamp & 0x3f);
    salt[1] = bin_to_ascii(( (ulong) timestamp >> 5) & 0x3f);
unknown's avatar
unknown committed
1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656
    salt[2] = 0;
    salt_ptr=salt;
  }
  else
  {					// obtain salt from the first two bytes
    String *salt_str=args[1]->val_str(&tmp_value);
    if ((null_value= (args[1]->null_value || salt_str->length() < 2)))
      return 0;
    salt_ptr= salt_str->c_ptr();
  }
  pthread_mutex_lock(&LOCK_crypt);
1657 1658 1659 1660 1661 1662 1663
  char *tmp= crypt(res->c_ptr(),salt_ptr);
  if (!tmp)
  {
    pthread_mutex_unlock(&LOCK_crypt);
    null_value= 1;
    return 0;
  }
1664
  str->set(tmp, (uint) strlen(tmp), &my_charset_bin);
unknown's avatar
unknown committed
1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676
  str->copy();
  pthread_mutex_unlock(&LOCK_crypt);
  return str;
#else
  null_value=1;
  return 0;
#endif	/* HAVE_CRYPT */
}

void Item_func_encode::fix_length_and_dec()
{
  max_length=args[0]->max_length;
1677
  maybe_null=args[0]->maybe_null || args[1]->maybe_null;
1678
  collation.set(&my_charset_bin);
unknown's avatar
unknown committed
1679 1680 1681 1682 1683
}

String *Item_func_encode::val_str(String *str)
{
  String *res;
1684 1685 1686 1687 1688
  char pw_buff[80];
  String tmp_pw_value(pw_buff, sizeof(pw_buff), system_charset_info);
  String *password;
  DBUG_ASSERT(fixed == 1);

unknown's avatar
unknown committed
1689 1690 1691 1692 1693
  if (!(res=args[0]->val_str(str)))
  {
    null_value=1; /* purecov: inspected */
    return 0; /* purecov: inspected */
  }
1694 1695 1696 1697 1698 1699 1700

  if (!(password=args[1]->val_str(& tmp_pw_value)))
  {
    null_value=1;
    return 0;
  }

unknown's avatar
unknown committed
1701 1702
  null_value=0;
  res=copy_if_not_alloced(str,res,res->length());
1703
  SQL_CRYPT sql_crypt(password->ptr());
unknown's avatar
unknown committed
1704 1705
  sql_crypt.init();
  sql_crypt.encode((char*) res->ptr(),res->length());
1706
  res->set_charset(&my_charset_bin);
unknown's avatar
unknown committed
1707 1708 1709 1710 1711 1712
  return res;
}

String *Item_func_decode::val_str(String *str)
{
  String *res;
1713 1714 1715 1716 1717
  char pw_buff[80];
  String tmp_pw_value(pw_buff, sizeof(pw_buff), system_charset_info);
  String *password;
  DBUG_ASSERT(fixed == 1);

unknown's avatar
unknown committed
1718 1719 1720 1721 1722
  if (!(res=args[0]->val_str(str)))
  {
    null_value=1; /* purecov: inspected */
    return 0; /* purecov: inspected */
  }
1723 1724 1725 1726 1727 1728 1729

  if (!(password=args[1]->val_str(& tmp_pw_value)))
  {
    null_value=1;
    return 0;
  }

unknown's avatar
unknown committed
1730 1731
  null_value=0;
  res=copy_if_not_alloced(str,res,res->length());
1732
  SQL_CRYPT sql_crypt(password->ptr());
unknown's avatar
unknown committed
1733 1734 1735 1736 1737 1738
  sql_crypt.init();
  sql_crypt.decode((char*) res->ptr(),res->length());
  return res;
}


1739 1740 1741 1742 1743 1744
Item *Item_func_sysconst::safe_charset_converter(CHARSET_INFO *tocs)
{
  Item_string *conv;
  uint conv_errors;
  String tmp, cstr, *ostr= val_str(&tmp);
  cstr.copy(ostr->ptr(), ostr->length(), ostr->charset(), tocs, &conv_errors);
1745 1746 1747 1748 1749
  if (conv_errors ||
      !(conv= new Item_static_string_func(fully_qualified_func_name(),
                                          cstr.ptr(), cstr.length(),
                                          cstr.charset(),
                                          collation.derivation)))
1750 1751 1752 1753
  {
    return NULL;
  }
  conv->str_value.copy();
unknown's avatar
unknown committed
1754
  conv->str_value.mark_as_const();
1755 1756 1757 1758
  return conv;
}


unknown's avatar
unknown committed
1759 1760
String *Item_func_database::val_str(String *str)
{
1761
  DBUG_ASSERT(fixed == 1);
unknown's avatar
unknown committed
1762
  THD *thd= current_thd;
unknown's avatar
unknown committed
1763
  if (thd->db == NULL)
1764
  {
1765 1766
    null_value= 1;
    return 0;
1767
  }
unknown's avatar
unknown committed
1768
  else
unknown's avatar
unknown committed
1769
    str->copy(thd->db, thd->db_length, system_charset_info);
unknown's avatar
unknown committed
1770 1771 1772
  return str;
}

unknown's avatar
unknown committed
1773

1774 1775 1776 1777
/*
  TODO: make USER() replicate properly (currently it is replicated to "")
*/
bool Item_func_user::init(const char *user, const char *host)
unknown's avatar
unknown committed
1778
{
1779
  DBUG_ASSERT(fixed == 1);
unknown's avatar
unknown committed
1780

1781 1782
  // For system threads (e.g. replication SQL thread) user may be empty
  if (user)
1783
  {
1784 1785
    CHARSET_INFO *cs= str_value.charset();
    uint res_length= (strlen(user)+strlen(host)+2) * cs->mbmaxlen;
1786

1787 1788 1789 1790 1791
    if (str_value.alloc(res_length))
    {
      null_value=1;
      return TRUE;
    }
1792

1793 1794 1795 1796
    res_length=cs->cset->snprintf(cs, (char*)str_value.ptr(), res_length,
                                  "%s@%s", user, host);
    str_value.length(res_length);
    str_value.mark_as_const();
1797
  }
1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817
  return FALSE;
}


bool Item_func_user::fix_fields(THD *thd, Item **ref)
{
  return (Item_func_sysconst::fix_fields(thd, ref) ||
          init(thd->main_security_ctx.user,
               thd->main_security_ctx.host_or_ip));
}


bool Item_func_current_user::fix_fields(THD *thd, Item **ref)
{
  if (Item_func_sysconst::fix_fields(thd, ref))
    return TRUE;

  Security_context *ctx= (context->security_ctx
                          ? context->security_ctx : thd->security_ctx);
  return init(ctx->priv_user, ctx->priv_host);
unknown's avatar
unknown committed
1818 1819
}

1820

unknown's avatar
unknown committed
1821 1822
void Item_func_soundex::fix_length_and_dec()
{
1823
  collation.set(args[0]->collation);
unknown's avatar
unknown committed
1824 1825 1826 1827 1828
  max_length=args[0]->max_length;
  set_if_bigger(max_length,4);
}


1829 1830 1831 1832 1833
/*
  If alpha, map input letter to soundex code.
  If not alpha and remove_garbage is set then skip to next char
  else return 0
*/
unknown's avatar
unknown committed
1834

1835
static char soundex_toupper(char ch)
unknown's avatar
unknown committed
1836
{
1837 1838 1839 1840 1841 1842
  return (ch >= 'a' && ch <= 'z') ? ch - 'a' + 'A' : ch;
}

static char get_scode(char *ptr)
{
  uchar ch= soundex_toupper(*ptr);
unknown's avatar
unknown committed
1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853
  if (ch < 'A' || ch > 'Z')
  {
					// Thread extended alfa (country spec)
    return '0';				// as vokal
  }
  return(soundex_map[ch-'A']);
}


String *Item_func_soundex::val_str(String *str)
{
1854
  DBUG_ASSERT(fixed == 1);
unknown's avatar
unknown committed
1855 1856
  String *res  =args[0]->val_str(str);
  char last_ch,ch;
1857
  CHARSET_INFO *cs= collation.collation;
unknown's avatar
unknown committed
1858

unknown's avatar
unknown committed
1859 1860 1861
  if ((null_value=args[0]->null_value))
    return 0; /* purecov: inspected */

unknown's avatar
unknown committed
1862
  if (tmp_value.alloc(max(res->length(),4)))
unknown's avatar
unknown committed
1863
    return str; /* purecov: inspected */
unknown's avatar
unknown committed
1864
  char *to= (char *) tmp_value.ptr();
unknown's avatar
unknown committed
1865
  char *from= (char *) res->ptr(), *end=from+res->length();
unknown's avatar
unknown committed
1866 1867
  tmp_value.set_charset(cs);
  
unknown's avatar
unknown committed
1868
  while (from != end && !my_isalpha(cs,*from)) // Skip pre-space
unknown's avatar
unknown committed
1869 1870
    from++; /* purecov: inspected */
  if (from == end)
unknown's avatar
SCRUM  
unknown committed
1871
    return &my_empty_string;		// No alpha characters.
1872 1873
  *to++ = soundex_toupper(*from);	// Copy first letter
  last_ch = get_scode(from);		// code of the first letter
unknown's avatar
unknown committed
1874 1875 1876 1877 1878 1879
					// for the first 'double-letter check.
					// Loop on input letters until
					// end of input (null) or output
					// letter code count = 3
  for (from++ ; from < end ; from++)
  {
unknown's avatar
unknown committed
1880
    if (!my_isalpha(cs,*from))
unknown's avatar
unknown committed
1881
      continue;
1882
    ch=get_scode(from);
unknown's avatar
unknown committed
1883 1884 1885 1886 1887 1888
    if ((ch != '0') && (ch != last_ch)) // if not skipped or double
    {
       *to++ = ch;			// letter, copy to output
       last_ch = ch;			// save code of last input letter
    }					// for next double-letter check
  }
unknown's avatar
unknown committed
1889
  for (end=(char*) tmp_value.ptr()+4 ; to < end ; to++)
unknown's avatar
unknown committed
1890 1891
    *to = '0';
  *to=0;				// end string
unknown's avatar
unknown committed
1892 1893
  tmp_value.length((uint) (to-tmp_value.ptr()));
  return &tmp_value;
unknown's avatar
unknown committed
1894 1895 1896 1897 1898 1899 1900 1901
}


/*
** Change a number to format '3,333,333,333.000'
** This should be 'internationalized' sometimes.
*/

1902 1903 1904 1905 1906 1907 1908 1909
const int FORMAT_MAX_DECIMALS= 30;

Item_func_format::Item_func_format(Item *org, Item *dec)
: Item_str_func(org, dec)
{
}

void Item_func_format::fix_length_and_dec()
unknown's avatar
unknown committed
1910
{
1911 1912 1913 1914
  collation.set(default_charset());
  uint char_length= args[0]->max_length/args[0]->collation.collation->mbmaxlen;
  max_length= ((char_length + (char_length-args[0]->decimals)/3) *
               collation.collation->mbmaxlen);
unknown's avatar
unknown committed
1915 1916 1917
}


unknown's avatar
unknown committed
1918 1919 1920 1921 1922
/*
  TODO: This needs to be fixed for multi-byte character set where numbers
  are stored in more than one byte
*/

unknown's avatar
unknown committed
1923 1924
String *Item_func_format::val_str(String *str)
{
1925 1926 1927 1928 1929 1930
  uint32 length;
  uint32 str_length;
  /* Number of decimal digits */
  int dec;
  /* Number of characters used to represent the decimals, including '.' */
  uint32 dec_length;
1931
  int diff;
1932
  DBUG_ASSERT(fixed == 1);
1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943

  dec= args[1]->val_int();
  if (args[1]->null_value)
  {
    null_value=1;
    return NULL;
  }

  dec= set_zone(dec, 0, FORMAT_MAX_DECIMALS);
  dec_length= dec ? dec+1 : 0;
  null_value=0;
1944

1945 1946 1947 1948 1949
  if (args[0]->result_type() == DECIMAL_RESULT ||
      args[0]->result_type() == INT_RESULT)
  {
    my_decimal dec_val, rnd_dec, *res;
    res= args[0]->val_decimal(&dec_val);
1950 1951
    if ((null_value=args[0]->null_value))
      return 0; /* purecov: inspected */
1952
    my_decimal_round(E_DEC_FATAL_ERROR, res, dec, false, &rnd_dec);
1953 1954 1955 1956 1957 1958 1959 1960 1961 1962
    my_decimal2string(E_DEC_FATAL_ERROR, &rnd_dec, 0, 0, 0, str);
    str_length= str->length();
    if (rnd_dec.sign())
      str_length--;
  }
  else
  {
    double nr= args[0]->val_real();
    if ((null_value=args[0]->null_value))
      return 0; /* purecov: inspected */
1963
    nr= my_double_round(nr, dec, FALSE);
1964
    /* Here default_charset() is right as this is not an automatic conversion */
1965
    str->set_real(nr, dec, default_charset());
1966 1967 1968 1969 1970 1971
    if (isnan(nr))
      return str;
    str_length=str->length();
    if (nr < 0)
      str_length--;				// Don't count sign
  }
1972
  /* We need this test to handle 'nan' values */
1973
  if (str_length >= dec_length+4)
unknown's avatar
unknown committed
1974 1975
  {
    char *tmp,*pos;
1976
    length= str->length()+(diff=((int)(str_length- dec_length-1))/3);
1977
    str= copy_if_not_alloced(&tmp_str,str,length);
unknown's avatar
unknown committed
1978
    str->length(length);
1979
    tmp= (char*) str->ptr()+length - dec_length-1;
unknown's avatar
unknown committed
1980
    for (pos= (char*) str->ptr()+length-1; pos != tmp; pos--)
1981
      pos[0]= pos[-diff];
unknown's avatar
unknown committed
1982 1983
    while (diff)
    {
1984 1985 1986 1987 1988 1989
      *pos= *(pos - diff);
      pos--;
      *pos= *(pos - diff);
      pos--;
      *pos= *(pos - diff);
      pos--;
unknown's avatar
unknown committed
1990 1991 1992 1993 1994 1995 1996 1997 1998
      pos[0]=',';
      pos--;
      diff--;
    }
  }
  return str;
}


1999 2000
void Item_func_format::print(String *str)
{
2001
  str->append(STRING_WITH_LEN("format("));
2002
  args[0]->print(str);
2003 2004
  str->append(',');
  args[1]->print(str);
2005 2006 2007
  str->append(')');
}

unknown's avatar
unknown committed
2008 2009 2010 2011
void Item_func_elt::fix_length_and_dec()
{
  max_length=0;
  decimals=0;
2012

2013
  if (agg_arg_charsets(collation, args+1, arg_count-1, MY_COLL_ALLOW_CONV, 1))
unknown's avatar
unknown committed
2014 2015
    return;

2016
  for (uint i= 1 ; i < arg_count ; i++)
unknown's avatar
unknown committed
2017 2018 2019 2020 2021 2022 2023 2024
  {
    set_if_bigger(max_length,args[i]->max_length);
    set_if_bigger(decimals,args[i]->decimals);
  }
  maybe_null=1;					// NULL if wrong first arg
}


2025
double Item_func_elt::val_real()
unknown's avatar
unknown committed
2026
{
2027
  DBUG_ASSERT(fixed == 1);
unknown's avatar
unknown committed
2028
  uint tmp;
2029
  null_value=1;
2030
  if ((tmp=(uint) args[0]->val_int()) == 0 || tmp >= arg_count)
unknown's avatar
unknown committed
2031
    return 0.0;
2032
  double result= args[tmp]->val_real();
unknown's avatar
unknown committed
2033
  null_value= args[tmp]->null_value;
2034
  return result;
unknown's avatar
unknown committed
2035 2036
}

unknown's avatar
unknown committed
2037

unknown's avatar
unknown committed
2038 2039
longlong Item_func_elt::val_int()
{
2040
  DBUG_ASSERT(fixed == 1);
unknown's avatar
unknown committed
2041
  uint tmp;
2042
  null_value=1;
2043
  if ((tmp=(uint) args[0]->val_int()) == 0 || tmp >= arg_count)
unknown's avatar
unknown committed
2044
    return 0;
unknown's avatar
unknown committed
2045 2046 2047

  longlong result= args[tmp]->val_int();
  null_value= args[tmp]->null_value;
2048
  return result;
unknown's avatar
unknown committed
2049 2050
}

unknown's avatar
unknown committed
2051

unknown's avatar
unknown committed
2052 2053
String *Item_func_elt::val_str(String *str)
{
2054
  DBUG_ASSERT(fixed == 1);
unknown's avatar
unknown committed
2055
  uint tmp;
2056
  null_value=1;
2057
  if ((tmp=(uint) args[0]->val_int()) == 0 || tmp >= arg_count)
unknown's avatar
unknown committed
2058
    return NULL;
2059

unknown's avatar
unknown committed
2060 2061 2062 2063
  String *result= args[tmp]->val_str(str);
  if (result)
    result->set_charset(collation.collation);
  null_value= args[tmp]->null_value;
2064
  return result;
unknown's avatar
unknown committed
2065 2066 2067
}


2068
void Item_func_make_set::split_sum_func(THD *thd, Item **ref_pointer_array,
2069
					List<Item> &fields)
2070
{
unknown's avatar
unknown committed
2071
  item->split_sum_func2(thd, ref_pointer_array, fields, &item, TRUE);
2072
  Item_str_func::split_sum_func(thd, ref_pointer_array, fields);
2073 2074 2075
}


unknown's avatar
unknown committed
2076 2077 2078
void Item_func_make_set::fix_length_and_dec()
{
  max_length=arg_count-1;
unknown's avatar
unknown committed
2079

2080
  if (agg_arg_charsets(collation, args, arg_count, MY_COLL_ALLOW_CONV, 1))
unknown's avatar
unknown committed
2081 2082
    return;
  
2083
  for (uint i=0 ; i < arg_count ; i++)
unknown's avatar
unknown committed
2084
    max_length+=args[i]->max_length;
unknown's avatar
unknown committed
2085

2086 2087 2088
  used_tables_cache|=	  item->used_tables();
  not_null_tables_cache&= item->not_null_tables();
  const_item_cache&=	  item->const_item();
2089
  with_sum_func= with_sum_func || item->with_sum_func;
unknown's avatar
unknown committed
2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103
}


void Item_func_make_set::update_used_tables()
{
  Item_func::update_used_tables();
  item->update_used_tables();
  used_tables_cache|=item->used_tables();
  const_item_cache&=item->const_item();
}


String *Item_func_make_set::val_str(String *str)
{
2104
  DBUG_ASSERT(fixed == 1);
unknown's avatar
unknown committed
2105 2106 2107
  ulonglong bits;
  bool first_found=0;
  Item **ptr=args;
unknown's avatar
SCRUM  
unknown committed
2108
  String *result=&my_empty_string;
unknown's avatar
unknown committed
2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121

  bits=item->val_int();
  if ((null_value=item->null_value))
    return NULL;

  if (arg_count < 64)
    bits &= ((ulonglong) 1 << arg_count)-1;

  for (; bits; bits >>= 1, ptr++)
  {
    if (bits & 1)
    {
      String *res= (*ptr)->val_str(str);
unknown's avatar
unknown committed
2122
      if (res)					// Skip nulls
unknown's avatar
unknown committed
2123 2124 2125 2126 2127 2128 2129 2130 2131
      {
	if (!first_found)
	{					// First argument
	  first_found=1;
	  if (res != str)
	    result=res;				// Use original string
	  else
	  {
	    if (tmp_str.copy(*res))		// Don't use 'str'
unknown's avatar
SCRUM  
unknown committed
2132
	      return &my_empty_string;
unknown's avatar
unknown committed
2133 2134 2135 2136 2137 2138 2139 2140 2141
	    result= &tmp_str;
	  }
	}
	else
	{
	  if (result != &tmp_str)
	  {					// Copy data to tmp_str
	    if (tmp_str.alloc(result->length()+res->length()+1) ||
		tmp_str.copy(*result))
unknown's avatar
SCRUM  
unknown committed
2142
	      return &my_empty_string;
unknown's avatar
unknown committed
2143 2144
	    result= &tmp_str;
	  }
2145
	  if (tmp_str.append(STRING_WITH_LEN(","), &my_charset_bin) || tmp_str.append(*res))
unknown's avatar
SCRUM  
unknown committed
2146
	    return &my_empty_string;
unknown's avatar
unknown committed
2147 2148 2149 2150 2151 2152 2153 2154
	}
      }
    }
  }
  return result;
}


2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174
Item *Item_func_make_set::transform(Item_transformer transformer, byte *arg)
{
  DBUG_ASSERT(!current_thd->is_stmt_prepare());

  Item *new_item= item->transform(transformer, arg);
  if (!new_item)
    return 0;

  /*
    THD::change_item_tree() should be called only if the tree was
    really transformed, i.e. when a new item has been created.
    Otherwise we'll be allocating a lot of unnecessary memory for
    change records at each execution.
  */
  if (item != new_item)
    current_thd->change_item_tree(&item, new_item);
  return Item_str_func::transform(transformer, arg);
}


2175 2176
void Item_func_make_set::print(String *str)
{
2177
  str->append(STRING_WITH_LEN("make_set("));
2178 2179 2180 2181
  item->print(str);
  if (arg_count)
  {
    str->append(',');
unknown's avatar
unknown committed
2182
    print_args(str, 0);
2183 2184 2185 2186 2187
  }
  str->append(')');
}


unknown's avatar
unknown committed
2188 2189
String *Item_func_char::val_str(String *str)
{
2190
  DBUG_ASSERT(fixed == 1);
unknown's avatar
unknown committed
2191 2192 2193 2194 2195
  str->length(0);
  for (uint i=0 ; i < arg_count ; i++)
  {
    int32 num=(int32) args[i]->val_int();
    if (!args[i]->null_value)
2196
    {
unknown's avatar
unknown committed
2197 2198 2199 2200 2201 2202 2203 2204
      if (num&0xFF000000L) {
        str->append((char)(num>>24));
        goto b2;
      } else if (num&0xFF0000L) {
    b2:        str->append((char)(num>>16));
        goto b1;
      } else if (num&0xFF00L) {
    b1:        str->append((char)(num>>8));
unknown's avatar
unknown committed
2205
      }
unknown's avatar
unknown committed
2206
      str->append((char) num);
2207
    }
unknown's avatar
unknown committed
2208
  }
2209
  str->set_charset(collation.collation);
unknown's avatar
unknown committed
2210
  str->realloc(str->length());			// Add end 0 (for Purify)
2211
  return check_well_formed_result(str);
unknown's avatar
unknown committed
2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225
}


inline String* alloc_buffer(String *res,String *str,String *tmp_value,
			    ulong length)
{
  if (res->alloced_length() < length)
  {
    if (str->alloced_length() >= length)
    {
      (void) str->copy(*res);
      str->length(length);
      return str;
    }
2226 2227 2228 2229 2230
    if (tmp_value->alloc(length))
      return 0;
    (void) tmp_value->copy(*res);
    tmp_value->length(length);
    return tmp_value;
unknown's avatar
unknown committed
2231 2232 2233 2234 2235 2236 2237 2238
  }
  res->length(length);
  return res;
}


void Item_func_repeat::fix_length_and_dec()
{
2239
  collation.set(args[0]->collation);
unknown's avatar
unknown committed
2240 2241
  if (args[1]->const_item())
  {
2242 2243 2244 2245 2246 2247 2248 2249 2250
    /* must be longlong to avoid truncation */
    longlong count= args[1]->val_int();

    /* Assumes that the maximum length of a String is < INT_MAX32. */
    /* Set here so that rest of code sees out-of-bound value as such. */
    if (count > INT_MAX32)
      count= INT_MAX32;

    ulonglong max_result_length= (ulonglong) args[0]->max_length * count;
2251
    if (max_result_length >= MAX_BLOB_WIDTH)
unknown's avatar
unknown committed
2252
    {
2253 2254
      max_result_length= MAX_BLOB_WIDTH;
      maybe_null= 1;
unknown's avatar
unknown committed
2255
    }
2256
    max_length= (ulong) max_result_length;
unknown's avatar
unknown committed
2257 2258 2259
  }
  else
  {
2260 2261
    max_length= MAX_BLOB_WIDTH;
    maybe_null= 1;
unknown's avatar
unknown committed
2262 2263 2264 2265 2266 2267 2268 2269 2270 2271
  }
}

/*
** Item_func_repeat::str is carefully written to avoid reallocs
** as much as possible at the cost of a local buffer
*/

String *Item_func_repeat::val_str(String *str)
{
2272
  DBUG_ASSERT(fixed == 1);
unknown's avatar
unknown committed
2273 2274
  uint length,tot_length;
  char *to;
2275
  /* must be longlong to avoid truncation */
2276
  longlong count= args[1]->val_int();
2277 2278
  String *res= args[0]->val_str(str);

unknown's avatar
unknown committed
2279 2280
  if (args[0]->null_value || args[1]->null_value)
    goto err;				// string and/or delim are null
2281
  null_value= 0;
2282
  if ((count <= 0) && !args[1]->unsigned_flag)	// For nicer SQL code
unknown's avatar
SCRUM  
unknown committed
2283
    return &my_empty_string;
2284 2285 2286 2287
  /* Assumes that the maximum length of a String is < INT_MAX32. */
  /* Bounds check on count:  If this is triggered, we will error. */
  if ((ulonglong) count > INT_MAX32)
    count= INT_MAX32;
unknown's avatar
unknown committed
2288 2289 2290
  if (count == 1)			// To avoid reallocs
    return res;
  length=res->length();
unknown's avatar
unknown committed
2291
  // Safe length check
2292
  if (length > current_thd->variables.max_allowed_packet / (uint) count)
2293 2294 2295
  {
    push_warning_printf(current_thd, MYSQL_ERROR::WARN_LEVEL_WARN,
			ER_WARN_ALLOWED_PACKET_OVERFLOWED,
2296 2297
			ER(ER_WARN_ALLOWED_PACKET_OVERFLOWED),
			func_name(), current_thd->variables.max_allowed_packet);
2298 2299
    goto err;
  }
unknown's avatar
unknown committed
2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319
  tot_length= length*(uint) count;
  if (!(res= alloc_buffer(res,str,&tmp_value,tot_length)))
    goto err;

  to=(char*) res->ptr()+length;
  while (--count)
  {
    memcpy(to,res->ptr(),length);
    to+=length;
  }
  return (res);

err:
  null_value=1;
  return 0;
}


void Item_func_rpad::fix_length_and_dec()
{
2320 2321
  // Handle character set for args[0] and args[2].
  if (agg_arg_charsets(collation, &args[0], 2, MY_COLL_ALLOW_CONV, 2))
2322
    return;
unknown's avatar
unknown committed
2323 2324
  if (args[1]->const_item())
  {
2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338
    ulonglong length= 0;

    if (collation.collation->mbmaxlen > 0)
    {
      ulonglong temp= (ulonglong) args[1]->val_int();

      /* Assumes that the maximum length of a String is < INT_MAX32. */
      /* Set here so that rest of code sees out-of-bound value as such. */
      if (temp > INT_MAX32)
	temp = INT_MAX32;

      length= temp * collation.collation->mbmaxlen;
    }

2339
    if (length >= MAX_BLOB_WIDTH)
unknown's avatar
unknown committed
2340
    {
2341 2342
      length= MAX_BLOB_WIDTH;
      maybe_null= 1;
unknown's avatar
unknown committed
2343
    }
2344
    max_length= (ulong) length;
unknown's avatar
unknown committed
2345 2346 2347
  }
  else
  {
2348 2349
    max_length= MAX_BLOB_WIDTH;
    maybe_null= 1;
unknown's avatar
unknown committed
2350 2351 2352 2353 2354 2355
  }
}


String *Item_func_rpad::val_str(String *str)
{
2356
  DBUG_ASSERT(fixed == 1);
2357
  uint32 res_byte_length,res_char_length,pad_char_length,pad_byte_length;
unknown's avatar
unknown committed
2358 2359
  char *to;
  const char *ptr_pad;
2360 2361 2362 2363 2364 2365
  /* must be longlong to avoid truncation */
  longlong count= args[1]->val_int();
  longlong byte_count;
  String *res= args[0]->val_str(str);
  String *rpad= args[2]->val_str(&rpad_str);

2366 2367 2368 2369
  if (!res || args[1]->null_value || !rpad || 
      ((count < 0) && !args[1]->unsigned_flag))
    goto err;
  null_value=0;
2370 2371
  /* Assumes that the maximum length of a String is < INT_MAX32. */
  /* Set here so that rest of code sees out-of-bound value as such. */
2372
  if ((ulonglong) count > INT_MAX32)
2373 2374
    count= INT_MAX32;
  if (count <= (res_char_length= res->numchars()))
2375
  {						// String to pad is big enough
2376
    res->length(res->charpos((int) count));	// Shorten result if longer
2377 2378
    return (res);
  }
2379
  pad_char_length= rpad->numchars();
2380 2381 2382

  byte_count= count * collation.collation->mbmaxlen;
  if ((ulonglong) byte_count > current_thd->variables.max_allowed_packet)
2383 2384 2385
  {
    push_warning_printf(current_thd, MYSQL_ERROR::WARN_LEVEL_WARN,
			ER_WARN_ALLOWED_PACKET_OVERFLOWED,
2386 2387
			ER(ER_WARN_ALLOWED_PACKET_OVERFLOWED),
			func_name(), current_thd->variables.max_allowed_packet);
2388 2389
    goto err;
  }
unknown's avatar
unknown committed
2390
  if (args[2]->null_value || !pad_char_length)
unknown's avatar
unknown committed
2391
    goto err;
2392
  res_byte_length= res->length();	/* Must be done before alloc_buffer */
2393
  if (!(res= alloc_buffer(res,str,&tmp_value, (ulong) byte_count)))
unknown's avatar
unknown committed
2394 2395
    goto err;

2396
  to= (char*) res->ptr()+res_byte_length;
unknown's avatar
unknown committed
2397
  ptr_pad=rpad->ptr();
2398 2399 2400
  pad_byte_length= rpad->length();
  count-= res_char_length;
  for ( ; (uint32) count > pad_char_length; count-= pad_char_length)
unknown's avatar
unknown committed
2401
  {
2402 2403
    memcpy(to,ptr_pad,pad_byte_length);
    to+= pad_byte_length;
unknown's avatar
unknown committed
2404
  }
2405 2406
  if (count)
  {
2407
    pad_byte_length= rpad->charpos((int) count);
2408 2409 2410 2411
    memcpy(to,ptr_pad,(size_t) pad_byte_length);
    to+= pad_byte_length;
  }
  res->length(to- (char*) res->ptr());
unknown's avatar
unknown committed
2412 2413 2414 2415 2416 2417 2418 2419 2420 2421
  return (res);

 err:
  null_value=1;
  return 0;
}


void Item_func_lpad::fix_length_and_dec()
{
2422 2423
  // Handle character set for args[0] and args[2].
  if (agg_arg_charsets(collation, &args[0], 2, MY_COLL_ALLOW_CONV, 2))
2424
    return;
2425
  
unknown's avatar
unknown committed
2426 2427
  if (args[1]->const_item())
  {
2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441
    ulonglong length= 0;

    if (collation.collation->mbmaxlen > 0)
    {
      ulonglong temp= (ulonglong) args[1]->val_int();

      /* Assumes that the maximum length of a String is < INT_MAX32. */
      /* Set here so that rest of code sees out-of-bound value as such. */
      if (temp > INT_MAX32)
        temp= INT_MAX32;

      length= temp * collation.collation->mbmaxlen;
    }

2442
    if (length >= MAX_BLOB_WIDTH)
unknown's avatar
unknown committed
2443
    {
2444 2445
      length= MAX_BLOB_WIDTH;
      maybe_null= 1;
unknown's avatar
unknown committed
2446
    }
2447
    max_length= (ulong) length;
unknown's avatar
unknown committed
2448 2449 2450
  }
  else
  {
2451 2452
    max_length= MAX_BLOB_WIDTH;
    maybe_null= 1;
unknown's avatar
unknown committed
2453 2454 2455 2456 2457 2458
  }
}


String *Item_func_lpad::val_str(String *str)
{
2459
  DBUG_ASSERT(fixed == 1);
unknown's avatar
unknown committed
2460
  uint32 res_char_length,pad_char_length;
2461 2462 2463
  /* must be longlong to avoid truncation */
  longlong count= args[1]->val_int();
  longlong byte_count;
2464 2465
  String *res= args[0]->val_str(&tmp_value);
  String *pad= args[2]->val_str(&lpad_str);
unknown's avatar
unknown committed
2466

2467 2468 2469 2470
  if (!res || args[1]->null_value || !pad ||  
      ((count < 0) && !args[1]->unsigned_flag))
    goto err;  
  null_value=0;
2471 2472
  /* Assumes that the maximum length of a String is < INT_MAX32. */
  /* Set here so that rest of code sees out-of-bound value as such. */
2473
  if ((ulonglong) count > INT_MAX32)
2474
    count= INT_MAX32;
2475 2476 2477 2478 2479

  res_char_length= res->numchars();

  if (count <= res_char_length)
  {
2480
    res->length(res->charpos((int) count));
2481
    return res;
2482
  }
2483 2484 2485 2486
  
  pad_char_length= pad->numchars();
  byte_count= count * collation.collation->mbmaxlen;
  
unknown's avatar
unknown committed
2487
  if ((ulonglong) byte_count > current_thd->variables.max_allowed_packet)
2488 2489 2490
  {
    push_warning_printf(current_thd, MYSQL_ERROR::WARN_LEVEL_WARN,
			ER_WARN_ALLOWED_PACKET_OVERFLOWED,
2491 2492
			ER(ER_WARN_ALLOWED_PACKET_OVERFLOWED),
			func_name(), current_thd->variables.max_allowed_packet);
2493 2494 2495
    goto err;
  }

2496 2497
  if (args[2]->null_value || !pad_char_length ||
      str->alloc((uint32) byte_count))
unknown's avatar
unknown committed
2498
    goto err;
2499 2500 2501 2502 2503
  
  str->length(0);
  str->set_charset(collation.collation);
  count-= res_char_length;
  while (count >= pad_char_length)
unknown's avatar
unknown committed
2504
  {
2505 2506
    str->append(*pad);
    count-= pad_char_length;
unknown's avatar
unknown committed
2507
  }
2508
  if (count > 0)
2509
    str->append(pad->ptr(), pad->charpos((int) count), collation.collation);
2510

2511 2512 2513
  str->append(*res);
  null_value= 0;
  return str;
unknown's avatar
unknown committed
2514

2515 2516
err:
  null_value= 1;
unknown's avatar
unknown committed
2517 2518 2519 2520 2521 2522
  return 0;
}


String *Item_func_conv::val_str(String *str)
{
2523
  DBUG_ASSERT(fixed == 1);
unknown's avatar
unknown committed
2524 2525 2526 2527 2528
  String *res= args[0]->val_str(str);
  char *endptr,ans[65],*ptr;
  longlong dec;
  int from_base= (int) args[1]->val_int();
  int to_base= (int) args[2]->val_int();
2529
  int err;
unknown's avatar
unknown committed
2530 2531 2532 2533 2534

  if (args[0]->null_value || args[1]->null_value || args[2]->null_value ||
      abs(to_base) > 36 || abs(to_base) < 2 ||
      abs(from_base) > 36 || abs(from_base) < 2 || !(res->length()))
  {
2535 2536
    null_value= 1;
    return NULL;
unknown's avatar
unknown committed
2537
  }
2538
  null_value= 0;
unknown's avatar
unknown committed
2539
  unsigned_flag= !(from_base < 0);
2540 2541 2542 2543 2544 2545 2546 2547 2548 2549

  if (args[0]->field_type() == MYSQL_TYPE_BIT) 
  {
    /* 
     Special case: The string representation of BIT doesn't resemble the
     decimal representation, so we shouldn't change it to string and then to
     decimal. 
    */
    dec= args[0]->val_int();
  }
unknown's avatar
unknown committed
2550
  else
2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561
  {
    if (from_base < 0)
      dec= my_strntoll(res->charset(), res->ptr(), res->length(),
                       -from_base, &endptr, &err);
    else
      dec= (longlong) my_strntoull(res->charset(), res->ptr(), res->length(),
                                   from_base, &endptr, &err);
  }

  ptr= longlong2str(dec, ans, to_base);
  if (str->copy(ans, (uint32) (ptr-ans), default_charset()))
unknown's avatar
SCRUM  
unknown committed
2562
    return &my_empty_string;
unknown's avatar
unknown committed
2563 2564 2565
  return str;
}

unknown's avatar
unknown committed
2566

2567 2568
String *Item_func_conv_charset::val_str(String *str)
{
2569
  DBUG_ASSERT(fixed == 1);
2570 2571
  if (use_cached_value)
    return null_value ? 0 : &str_value;
2572
  String *arg= args[0]->val_str(str);
unknown's avatar
unknown committed
2573
  uint dummy_errors;
2574 2575 2576 2577 2578
  if (!arg)
  {
    null_value=1;
    return 0;
  }
unknown's avatar
unknown committed
2579
  null_value= str_value.copy(arg->ptr(),arg->length(),arg->charset(),
unknown's avatar
unknown committed
2580
                             conv_charset, &dummy_errors);
2581
  return null_value ? 0 : check_well_formed_result(&str_value);
2582 2583 2584 2585
}

void Item_func_conv_charset::fix_length_and_dec()
{
2586
  collation.set(conv_charset, DERIVATION_IMPLICIT);
2587
  max_length = args[0]->max_length*conv_charset->mbmaxlen;
2588 2589
}

2590 2591
void Item_func_conv_charset::print(String *str)
{
2592
  str->append(STRING_WITH_LEN("convert("));
2593
  args[0]->print(str);
2594
  str->append(STRING_WITH_LEN(" using "));
2595 2596 2597
  str->append(conv_charset->csname);
  str->append(')');
}
unknown's avatar
unknown committed
2598 2599 2600

String *Item_func_set_collation::val_str(String *str)
{
2601
  DBUG_ASSERT(fixed == 1);
unknown's avatar
unknown committed
2602
  str=args[0]->val_str(str);
unknown's avatar
unknown committed
2603 2604
  if ((null_value=args[0]->null_value))
    return 0;
2605
  str->set_charset(collation.collation);
unknown's avatar
unknown committed
2606 2607 2608
  return str;
}

2609
void Item_func_set_collation::fix_length_and_dec()
unknown's avatar
unknown committed
2610
{
unknown's avatar
unknown committed
2611 2612
  CHARSET_INFO *set_collation;
  const char *colname;
2613
  String tmp, *str= args[1]->val_str(&tmp);
unknown's avatar
unknown committed
2614
  colname= str->c_ptr();
unknown's avatar
unknown committed
2615
  if (colname == binary_keyword)
2616
    set_collation= get_charset_by_csname(args[0]->collation.collation->csname,
unknown's avatar
unknown committed
2617 2618
					 MY_CS_BINSORT,MYF(0));
  else
2619 2620 2621 2622 2623 2624 2625
  {
    if (!(set_collation= get_charset_by_name(colname,MYF(0))))
    {
      my_error(ER_UNKNOWN_COLLATION, MYF(0), colname);
      return;
    }
  }
unknown's avatar
unknown committed
2626

2627 2628
  if (!set_collation || 
      !my_charset_same(args[0]->collation.collation,set_collation))
2629
  {
2630 2631
    my_error(ER_COLLATION_CHARSET_MISMATCH, MYF(0),
             colname, args[0]->collation.collation->csname);
2632
    return;
2633
  }
2634
  collation.set(set_collation, DERIVATION_EXPLICIT);
2635
  max_length= args[0]->max_length;
unknown's avatar
unknown committed
2636 2637
}

2638

2639 2640 2641 2642 2643 2644 2645 2646 2647
bool Item_func_set_collation::eq(const Item *item, bool binary_cmp) const
{
  /* Assume we don't have rtti */
  if (this == item)
    return 1;
  if (item->type() != FUNC_ITEM)
    return 0;
  Item_func *item_func=(Item_func*) item;
  if (arg_count != item_func->arg_count ||
2648
      functype() != item_func->functype())
2649 2650
    return 0;
  Item_func_set_collation *item_func_sc=(Item_func_set_collation*) item;
2651
  if (collation.collation != item_func_sc->collation.collation)
2652 2653 2654 2655 2656 2657 2658
    return 0;
  for (uint i=0; i < arg_count ; i++)
    if (!args[i]->eq(item_func_sc->args[i], binary_cmp))
      return 0;
  return 1;
}

2659 2660 2661 2662 2663

void Item_func_set_collation::print(String *str)
{
  str->append('(');
  args[0]->print(str);
2664
  str->append(STRING_WITH_LEN(" collate "));
2665 2666 2667 2668 2669 2670
  DBUG_ASSERT(args[1]->basic_const_item() &&
              args[1]->type() == Item::STRING_ITEM);
  args[1]->str_value.print(str);
  str->append(')');
}

2671 2672
String *Item_func_charset::val_str(String *str)
{
2673
  DBUG_ASSERT(fixed == 1);
unknown's avatar
unknown committed
2674
  uint dummy_errors;
2675

2676 2677 2678
  CHARSET_INFO *cs= args[0]->collation.collation; 
  null_value= 0;
  str->copy(cs->csname, strlen(cs->csname),
unknown's avatar
unknown committed
2679
	    &my_charset_latin1, collation.collation, &dummy_errors);
unknown's avatar
unknown committed
2680 2681 2682 2683 2684
  return str;
}

String *Item_func_collation::val_str(String *str)
{
2685
  DBUG_ASSERT(fixed == 1);
unknown's avatar
unknown committed
2686
  uint dummy_errors;
2687
  CHARSET_INFO *cs= args[0]->collation.collation; 
unknown's avatar
unknown committed
2688

2689 2690
  null_value= 0;
  str->copy(cs->name, strlen(cs->name),
unknown's avatar
unknown committed
2691
	    &my_charset_latin1, collation.collation, &dummy_errors);
2692 2693
  return str;
}
unknown's avatar
unknown committed
2694 2695


unknown's avatar
unknown committed
2696 2697
String *Item_func_hex::val_str(String *str)
{
unknown's avatar
unknown committed
2698
  String *res;
2699
  DBUG_ASSERT(fixed == 1);
unknown's avatar
unknown committed
2700 2701
  if (args[0]->result_type() != STRING_RESULT)
  {
2702
    ulonglong dec;
unknown's avatar
unknown committed
2703
    char ans[65],*ptr;
2704
    /* Return hex of unsigned longlong value */
unknown's avatar
unknown committed
2705 2706
    if (args[0]->result_type() == REAL_RESULT ||
        args[0]->result_type() == DECIMAL_RESULT)
2707
    {
unknown's avatar
unknown committed
2708
      double val= args[0]->val_real();
2709 2710 2711 2712 2713 2714 2715 2716 2717
      if ((val <= (double) LONGLONG_MIN) || 
          (val >= (double) (ulonglong) ULONGLONG_MAX))
        dec=  ~(longlong) 0;
      else
        dec= (ulonglong) (val + (val > 0 ? 0.5 : -0.5));
    }
    else
      dec= (ulonglong) args[0]->val_int();

unknown's avatar
unknown committed
2718 2719 2720
    if ((null_value= args[0]->null_value))
      return 0;
    ptr= longlong2str(dec,ans,16);
2721
    if (str->copy(ans,(uint32) (ptr-ans),default_charset()))
unknown's avatar
SCRUM  
unknown committed
2722
      return &my_empty_string;			// End of memory
unknown's avatar
unknown committed
2723 2724 2725 2726
    return str;
  }

  /* Convert given string to a hex string, character by character */
unknown's avatar
unknown committed
2727 2728
  res= args[0]->val_str(str);
  if (!res || tmp_value.alloc(res->length()*2+1))
unknown's avatar
unknown committed
2729 2730 2731 2732 2733 2734
  {
    null_value=1;
    return 0;
  }
  null_value=0;
  tmp_value.length(res->length()*2);
unknown's avatar
unknown committed
2735 2736

  octet2hex((char*) tmp_value.ptr(), res->ptr(), res->length());
unknown's avatar
unknown committed
2737 2738 2739
  return &tmp_value;
}

unknown's avatar
unknown committed
2740 2741
  /* Convert given hex string to a binary string */

unknown's avatar
unknown committed
2742 2743
String *Item_func_unhex::val_str(String *str)
{
unknown's avatar
unknown committed
2744 2745 2746 2747
  const char *from, *end;
  char *to;
  String *res;
  uint length;
2748
  DBUG_ASSERT(fixed == 1);
unknown's avatar
unknown committed
2749

unknown's avatar
unknown committed
2750 2751
  res= args[0]->val_str(str);
  if (!res || tmp_value.alloc(length= (1+res->length())/2))
unknown's avatar
unknown committed
2752 2753 2754 2755
  {
    null_value=1;
    return 0;
  }
unknown's avatar
unknown committed
2756

unknown's avatar
unknown committed
2757 2758 2759
  from= res->ptr();
  null_value= 0;
  tmp_value.length(length);
unknown's avatar
unknown committed
2760 2761 2762
  to= (char*) tmp_value.ptr();
  if (res->length() % 2)
  {
unknown's avatar
unknown committed
2763 2764 2765
    int hex_char;
    *to++= hex_char= hexchar_to_int(*from++);
    if ((null_value= (hex_char == -1)))
unknown's avatar
unknown committed
2766 2767 2768 2769
      return 0;
  }
  for (end=res->ptr()+res->length(); from < end ; from+=2, to++)
  {
unknown's avatar
unknown committed
2770 2771 2772
    int hex_char;
    *to= (hex_char= hexchar_to_int(from[0])) << 4;
    if ((null_value= (hex_char == -1)))
unknown's avatar
unknown committed
2773
      return 0;
unknown's avatar
unknown committed
2774 2775
    *to|= hex_char= hexchar_to_int(from[1]);
    if ((null_value= (hex_char == -1)))
unknown's avatar
unknown committed
2776 2777 2778 2779
      return 0;
  }
  return &tmp_value;
}
unknown's avatar
unknown committed
2780

unknown's avatar
unknown committed
2781

2782 2783
void Item_func_binary::print(String *str)
{
2784
  str->append(STRING_WITH_LEN("cast("));
2785
  args[0]->print(str);
2786
  str->append(STRING_WITH_LEN(" as binary)"));
2787 2788 2789
}


unknown's avatar
unknown committed
2790 2791 2792 2793
#include <my_dir.h>				// For my_stat

String *Item_load_file::val_str(String *str)
{
2794
  DBUG_ASSERT(fixed == 1);
unknown's avatar
unknown committed
2795 2796 2797
  String *file_name;
  File file;
  MY_STAT stat_info;
2798
  char path[FN_REFLEN];
unknown's avatar
unknown committed
2799 2800
  DBUG_ENTER("load_file");

2801
  if (!(file_name= args[0]->val_str(str))
unknown's avatar
SCRUM:  
unknown committed
2802
#ifndef NO_EMBEDDED_ACCESS_CHECKS
2803
      || !(current_thd->security_ctx->master_access & FILE_ACL)
unknown's avatar
SCRUM:  
unknown committed
2804
#endif
2805
      )
unknown's avatar
unknown committed
2806
    goto err;
2807

unknown's avatar
unknown committed
2808 2809
  (void) fn_format(path, file_name->c_ptr(), mysql_real_data_home, "",
		   MY_RELATIVE_PATH | MY_UNPACK_FILENAME);
2810

2811
  if (!my_stat(path, &stat_info, MYF(0)))
2812 2813
    goto err;

unknown's avatar
unknown committed
2814 2815 2816 2817 2818
  if (!(stat_info.st_mode & S_IROTH))
  {
    /* my_error(ER_TEXTFILE_NOT_READABLE, MYF(0), file_name->c_ptr()); */
    goto err;
  }
unknown's avatar
unknown committed
2819
  if (stat_info.st_size > (long) current_thd->variables.max_allowed_packet)
unknown's avatar
unknown committed
2820
  {
2821 2822
    push_warning_printf(current_thd, MYSQL_ERROR::WARN_LEVEL_WARN,
			ER_WARN_ALLOWED_PACKET_OVERFLOWED,
2823 2824
			ER(ER_WARN_ALLOWED_PACKET_OVERFLOWED),
			func_name(), current_thd->variables.max_allowed_packet);
unknown's avatar
unknown committed
2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838
    goto err;
  }
  if (tmp_value.alloc(stat_info.st_size))
    goto err;
  if ((file = my_open(file_name->c_ptr(), O_RDONLY, MYF(0))) < 0)
    goto err;
  if (my_read(file, (byte*) tmp_value.ptr(), stat_info.st_size, MYF(MY_NABP)))
  {
    my_close(file, MYF(0));
    goto err;
  }
  tmp_value.length(stat_info.st_size);
  my_close(file, MYF(0));
  null_value = 0;
unknown's avatar
unknown committed
2839
  DBUG_RETURN(&tmp_value);
unknown's avatar
unknown committed
2840 2841 2842 2843 2844 2845 2846 2847 2848

err:
  null_value = 1;
  DBUG_RETURN(0);
}


String* Item_func_export_set::val_str(String* str)
{
2849
  DBUG_ASSERT(fixed == 1);
unknown's avatar
unknown committed
2850
  ulonglong the_set = (ulonglong) args[0]->val_int();
2851
  String yes_buf, *yes;
unknown's avatar
unknown committed
2852
  yes = args[1]->val_str(&yes_buf);
2853
  String no_buf, *no;
unknown's avatar
unknown committed
2854
  no = args[2]->val_str(&no_buf);
2855
  String *sep = NULL, sep_buf ;
unknown's avatar
unknown committed
2856 2857 2858 2859

  uint num_set_values = 64;
  ulonglong mask = 0x1;
  str->length(0);
2860
  str->set_charset(collation.collation);
unknown's avatar
unknown committed
2861 2862 2863 2864 2865 2866 2867

  /* Check if some argument is a NULL value */
  if (args[0]->null_value || args[1]->null_value || args[2]->null_value)
  {
    null_value=1;
    return 0;
  }
2868 2869 2870 2871
  /*
    Arg count can only be 3, 4 or 5 here. This is guaranteed from the
    grammar for EXPORT_SET()
  */
unknown's avatar
unknown committed
2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890
  switch(arg_count) {
  case 5:
    num_set_values = (uint) args[4]->val_int();
    if (num_set_values > 64)
      num_set_values=64;
    if (args[4]->null_value)
    {
      null_value=1;
      return 0;
    }
    /* Fall through */
  case 4:
    if (!(sep = args[3]->val_str(&sep_buf)))	// Only true if NULL
    {
      null_value=1;
      return 0;
    }
    break;
  case 3:
2891 2892 2893
    {
      /* errors is not checked - assume "," can always be converted */
      uint errors;
2894
      sep_buf.copy(STRING_WITH_LEN(","), &my_charset_bin, collation.collation, &errors);
2895 2896
      sep = &sep_buf;
    }
2897 2898 2899
    break;
  default:
    DBUG_ASSERT(0); // cannot happen
unknown's avatar
unknown committed
2900 2901 2902 2903 2904 2905 2906 2907 2908
  }
  null_value=0;

  for (uint i = 0; i < num_set_values; i++, mask = (mask << 1))
  {
    if (the_set & mask)
      str->append(*yes);
    else
      str->append(*no);
2909
    if (i != num_set_values - 1)
unknown's avatar
unknown committed
2910 2911 2912 2913 2914 2915 2916 2917 2918 2919
      str->append(*sep);
  }
  return str;
}

void Item_func_export_set::fix_length_and_dec()
{
  uint length=max(args[1]->max_length,args[2]->max_length);
  uint sep_length=(arg_count > 3 ? args[3]->max_length : 1);
  max_length=length*64+sep_length*63;
2920

2921 2922
  if (agg_arg_charsets(collation, args+1, min(4,arg_count)-1,
                       MY_COLL_ALLOW_CONV, 1))
unknown's avatar
unknown committed
2923
    return;
unknown's avatar
unknown committed
2924 2925 2926 2927
}

String* Item_func_inet_ntoa::val_str(String* str)
{
2928
  DBUG_ASSERT(fixed == 1);
unknown's avatar
unknown committed
2929 2930 2931
  uchar buf[8], *p;
  ulonglong n = (ulonglong) args[0]->val_int();
  char num[4];
unknown's avatar
unknown committed
2932

unknown's avatar
unknown committed
2933
  /*
unknown's avatar
unknown committed
2934
    We do not know if args[0] is NULL until we have called
unknown's avatar
unknown committed
2935
    some val function on it if args[0] is not a constant!
unknown's avatar
unknown committed
2936 2937

    Also return null if n > 255.255.255.255
unknown's avatar
unknown committed
2938
  */
unknown's avatar
unknown committed
2939
  if ((null_value= (args[0]->null_value || n > (ulonglong) LL(4294967295))))
unknown's avatar
unknown committed
2940
    return 0;					// Null value
unknown's avatar
unknown committed
2941

unknown's avatar
unknown committed
2942
  str->length(0);
unknown's avatar
unknown committed
2943
  int4store(buf,n);
unknown's avatar
unknown committed
2944

unknown's avatar
unknown committed
2945
  /* Now we can assume little endian. */
2946

unknown's avatar
unknown committed
2947
  num[3]='.';
unknown's avatar
unknown committed
2948
  for (p=buf+4 ; p-- > buf ; )
unknown's avatar
unknown committed
2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965
  {
    uint c = *p;
    uint n1,n2;					// Try to avoid divisions
    n1= c / 100;				// 100 digits
    c-= n1*100;
    n2= c / 10;					// 10 digits
    c-=n2*10;					// last digit
    num[0]=(char) n1+'0';
    num[1]=(char) n2+'0';
    num[2]=(char) c+'0';
    uint length=(n1 ? 4 : n2 ? 3 : 2);		// Remove pre-zero

    (void) str->append(num+4-length,length);
  }
  str->length(str->length()-1);			// Remove last '.';
  return str;
}
unknown's avatar
unknown committed
2966

unknown's avatar
unknown committed
2967

2968
/*
2969 2970 2971 2972 2973 2974
  QUOTE() function returns argument string in single quotes suitable for
  using in a SQL statement.

  DESCRIPTION
    Adds a \ before all characters that needs to be escaped in a SQL string.
    We also escape '^Z' (END-OF-FILE in windows) to avoid probelms when
2975
    running commands from a file in windows.
2976 2977 2978

    This function is very useful when you want to generate SQL statements

2979 2980 2981 2982
  NOTE
    QUOTE(NULL) returns the string 'NULL' (4 letters, without quotes).

  RETURN VALUES
2983
    str		Quoted string
2984
    NULL	Out of memory.
2985
*/
2986 2987 2988

#define get_esc_bit(mask, num) (1 & (*((mask) + ((num) >> 3))) >> ((num) & 7))

unknown's avatar
unknown committed
2989 2990
String *Item_func_quote::val_str(String *str)
{
2991
  DBUG_ASSERT(fixed == 1);
2992 2993 2994
  /*
    Bit mask that has 1 for set for the position of the following characters:
    0, \, ' and ^Z
2995
  */
2996

2997
  static uchar escmask[32]=
2998 2999 3000 3001 3002 3003
  {
    0x01, 0x00, 0x00, 0x04, 0x80, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x10, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
  };
unknown's avatar
unknown committed
3004

3005 3006 3007 3008
  char *from, *to, *end, *start;
  String *arg= args[0]->val_str(str);
  uint arg_length, new_length;
  if (!arg)					// Null argument
3009
  {
3010 3011
    /* Return the string 'NULL' */
    str->copy(STRING_WITH_LEN("NULL"), collation.collation);
3012 3013 3014 3015
    null_value= 0;
    return str;
  }

3016 3017
  arg_length= arg->length();
  new_length= arg_length+2; /* for beginning and ending ' signs */
3018

3019
  for (from= (char*) arg->ptr(), end= from + arg_length; from < end; from++)
3020
    new_length+= get_esc_bit(escmask, (uchar) *from);
unknown's avatar
unknown committed
3021

3022
  if (tmp_value.alloc(new_length))
3023
    goto null;
3024 3025

  /*
3026
    We replace characters from the end to the beginning
3027
  */
3028
  to= (char*) tmp_value.ptr() + new_length - 1;
3029
  *to--= '\'';
unknown's avatar
unknown committed
3030
  for (start= (char*) arg->ptr(),end= start + arg_length; end-- != start; to--)
unknown's avatar
unknown committed
3031
  {
3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053
    /*
      We can't use the bitmask here as we want to replace \O and ^Z with 0
      and Z
    */
    switch (*end)  {
    case 0:
      *to--= '0';
      *to=   '\\';
      break;
    case '\032':
      *to--= 'Z';
      *to=   '\\';
      break;
    case '\'':
    case '\\':
      *to--= *end;
      *to=   '\\';
      break;
    default:
      *to= *end;
      break;
    }
unknown's avatar
unknown committed
3054
  }
3055
  *to= '\'';
3056
  tmp_value.length(new_length);
unknown's avatar
unknown committed
3057
  tmp_value.set_charset(collation.collation);
3058
  null_value= 0;
3059
  return &tmp_value;
3060 3061 3062 3063

null:
  null_value= 1;
  return 0;
unknown's avatar
unknown committed
3064
}
unknown's avatar
unknown committed
3065

3066 3067
longlong Item_func_uncompressed_length::val_int()
{
3068
  DBUG_ASSERT(fixed == 1);
3069 3070 3071 3072 3073 3074 3075 3076
  String *res= args[0]->val_str(&value);
  if (!res)
  {
    null_value=1;
    return 0; /* purecov: inspected */
  }
  null_value=0;
  if (res->is_empty()) return 0;
unknown's avatar
fixed:  
unknown committed
3077 3078 3079 3080 3081 3082 3083 3084 3085

  /*
    res->ptr() using is safe because we have tested that string is not empty,
    res->c_ptr() is not used because:
      - we do not need \0 terminated string to get first 4 bytes
      - c_ptr() tests simbol after string end (uninitialiozed memory) which
        confuse valgrind
  */
  return uint4korr(res->ptr()) & 0x3FFFFFFF;
3086 3087 3088 3089
}

longlong Item_func_crc32::val_int()
{
3090
  DBUG_ASSERT(fixed == 1);
3091 3092 3093 3094 3095 3096 3097
  String *res=args[0]->val_str(&value);
  if (!res)
  {
    null_value=1;
    return 0; /* purecov: inspected */
  }
  null_value=0;
3098
  return (longlong) crc32(0L, (uchar*)res->ptr(), res->length());
3099 3100
}

unknown's avatar
unknown committed
3101
#ifdef HAVE_COMPRESS
3102
#include "zlib.h"
unknown's avatar
unknown committed
3103 3104 3105

String *Item_func_compress::val_str(String *str)
{
unknown's avatar
unknown committed
3106 3107 3108 3109 3110
  int err= Z_OK, code;
  ulong new_size;
  String *res;
  Byte *body;
  char *tmp, *last_char;
3111
  DBUG_ASSERT(fixed == 1);
unknown's avatar
unknown committed
3112 3113

  if (!(res= args[0]->val_str(str)))
3114 3115 3116 3117
  {
    null_value= 1;
    return 0;
  }
3118
  null_value= 0;
3119 3120
  if (res->is_empty()) return res;

unknown's avatar
unknown committed
3121
  /*
unknown's avatar
unknown committed
3122
    Citation from zlib.h (comment for compress function):
unknown's avatar
unknown committed
3123 3124

    Compresses the source buffer into the destination buffer.  sourceLen is
unknown's avatar
unknown committed
3125 3126 3127 3128
    the byte length of the source buffer. Upon entry, destLen is the total
    size of the destination buffer, which must be at least 0.1% larger than
    sourceLen plus 12 bytes.
    We assume here that the buffer can't grow more than .25 %.
unknown's avatar
unknown committed
3129
  */
unknown's avatar
unknown committed
3130
  new_size= res->length() + res->length() / 5 + 12;
unknown's avatar
unknown committed
3131

unknown's avatar
unknown committed
3132 3133
  // Check new_size overflow: new_size <= res->length()
  if (((uint32) (new_size+5) <= res->length()) || 
3134 3135 3136 3137 3138
      buffer.realloc((uint32) new_size + 4 + 1))
  {
    null_value= 1;
    return 0;
  }
unknown's avatar
fixed:  
unknown committed
3139

unknown's avatar
unknown committed
3140
  body= ((Byte*)buffer.ptr()) + 4;
3141

unknown's avatar
fixed:  
unknown committed
3142
  // As far as we have checked res->is_empty() we can use ptr()
3143
  if ((err= compress(body, &new_size,
unknown's avatar
fixed:  
unknown committed
3144
		     (const Bytef*)res->ptr(), res->length())) != Z_OK)
unknown's avatar
unknown committed
3145 3146 3147 3148 3149 3150
  {
    code= err==Z_MEM_ERROR ? ER_ZLIB_Z_MEM_ERROR : ER_ZLIB_Z_BUF_ERROR;
    push_warning(current_thd,MYSQL_ERROR::WARN_LEVEL_ERROR,code,ER(code));
    null_value= 1;
    return 0;
  }
3151

unknown's avatar
unknown committed
3152
  tmp= (char*)buffer.ptr(); // int4store is a macro; avoid side effects
3153
  int4store(tmp, res->length() & 0x3FFFFFFF);
3154

unknown's avatar
unknown committed
3155 3156
  /* This is to ensure that things works for CHAR fields, which trim ' ': */
  last_char= ((char*)body)+new_size-1;
unknown's avatar
unknown committed
3157 3158 3159 3160 3161
  if (*last_char == ' ')
  {
    *++last_char= '.';
    new_size++;
  }
3162

3163
  buffer.length((uint32)new_size + 4);
unknown's avatar
unknown committed
3164 3165 3166
  return &buffer;
}

3167

unknown's avatar
unknown committed
3168 3169
String *Item_func_uncompress::val_str(String *str)
{
3170
  DBUG_ASSERT(fixed == 1);
unknown's avatar
unknown committed
3171
  String *res= args[0]->val_str(str);
3172 3173
  ulong new_size;
  int err;
unknown's avatar
unknown committed
3174
  uint code;
3175

3176 3177
  if (!res)
    goto err;
3178
  null_value= 0;
3179 3180 3181
  if (res->is_empty())
    return res;

3182 3183 3184 3185 3186 3187 3188 3189 3190 3191
  /* If length is less than 4 bytes, data is corrupt */
  if (res->length() <= 4)
  {
    push_warning_printf(current_thd,MYSQL_ERROR::WARN_LEVEL_ERROR,
			ER_ZLIB_Z_DATA_ERROR,
			ER(ER_ZLIB_Z_DATA_ERROR));
    goto err;
  }

  /* Size of uncompressed data is stored as first 4 bytes of field */
3192
  new_size= uint4korr(res->ptr()) & 0x3FFFFFFF;
3193
  if (new_size > current_thd->variables.max_allowed_packet)
unknown's avatar
unknown committed
3194 3195 3196
  {
    push_warning_printf(current_thd,MYSQL_ERROR::WARN_LEVEL_ERROR,
			ER_TOO_BIG_FOR_UNCOMPRESS,
3197 3198
			ER(ER_TOO_BIG_FOR_UNCOMPRESS),
                        current_thd->variables.max_allowed_packet);
3199
    goto err;
unknown's avatar
unknown committed
3200
  }
3201 3202
  if (buffer.realloc((uint32)new_size))
    goto err;
3203

3204 3205
  if ((err= uncompress((Byte*)buffer.ptr(), &new_size,
		       ((const Bytef*)res->ptr())+4,res->length())) == Z_OK)
unknown's avatar
unknown committed
3206
  {
3207
    buffer.length((uint32) new_size);
unknown's avatar
unknown committed
3208 3209
    return &buffer;
  }
3210

3211 3212
  code= ((err == Z_BUF_ERROR) ? ER_ZLIB_Z_BUF_ERROR :
	 ((err == Z_MEM_ERROR) ? ER_ZLIB_Z_MEM_ERROR : ER_ZLIB_Z_DATA_ERROR));
unknown's avatar
unknown committed
3213
  push_warning(current_thd,MYSQL_ERROR::WARN_LEVEL_ERROR,code,ER(code));
3214 3215

err:
unknown's avatar
unknown committed
3216 3217 3218 3219
  null_value= 1;
  return 0;
}
#endif
unknown's avatar
unknown committed
3220 3221 3222 3223

/*
  UUID, as in
    DCE 1.1: Remote Procedure Call,
unknown's avatar
unknown committed
3224
    Open Group Technical Standard Document Number C706, October 1997,
unknown's avatar
unknown committed
3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245
    (supersedes C309 DCE: Remote Procedure Call 8/1994,
    which was basis for ISO/IEC 11578:1996 specification)
*/

static struct rand_struct uuid_rand;
static uint nanoseq;
static ulonglong uuid_time=0;
static char clock_seq_and_node_str[]="-0000-000000000000";

/* number of 100-nanosecond intervals between
   1582-10-15 00:00:00.00 and 1970-01-01 00:00:00.00 */
#define UUID_TIME_OFFSET ((ulonglong) 141427 * 24 * 60 * 60 * 1000 * 10 )

#define UUID_VERSION      0x1000
#define UUID_VARIANT      0x8000

static void tohex(char *to, uint from, uint len)
{
  to+= len;
  while (len--)
  {
3246
    *--to= _dig_vec_lower[from & 15];
unknown's avatar
unknown committed
3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259
    from >>= 4;
  }
}

static void set_clock_seq_str()
{
  uint16 clock_seq= ((uint)(my_rnd(&uuid_rand)*16383)) | UUID_VARIANT;
  tohex(clock_seq_and_node_str+1, clock_seq, 4);
  nanoseq= 0;
}

String *Item_func_uuid::val_str(String *str)
{
3260
  DBUG_ASSERT(fixed == 1);
unknown's avatar
unknown committed
3261
  char *s;
3262 3263
  THD *thd= current_thd;

unknown's avatar
unknown committed
3264 3265 3266 3267 3268
  pthread_mutex_lock(&LOCK_uuid_generator);
  if (! uuid_time) /* first UUID() call. initializing data */
  {
    ulong tmp=sql_rnd_with_mutex();
    uchar mac[6];
unknown's avatar
unknown committed
3269
    int i;
unknown's avatar
unknown committed
3270 3271 3272 3273 3274 3275 3276 3277
    if (my_gethwaddr(mac))
    {
      /*
        generating random "hardware addr"
        and because specs explicitly specify that it should NOT correlate
        with a clock_seq value (initialized random below), we use a separate
        randominit() here
      */
3278
      randominit(&uuid_rand, tmp + (ulong) thd, tmp + (ulong)query_id);
unknown's avatar
unknown committed
3279
      for (i=0; i < (int)sizeof(mac); i++)
unknown's avatar
unknown committed
3280 3281 3282 3283 3284
        mac[i]=(uchar)(my_rnd(&uuid_rand)*255);
    }
    s=clock_seq_and_node_str+sizeof(clock_seq_and_node_str)-1;
    for (i=sizeof(mac)-1 ; i>=0 ; i--)
    {
3285 3286
      *--s=_dig_vec_lower[mac[i] & 15];
      *--s=_dig_vec_lower[mac[i] >> 4];
unknown's avatar
unknown committed
3287
    }
3288 3289
    randominit(&uuid_rand, tmp + (ulong)start_time,
	       tmp + thd->status_var.bytes_sent);
unknown's avatar
unknown committed
3290 3291 3292
    set_clock_seq_str();
  }

unknown's avatar
unknown committed
3293
  ulonglong tv=my_getsystime() + UUID_TIME_OFFSET + nanoseq;
unknown's avatar
unknown committed
3294 3295
  if (unlikely(tv < uuid_time))
    set_clock_seq_str();
3296 3297 3298
  else if (unlikely(tv == uuid_time))
  {
    /* special protection from low-res system clocks */
unknown's avatar
unknown committed
3299 3300 3301 3302
    nanoseq++;
    tv++;
  }
  else
3303 3304 3305 3306 3307 3308 3309 3310
  {
    if (nanoseq)
    {
      tv-=nanoseq;
      nanoseq=0;
    }
    DBUG_ASSERT(tv > uuid_time);
  }
unknown's avatar
unknown committed
3311 3312 3313
  uuid_time=tv;
  pthread_mutex_unlock(&LOCK_uuid_generator);

3314 3315 3316
  uint32 time_low=            (uint32) (tv & 0xFFFFFFFF);
  uint16 time_mid=            (uint16) ((tv >> 32) & 0xFFFF);
  uint16 time_hi_and_version= (uint16) ((tv >> 48) | UUID_VERSION);
unknown's avatar
unknown committed
3317 3318 3319

  str->realloc(UUID_LENGTH+1);
  str->length(UUID_LENGTH);
unknown's avatar
unknown committed
3320
  str->set_charset(system_charset_info);
unknown's avatar
unknown committed
3321 3322 3323 3324 3325 3326 3327 3328
  s=(char *) str->ptr();
  s[8]=s[13]='-';
  tohex(s, time_low, 8);
  tohex(s+9, time_mid, 4);
  tohex(s+14, time_hi_and_version, 4);
  strmov(s+18, clock_seq_and_node_str);
  return str;
}