1 /*
2    Copyright (c) 2000, 2020, Oracle and/or its affiliates. All rights reserved.
3 
4    This program is free software; you can redistribute it and/or modify
5    it under the terms of the GNU General Public License, version 2.0,
6    as published by the Free Software Foundation.
7 
8    This program is also distributed with certain software (including
9    but not limited to OpenSSL) that is licensed under separate terms,
10    as designated in a particular file or component or in included license
11    documentation.  The authors of MySQL hereby grant you an additional
12    permission to link the program and your derivative works with the
13    separately licensed software that they have included with MySQL.
14 
15    This program is distributed in the hope that it will be useful,
16    but WITHOUT ANY WARRANTY; without even the implied warranty of
17    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18    GNU General Public License, version 2.0, for more details.
19 
20    You should have received a copy of the GNU General Public License
21    along with this program; if not, write to the Free Software
22    Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301  USA
23 */
24 
25 
26 /**
27   @file
28 
29   @brief
30   This file defines all string functions
31 
32   @warning
33     Some string functions don't always put and end-null on a String.
34     (This shouldn't be needed)
35 */
36 
37 /* May include caustic 3rd-party defs. Use early, so it can override nothing. */
38 #include "sha2.h"
39 #include "my_global.h"                          // HAVE_*
40 
41 
42 #include "sql_priv.h"
43 /*
44   It is necessary to include set_var.h instead of item.h because there
45   are dependencies on include order for set_var.h and item.h. This
46   will be resolved later.
47 */
48 #include "sql_class.h"                          // set_var.h: THD
49 #include "set_var.h"
50 #include "mysqld.h"                             // LOCK_uuid_generator
51 #include "sql_acl.h"                            // SUPER_ACL
52 #include "des_key_file.h"       // st_des_keyschedule, st_des_keyblock
53 #include "password.h"           // my_make_scrambled_password,
54                                 // my_make_scrambled_password_323
55 #include "crypt_genhash_impl.h"
56 #include <m_ctype.h>
57 #include <base64.h>
58 #include "my_md5.h"
59 #include "sha1.h"
60 #include "my_aes.h"
61 #include <zlib.h>
62 #include "my_rnd.h"
63 C_MODE_START
64 #include "../mysys/my_static.h"			// For soundex_map
65 C_MODE_END
66 
67 using std::min;
68 using std::max;
69 
70 /*
71   For the Items which have only val_str_ascii() method
72   and don't have their own "native" val_str(),
73   we provide a "wrapper" method to convert from ASCII
74   to Item character set when it's necessary.
75   Conversion happens only in case of "tricky" Item character set (e.g. UCS2).
76   Normally conversion does not happen, and val_str_ascii() is immediately
77   returned instead.
78 */
val_str_from_val_str_ascii(String * str,String * str2)79 String *Item_str_func::val_str_from_val_str_ascii(String *str, String *str2)
80 {
81   DBUG_ASSERT(fixed == 1);
82 
83   if (!(collation.collation->state & MY_CS_NONASCII))
84   {
85     String *res= val_str_ascii(str);
86     if (res)
87       res->set_charset(collation.collation);
88     return res;
89   }
90 
91   DBUG_ASSERT(str != str2);
92 
93   uint errors;
94   String *res= val_str_ascii(str);
95   if (!res)
96     return 0;
97 
98   if ((null_value= str2->copy(res->ptr(), res->length(),
99                               &my_charset_latin1, collation.collation,
100                               &errors)))
101     return 0;
102 
103   return str2;
104 }
105 
fix_fields(THD * thd,Item ** ref)106 bool Item_str_func::fix_fields(THD *thd, Item **ref)
107 {
108   bool res= Item_func::fix_fields(thd, ref);
109   /*
110     In Item_str_func::check_well_formed_result() we may set null_value
111     flag on the same condition as in test() below.
112   */
113   maybe_null= (maybe_null || thd->is_strict_mode());
114   return res;
115 }
116 
117 
val_decimal(my_decimal * decimal_value)118 my_decimal *Item_str_func::val_decimal(my_decimal *decimal_value)
119 {
120   DBUG_ASSERT(fixed == 1);
121   char buff[64];
122   String *res, tmp(buff,sizeof(buff), &my_charset_bin);
123   res= val_str(&tmp);
124   if (!res)
125     return 0;
126   (void)str2my_decimal(E_DEC_FATAL_ERROR, (char*) res->ptr(),
127                        res->length(), res->charset(), decimal_value);
128   return decimal_value;
129 }
130 
131 
val_real()132 double Item_str_func::val_real()
133 {
134   DBUG_ASSERT(fixed == 1);
135   int err_not_used;
136   char *end_not_used, buff[64];
137   String *res, tmp(buff,sizeof(buff), &my_charset_bin);
138   res= val_str(&tmp);
139   return res ? my_strntod(res->charset(), (char*) res->ptr(), res->length(),
140 			  &end_not_used, &err_not_used) : 0.0;
141 }
142 
143 
val_int()144 longlong Item_str_func::val_int()
145 {
146   DBUG_ASSERT(fixed == 1);
147   int err;
148   char buff[22];
149   String *res, tmp(buff,sizeof(buff), &my_charset_bin);
150   res= val_str(&tmp);
151   return (res ?
152 	  my_strntoll(res->charset(), res->ptr(), res->length(), 10, NULL,
153 		      &err) :
154 	  (longlong) 0);
155 }
156 
157 
val_str_ascii(String * str)158 String *Item_func_md5::val_str_ascii(String *str)
159 {
160   DBUG_ASSERT(fixed == 1);
161   String * sptr= args[0]->val_str(str);
162   str->set_charset(&my_charset_bin);
163   if (sptr)
164   {
165     uchar digest[MD5_HASH_SIZE];
166 
167     null_value=0;
168     compute_md5_hash((char *) digest, (const char *) sptr->ptr(), sptr->length());
169     if (str->alloc(32))				// Ensure that memory is free
170     {
171       null_value=1;
172       return 0;
173     }
174     array_to_hex((char *) str->ptr(), digest, MD5_HASH_SIZE);
175     str->length((uint) 32);
176     return str;
177   }
178   null_value=1;
179   return 0;
180 }
181 
182 
183 /*
184   The MD5()/SHA() functions treat their parameter as being a case sensitive.
185   Thus we set binary collation on it so different instances of MD5() will be
186   compared properly.
187 */
get_checksum_charset(const char * csname)188 static CHARSET_INFO *get_checksum_charset(const char *csname)
189 {
190   CHARSET_INFO *cs= get_charset_by_csname(csname, MY_CS_BINSORT, MYF(0));
191   if (!cs)
192   {
193     // Charset has no binary collation: use my_charset_bin.
194     cs= &my_charset_bin;
195   }
196   return cs;
197 }
198 
199 
fix_length_and_dec()200 void Item_func_md5::fix_length_and_dec()
201 {
202   CHARSET_INFO *cs= get_checksum_charset(args[0]->collation.collation->csname);
203   args[0]->collation.set(cs, DERIVATION_COERCIBLE);
204   fix_length_and_charset(32, default_charset());
205 }
206 
207 
val_str_ascii(String * str)208 String *Item_func_sha::val_str_ascii(String *str)
209 {
210   DBUG_ASSERT(fixed == 1);
211   String * sptr= args[0]->val_str(str);
212   str->set_charset(&my_charset_bin);
213   if (sptr)  /* If we got value different from NULL */
214   {
215     /* Temporary buffer to store 160bit digest */
216     uint8 digest[SHA1_HASH_SIZE];
217     compute_sha1_hash(digest, (const char *) sptr->ptr(), sptr->length());
218     /* Ensure that memory is free */
219     if (!(str->alloc(SHA1_HASH_SIZE * 2)))
220     {
221       array_to_hex((char *) str->ptr(), digest, SHA1_HASH_SIZE);
222       str->length((uint)  SHA1_HASH_SIZE*2);
223       null_value=0;
224       return str;
225     }
226   }
227   null_value=1;
228   return 0;
229 }
230 
fix_length_and_dec()231 void Item_func_sha::fix_length_and_dec()
232 {
233   CHARSET_INFO *cs= get_checksum_charset(args[0]->collation.collation->csname);
234   args[0]->collation.set(cs, DERIVATION_COERCIBLE);
235   // size of hex representation of hash
236   fix_length_and_charset(SHA1_HASH_SIZE * 2, default_charset());
237 }
238 
val_str_ascii(String * str)239 String *Item_func_sha2::val_str_ascii(String *str)
240 {
241   DBUG_ASSERT(fixed == 1);
242 #if defined(HAVE_OPENSSL) && !defined(EMBEDDED_LIBRARY)
243   unsigned char digest_buf[SHA512_DIGEST_LENGTH];
244   String *input_string;
245   unsigned char *input_ptr;
246   size_t input_len;
247   uint digest_length= 0;
248 
249   input_string= args[0]->val_str(str);
250   str->set_charset(&my_charset_bin);
251 
252   if (input_string == NULL)
253   {
254     null_value= TRUE;
255     return (String *) NULL;
256   }
257 
258   null_value= args[0]->null_value;
259   if (null_value)
260     return (String *) NULL;
261 
262   input_ptr= (unsigned char *) input_string->ptr();
263   input_len= input_string->length();
264 
265   switch ((uint) args[1]->val_int()) {
266 #ifndef OPENSSL_NO_SHA512
267   case 512:
268     digest_length= SHA512_DIGEST_LENGTH;
269     (void) SHA512(input_ptr, input_len, digest_buf);
270     break;
271   case 384:
272     digest_length= SHA384_DIGEST_LENGTH;
273     (void) SHA384(input_ptr, input_len, digest_buf);
274     break;
275 #endif
276 #ifndef OPENSSL_NO_SHA256
277   case 224:
278     digest_length= SHA224_DIGEST_LENGTH;
279     (void) SHA224(input_ptr, input_len, digest_buf);
280     break;
281   case 256:
282   case 0: // SHA-256 is the default
283     digest_length= SHA256_DIGEST_LENGTH;
284     (void) SHA256(input_ptr, input_len, digest_buf);
285     break;
286 #endif
287   default:
288     if (!args[1]->const_item())
289       push_warning_printf(current_thd,
290         Sql_condition::WARN_LEVEL_WARN,
291         ER_WRONG_PARAMETERS_TO_NATIVE_FCT,
292         ER(ER_WRONG_PARAMETERS_TO_NATIVE_FCT), "sha2");
293     null_value= TRUE;
294     return NULL;
295   }
296 
297   /*
298     Since we're subverting the usual String methods, we must make sure that
299     the destination has space for the bytes we're about to write.
300   */
301   str->realloc((uint) digest_length*2 + 1); /* Each byte as two nybbles */
302 
303   /* Convert the large number to a string-hex representation. */
304   array_to_hex((char *) str->ptr(), digest_buf, digest_length);
305 
306   /* We poked raw bytes in.  We must inform the the String of its length. */
307   str->length((uint) digest_length*2); /* Each byte as two nybbles */
308 
309   null_value= FALSE;
310   return str;
311 
312 #else
313   push_warning_printf(current_thd,
314     Sql_condition::WARN_LEVEL_WARN,
315     ER_FEATURE_DISABLED,
316     ER(ER_FEATURE_DISABLED),
317     "sha2", "--with-ssl");
318   null_value= TRUE;
319   return (String *) NULL;
320 #endif /* defined(HAVE_OPENSSL) && !defined(EMBEDDED_LIBRARY) */
321 }
322 
323 
fix_length_and_dec()324 void Item_func_sha2::fix_length_and_dec()
325 {
326   maybe_null = 1;
327   max_length = 0;
328 
329 #if defined(HAVE_OPENSSL) && !defined(EMBEDDED_LIBRARY)
330   int sha_variant= args[1]->const_item() ? args[1]->val_int() : 512;
331 
332   switch (sha_variant) {
333 #ifndef OPENSSL_NO_SHA512
334   case 512:
335     fix_length_and_charset(SHA512_DIGEST_LENGTH * 2, default_charset());
336     break;
337   case 384:
338     fix_length_and_charset(SHA384_DIGEST_LENGTH * 2, default_charset());
339     break;
340 #endif
341 #ifndef OPENSSL_NO_SHA256
342   case 256:
343   case 0: // SHA-256 is the default
344     fix_length_and_charset(SHA256_DIGEST_LENGTH * 2, default_charset());
345     break;
346   case 224:
347     fix_length_and_charset(SHA224_DIGEST_LENGTH * 2, default_charset());
348     break;
349 #endif
350   default:
351     push_warning_printf(current_thd,
352       Sql_condition::WARN_LEVEL_WARN,
353       ER_WRONG_PARAMETERS_TO_NATIVE_FCT,
354       ER(ER_WRONG_PARAMETERS_TO_NATIVE_FCT), "sha2");
355   }
356 
357   CHARSET_INFO *cs= get_checksum_charset(args[0]->collation.collation->csname);
358   args[0]->collation.set(cs, DERIVATION_COERCIBLE);
359 
360 #else
361   push_warning_printf(current_thd,
362     Sql_condition::WARN_LEVEL_WARN,
363     ER_FEATURE_DISABLED,
364     ER(ER_FEATURE_DISABLED),
365     "sha2", "--with-ssl");
366 #endif /* defined(HAVE_OPENSSL) && !defined(EMBEDDED_LIBRARY) */
367 }
368 
369 /* Implementation of AES encryption routines */
370 
371 /** helper class to process an IV argument to aes_encrypt/aes_decrypt */
372 class iv_argument
373 {
374   char iv_buff[MY_AES_IV_SIZE + 1];  // +1 to cater for the terminating NULL
375   String tmp_iv_value;
376 public:
iv_argument()377   iv_argument() :
378     tmp_iv_value(iv_buff, sizeof(iv_buff), system_charset_info)
379   {}
380 
381   /**
382     Validate the arguments and retrieve the IV value.
383 
384     Processes a 3d optional IV argument to an Item_func function.
385     Contains all the necessary stack buffers etc.
386 
387     @param aes_opmode  the encryption mode
388     @param arg_count   number of parameters passed to the function
389     @param args        array of arguments passed to the function
390     @param func_name   the name of the function (for errors)
391     @param thd         the current thread (for errors)
392     @param [out] error_generated  set to true if error was generated.
393 
394     @return a pointer to the retrived validated IV or NULL
395   */
retrieve_iv_ptr(enum my_aes_opmode aes_opmode,uint arg_count,Item ** args,const char * func_name,THD * thd,my_bool * error_generated)396   const unsigned char *retrieve_iv_ptr(enum my_aes_opmode aes_opmode,
397                                        uint arg_count,
398                                        Item **args,
399                                        const char *func_name,
400                                        THD *thd,
401                                        my_bool *error_generated)
402   {
403     const unsigned char *iv_str= NULL;
404 
405     *error_generated= FALSE;
406 
407     if (my_aes_needs_iv(aes_opmode))
408     {
409       /* we only enforce the need for IV */
410       if (arg_count == 3)
411       {
412         String *iv= args[2]->val_str(&tmp_iv_value);
413         if (!iv || iv->length() < MY_AES_IV_SIZE)
414         {
415           my_error(ER_AES_INVALID_IV, MYF(0), func_name, (long long) MY_AES_IV_SIZE);
416           *error_generated= TRUE;
417           return NULL;
418         }
419         iv_str= (unsigned char *) iv->ptr();
420       }
421       else
422       {
423         my_error(ER_WRONG_PARAMCOUNT_TO_NATIVE_FCT, MYF(0), func_name);
424         *error_generated= TRUE;
425         return NULL;
426       }
427     }
428     else
429     {
430       if (arg_count == 3)
431       {
432         push_warning_printf(thd, Sql_condition::WARN_LEVEL_WARN,
433                             WARN_OPTION_IGNORED,
434                             ER(WARN_OPTION_IGNORED), "IV");
435       }
436     }
437     return iv_str;
438   }
439 };
440 
441 
val_str(String * str)442 String *Item_func_aes_encrypt::val_str(String *str)
443 {
444   DBUG_ASSERT(fixed == 1);
445   char key_buff[80];
446   String tmp_key_value(key_buff, sizeof(key_buff), system_charset_info);
447   String *sptr, *key;
448   int aes_length;
449   THD *thd= current_thd;
450   ulong aes_opmode;
451   iv_argument iv_arg;
452   DBUG_ENTER("Item_func_aes_decrypt::val_str");
453 
454   sptr= args[0]->val_str(str);			// String to encrypt
455   key=  args[1]->val_str(&tmp_key_value);	// key
456   aes_opmode= thd->variables.my_aes_mode;
457 
458   DBUG_ASSERT(aes_opmode <= MY_AES_END);
459 
460   if (sptr && key) // we need both arguments to be not NULL
461   {
462     const unsigned char *iv_str=
463       iv_arg.retrieve_iv_ptr((enum my_aes_opmode) aes_opmode, arg_count, args,
464                              func_name(), thd, &null_value);
465     if (null_value)
466       DBUG_RETURN(NULL);
467 
468     // Calculate result length
469     aes_length= my_aes_get_size(sptr->length(),
470                                 (enum my_aes_opmode) aes_opmode);
471 
472     str_value.set_charset(&my_charset_bin);
473     if (!str_value.alloc(aes_length))		// Ensure that memory is free
474     {
475       // finally encrypt directly to allocated buffer.
476       if (my_aes_encrypt((unsigned char *) sptr->ptr(), sptr->length(),
477                          (unsigned char *) str_value.ptr(),
478                          (unsigned char *) key->ptr(), key->length(),
479                          (enum my_aes_opmode) aes_opmode,
480                          iv_str) == aes_length)
481       {
482 	// We got the expected result length
483 	str_value.length((uint) aes_length);
484         DBUG_RETURN(&str_value);
485       }
486     }
487   }
488   null_value=1;
489   DBUG_RETURN(0);
490 }
491 
492 
fix_length_and_dec()493 void Item_func_aes_encrypt::fix_length_and_dec()
494 {
495   ulong aes_opmode= current_thd->variables.my_aes_mode;
496   DBUG_ASSERT(aes_opmode <= MY_AES_END);
497 
498   max_length=my_aes_get_size(args[0]->max_length,
499                              (enum my_aes_opmode) aes_opmode);
500 }
501 
502 
val_str(String * str)503 String *Item_func_aes_decrypt::val_str(String *str)
504 {
505   DBUG_ASSERT(fixed == 1);
506   char key_buff[80];
507   String tmp_key_value(key_buff, sizeof(key_buff), system_charset_info);
508   String *sptr, *key;
509   THD *thd= current_thd;
510   ulong aes_opmode;
511   iv_argument iv_arg;
512   DBUG_ENTER("Item_func_aes_decrypt::val_str");
513 
514   sptr= args[0]->val_str(str);			// String to decrypt
515   key=  args[1]->val_str(&tmp_key_value);	// Key
516   aes_opmode= thd->variables.my_aes_mode;
517   DBUG_ASSERT(aes_opmode <= MY_AES_END);
518 
519   if (sptr && key)  			// Need to have both arguments not NULL
520   {
521     const unsigned char *iv_str=
522       iv_arg.retrieve_iv_ptr((enum my_aes_opmode) aes_opmode, arg_count, args,
523       func_name(), thd, &null_value);
524     if (null_value)
525       DBUG_RETURN(NULL);
526     str_value.set_charset(&my_charset_bin);
527     if (!str_value.alloc(sptr->length()))  // Ensure that memory is free
528     {
529       // finally decrypt directly to allocated buffer.
530       int length;
531       length= my_aes_decrypt((unsigned char *) sptr->ptr(), sptr->length(),
532                              (unsigned char *) str_value.ptr(),
533                              (unsigned char *) key->ptr(), key->length(),
534                              (enum my_aes_opmode) aes_opmode, iv_str);
535       if (length >= 0)  // if we got correct data data
536       {
537         str_value.length((uint) length);
538         DBUG_RETURN(&str_value);
539       }
540     }
541   }
542   // Bad parameters. No memory or bad data will all go here
543   null_value=1;
544   DBUG_RETURN(0);
545 }
546 
547 
fix_length_and_dec()548 void Item_func_aes_decrypt::fix_length_and_dec()
549 {
550    max_length=args[0]->max_length;
551    maybe_null= 1;
552 }
553 
554 /*
555   Artificially limited to 1k to avoid excessive memory usage.
556   The SSL lib supports up to INT_MAX.
557 */
558 const longlong Item_func_random_bytes::MAX_RANDOM_BYTES_BUFFER= 1024;
559 
560 
fix_length_and_dec()561 void Item_func_random_bytes::fix_length_and_dec()
562 {
563   collation.set(&my_charset_bin);
564   max_length= MAX_RANDOM_BYTES_BUFFER;
565 }
566 
567 
val_str(String * a)568 String *Item_func_random_bytes::val_str(String *a)
569 {
570   DBUG_ASSERT(fixed == 1);
571   longlong n_bytes= args[0]->val_int();
572   null_value= args[0]->null_value;
573 
574   if (null_value)
575     return NULL;
576 
577   str_value.set_charset(&my_charset_bin);
578 
579   if (n_bytes <= 0 || n_bytes > MAX_RANDOM_BYTES_BUFFER)
580   {
581     my_error(ER_DATA_OUT_OF_RANGE, MYF(0), "length", func_name());
582     null_value= TRUE;
583     return NULL;
584   }
585 
586   if (str_value.alloc(n_bytes))
587   {
588     my_error(ER_OUTOFMEMORY, n_bytes);
589     null_value= TRUE;
590     return NULL;
591   }
592 
593   str_value.set_charset(&my_charset_bin);
594 
595   if (my_rand_buffer((unsigned char *) str_value.ptr(), n_bytes))
596   {
597     my_error(ER_ERROR_WHEN_EXECUTING_COMMAND, MYF(0), func_name(),
598              "SSL library can't generate random bytes");
599     null_value= TRUE;
600     return NULL;
601   }
602 
603   str_value.length(n_bytes);
604   return &str_value;
605 }
606 
607 
fix_length_and_dec()608 void Item_func_to_base64::fix_length_and_dec()
609 {
610   maybe_null= args[0]->maybe_null;
611   collation.set(default_charset(), DERIVATION_COERCIBLE, MY_REPERTOIRE_ASCII);
612   if (args[0]->max_length > (uint) base64_encode_max_arg_length())
613   {
614     maybe_null= 1;
615     fix_char_length_ulonglong((ulonglong) base64_encode_max_arg_length());
616   }
617   else
618   {
619     uint64 length= base64_needed_encoded_length((uint64) args[0]->max_length);
620     DBUG_ASSERT(length > 0);
621     fix_char_length_ulonglong((ulonglong) length - 1);
622   }
623 }
624 
625 
val_str_ascii(String * str)626 String *Item_func_to_base64::val_str_ascii(String *str)
627 {
628   String *res= args[0]->val_str(str);
629   bool too_long= false;
630   uint64 length;
631   if (!res ||
632       res->length() > (uint) base64_encode_max_arg_length() ||
633       (too_long=
634        ((uint64) (length= base64_needed_encoded_length((uint64) res->length())) >
635         current_thd->variables.max_allowed_packet)) ||
636       tmp_value.alloc((uint) length))
637   {
638     null_value= 1; // NULL input, too long input, or OOM.
639     if (too_long)
640     {
641       push_warning_printf(current_thd, Sql_condition::WARN_LEVEL_WARN,
642                           ER_WARN_ALLOWED_PACKET_OVERFLOWED,
643                           ER(ER_WARN_ALLOWED_PACKET_OVERFLOWED), func_name(),
644                           current_thd->variables.max_allowed_packet);
645     }
646     return 0;
647   }
648   base64_encode(res->ptr(), (int) res->length(), (char*) tmp_value.ptr());
649   DBUG_ASSERT(length > 0);
650   tmp_value.length((uint) length - 1); // Without trailing '\0'
651   null_value= 0;
652   return &tmp_value;
653 }
654 
655 
fix_length_and_dec()656 void Item_func_from_base64::fix_length_and_dec()
657 {
658   if (args[0]->max_length > (uint) base64_decode_max_arg_length())
659   {
660     fix_char_length_ulonglong((ulonglong) base64_decode_max_arg_length());
661   }
662   else
663   {
664     uint64 length= base64_needed_decoded_length((uint64) args[0]->max_length);
665     fix_char_length_ulonglong((ulonglong) length);
666   }
667   maybe_null= 1; // Can be NULL, e.g. in case of badly formed input string
668 }
669 
670 
val_str(String * str)671 String *Item_func_from_base64::val_str(String *str)
672 {
673   String *res= args[0]->val_str_ascii(str);
674   bool too_long= false;
675   int64 length;
676   const char *end_ptr;
677 
678   if (!res ||
679       res->length() > (uint) base64_decode_max_arg_length() ||
680       (too_long=
681        ((uint64) (length= base64_needed_decoded_length((uint64) res->length())) >
682         current_thd->variables.max_allowed_packet)) ||
683       tmp_value.alloc((uint) length) ||
684       (length= base64_decode(res->ptr(), (uint64) res->length(),
685                              (char *) tmp_value.ptr(), &end_ptr, 0)) < 0 ||
686       end_ptr < res->ptr() + res->length())
687   {
688     null_value= 1; // NULL input, too long input, OOM, or badly formed input
689     if (too_long)
690     {
691       push_warning_printf(current_thd, Sql_condition::WARN_LEVEL_WARN,
692                           ER_WARN_ALLOWED_PACKET_OVERFLOWED,
693                           ER(ER_WARN_ALLOWED_PACKET_OVERFLOWED), func_name(),
694                           current_thd->variables.max_allowed_packet);
695     }
696     return 0;
697   }
698   tmp_value.length((uint) length);
699   null_value= 0;
700   return &tmp_value;
701 }
702 
703 
704 /**
705   Concatenate args with the following premises:
706   If only one arg (which is ok), return value of arg;
707   Don't reallocate val_str() if not absolute necessary.
708 */
709 
val_str(String * str)710 String *Item_func_concat::val_str(String *str) {
711   DBUG_ASSERT(fixed == 1);
712   String *res;
713 
714   THD *thd = current_thd;
715   null_value = false;
716   tmp_value.length(0);
717   for (uint i = 0; i < arg_count; ++i) {
718     if (!(res = args[i]->val_str(str))) {
719       null_value = 1;
720       return 0;
721     }
722     if (res->length() + tmp_value.length() >
723         thd->variables.max_allowed_packet) {
724       push_warning_printf(thd, Sql_condition::WARN_LEVEL_WARN,
725                           ER_WARN_ALLOWED_PACKET_OVERFLOWED,
726                           ER(ER_WARN_ALLOWED_PACKET_OVERFLOWED), func_name(),
727                           thd->variables.max_allowed_packet);
728       null_value = 1;
729       return 0;
730     }
731     if (tmp_value.append(*res)) {
732       null_value = 1;
733       return 0;
734     }
735   }
736   res = &tmp_value;
737   res->set_charset(collation.collation);
738   return res;
739 }
740 
fix_length_and_dec()741 void Item_func_concat::fix_length_and_dec()
742 {
743   ulonglong char_length= 0;
744 
745   if (agg_arg_charsets_for_string_result(collation, args, arg_count))
746     return;
747 
748   for (uint i=0 ; i < arg_count ; i++)
749     char_length+= args[i]->max_char_length();
750 
751   fix_char_length_ulonglong(char_length);
752 }
753 
754 /**
755   @details
756   Function des_encrypt() by tonu@spam.ee & monty
757   Works only if compiled with OpenSSL library support.
758   @return
759     A binary string where first character is CHAR(128 | key-number).
760     If one uses a string key key_number is 127.
761     Encryption result is longer than original by formula:
762   @code new_length= org_length + (8-(org_length % 8))+1 @endcode
763 */
764 
val_str(String * str)765 String *Item_func_des_encrypt::val_str(String *str)
766 {
767   DBUG_ASSERT(fixed == 1);
768 #if defined(HAVE_OPENSSL) && !defined(EMBEDDED_LIBRARY)
769   uint code= ER_WRONG_PARAMETERS_TO_PROCEDURE;
770   DES_cblock ivec;
771   struct st_des_keyblock keyblock;
772   struct st_des_keyschedule keyschedule;
773   const char *append_str="********";
774   uint key_number, res_length, tail;
775   String *res= args[0]->val_str(str);
776 
777   if ((null_value= args[0]->null_value))
778     return 0;                                   // ENCRYPT(NULL) == NULL
779   if ((res_length=res->length()) == 0)
780     return make_empty_result();
781   if (arg_count == 1)
782   {
783     /* Protect against someone doing FLUSH DES_KEY_FILE */
784     mysql_mutex_lock(&LOCK_des_key_file);
785     keyschedule= des_keyschedule[key_number=des_default_key];
786     mysql_mutex_unlock(&LOCK_des_key_file);
787   }
788   else if (args[1]->result_type() == INT_RESULT)
789   {
790     key_number= (uint) args[1]->val_int();
791     if (key_number > 9)
792       goto error;
793     mysql_mutex_lock(&LOCK_des_key_file);
794     keyschedule= des_keyschedule[key_number];
795     mysql_mutex_unlock(&LOCK_des_key_file);
796   }
797   else
798   {
799     String *keystr=args[1]->val_str(&tmp_value);
800     if (!keystr)
801       goto error;
802     key_number=127;				// User key string
803 
804     /* We make good 24-byte (168 bit) key from given plaintext key with MD5 */
805     memset(&ivec, 0, sizeof(ivec));
806     EVP_BytesToKey(EVP_des_ede3_cbc(),EVP_md5(),NULL,
807 		   (uchar*) keystr->ptr(), (int) keystr->length(),
808 		   1, (uchar*) &keyblock,ivec);
809     DES_set_key_unchecked(&keyblock.key1,&keyschedule.ks1);
810     DES_set_key_unchecked(&keyblock.key2,&keyschedule.ks2);
811     DES_set_key_unchecked(&keyblock.key3,&keyschedule.ks3);
812   }
813 
814   /*
815      The problem: DES algorithm requires original data to be in 8-bytes
816      chunks. Missing bytes get filled with '*'s and result of encryption
817      can be up to 8 bytes longer than original string. When decrypted,
818      we do not know the size of original string :(
819      We add one byte with value 0x1..0x8 as the last byte of the padded
820      string marking change of string length.
821   */
822 
823   tail= 8 - (res_length % 8);                   // 1..8 marking extra length
824   res_length+=tail;
825   tmp_arg.realloc(res_length);
826   tmp_arg.length(0);
827   tmp_arg.append(res->ptr(), res->length());
828   code= ER_OUT_OF_RESOURCES;
829   if (tmp_arg.append(append_str, tail) || tmp_value.alloc(res_length+1))
830     goto error;
831   tmp_arg[res_length-1]=tail;                   // save extra length
832   tmp_value.realloc(res_length+1);
833   tmp_value.length(res_length+1);
834   tmp_value.set_charset(&my_charset_bin);
835   tmp_value[0]=(char) (128 | key_number);
836   // Real encryption
837   memset(&ivec, 0, sizeof(ivec));
838   DES_ede3_cbc_encrypt((const uchar*) (tmp_arg.ptr()),
839 		       (uchar*) (tmp_value.ptr()+1),
840 		       res_length,
841 		       &keyschedule.ks1,
842 		       &keyschedule.ks2,
843 		       &keyschedule.ks3,
844 		       &ivec, TRUE);
845   return &tmp_value;
846 
847 error:
848   push_warning_printf(current_thd,Sql_condition::WARN_LEVEL_WARN,
849                           code, ER(code),
850                           "des_encrypt");
851 #else
852   push_warning_printf(current_thd,Sql_condition::WARN_LEVEL_WARN,
853                       ER_FEATURE_DISABLED, ER(ER_FEATURE_DISABLED),
854                       "des_encrypt", "--with-ssl");
855 #endif /* defined(HAVE_OPENSSL) && !defined(EMBEDDED_LIBRARY) */
856   null_value=1;
857   return 0;
858 }
859 
860 
val_str(String * str)861 String *Item_func_des_decrypt::val_str(String *str)
862 {
863   DBUG_ASSERT(fixed == 1);
864 #if defined(HAVE_OPENSSL) && !defined(EMBEDDED_LIBRARY)
865   uint code= ER_WRONG_PARAMETERS_TO_PROCEDURE;
866   DES_cblock ivec;
867   struct st_des_keyblock keyblock;
868   struct st_des_keyschedule keyschedule;
869   String *res= args[0]->val_str(str);
870   uint length,tail;
871 
872   if ((null_value= args[0]->null_value))
873     return 0;
874   length= res->length();
875   if (length < 9 || (length % 8) != 1 || !((*res)[0] & 128))
876     return res;				// Skip decryption if not encrypted
877 
878   if (arg_count == 1)			// If automatic uncompression
879   {
880     uint key_number=(uint) (*res)[0] & 127;
881     // Check if automatic key and that we have privilege to uncompress using it
882     if (!(current_thd->security_ctx->master_access & SUPER_ACL) ||
883         key_number > 9)
884       goto error;
885 
886     mysql_mutex_lock(&LOCK_des_key_file);
887     keyschedule= des_keyschedule[key_number];
888     mysql_mutex_unlock(&LOCK_des_key_file);
889   }
890   else
891   {
892     // We make good 24-byte (168 bit) key from given plaintext key with MD5
893     String *keystr=args[1]->val_str(&tmp_value);
894     if (!keystr)
895       goto error;
896 
897     memset(&ivec, 0, sizeof(ivec));
898     EVP_BytesToKey(EVP_des_ede3_cbc(),EVP_md5(),NULL,
899 		   (uchar*) keystr->ptr(),(int) keystr->length(),
900 		   1,(uchar*) &keyblock,ivec);
901     // Here we set all 64-bit keys (56 effective) one by one
902     DES_set_key_unchecked(&keyblock.key1,&keyschedule.ks1);
903     DES_set_key_unchecked(&keyblock.key2,&keyschedule.ks2);
904     DES_set_key_unchecked(&keyblock.key3,&keyschedule.ks3);
905   }
906   code= ER_OUT_OF_RESOURCES;
907   if (tmp_value.alloc(length-1))
908     goto error;
909 
910   memset(&ivec, 0, sizeof(ivec));
911   DES_ede3_cbc_encrypt((const uchar*) res->ptr()+1,
912 		       (uchar*) (tmp_value.ptr()),
913 		       length-1,
914 		       &keyschedule.ks1,
915 		       &keyschedule.ks2,
916 		       &keyschedule.ks3,
917 		       &ivec, FALSE);
918   /* Restore old length of key */
919   if ((tail=(uint) (uchar) tmp_value[length-2]) > 8)
920     goto wrong_key;				     // Wrong key
921   tmp_value.length(length-1-tail);
922   tmp_value.set_charset(&my_charset_bin);
923   return &tmp_value;
924 
925 error:
926   push_warning_printf(current_thd,Sql_condition::WARN_LEVEL_WARN,
927                           code, ER(code),
928                           "des_decrypt");
929 wrong_key:
930 #else
931   push_warning_printf(current_thd,Sql_condition::WARN_LEVEL_WARN,
932                       ER_FEATURE_DISABLED, ER(ER_FEATURE_DISABLED),
933                       "des_decrypt", "--with-ssl");
934 #endif /* defined(HAVE_OPENSSL) && !defined(EMBEDDED_LIBRARY) */
935   null_value=1;
936   return 0;
937 }
938 
939 
940 /**
941   concat with separator. First arg is the separator
942   concat_ws takes at least two arguments.
943 */
944 
val_str(String * str)945 String *Item_func_concat_ws::val_str(String *str) {
946   DBUG_ASSERT(fixed == 1);
947   char tmp_str_buff[10];
948   String tmp_sep_str(tmp_str_buff, sizeof(tmp_str_buff), default_charset_info);
949   String *sep_str, *res = NULL, *res2;
950   uint i;
951 
952   THD *thd = current_thd;
953   null_value = false;
954   if (!(sep_str = args[0]->val_str(&tmp_sep_str))) {
955     null_value = 1;
956     return 0;
957   }
958   tmp_value.length(0);
959 
960   // Skip until non-null argument is found.
961   // If not, return the empty string
962   for (i = 1; i < arg_count; i++)
963     if ((res = args[i]->val_str(str))) {
964       break;
965     }
966 
967   if (i == arg_count)
968     return make_empty_result();
969 
970   if (tmp_value.append(*res)) {
971     null_value = 1;
972     return 0;
973   }
974 
975   for (i++; i < arg_count; i++) {
976     if (!(res2 = args[i]->val_str(str)))
977       continue; // Skip NULL
978 
979     if (tmp_value.length() + sep_str->length() + res2->length() >
980         thd->variables.max_allowed_packet) {
981       push_warning_printf(thd, Sql_condition::WARN_LEVEL_WARN,
982                           ER_WARN_ALLOWED_PACKET_OVERFLOWED,
983                           ER(ER_WARN_ALLOWED_PACKET_OVERFLOWED), func_name(),
984                           thd->variables.max_allowed_packet);
985       null_value = 1;
986       return 0;
987     }
988     if (tmp_value.append(*sep_str) || tmp_value.append(*res2)) {
989       null_value = 1;
990       return 0;
991     }
992   }
993   res = &tmp_value;
994   res->set_charset(collation.collation);
995   return res;
996 }
997 
fix_length_and_dec()998 void Item_func_concat_ws::fix_length_and_dec()
999 {
1000   ulonglong char_length;
1001 
1002   if (agg_arg_charsets_for_string_result(collation, args, arg_count))
1003     return;
1004 
1005   /*
1006      arg_count cannot be less than 2,
1007      it is done on parser level in sql_yacc.yy
1008      so, (arg_count - 2) is safe here.
1009   */
1010   char_length= (ulonglong) args[0]->max_char_length() * (arg_count - 2);
1011   for (uint i=1 ; i < arg_count ; i++)
1012     char_length+= args[i]->max_char_length();
1013 
1014   fix_char_length_ulonglong(char_length);
1015 }
1016 
1017 
val_str(String * str)1018 String *Item_func_reverse::val_str(String *str)
1019 {
1020   DBUG_ASSERT(fixed == 1);
1021   String *res = args[0]->val_str(str);
1022   char *ptr, *end, *tmp;
1023 
1024   if ((null_value=args[0]->null_value))
1025     return 0;
1026   /* An empty string is a special case as the string pointer may be null */
1027   if (!res->length())
1028     return make_empty_result();
1029   if (tmp_value.alloced_length() < res->length() &&
1030       tmp_value.realloc(res->length()))
1031   {
1032     null_value= 1;
1033     return 0;
1034   }
1035   tmp_value.length(res->length());
1036   tmp_value.set_charset(res->charset());
1037   ptr= (char *) res->ptr();
1038   end= ptr + res->length();
1039   tmp= (char *) tmp_value.ptr() + tmp_value.length();
1040 #ifdef USE_MB
1041   if (use_mb(res->charset()))
1042   {
1043     register uint32 l;
1044     while (ptr < end)
1045     {
1046       if ((l= my_ismbchar(res->charset(),ptr,end)))
1047       {
1048         tmp-= l;
1049         DBUG_ASSERT(tmp >= tmp_value.ptr());
1050         memcpy(tmp,ptr,l);
1051         ptr+= l;
1052       }
1053       else
1054         *--tmp= *ptr++;
1055     }
1056   }
1057   else
1058 #endif /* USE_MB */
1059   {
1060     while (ptr < end)
1061       *--tmp= *ptr++;
1062   }
1063   return &tmp_value;
1064 }
1065 
1066 
fix_length_and_dec()1067 void Item_func_reverse::fix_length_and_dec()
1068 {
1069   agg_arg_charsets_for_string_result(collation, args, 1);
1070   DBUG_ASSERT(collation.collation != NULL);
1071   fix_char_length(args[0]->max_char_length());
1072 }
1073 
1074 /**
1075   Replace all occurences of string2 in string1 with string3.
1076 
1077   Don't reallocate val_str() if not needed.
1078 
1079   @todo
1080     Fix that this works with binary strings when using USE_MB
1081 */
1082 
val_str(String * str)1083 String *Item_func_replace::val_str(String *str)
1084 {
1085   DBUG_ASSERT(fixed == 1);
1086   String *res,*res2,*res3;
1087   int offset;
1088   uint from_length,to_length;
1089   bool alloced=0;
1090 #ifdef USE_MB
1091   const char *ptr,*end,*strend,*search,*search_end;
1092   register uint32 l;
1093   bool binary_cmp;
1094 #endif
1095 
1096   null_value=0;
1097   res=args[0]->val_str(str);
1098   if (args[0]->null_value)
1099     goto null;
1100   res2=args[1]->val_str(&tmp_value);
1101   if (args[1]->null_value)
1102     goto null;
1103 
1104   res->set_charset(collation.collation);
1105 
1106 #ifdef USE_MB
1107   binary_cmp = ((res->charset()->state & MY_CS_BINSORT) || !use_mb(res->charset()));
1108 #endif
1109 
1110   if (res2->length() == 0)
1111     return res;
1112 #ifndef USE_MB
1113   if ((offset=res->strstr(*res2)) < 0)
1114     return res;
1115 #else
1116   offset=0;
1117   if (binary_cmp && (offset=res->strstr(*res2)) < 0)
1118     return res;
1119 #endif
1120   if (!(res3=args[2]->val_str(&tmp_value2)))
1121     goto null;
1122   from_length= res2->length();
1123   to_length=   res3->length();
1124 
1125 #ifdef USE_MB
1126   if (!binary_cmp)
1127   {
1128     search=res2->ptr();
1129     search_end=search+from_length;
1130 redo:
1131     DBUG_ASSERT(res->ptr() || !offset);
1132     ptr=res->ptr()+offset;
1133     strend=res->ptr()+res->length();
1134     /*
1135       In some cases val_str() can return empty string
1136       with ptr() == NULL and length() == 0.
1137       Let's check strend to avoid overflow.
1138     */
1139     end= strend ? strend - from_length + 1 : NULL;
1140     while (ptr < end)
1141     {
1142         if (*ptr == *search)
1143         {
1144           register char *i,*j;
1145           i=(char*) ptr+1; j=(char*) search+1;
1146           while (j != search_end)
1147             if (*i++ != *j++) goto skip;
1148           offset= (int) (ptr-res->ptr());
1149           if (res->length()-from_length + to_length >
1150 	      current_thd->variables.max_allowed_packet)
1151 	  {
1152 	    push_warning_printf(current_thd, Sql_condition::WARN_LEVEL_WARN,
1153 				ER_WARN_ALLOWED_PACKET_OVERFLOWED,
1154 				ER(ER_WARN_ALLOWED_PACKET_OVERFLOWED),
1155 				func_name(),
1156 				current_thd->variables.max_allowed_packet);
1157 
1158             goto null;
1159 	  }
1160           if (!alloced)
1161           {
1162             alloced=1;
1163             if (res->uses_buffer_owned_by(str))
1164             {
1165               if (tmp_value_res.alloc(res->length() + to_length) ||
1166                   tmp_value_res.copy(*res))
1167                 goto null;
1168               res= &tmp_value_res;
1169             }
1170             else
1171               res= copy_if_not_alloced(str, res, res->length() + to_length);
1172           }
1173           res->replace((uint) offset,from_length,*res3);
1174 	  offset+=(int) to_length;
1175           goto redo;
1176         }
1177 skip:
1178         if ((l=my_ismbchar(res->charset(), ptr,strend))) ptr+=l;
1179         else ++ptr;
1180     }
1181   }
1182   else
1183 #endif /* USE_MB */
1184     do
1185     {
1186       if (res->length()-from_length + to_length >
1187 	  current_thd->variables.max_allowed_packet)
1188       {
1189 	push_warning_printf(current_thd, Sql_condition::WARN_LEVEL_WARN,
1190 			    ER_WARN_ALLOWED_PACKET_OVERFLOWED,
1191 			    ER(ER_WARN_ALLOWED_PACKET_OVERFLOWED), func_name(),
1192 			    current_thd->variables.max_allowed_packet);
1193         goto null;
1194       }
1195       if (!alloced)
1196       {
1197         alloced=1;
1198         if (res->uses_buffer_owned_by(str))
1199         {
1200           if (tmp_value_res.alloc(res->length() + to_length) ||
1201               tmp_value_res.copy(*res))
1202             goto null;
1203           res= &tmp_value_res;
1204         }
1205         else
1206           res= copy_if_not_alloced(str, res, res->length() + to_length);
1207       }
1208       res->replace((uint) offset,from_length,*res3);
1209       offset+=(int) to_length;
1210     }
1211     while ((offset=res->strstr(*res2,(uint) offset)) >= 0);
1212   return res;
1213 
1214 null:
1215   null_value=1;
1216   return 0;
1217 }
1218 
1219 
fix_length_and_dec()1220 void Item_func_replace::fix_length_and_dec()
1221 {
1222   ulonglong char_length= (ulonglong) args[0]->max_char_length();
1223   int diff=(int) (args[2]->max_char_length() - args[1]->max_char_length());
1224   if (diff > 0 && args[1]->max_char_length())
1225   {						// Calculate of maxreplaces
1226     ulonglong max_substrs= char_length / args[1]->max_char_length();
1227     char_length+= max_substrs * (uint) diff;
1228   }
1229 
1230   if (agg_arg_charsets_for_string_result_with_comparison(collation, args, 3))
1231     return;
1232   fix_char_length_ulonglong(char_length);
1233 }
1234 
1235 
val_str(String * str)1236 String *Item_func_insert::val_str(String *str)
1237 {
1238   DBUG_ASSERT(fixed == 1);
1239   String *res,*res2;
1240   longlong start, length, orig_len;  /* must be longlong to avoid truncation */
1241 
1242   null_value=0;
1243   res=args[0]->val_str(str);
1244   res2=args[3]->val_str(&tmp_value);
1245   start= args[1]->val_int();
1246   length= args[2]->val_int();
1247 
1248   if (args[0]->null_value || args[1]->null_value || args[2]->null_value ||
1249       args[3]->null_value)
1250     goto null; /* purecov: inspected */
1251 
1252   orig_len= static_cast<longlong>(res->length());
1253 
1254   if ((start < 1) || (start > orig_len))
1255     return res;                                 // Wrong param; skip insert
1256 
1257   --start;    // Internal start from '0'
1258 
1259   if ((length < 0) || (length > orig_len))
1260     length= orig_len;
1261 
1262   /*
1263     There is one exception not handled (intentionaly) by the character set
1264     aggregation code. If one string is strong side and is binary, and
1265     another one is weak side and is a multi-byte character string,
1266     then we need to operate on the second string in terms on bytes when
1267     calling ::numchars() and ::charpos(), rather than in terms of characters.
1268     Lets substitute its character set to binary.
1269   */
1270   if (collation.collation == &my_charset_bin)
1271   {
1272     res->set_charset(&my_charset_bin);
1273     res2->set_charset(&my_charset_bin);
1274   }
1275 
1276   /* start and length are now sufficiently valid to pass to charpos function */
1277    start= res->charpos((int) start);
1278    length= res->charpos((int) length, (uint32) start);
1279 
1280   /* Re-testing with corrected params */
1281   if (start > orig_len)
1282     return res; /* purecov: inspected */        // Wrong param; skip insert
1283   if (length > orig_len - start)
1284     length= orig_len - start;
1285 
1286   if ((ulonglong) (orig_len - length + res2->length()) >
1287       (ulonglong) current_thd->variables.max_allowed_packet)
1288   {
1289     push_warning_printf(current_thd, Sql_condition::WARN_LEVEL_WARN,
1290 			ER_WARN_ALLOWED_PACKET_OVERFLOWED,
1291 			ER(ER_WARN_ALLOWED_PACKET_OVERFLOWED),
1292 			func_name(), current_thd->variables.max_allowed_packet);
1293     goto null;
1294   }
1295   if (res->uses_buffer_owned_by(str))
1296   {
1297     if (tmp_value_res.alloc(orig_len) ||
1298         tmp_value_res.copy(*res))
1299       goto null;
1300     res= &tmp_value_res;
1301   }
1302   else
1303     res= copy_if_not_alloced(str, res, orig_len);
1304 
1305   res->replace((uint32) start,(uint32) length,*res2);
1306   return res;
1307 null:
1308   null_value=1;
1309   return 0;
1310 }
1311 
1312 
fix_length_and_dec()1313 void Item_func_insert::fix_length_and_dec()
1314 {
1315   ulonglong char_length;
1316 
1317   // Handle character set for args[0] and args[3].
1318   if (agg_arg_charsets_for_string_result(collation, args, 2, 3))
1319     return;
1320   char_length= ((ulonglong) args[0]->max_char_length() +
1321                 (ulonglong) args[3]->max_char_length());
1322   fix_char_length_ulonglong(char_length);
1323 }
1324 
1325 
val_str(String * str)1326 String *Item_str_conv::val_str(String *str)
1327 {
1328   DBUG_ASSERT(fixed == 1);
1329   String *res;
1330   if (!(res=args[0]->val_str(str)))
1331   {
1332     null_value=1; /* purecov: inspected */
1333     return 0; /* purecov: inspected */
1334   }
1335   null_value=0;
1336   if (multiply == 1)
1337   {
1338     uint len;
1339     if (res->uses_buffer_owned_by(str))
1340     {
1341        if (tmp_value.copy(*res))
1342          goto null;
1343        res= &tmp_value;
1344     }
1345     else
1346       res= copy_if_not_alloced(str, res, res->length());
1347 
1348     len= converter(collation.collation, (char*) res->ptr(), res->length(),
1349                                         (char*) res->ptr(), res->length());
1350     DBUG_ASSERT(len <= res->length());
1351     res->length(len);
1352   }
1353   else
1354   {
1355     uint len= res->length() * multiply;
1356     tmp_value.alloc(len);
1357     tmp_value.set_charset(collation.collation);
1358     len= converter(collation.collation, (char*) res->ptr(), res->length(),
1359                                         (char*) tmp_value.ptr(), len);
1360     tmp_value.length(len);
1361     res= &tmp_value;
1362   }
1363   return res;
1364 null:
1365   null_value= maybe_null;
1366   return 0;
1367 }
1368 
1369 
fix_length_and_dec()1370 void Item_func_lcase::fix_length_and_dec()
1371 {
1372   agg_arg_charsets_for_string_result(collation, args, 1);
1373   DBUG_ASSERT(collation.collation != NULL);
1374   multiply= collation.collation->casedn_multiply;
1375   converter= collation.collation->cset->casedn;
1376   fix_char_length_ulonglong((ulonglong) args[0]->max_char_length() * multiply);
1377 }
1378 
fix_length_and_dec()1379 void Item_func_ucase::fix_length_and_dec()
1380 {
1381   agg_arg_charsets_for_string_result(collation, args, 1);
1382   DBUG_ASSERT(collation.collation != NULL);
1383   multiply= collation.collation->caseup_multiply;
1384   converter= collation.collation->cset->caseup;
1385   fix_char_length_ulonglong((ulonglong) args[0]->max_char_length() * multiply);
1386 }
1387 
1388 
val_str(String * str)1389 String *Item_func_left::val_str(String *str)
1390 {
1391   DBUG_ASSERT(fixed == 1);
1392   String *res= args[0]->val_str(str);
1393 
1394   /* must be longlong to avoid truncation */
1395   longlong length= args[1]->val_int();
1396   uint char_pos;
1397 
1398   if ((null_value=(args[0]->null_value || args[1]->null_value)))
1399     return 0;
1400 
1401   /* if "unsigned_flag" is set, we have a *huge* positive number. */
1402   if ((length <= 0) && (!args[1]->unsigned_flag))
1403     return make_empty_result();
1404   if ((res->length() <= (ulonglong) length) ||
1405       (res->length() <= (char_pos= res->charpos((int) length))))
1406     return res;
1407 
1408   tmp_value.set(*res, 0, char_pos);
1409   return &tmp_value;
1410 }
1411 
1412 
left_right_max_length()1413 void Item_str_func::left_right_max_length()
1414 {
1415   uint32 char_length= args[0]->max_char_length();
1416   if (args[1]->const_item())
1417   {
1418     int length= (int) args[1]->val_int();
1419     if (args[1]->null_value)
1420       goto end;
1421 
1422     if (length <= 0)
1423       char_length=0;
1424     else
1425       set_if_smaller(char_length, (uint) length);
1426   }
1427 
1428 end:
1429   fix_char_length(char_length);
1430 }
1431 
1432 
fix_length_and_dec()1433 void Item_func_left::fix_length_and_dec()
1434 {
1435   agg_arg_charsets_for_string_result(collation, args, 1);
1436   DBUG_ASSERT(collation.collation != NULL);
1437   left_right_max_length();
1438 }
1439 
1440 
val_str(String * str)1441 String *Item_func_right::val_str(String *str)
1442 {
1443   DBUG_ASSERT(fixed == 1);
1444   String *res= args[0]->val_str(str);
1445   /* must be longlong to avoid truncation */
1446   longlong length= args[1]->val_int();
1447 
1448   if ((null_value=(args[0]->null_value || args[1]->null_value)))
1449     return 0; /* purecov: inspected */
1450 
1451   /* if "unsigned_flag" is set, we have a *huge* positive number. */
1452   if ((length <= 0) && (!args[1]->unsigned_flag))
1453     return make_empty_result(); /* purecov: inspected */
1454 
1455   if (res->length() <= (ulonglong) length)
1456     return res; /* purecov: inspected */
1457 
1458   uint start=res->numchars();
1459   if (start <= (uint) length)
1460     return res;
1461   start=res->charpos(start - (uint) length);
1462   tmp_value.set(*res,start,res->length()-start);
1463   return &tmp_value;
1464 }
1465 
1466 
fix_length_and_dec()1467 void Item_func_right::fix_length_and_dec()
1468 {
1469   agg_arg_charsets_for_string_result(collation, args, 1);
1470   DBUG_ASSERT(collation.collation != NULL);
1471   left_right_max_length();
1472 }
1473 
1474 
val_str(String * str)1475 String *Item_func_substr::val_str(String *str)
1476 {
1477   DBUG_ASSERT(fixed == 1);
1478   String *res  = args[0]->val_str(str);
1479   /* must be longlong to avoid truncation */
1480   longlong start= args[1]->val_int();
1481   /* Assumes that the maximum length of a String is < INT_MAX32. */
1482   /* Limit so that code sees out-of-bound value properly. */
1483   longlong length= arg_count == 3 ? args[2]->val_int() : INT_MAX32;
1484   longlong tmp_length;
1485 
1486   if ((null_value=(args[0]->null_value || args[1]->null_value ||
1487 		   (arg_count == 3 && args[2]->null_value))))
1488     return 0; /* purecov: inspected */
1489 
1490   /* Negative or zero length, will return empty string. */
1491   if ((arg_count == 3) && (length <= 0) &&
1492       (length == 0 || !args[2]->unsigned_flag))
1493     return make_empty_result();
1494 
1495   /* Assumes that the maximum length of a String is < INT_MAX32. */
1496   /* Set here so that rest of code sees out-of-bound value as such. */
1497   if ((length <= 0) || (length > INT_MAX32))
1498     length= INT_MAX32;
1499 
1500   /* if "unsigned_flag" is set, we have a *huge* positive number. */
1501   /* Assumes that the maximum length of a String is < INT_MAX32. */
1502   if ((!args[1]->unsigned_flag && (start < INT_MIN32 || start > INT_MAX32)) ||
1503       (args[1]->unsigned_flag && ((ulonglong) start > INT_MAX32)))
1504     return make_empty_result();
1505 
1506   start= ((start < 0) ? res->numchars() + start : start - 1);
1507   start= res->charpos((int) start);
1508   if ((start < 0) || ((uint) start + 1 > res->length()))
1509     return make_empty_result();
1510 
1511   length= res->charpos((int) length, (uint32) start);
1512   tmp_length= res->length() - start;
1513   length= min(length, tmp_length);
1514 
1515   if (!start && (longlong) res->length() == length)
1516     return res;
1517   tmp_value.set(*res, (uint32) start, (uint32) length);
1518   return &tmp_value;
1519 }
1520 
1521 
fix_length_and_dec()1522 void Item_func_substr::fix_length_and_dec()
1523 {
1524   max_length=args[0]->max_length;
1525 
1526   agg_arg_charsets_for_string_result(collation, args, 1);
1527   DBUG_ASSERT(collation.collation != NULL);
1528   if (args[1]->const_item())
1529   {
1530     int32 start= (int32) args[1]->val_int();
1531     if (args[1]->null_value)
1532       goto end;
1533     if (start < 0)
1534       max_length= ((uint)(-start) > max_length) ? 0 : (uint)(-start);
1535     else
1536       max_length-= min((uint)(start - 1), max_length);
1537   }
1538   if (arg_count == 3 && args[2]->const_item())
1539   {
1540     int32 length= (int32) args[2]->val_int();
1541     if (args[2]->null_value)
1542       goto end;
1543     if (length <= 0)
1544       max_length=0; /* purecov: inspected */
1545     else
1546       set_if_smaller(max_length,(uint) length);
1547   }
1548 
1549 end:
1550   max_length*= collation.collation->mbmaxlen;
1551 }
1552 
1553 
fix_length_and_dec()1554 void Item_func_substr_index::fix_length_and_dec()
1555 {
1556   if (agg_arg_charsets_for_string_result_with_comparison(collation, args, 2))
1557     return;
1558   fix_char_length(args[0]->max_char_length());
1559 }
1560 
1561 
val_str(String * str)1562 String *Item_func_substr_index::val_str(String *str)
1563 {
1564   DBUG_ASSERT(fixed == 1);
1565   char buff[MAX_FIELD_WIDTH];
1566   String tmp(buff,sizeof(buff),system_charset_info);
1567   String *res= args[0]->val_str(str);
1568   String *delimiter= args[1]->val_str(&tmp);
1569   int32 count= (int32) args[2]->val_int();
1570   int offset;
1571 
1572   if (args[0]->null_value || args[1]->null_value || args[2]->null_value)
1573   {					// string and/or delim are null
1574     null_value=1;
1575     return 0;
1576   }
1577   null_value=0;
1578   uint delimiter_length= delimiter->length();
1579   if (!res->length() || !delimiter_length || !count)
1580     return make_empty_result();		// Wrong parameters
1581 
1582   res->set_charset(collation.collation);
1583 
1584 #ifdef USE_MB
1585   if (use_mb(res->charset()))
1586   {
1587     const char *ptr= res->ptr();
1588     const char *strend= ptr+res->length();
1589     const char *end= strend-delimiter_length+1;
1590     const char *search= delimiter->ptr();
1591     const char *search_end= search+delimiter_length;
1592     int32 n=0,c=count,pass;
1593     register uint32 l;
1594     for (pass=(count>0);pass<2;++pass)
1595     {
1596       while (ptr < end)
1597       {
1598         if (*ptr == *search)
1599         {
1600 	  register char *i,*j;
1601 	  i=(char*) ptr+1; j=(char*) search+1;
1602 	  while (j != search_end)
1603 	    if (*i++ != *j++) goto skip;
1604 	  if (pass==0) ++n;
1605 	  else if (!--c) break;
1606 	  ptr+= delimiter_length;
1607 	  continue;
1608 	}
1609     skip:
1610         if ((l=my_ismbchar(res->charset(), ptr,strend))) ptr+=l;
1611         else ++ptr;
1612       } /* either not found or got total number when count<0 */
1613       if (pass == 0) /* count<0 */
1614       {
1615         c+=n+1;
1616         if (c<=0) return res; /* not found, return original string */
1617         ptr=res->ptr();
1618       }
1619       else
1620       {
1621         if (c) return res; /* Not found, return original string */
1622         if (count>0) /* return left part */
1623         {
1624 	  tmp_value.set(*res,0,(ulong) (ptr-res->ptr()));
1625         }
1626         else /* return right part */
1627         {
1628 	  ptr+= delimiter_length;
1629 	  tmp_value.set(*res,(ulong) (ptr-res->ptr()), (ulong) (strend-ptr));
1630         }
1631       }
1632     }
1633   }
1634   else
1635 #endif /* USE_MB */
1636   {
1637     if (count > 0)
1638     {					// start counting from the beginning
1639       for (offset=0; ; offset+= delimiter_length)
1640       {
1641 	if ((offset= res->strstr(*delimiter, offset)) < 0)
1642 	  return res;			// Didn't find, return org string
1643 	if (!--count)
1644 	{
1645 	  tmp_value.set(*res,0,offset);
1646 	  break;
1647 	}
1648       }
1649     }
1650     else
1651     {
1652       /*
1653         Negative index, start counting at the end
1654       */
1655       for (offset=res->length(); offset; )
1656       {
1657         /*
1658           this call will result in finding the position pointing to one
1659           address space less than where the found substring is located
1660           in res
1661         */
1662 	if ((offset= res->strrstr(*delimiter, offset)) < 0)
1663 	  return res;			// Didn't find, return org string
1664         /*
1665           At this point, we've searched for the substring
1666           the number of times as supplied by the index value
1667         */
1668 	if (!++count)
1669 	{
1670 	  offset+= delimiter_length;
1671 	  tmp_value.set(*res,offset,res->length()- offset);
1672 	  break;
1673 	}
1674       }
1675       if (count)
1676         return res;			// Didn't find, return org string
1677     }
1678   }
1679   return (&tmp_value);
1680 }
1681 
1682 
1683 /**
1684   A helper function for trim(leading ...) for multibyte charsets.
1685   @param res        Copy of 'res' in calling functions.
1686   @param ptr        Where to start trimming.
1687   @param end        End of string to be trimmed.
1688   @param remove_str The string to be removed from [ptr .. end)
1689   @return           Pointer to left-trimmed string.
1690  */
1691 static inline
trim_left_mb(String * res,char * ptr,char * end,String * remove_str)1692 char *trim_left_mb(String *res, char *ptr, char *end, String *remove_str)
1693 {
1694   const char * const r_ptr= remove_str->ptr();
1695   const uint remove_length= remove_str->length();
1696 
1697   while (ptr + remove_length <= end)
1698   {
1699     uint num_bytes= 0;
1700     while (num_bytes < remove_length)
1701     {
1702       uint len;
1703       if ((len= my_ismbchar(res->charset(), ptr + num_bytes, end)))
1704         num_bytes+= len;
1705       else
1706         ++num_bytes;
1707     }
1708     if (num_bytes != remove_length)
1709       break;
1710     if (memcmp(ptr, r_ptr, remove_length))
1711       break;
1712     ptr+= remove_length;
1713   }
1714   return ptr;
1715 }
1716 
1717 
1718 /*
1719 ** The trim functions are extension to ANSI SQL because they trim substrings
1720 ** They ltrim() and rtrim() functions are optimized for 1 byte strings
1721 ** They also return the original string if possible, else they return
1722 ** a substring that points at the original string.
1723 */
1724 
1725 
val_str(String * str)1726 String *Item_func_ltrim::val_str(String *str)
1727 {
1728   DBUG_ASSERT(fixed == 1);
1729   char buff[MAX_FIELD_WIDTH], *ptr, *end;
1730   String tmp(buff,sizeof(buff),system_charset_info);
1731   String *res, *remove_str;
1732   uint remove_length;
1733   LINT_INIT(remove_length);
1734 
1735   res= args[0]->val_str(str);
1736   if ((null_value=args[0]->null_value))
1737     return 0;
1738   remove_str= &remove;                          /* Default value. */
1739   if (arg_count == 2)
1740   {
1741     remove_str= args[1]->val_str(&tmp);
1742     if ((null_value= args[1]->null_value))
1743       return 0;
1744   }
1745 
1746   if ((remove_length= remove_str->length()) == 0 ||
1747       remove_length > res->length())
1748     return res;
1749 
1750   ptr= (char*) res->ptr();
1751   end= ptr+res->length();
1752 #ifdef USE_MB
1753   if (use_mb(res->charset()))
1754   {
1755     ptr= trim_left_mb(res, ptr, end, remove_str);
1756   }
1757   else
1758 #endif /* USE_MB */
1759   {
1760     if (remove_length == 1)
1761     {
1762       char chr=(*remove_str)[0];
1763       while (ptr != end && *ptr == chr)
1764         ptr++;
1765     }
1766     else
1767     {
1768       const char *r_ptr=remove_str->ptr();
1769       end-=remove_length;
1770       while (ptr <= end && !memcmp(ptr, r_ptr, remove_length))
1771         ptr+=remove_length;
1772       end+=remove_length;
1773     }
1774   }
1775   if (ptr == res->ptr())
1776     return res;
1777   tmp_value.set(*res,(uint) (ptr - res->ptr()),(uint) (end-ptr));
1778   return &tmp_value;
1779 }
1780 
1781 
val_str(String * str)1782 String *Item_func_rtrim::val_str(String *str)
1783 {
1784   DBUG_ASSERT(fixed == 1);
1785   char buff[MAX_FIELD_WIDTH], *ptr, *end;
1786   String tmp(buff, sizeof(buff), system_charset_info);
1787   String *res, *remove_str;
1788   uint remove_length;
1789   LINT_INIT(remove_length);
1790 
1791   res= args[0]->val_str(str);
1792   if ((null_value=args[0]->null_value))
1793     return 0;
1794   remove_str= &remove;                          /* Default value. */
1795   if (arg_count == 2)
1796   {
1797     remove_str= args[1]->val_str(&tmp);
1798     if ((null_value= args[1]->null_value))
1799       return 0;
1800   }
1801 
1802   if ((remove_length= remove_str->length()) == 0 ||
1803       remove_length > res->length())
1804     return res;
1805 
1806   ptr= (char*) res->ptr();
1807   end= ptr+res->length();
1808 #ifdef USE_MB
1809   char *p=ptr;
1810   register uint32 l;
1811 #endif
1812   if (remove_length == 1)
1813   {
1814     char chr=(*remove_str)[0];
1815 #ifdef USE_MB
1816     if (use_mb(res->charset()))
1817     {
1818       while (ptr < end)
1819       {
1820 	if ((l=my_ismbchar(res->charset(), ptr,end))) ptr+=l,p=ptr;
1821 	else ++ptr;
1822       }
1823       ptr=p;
1824     }
1825 #endif
1826     while (ptr != end  && end[-1] == chr)
1827       end--;
1828   }
1829   else
1830   {
1831     const char *r_ptr=remove_str->ptr();
1832 #ifdef USE_MB
1833     if (use_mb(res->charset()))
1834     {
1835   loop:
1836       while (ptr + remove_length < end)
1837       {
1838 	if ((l=my_ismbchar(res->charset(), ptr,end))) ptr+=l;
1839 	else ++ptr;
1840       }
1841       if (ptr + remove_length == end && !memcmp(ptr,r_ptr,remove_length))
1842       {
1843 	end-=remove_length;
1844 	ptr=p;
1845 	goto loop;
1846       }
1847     }
1848     else
1849 #endif /* USE_MB */
1850     {
1851       while (ptr + remove_length <= end &&
1852 	     !memcmp(end-remove_length, r_ptr, remove_length))
1853 	end-=remove_length;
1854     }
1855   }
1856   if (end == res->ptr()+res->length())
1857     return res;
1858   tmp_value.set(*res,0,(uint) (end-res->ptr()));
1859   return &tmp_value;
1860 }
1861 
1862 
val_str(String * str)1863 String *Item_func_trim::val_str(String *str)
1864 {
1865   DBUG_ASSERT(fixed == 1);
1866   char buff[MAX_FIELD_WIDTH], *ptr, *end;
1867   String tmp(buff, sizeof(buff), system_charset_info);
1868   String *res, *remove_str;
1869 
1870   res= args[0]->val_str(str);
1871   if ((null_value=args[0]->null_value))
1872     return 0;
1873   remove_str= &remove;                          /* Default value. */
1874   if (arg_count == 2)
1875   {
1876     remove_str= args[1]->val_str(&tmp);
1877     if ((null_value= args[1]->null_value))
1878       return 0;
1879   }
1880 
1881   const uint remove_length= remove_str->length();
1882   if (remove_length == 0 ||
1883       remove_length > res->length())
1884     return res;
1885 
1886   ptr= (char*) res->ptr();
1887   end= ptr+res->length();
1888   const char * const r_ptr= remove_str->ptr();
1889 #ifdef USE_MB
1890   if (use_mb(res->charset()))
1891   {
1892     ptr= trim_left_mb(res, ptr, end, remove_str);
1893 
1894     char *p=ptr;
1895     register uint32 l;
1896  loop:
1897     while (ptr + remove_length < end)
1898     {
1899       if ((l= my_ismbchar(res->charset(), ptr,end)))
1900         ptr+= l;
1901       else
1902         ++ptr;
1903     }
1904     if (ptr + remove_length == end && !memcmp(ptr,r_ptr,remove_length))
1905     {
1906       end-=remove_length;
1907       ptr=p;
1908       goto loop;
1909     }
1910     ptr=p;
1911   }
1912   else
1913 #endif /* USE_MB */
1914   {
1915     while (ptr+remove_length <= end && !memcmp(ptr,r_ptr,remove_length))
1916       ptr+=remove_length;
1917     while (ptr + remove_length <= end &&
1918 	   !memcmp(end-remove_length,r_ptr,remove_length))
1919       end-=remove_length;
1920   }
1921   if (ptr == res->ptr() && end == ptr+res->length())
1922     return res;
1923   tmp_value.set(*res,(uint) (ptr - res->ptr()),(uint) (end-ptr));
1924   return &tmp_value;
1925 }
1926 
fix_length_and_dec()1927 void Item_func_trim::fix_length_and_dec()
1928 {
1929   if (arg_count == 1)
1930   {
1931     agg_arg_charsets_for_string_result(collation, args, 1);
1932     DBUG_ASSERT(collation.collation != NULL);
1933     remove.set_charset(collation.collation);
1934     remove.set_ascii(" ",1);
1935   }
1936   else
1937   {
1938     // Handle character set for args[1] and args[0].
1939     // Note that we pass args[1] as the first item, and args[0] as the second.
1940     if (agg_arg_charsets_for_string_result_with_comparison(collation,
1941                                                            &args[1], 2, -1))
1942       return;
1943   }
1944   fix_char_length(args[0]->max_char_length());
1945 }
1946 
print(String * str,enum_query_type query_type)1947 void Item_func_trim::print(String *str, enum_query_type query_type)
1948 {
1949   if (arg_count == 1)
1950   {
1951     Item_func::print(str, query_type);
1952     return;
1953   }
1954   str->append(Item_func_trim::func_name());
1955   str->append('(');
1956   str->append(mode_name());
1957   str->append(' ');
1958   args[1]->print(str, query_type);
1959   str->append(STRING_WITH_LEN(" from "));
1960   args[0]->print(str, query_type);
1961   str->append(')');
1962 }
1963 
1964 
1965 /**
1966   Helper function for calculating a new password. Used in
1967   Item_func_password::fix_length_and_dec() for const parameters and in
1968   Item_func_password::val_str_ascii() for non-const parameters.
1969   @param str The plain text password which should be digested
1970   @param buffer a pointer to the buffer where the digest will be stored.
1971 
1972   @note The buffer must be of at least CRYPT_MAX_PASSWORD_SIZE size.
1973 
1974   @return Size of the password.
1975 */
1976 
calculate_password(String * str,char * buffer)1977 static int calculate_password(String *str, char *buffer)
1978 {
1979   DBUG_ASSERT(str);
1980   if (str->length() == 0) // PASSWORD('') returns ''
1981     return 0;
1982 
1983   int buffer_len= 0;
1984   THD *thd= current_thd;
1985   int old_passwords= 0;
1986   if (thd)
1987     old_passwords= thd->variables.old_passwords;
1988 
1989 #if defined(HAVE_OPENSSL)
1990   if (old_passwords == 2)
1991   {
1992     if (str->length() > MAX_PLAINTEXT_LENGTH)
1993     {
1994       my_error(ER_NOT_VALID_PASSWORD, MYF(0));
1995       return 0;
1996     }
1997     my_make_scrambled_password(buffer, str->ptr(),
1998                                str->length());
1999     buffer_len= (int) strlen(buffer) + 1;
2000   }
2001   else
2002 #endif
2003   if (old_passwords == 0)
2004   {
2005     my_make_scrambled_password_sha1(buffer, str->ptr(),
2006                                     str->length());
2007     buffer_len= SCRAMBLED_PASSWORD_CHAR_LENGTH;
2008   }
2009   else
2010   if (old_passwords == 1)
2011   {
2012     my_make_scrambled_password_323(buffer, str->ptr(),
2013                                    str->length());
2014     buffer_len= SCRAMBLED_PASSWORD_CHAR_LENGTH_323;
2015   }
2016   return buffer_len;
2017 }
2018 
2019 /* Item_func_password */
fix_length_and_dec()2020 void Item_func_password::fix_length_and_dec()
2021 {
2022   maybe_null= false; // PASSWORD() never returns NULL
2023 
2024   if (args[0]->const_item())
2025   {
2026     String str;
2027     String *res= args[0]->val_str(&str);
2028     if (!args[0]->null_value)
2029     {
2030       m_hashed_password_buffer_len=
2031         calculate_password(res, m_hashed_password_buffer);
2032       fix_length_and_charset(m_hashed_password_buffer_len, default_charset());
2033       m_recalculate_password= false;
2034       return;
2035     }
2036   }
2037 
2038   m_recalculate_password= true;
2039   fix_length_and_charset(CRYPT_MAX_PASSWORD_SIZE, default_charset());
2040 }
2041 
val_str_ascii(String * str)2042 String *Item_func_password::val_str_ascii(String *str)
2043 {
2044   DBUG_ASSERT(fixed == 1);
2045 
2046   String *res= args[0]->val_str(str);
2047 
2048   if (args[0]->null_value)
2049     res= make_empty_result();
2050 
2051   /* we treat NULLs as equal to empty string when calling the plugin */
2052   check_password_policy(res);
2053 
2054   null_value= 0;
2055   if (args[0]->null_value)  // PASSWORD(NULL) returns ''
2056     return res;
2057 
2058   if (m_recalculate_password)
2059     m_hashed_password_buffer_len= calculate_password(res,
2060                                                      m_hashed_password_buffer);
2061 
2062   if (m_hashed_password_buffer_len == 0)
2063     return make_empty_result();
2064 
2065   str->set(m_hashed_password_buffer, m_hashed_password_buffer_len,
2066            default_charset());
2067 
2068   return str;
2069 }
2070 
2071 char *Item_func_password::
create_password_hash_buffer(THD * thd,const char * password,size_t pass_len)2072   create_password_hash_buffer(THD *thd, const char *password,  size_t pass_len)
2073 {
2074   String *password_str= new (thd->mem_root)String(password, thd->variables.
2075                                                     character_set_client);
2076   check_password_policy(password_str);
2077 
2078   char *buff= NULL;
2079   if (thd->variables.old_passwords == 0)
2080   {
2081     /* Allocate memory for the password scramble and one extra byte for \0 */
2082     buff= (char *) thd->alloc(SCRAMBLED_PASSWORD_CHAR_LENGTH + 1);
2083     my_make_scrambled_password_sha1(buff, password, pass_len);
2084   }
2085 #if defined(HAVE_OPENSSL)
2086   else
2087   {
2088     if (pass_len <= MAX_PLAINTEXT_LENGTH)
2089     {
2090       /* Allocate memory for the password scramble and one extra byte for \0 */
2091       buff= (char *) thd->alloc(CRYPT_MAX_PASSWORD_SIZE + 1);
2092       my_make_scrambled_password(buff, password, pass_len);
2093     }
2094     else
2095       my_error(ER_NOT_VALID_PASSWORD, MYF(0));
2096   }
2097 #endif
2098   return buff;
2099 }
2100 
2101 /* Item_func_old_password */
2102 
val_str_ascii(String * str)2103 String *Item_func_old_password::val_str_ascii(String *str)
2104 {
2105   String *res;
2106 
2107   DBUG_ASSERT(fixed == 1);
2108 
2109   res= args[0]->val_str(str);
2110 
2111   if ((null_value= args[0]->null_value))
2112     res= make_empty_result();
2113 
2114   /* we treat NULLs as equal to empty string when calling the plugin */
2115   check_password_policy(res);
2116 
2117   if (null_value)
2118     return 0;
2119 
2120   if (res->length() == 0)
2121     return make_empty_result();
2122 
2123   my_make_scrambled_password_323(tmp_value, res->ptr(), res->length());
2124   str->set(tmp_value, SCRAMBLED_PASSWORD_CHAR_LENGTH_323, &my_charset_latin1);
2125   return str;
2126 }
2127 
alloc(THD * thd,const char * password,size_t pass_len)2128 char *Item_func_old_password::alloc(THD *thd, const char *password,
2129                                     size_t pass_len)
2130 {
2131   char *buff= (char *) thd->alloc(SCRAMBLED_PASSWORD_CHAR_LENGTH_323+1);
2132   if (buff)
2133   {
2134     String *password_str= new (thd->mem_root)String(password, thd->variables.
2135                                                     character_set_client);
2136     check_password_policy(password_str);
2137     my_make_scrambled_password_323(buff, password, pass_len);
2138   }
2139   return buff;
2140 }
2141 
2142 
2143 #define bin_to_ascii(c) ((c)>=38?((c)-38+'a'):(c)>=12?((c)-12+'A'):(c)+'.')
2144 
val_str(String * str)2145 String *Item_func_encrypt::val_str(String *str)
2146 {
2147   DBUG_ASSERT(fixed == 1);
2148   String *res  =args[0]->val_str(str);
2149 
2150 #ifdef HAVE_CRYPT
2151   char salt[3],*salt_ptr;
2152   if ((null_value=args[0]->null_value))
2153     return 0;
2154   if (res->length() == 0)
2155     return make_empty_result();
2156   if (arg_count == 1)
2157   {					// generate random salt
2158     time_t timestamp=current_thd->query_start();
2159     salt[0] = bin_to_ascii( (ulong) timestamp & 0x3f);
2160     salt[1] = bin_to_ascii(( (ulong) timestamp >> 5) & 0x3f);
2161     salt[2] = 0;
2162     salt_ptr=salt;
2163   }
2164   else
2165   {					// obtain salt from the first two bytes
2166     String *salt_str=args[1]->val_str(&tmp_value);
2167     if ((null_value= (args[1]->null_value || salt_str->length() < 2)))
2168       return 0;
2169     salt_ptr= salt_str->c_ptr_safe();
2170   }
2171   mysql_mutex_lock(&LOCK_crypt);
2172   char *tmp= crypt(res->c_ptr_safe(),salt_ptr);
2173   if (!tmp)
2174   {
2175     mysql_mutex_unlock(&LOCK_crypt);
2176     null_value= 1;
2177     return 0;
2178   }
2179   str->set(tmp, (uint) strlen(tmp), &my_charset_bin);
2180   str->copy();
2181   mysql_mutex_unlock(&LOCK_crypt);
2182   return str;
2183 #else
2184   null_value=1;
2185   return 0;
2186 #endif	/* HAVE_CRYPT */
2187 }
2188 
seed()2189 bool Item_func_encode::seed()
2190 {
2191   char buf[80];
2192   ulong rand_nr[2];
2193   String *key, tmp(buf, sizeof(buf), system_charset_info);
2194 
2195   if (!(key= args[1]->val_str(&tmp)))
2196     return TRUE;
2197 
2198   hash_password(rand_nr, key->ptr(), key->length());
2199   sql_crypt.init(rand_nr);
2200 
2201   return FALSE;
2202 }
2203 
fix_length_and_dec()2204 void Item_func_encode::fix_length_and_dec()
2205 {
2206   max_length=args[0]->max_length;
2207   maybe_null=args[0]->maybe_null || args[1]->maybe_null;
2208   collation.set(&my_charset_bin);
2209   /* Precompute the seed state if the item is constant. */
2210   seeded= args[1]->const_item() &&
2211           (args[1]->result_type() == STRING_RESULT) && !seed();
2212 }
2213 
val_str(String * str)2214 String *Item_func_encode::val_str(String *str)
2215 {
2216   String *res;
2217   DBUG_ASSERT(fixed == 1);
2218 
2219   if (!(res=args[0]->val_str(str)))
2220   {
2221     null_value= 1;
2222     return NULL;
2223   }
2224 
2225   if (!seeded && seed())
2226   {
2227     null_value= 1;
2228     return NULL;
2229   }
2230 
2231   null_value= 0;
2232   if (res->uses_buffer_owned_by(str))
2233   {
2234     if (tmp_value_res.copy(*res))
2235       goto null;
2236     res= &tmp_value_res;
2237   }
2238   else
2239     res= copy_if_not_alloced(str, res, res->length());
2240 
2241   crypto_transform(res);
2242   sql_crypt.reinit();
2243 
2244   return res;
2245 null:
2246   null_value= maybe_null;
2247   return 0;
2248 }
2249 
crypto_transform(String * res)2250 void Item_func_encode::crypto_transform(String *res)
2251 {
2252   sql_crypt.encode((char*) res->ptr(),res->length());
2253   res->set_charset(&my_charset_bin);
2254 }
2255 
crypto_transform(String * res)2256 void Item_func_decode::crypto_transform(String *res)
2257 {
2258   sql_crypt.decode((char*) res->ptr(),res->length());
2259 }
2260 
2261 
safe_charset_converter(const CHARSET_INFO * tocs)2262 Item *Item_func_sysconst::safe_charset_converter(const CHARSET_INFO *tocs)
2263 {
2264   Item_string *conv;
2265   uint conv_errors;
2266   String tmp, cstr, *ostr= val_str(&tmp);
2267   if (null_value)
2268   {
2269     Item *null_item= new Item_null(fully_qualified_func_name());
2270     null_item->collation.set (tocs);
2271     return null_item;
2272   }
2273   cstr.copy(ostr->ptr(), ostr->length(), ostr->charset(), tocs, &conv_errors);
2274   if (conv_errors ||
2275       !(conv= new Item_static_string_func(fully_qualified_func_name(),
2276                                           cstr.ptr(), cstr.length(),
2277                                           cstr.charset(),
2278                                           collation.derivation)))
2279   {
2280     return NULL;
2281   }
2282   conv->str_value.copy();
2283   conv->str_value.mark_as_const();
2284   return conv;
2285 }
2286 
2287 
val_str(String * str)2288 String *Item_func_database::val_str(String *str)
2289 {
2290   DBUG_ASSERT(fixed == 1);
2291   THD *thd= current_thd;
2292   if (thd->db == NULL)
2293   {
2294     null_value= 1;
2295     return 0;
2296   }
2297   else
2298     str->copy(thd->db, thd->db_length, system_charset_info);
2299   return str;
2300 }
2301 
2302 
2303 /**
2304   @note USER() is replicated correctly if binlog_format=ROW or (as of
2305   BUG#28086) binlog_format=MIXED, but is incorrectly replicated to ''
2306   if binlog_format=STATEMENT.
2307 */
init(const char * user,const char * host)2308 bool Item_func_user::init(const char *user, const char *host)
2309 {
2310   DBUG_ASSERT(fixed == 1);
2311 
2312   // For system threads (e.g. replication SQL thread) user may be empty
2313   if (user)
2314   {
2315     const CHARSET_INFO *cs= str_value.charset();
2316     size_t res_length= (strlen(user)+strlen(host)+2) * cs->mbmaxlen;
2317 
2318     if (str_value.alloc((uint) res_length))
2319     {
2320       null_value=1;
2321       return TRUE;
2322     }
2323 
2324     res_length=cs->cset->snprintf(cs, (char*)str_value.ptr(), (uint) res_length,
2325                                   "%s@%s", user, host);
2326     str_value.length((uint) res_length);
2327     str_value.mark_as_const();
2328   }
2329   return FALSE;
2330 }
2331 
2332 
fix_fields(THD * thd,Item ** ref)2333 bool Item_func_user::fix_fields(THD *thd, Item **ref)
2334 {
2335   return (Item_func_sysconst::fix_fields(thd, ref) ||
2336           init(thd->main_security_ctx.user,
2337                thd->main_security_ctx.host_or_ip));
2338 }
2339 
2340 
fix_fields(THD * thd,Item ** ref)2341 bool Item_func_current_user::fix_fields(THD *thd, Item **ref)
2342 {
2343   if (Item_func_sysconst::fix_fields(thd, ref))
2344     return TRUE;
2345 
2346   Security_context *ctx=
2347 #ifndef NO_EMBEDDED_ACCESS_CHECKS
2348                          (context->security_ctx
2349                           ? context->security_ctx : thd->security_ctx);
2350 #else
2351                          thd->security_ctx;
2352 #endif /*NO_EMBEDDED_ACCESS_CHECKS*/
2353   return init(ctx->priv_user, ctx->priv_host);
2354 }
2355 
2356 
fix_length_and_dec()2357 void Item_func_soundex::fix_length_and_dec()
2358 {
2359   uint32 char_length= args[0]->max_char_length();
2360   agg_arg_charsets_for_string_result(collation, args, 1);
2361   DBUG_ASSERT(collation.collation != NULL);
2362   set_if_bigger(char_length, 4);
2363   fix_char_length(char_length);
2364   tmp_value.set_charset(collation.collation);
2365 }
2366 
2367 
2368 /**
2369   If alpha, map input letter to soundex code.
2370   If not alpha and remove_garbage is set then skip to next char
2371   else return 0
2372 */
2373 
soundex_toupper(int ch)2374 static int soundex_toupper(int ch)
2375 {
2376   return (ch >= 'a' && ch <= 'z') ? ch - 'a' + 'A' : ch;
2377 }
2378 
2379 
get_scode(int wc)2380 static char get_scode(int wc)
2381 {
2382   int ch= soundex_toupper(wc);
2383   if (ch < 'A' || ch > 'Z')
2384   {
2385 					// Thread extended alfa (country spec)
2386     return '0';				// as vokal
2387   }
2388   return(soundex_map[ch-'A']);
2389 }
2390 
2391 
my_uni_isalpha(int wc)2392 static bool my_uni_isalpha(int wc)
2393 {
2394   /*
2395     Return true for all Basic Latin letters: a..z A..Z.
2396     Return true for all Unicode characters with code higher than U+00C0:
2397     - characters between 'z' and U+00C0 are controls and punctuations.
2398     - "U+00C0 LATIN CAPITAL LETTER A WITH GRAVE" is the first letter after 'z'.
2399   */
2400   return (wc >= 'a' && wc <= 'z') ||
2401          (wc >= 'A' && wc <= 'Z') ||
2402          (wc >= 0xC0);
2403 }
2404 
2405 
val_str(String * str)2406 String *Item_func_soundex::val_str(String *str)
2407 {
2408   DBUG_ASSERT(fixed == 1);
2409   String *res  =args[0]->val_str(str);
2410   char last_ch,ch;
2411   const CHARSET_INFO *cs= collation.collation;
2412   my_wc_t wc;
2413   uint nchars;
2414   int rc;
2415 
2416   if ((null_value= args[0]->null_value))
2417     return 0; /* purecov: inspected */
2418 
2419   if (tmp_value.alloc(max(res->length(), 4 * cs->mbminlen)))
2420     return str; /* purecov: inspected */
2421   char *to= (char *) tmp_value.ptr();
2422   char *to_end= to + tmp_value.alloced_length();
2423   char *from= (char *) res->ptr(), *end= from + res->length();
2424 
2425   for ( ; ; ) /* Skip pre-space */
2426   {
2427     if ((rc= cs->cset->mb_wc(cs, &wc, (uchar*) from, (uchar*) end)) <= 0)
2428       return make_empty_result(); /* EOL or invalid byte sequence */
2429 
2430     if (rc == 1 && cs->ctype)
2431     {
2432       /* Single byte letter found */
2433       if (my_isalpha(cs, *from))
2434       {
2435         last_ch= get_scode(*from);       // Code of the first letter
2436         *to++= soundex_toupper(*from++); // Copy first letter
2437         break;
2438       }
2439       from++;
2440     }
2441     else
2442     {
2443       from+= rc;
2444       if (my_uni_isalpha(wc))
2445       {
2446         /* Multibyte letter found */
2447         wc= soundex_toupper(wc);
2448         last_ch= get_scode(wc);     // Code of the first letter
2449         if ((rc= cs->cset->wc_mb(cs, wc, (uchar*) to, (uchar*) to_end)) <= 0)
2450         {
2451           /* Extra safety - should not really happen */
2452           DBUG_ASSERT(false);
2453           return make_empty_result();
2454         }
2455         to+= rc;
2456         break;
2457       }
2458     }
2459   }
2460 
2461   /*
2462      last_ch is now set to the first 'double-letter' check.
2463      loop on input letters until end of input
2464   */
2465   for (nchars= 1 ; ; )
2466   {
2467     if ((rc= cs->cset->mb_wc(cs, &wc, (uchar*) from, (uchar*) end)) <= 0)
2468       break; /* EOL or invalid byte sequence */
2469 
2470     if (rc == 1 && cs->ctype)
2471     {
2472       if (!my_isalpha(cs, *from++))
2473         continue;
2474     }
2475     else
2476     {
2477       from+= rc;
2478       if (!my_uni_isalpha(wc))
2479         continue;
2480     }
2481 
2482     ch= get_scode(wc);
2483     if ((ch != '0') && (ch != last_ch)) // if not skipped or double
2484     {
2485       // letter, copy to output
2486       if ((rc= cs->cset->wc_mb(cs, (my_wc_t) ch,
2487                                (uchar*) to, (uchar*) to_end)) <= 0)
2488       {
2489         // Extra safety - should not really happen
2490         DBUG_ASSERT(false);
2491         break;
2492       }
2493       to+= rc;
2494       nchars++;
2495       last_ch= ch;  // save code of last input letter
2496     }               // for next double-letter check
2497   }
2498 
2499   /* Pad up to 4 characters with DIGIT ZERO, if the string is shorter */
2500   if (nchars < 4)
2501   {
2502     uint nbytes= (4 - nchars) * cs->mbminlen;
2503     cs->cset->fill(cs, to, nbytes, '0');
2504     to+= nbytes;
2505   }
2506 
2507   tmp_value.length((uint) (to-tmp_value.ptr()));
2508   return &tmp_value;
2509 }
2510 
2511 
2512 /**
2513   Change a number to format '3,333,333,333.000'.
2514 
2515   This should be 'internationalized' sometimes.
2516 */
2517 
2518 const int FORMAT_MAX_DECIMALS= 30;
2519 
2520 
get_locale(Item * item)2521 MY_LOCALE *Item_func_format::get_locale(Item *item)
2522 {
2523   DBUG_ASSERT(arg_count == 3);
2524   String tmp, *locale_name= args[2]->val_str_ascii(&tmp);
2525   MY_LOCALE *lc;
2526   if (!locale_name ||
2527       !(lc= my_locale_by_name(locale_name->c_ptr_safe())))
2528   {
2529     push_warning_printf(current_thd, Sql_condition::WARN_LEVEL_WARN,
2530                         ER_UNKNOWN_LOCALE,
2531                         ER(ER_UNKNOWN_LOCALE),
2532                         locale_name ? locale_name->c_ptr_safe() : "NULL");
2533     lc= &my_locale_en_US;
2534   }
2535   return lc;
2536 }
2537 
fix_length_and_dec()2538 void Item_func_format::fix_length_and_dec()
2539 {
2540   uint32 char_length= args[0]->max_char_length();
2541   uint32 max_sep_count= (char_length / 3) + (decimals ? 1 : 0) + /*sign*/1;
2542   collation.set(default_charset());
2543   fix_char_length(char_length + max_sep_count + decimals);
2544   if (arg_count == 3)
2545     locale= args[2]->basic_const_item() ? get_locale(args[2]) : NULL;
2546   else
2547     locale= &my_locale_en_US; /* Two arguments */
2548 }
2549 
2550 
2551 /**
2552   @todo
2553   This needs to be fixed for multi-byte character set where numbers
2554   are stored in more than one byte
2555 */
2556 
val_str_ascii(String * str)2557 String *Item_func_format::val_str_ascii(String *str)
2558 {
2559   uint32 str_length;
2560   /* Number of decimal digits */
2561   int dec;
2562   /* Number of characters used to represent the decimals, including '.' */
2563   uint32 dec_length;
2564   MY_LOCALE *lc;
2565   DBUG_ASSERT(fixed == 1);
2566 
2567   dec= (int) args[1]->val_int();
2568   if (args[1]->null_value)
2569   {
2570     null_value=1;
2571     return NULL;
2572   }
2573 
2574   lc= locale ? locale : get_locale(args[2]);
2575 
2576   dec= set_zone(dec, 0, FORMAT_MAX_DECIMALS);
2577   dec_length= dec ? dec+1 : 0;
2578   null_value=0;
2579 
2580   if (args[0]->result_type() == DECIMAL_RESULT ||
2581       args[0]->result_type() == INT_RESULT)
2582   {
2583     my_decimal dec_val, rnd_dec, *res;
2584     res= args[0]->val_decimal(&dec_val);
2585     if ((null_value=args[0]->null_value))
2586       return 0; /* purecov: inspected */
2587     my_decimal_round(E_DEC_FATAL_ERROR, res, dec, false, &rnd_dec);
2588     my_decimal2string(E_DEC_FATAL_ERROR, &rnd_dec, 0, 0, 0, str);
2589     str_length= str->length();
2590   }
2591   else
2592   {
2593     double nr= args[0]->val_real();
2594     if ((null_value=args[0]->null_value))
2595       return 0; /* purecov: inspected */
2596     nr= my_double_round(nr, (longlong) dec, FALSE, FALSE);
2597     str->set_real(nr, dec, &my_charset_numeric);
2598     if (my_isnan(nr) || my_isinf(nr))
2599       return str;
2600     str_length=str->length();
2601   }
2602   /* We need this test to handle 'nan' and short values */
2603   if (lc->grouping[0] > 0 &&
2604       str_length >= dec_length + 1 + lc->grouping[0])
2605   {
2606     /* We need space for ',' between each group of digits as well. */
2607     char buf[2 * FLOATING_POINT_BUFFER];
2608     int count;
2609     const char *grouping= lc->grouping;
2610     char sign_length= *str->ptr() == '-' ? 1 : 0;
2611     const char *src= str->ptr() + str_length - dec_length - 1;
2612     const char *src_begin= str->ptr() + sign_length;
2613     char *dst= buf + sizeof(buf);
2614 
2615     /* Put the fractional part */
2616     if (dec)
2617     {
2618       dst-= (dec + 1);
2619       *dst= lc->decimal_point;
2620       memcpy(dst + 1, src + 2, dec);
2621     }
2622 
2623     /* Put the integer part with grouping */
2624     for (count= *grouping; src >= src_begin; count--)
2625     {
2626       /*
2627         When *grouping==0x80 (which means "end of grouping")
2628         count will be initialized to -1 and
2629         we'll never get into this "if" anymore.
2630       */
2631       if (count == 0)
2632       {
2633         *--dst= lc->thousand_sep;
2634         if (grouping[1])
2635           grouping++;
2636         count= *grouping;
2637       }
2638       DBUG_ASSERT(dst > buf);
2639       *--dst= *src--;
2640     }
2641 
2642     if (sign_length) /* Put '-' */
2643       *--dst= *str->ptr();
2644 
2645     /* Put the rest of the integer part without grouping */
2646     str->copy(dst, buf + sizeof(buf) - dst, &my_charset_latin1);
2647   }
2648   else if (dec_length && lc->decimal_point != '.')
2649   {
2650     /*
2651       For short values without thousands (<1000)
2652       replace decimal point to localized value.
2653     */
2654     DBUG_ASSERT(dec_length <= str_length);
2655     ((char*) str->ptr())[str_length - dec_length]= lc->decimal_point;
2656   }
2657   return str;
2658 }
2659 
2660 
print(String * str,enum_query_type query_type)2661 void Item_func_format::print(String *str, enum_query_type query_type)
2662 {
2663   str->append(STRING_WITH_LEN("format("));
2664   args[0]->print(str, query_type);
2665   str->append(',');
2666   args[1]->print(str, query_type);
2667   if(arg_count > 2)
2668   {
2669     str->append(',');
2670     args[2]->print(str,query_type);
2671   }
2672   str->append(')');
2673 }
2674 
fix_length_and_dec()2675 void Item_func_elt::fix_length_and_dec()
2676 {
2677   uint32 char_length= 0;
2678   decimals=0;
2679 
2680   if (agg_arg_charsets_for_string_result(collation, args + 1, arg_count - 1))
2681     return;
2682 
2683   for (uint i= 1 ; i < arg_count ; i++)
2684   {
2685     set_if_bigger(char_length, args[i]->max_char_length());
2686     set_if_bigger(decimals,args[i]->decimals);
2687   }
2688   fix_char_length(char_length);
2689   maybe_null=1;					// NULL if wrong first arg
2690 }
2691 
2692 
val_real()2693 double Item_func_elt::val_real()
2694 {
2695   DBUG_ASSERT(fixed == 1);
2696   uint tmp;
2697   null_value=1;
2698   if ((tmp=(uint) args[0]->val_int()) == 0 || tmp >= arg_count)
2699     return 0.0;
2700   double result= args[tmp]->val_real();
2701   null_value= args[tmp]->null_value;
2702   return result;
2703 }
2704 
2705 
val_int()2706 longlong Item_func_elt::val_int()
2707 {
2708   DBUG_ASSERT(fixed == 1);
2709   uint tmp;
2710   null_value=1;
2711   if ((tmp=(uint) args[0]->val_int()) == 0 || tmp >= arg_count)
2712     return 0;
2713 
2714   longlong result= args[tmp]->val_int();
2715   null_value= args[tmp]->null_value;
2716   return result;
2717 }
2718 
2719 
val_str(String * str)2720 String *Item_func_elt::val_str(String *str)
2721 {
2722   DBUG_ASSERT(fixed == 1);
2723   uint tmp;
2724   null_value=1;
2725   if ((tmp=(uint) args[0]->val_int()) == 0 || tmp >= arg_count)
2726     return NULL;
2727 
2728   String *result= args[tmp]->val_str(str);
2729   if (result)
2730     result->set_charset(collation.collation);
2731   null_value= args[tmp]->null_value;
2732   return result;
2733 }
2734 
2735 
split_sum_func(THD * thd,Ref_ptr_array ref_pointer_array,List<Item> & fields)2736 void Item_func_make_set::split_sum_func(THD *thd,
2737                                         Ref_ptr_array ref_pointer_array,
2738 					List<Item> &fields)
2739 {
2740   item->split_sum_func2(thd, ref_pointer_array, fields, &item, TRUE);
2741   Item_str_func::split_sum_func(thd, ref_pointer_array, fields);
2742 }
2743 
2744 
fix_length_and_dec()2745 void Item_func_make_set::fix_length_and_dec()
2746 {
2747   uint32 char_length= arg_count - 1; /* Separators */
2748 
2749   if (agg_arg_charsets_for_string_result(collation, args, arg_count))
2750     return;
2751 
2752   for (uint i=0 ; i < arg_count ; i++)
2753     char_length+= args[i]->max_char_length();
2754   fix_char_length(char_length);
2755   used_tables_cache|=	  item->used_tables();
2756   not_null_tables_cache&= item->not_null_tables();
2757   const_item_cache&=	  item->const_item();
2758   with_sum_func= with_sum_func || item->with_sum_func;
2759 }
2760 
2761 
update_used_tables()2762 void Item_func_make_set::update_used_tables()
2763 {
2764   Item_func::update_used_tables();
2765   item->update_used_tables();
2766   used_tables_cache|=item->used_tables();
2767   const_item_cache&=item->const_item();
2768   with_subselect|= item->has_subquery();
2769   with_stored_program|= item->has_stored_program();
2770 }
2771 
2772 
val_str(String * str)2773 String *Item_func_make_set::val_str(String *str)
2774 {
2775   DBUG_ASSERT(fixed == 1);
2776   ulonglong bits;
2777   bool first_found=0;
2778   Item **ptr=args;
2779   String *result= NULL;
2780 
2781   bits=item->val_int();
2782   if ((null_value=item->null_value))
2783     return NULL;
2784 
2785   if (arg_count < 64)
2786     bits &= ((ulonglong) 1 << arg_count)-1;
2787 
2788   for (; bits; bits >>= 1, ptr++)
2789   {
2790     if (bits & 1)
2791     {
2792       String *res= (*ptr)->val_str(str);
2793       if (res)					// Skip nulls
2794       {
2795 	if (!first_found)
2796 	{					// First argument
2797 	  first_found=1;
2798 	  if (res != str)
2799 	    result=res;				// Use original string
2800 	  else
2801 	  {
2802 	    if (tmp_str.copy(*res))		// Don't use 'str'
2803               return make_empty_result();
2804 	    result= &tmp_str;
2805 	  }
2806 	}
2807 	else
2808 	{
2809 	  if (result != &tmp_str)
2810 	  {					// Copy data to tmp_str
2811             if (tmp_str.alloc((result != NULL ? result->length() : 0) +
2812                               res->length() + 1) ||
2813 		tmp_str.copy(*result))
2814               return make_empty_result();
2815 	    result= &tmp_str;
2816 	  }
2817 	  if (tmp_str.append(STRING_WITH_LEN(","), &my_charset_bin) ||
2818               tmp_str.append(*res))
2819             return make_empty_result();
2820 	}
2821       }
2822     }
2823   }
2824   if (result == NULL)
2825     return make_empty_result();
2826   return result;
2827 }
2828 
2829 
transform(Item_transformer transformer,uchar * arg)2830 Item *Item_func_make_set::transform(Item_transformer transformer, uchar *arg)
2831 {
2832   DBUG_ASSERT(!current_thd->stmt_arena->is_stmt_prepare());
2833 
2834   Item *new_item= item->transform(transformer, arg);
2835   if (!new_item)
2836     return 0;
2837 
2838   /*
2839     THD::change_item_tree() should be called only if the tree was
2840     really transformed, i.e. when a new item has been created.
2841     Otherwise we'll be allocating a lot of unnecessary memory for
2842     change records at each execution.
2843   */
2844   if (item != new_item)
2845     current_thd->change_item_tree(&item, new_item);
2846   return Item_str_func::transform(transformer, arg);
2847 }
2848 
2849 
print(String * str,enum_query_type query_type)2850 void Item_func_make_set::print(String *str, enum_query_type query_type)
2851 {
2852   str->append(STRING_WITH_LEN("make_set("));
2853   item->print(str, query_type);
2854   if (arg_count)
2855   {
2856     str->append(',');
2857     print_args(str, 0, query_type);
2858   }
2859   str->append(')');
2860 }
2861 
2862 
val_str(String * str)2863 String *Item_func_char::val_str(String *str)
2864 {
2865   DBUG_ASSERT(fixed == 1);
2866   str->length(0);
2867   str->set_charset(collation.collation);
2868   for (uint i=0 ; i < arg_count ; i++)
2869   {
2870     int32 num=(int32) args[i]->val_int();
2871     if (!args[i]->null_value)
2872     {
2873       char tmp[4];
2874       if (num & 0xFF000000L)
2875       {
2876         mi_int4store(tmp, num);
2877         str->append(tmp, 4, &my_charset_bin);
2878       }
2879       else if (num & 0xFF0000L)
2880       {
2881         mi_int3store(tmp, num);
2882         str->append(tmp, 3, &my_charset_bin);
2883       }
2884       else if (num & 0xFF00L)
2885       {
2886         mi_int2store(tmp, num);
2887         str->append(tmp, 2, &my_charset_bin);
2888       }
2889       else
2890       {
2891         tmp[0]= (char) num;
2892         str->append(tmp, 1, &my_charset_bin);
2893       }
2894     }
2895   }
2896   str->realloc(str->length());			// Add end 0 (for Purify)
2897   return check_well_formed_result(str,
2898                                   false,  // send warning
2899                                   true);  // truncate
2900 }
2901 
2902 
alloc_buffer(String * res,String * str,String * tmp_value,ulong length)2903 inline String* alloc_buffer(String *res,String *str,String *tmp_value,
2904 			    ulong length)
2905 {
2906   if (res->alloced_length() < length)
2907   {
2908     if (str->alloced_length() >= length)
2909     {
2910       (void) str->copy(*res);
2911       str->length(length);
2912       return str;
2913     }
2914     if (tmp_value->alloc(length))
2915       return 0;
2916     (void) tmp_value->copy(*res);
2917     tmp_value->length(length);
2918     return tmp_value;
2919   }
2920   res->length(length);
2921   return res;
2922 }
2923 
2924 
fix_length_and_dec()2925 void Item_func_repeat::fix_length_and_dec()
2926 {
2927   agg_arg_charsets_for_string_result(collation, args, 1);
2928   DBUG_ASSERT(collation.collation != NULL);
2929   if (args[1]->const_item())
2930   {
2931     /* must be longlong to avoid truncation */
2932     longlong count= args[1]->val_int();
2933     if (args[1]->null_value)
2934       goto end;
2935 
2936     /* Assumes that the maximum length of a String is < INT_MAX32. */
2937     /* Set here so that rest of code sees out-of-bound value as such. */
2938     if (count > INT_MAX32)
2939       count= INT_MAX32;
2940 
2941     ulonglong char_length= (ulonglong) args[0]->max_char_length() * count;
2942     fix_char_length_ulonglong(char_length);
2943     return;
2944   }
2945 
2946 end:
2947   max_length= MAX_BLOB_WIDTH;
2948   maybe_null= 1;
2949 }
2950 
2951 /**
2952   Item_func_repeat::str is carefully written to avoid reallocs
2953   as much as possible at the cost of a local buffer
2954 */
2955 
val_str(String * str)2956 String *Item_func_repeat::val_str(String *str)
2957 {
2958   DBUG_ASSERT(fixed == 1);
2959   uint length,tot_length;
2960   char *to;
2961   /* must be longlong to avoid truncation */
2962   longlong count= args[1]->val_int();
2963   String *res= args[0]->val_str(str);
2964 
2965   if (args[0]->null_value || args[1]->null_value)
2966     goto err;				// string and/or delim are null
2967   null_value= 0;
2968 
2969   if (count <= 0 && (count == 0 || !args[1]->unsigned_flag))
2970     return make_empty_result();
2971 
2972   /* Assumes that the maximum length of a String is < INT_MAX32. */
2973   /* Bounds check on count:  If this is triggered, we will error. */
2974   if ((ulonglong) count > INT_MAX32)
2975     count= INT_MAX32;
2976   if (count == 1)			// To avoid reallocs
2977     return res;
2978   length=res->length();
2979   // Safe length check
2980   if (length > current_thd->variables.max_allowed_packet / (uint) count)
2981   {
2982     push_warning_printf(current_thd, Sql_condition::WARN_LEVEL_WARN,
2983 			ER_WARN_ALLOWED_PACKET_OVERFLOWED,
2984 			ER(ER_WARN_ALLOWED_PACKET_OVERFLOWED),
2985 			func_name(), current_thd->variables.max_allowed_packet);
2986     goto err;
2987   }
2988   tot_length= length*(uint) count;
2989   if (!(res= alloc_buffer(res,str,&tmp_value,tot_length)))
2990     goto err;
2991 
2992   to=(char*) res->ptr()+length;
2993   while (--count)
2994   {
2995     memcpy(to,res->ptr(),length);
2996     to+=length;
2997   }
2998   return (res);
2999 
3000 err:
3001   null_value=1;
3002   return 0;
3003 }
3004 
3005 
3006 
fix_length_and_dec()3007 void Item_func_space::fix_length_and_dec()
3008 {
3009   collation.set(default_charset(), DERIVATION_COERCIBLE, MY_REPERTOIRE_ASCII);
3010   if (args[0]->const_item())
3011   {
3012     /* must be longlong to avoid truncation */
3013     longlong count= args[0]->val_int();
3014     if (args[0]->null_value)
3015       goto end;
3016     /*
3017      Assumes that the maximum length of a String is < INT_MAX32.
3018      Set here so that rest of code sees out-of-bound value as such.
3019     */
3020     if (count > INT_MAX32)
3021       count= INT_MAX32;
3022     fix_char_length_ulonglong(count);
3023     return;
3024   }
3025 
3026 end:
3027   max_length= MAX_BLOB_WIDTH;
3028   maybe_null= 1;
3029 }
3030 
3031 
val_str(String * str)3032 String *Item_func_space::val_str(String *str)
3033 {
3034   uint tot_length;
3035   longlong count= args[0]->val_int();
3036   const CHARSET_INFO *cs= collation.collation;
3037 
3038   if (args[0]->null_value)
3039     goto err;				// string and/or delim are null
3040   null_value= 0;
3041 
3042   if (count <= 0 && (count == 0 || !args[0]->unsigned_flag))
3043     return make_empty_result();
3044   /*
3045    Assumes that the maximum length of a String is < INT_MAX32.
3046    Bounds check on count:  If this is triggered, we will error.
3047   */
3048   if ((ulonglong) count > INT_MAX32)
3049     count= INT_MAX32;
3050 
3051   // Safe length check
3052   tot_length= (uint) count * cs->mbminlen;
3053   if (tot_length > current_thd->variables.max_allowed_packet)
3054   {
3055     push_warning_printf(current_thd, Sql_condition::WARN_LEVEL_WARN,
3056                         ER_WARN_ALLOWED_PACKET_OVERFLOWED,
3057                         ER(ER_WARN_ALLOWED_PACKET_OVERFLOWED),
3058                         func_name(),
3059                         current_thd->variables.max_allowed_packet);
3060     goto err;
3061    }
3062 
3063   if (str->alloc(tot_length))
3064     goto err;
3065   str->length(tot_length);
3066   str->set_charset(cs);
3067   cs->cset->fill(cs, (char*) str->ptr(), tot_length, ' ');
3068   return str;
3069 
3070 err:
3071   null_value= 1;
3072   return 0;
3073 }
3074 
3075 
fix_length_and_dec()3076 void Item_func_rpad::fix_length_and_dec()
3077 {
3078   // Handle character set for args[0] and args[2].
3079   if (agg_arg_charsets_for_string_result(collation, &args[0], 2, 2))
3080     return;
3081   if (args[1]->const_item())
3082   {
3083     ulonglong char_length= (ulonglong) args[1]->val_int();
3084     if (args[1]->null_value)
3085       goto end;
3086     DBUG_ASSERT(collation.collation->mbmaxlen > 0);
3087     /* Assumes that the maximum length of a String is < INT_MAX32. */
3088     /* Set here so that rest of code sees out-of-bound value as such. */
3089     if (char_length > INT_MAX32)
3090       char_length= INT_MAX32;
3091     fix_char_length_ulonglong(char_length);
3092     return;
3093   }
3094 
3095 end:
3096   max_length= MAX_BLOB_WIDTH;
3097   maybe_null= 1;
3098 }
3099 
3100 
val_str(String * str)3101 String *Item_func_rpad::val_str(String *str)
3102 {
3103   DBUG_ASSERT(fixed == 1);
3104   uint32 res_byte_length,res_char_length,pad_char_length,pad_byte_length;
3105   char *to;
3106   const char *ptr_pad;
3107   /* must be longlong to avoid truncation */
3108   longlong count= args[1]->val_int();
3109   longlong byte_count;
3110   String *res= args[0]->val_str(str);
3111   String *rpad= args[2]->val_str(&rpad_str);
3112 
3113   if (!res || args[1]->null_value || !rpad ||
3114       ((count < 0) && !args[1]->unsigned_flag))
3115     goto err;
3116   null_value=0;
3117   /* Assumes that the maximum length of a String is < INT_MAX32. */
3118   /* Set here so that rest of code sees out-of-bound value as such. */
3119   if ((ulonglong) count > INT_MAX32)
3120     count= INT_MAX32;
3121   /*
3122     There is one exception not handled (intentionaly) by the character set
3123     aggregation code. If one string is strong side and is binary, and
3124     another one is weak side and is a multi-byte character string,
3125     then we need to operate on the second string in terms on bytes when
3126     calling ::numchars() and ::charpos(), rather than in terms of characters.
3127     Lets substitute its character set to binary.
3128   */
3129   if (collation.collation == &my_charset_bin)
3130   {
3131     res->set_charset(&my_charset_bin);
3132     rpad->set_charset(&my_charset_bin);
3133   }
3134 
3135 #ifdef USE_MB
3136   if (use_mb(rpad->charset()))
3137   {
3138     // This will chop off any trailing illegal characters from rpad.
3139     String *well_formed_pad= args[2]->check_well_formed_result(rpad,
3140                                                                false, //send warning
3141                                                                true); //truncate
3142     if (!well_formed_pad)
3143       goto err;
3144   }
3145 #endif
3146 
3147   if (count <= (res_char_length= res->numchars()))
3148   {						// String to pad is big enough
3149     res->length(res->charpos((int) count));	// Shorten result if longer
3150     return (res);
3151   }
3152   pad_char_length= rpad->numchars();
3153 
3154   byte_count= count * collation.collation->mbmaxlen;
3155   if ((ulonglong) byte_count > current_thd->variables.max_allowed_packet)
3156   {
3157     push_warning_printf(current_thd, Sql_condition::WARN_LEVEL_WARN,
3158 			ER_WARN_ALLOWED_PACKET_OVERFLOWED,
3159 			ER(ER_WARN_ALLOWED_PACKET_OVERFLOWED),
3160 			func_name(), current_thd->variables.max_allowed_packet);
3161     goto err;
3162   }
3163   if (args[2]->null_value || !pad_char_length)
3164     goto err;
3165   res_byte_length= res->length();	/* Must be done before alloc_buffer */
3166   if (!(res= alloc_buffer(res,str,&tmp_value, (ulong) byte_count)))
3167     goto err;
3168 
3169   to= (char*) res->ptr()+res_byte_length;
3170   ptr_pad=rpad->ptr();
3171   pad_byte_length= rpad->length();
3172   count-= res_char_length;
3173   for ( ; (uint32) count > pad_char_length; count-= pad_char_length)
3174   {
3175     memcpy(to,ptr_pad,pad_byte_length);
3176     to+= pad_byte_length;
3177   }
3178   if (count)
3179   {
3180     pad_byte_length= rpad->charpos((int) count);
3181     memcpy(to,ptr_pad,(size_t) pad_byte_length);
3182     to+= pad_byte_length;
3183   }
3184   res->length((uint) (to- (char*) res->ptr()));
3185   return (res);
3186 
3187  err:
3188   null_value=1;
3189   return 0;
3190 }
3191 
3192 
fix_length_and_dec()3193 void Item_func_lpad::fix_length_and_dec()
3194 {
3195   // Handle character set for args[0] and args[2].
3196   if (agg_arg_charsets_for_string_result(collation, &args[0], 2, 2))
3197     return;
3198 
3199   if (args[1]->const_item())
3200   {
3201     ulonglong char_length= (ulonglong) args[1]->val_int();
3202     if (args[1]->null_value)
3203       goto end;
3204     DBUG_ASSERT(collation.collation->mbmaxlen > 0);
3205     /* Assumes that the maximum length of a String is < INT_MAX32. */
3206     /* Set here so that rest of code sees out-of-bound value as such. */
3207     if (char_length > INT_MAX32)
3208       char_length= INT_MAX32;
3209     fix_char_length_ulonglong(char_length);
3210     return;
3211   }
3212 
3213 end:
3214   max_length= MAX_BLOB_WIDTH;
3215   maybe_null= 1;
3216 }
3217 
3218 
val_str(String * str)3219 String *Item_func_lpad::val_str(String *str)
3220 {
3221   DBUG_ASSERT(fixed == 1);
3222   uint32 res_char_length,pad_char_length;
3223   /* must be longlong to avoid truncation */
3224   longlong count= args[1]->val_int();
3225   longlong byte_count;
3226   String *res= args[0]->val_str(&tmp_value);
3227   String *pad= args[2]->val_str(&lpad_str);
3228 
3229   if (!res || args[1]->null_value || !pad ||
3230       ((count < 0) && !args[1]->unsigned_flag))
3231     goto err;
3232   null_value=0;
3233   /* Assumes that the maximum length of a String is < INT_MAX32. */
3234   /* Set here so that rest of code sees out-of-bound value as such. */
3235   if ((ulonglong) count > INT_MAX32)
3236     count= INT_MAX32;
3237 
3238   /*
3239     There is one exception not handled (intentionaly) by the character set
3240     aggregation code. If one string is strong side and is binary, and
3241     another one is weak side and is a multi-byte character string,
3242     then we need to operate on the second string in terms on bytes when
3243     calling ::numchars() and ::charpos(), rather than in terms of characters.
3244     Lets substitute its character set to binary.
3245   */
3246   if (collation.collation == &my_charset_bin)
3247   {
3248     res->set_charset(&my_charset_bin);
3249     pad->set_charset(&my_charset_bin);
3250   }
3251 
3252 #ifdef USE_MB
3253   if (use_mb(pad->charset()))
3254   {
3255     // This will chop off any trailing illegal characters from pad.
3256     String *well_formed_pad= args[2]->check_well_formed_result(pad,
3257                                                                false, // send warning
3258                                                                true); // truncate
3259     if (!well_formed_pad)
3260       goto err;
3261   }
3262 #endif
3263 
3264   res_char_length= res->numchars();
3265 
3266   if (count <= res_char_length)
3267   {
3268     res->length(res->charpos((int) count));
3269     return res;
3270   }
3271 
3272   pad_char_length= pad->numchars();
3273   byte_count= count * collation.collation->mbmaxlen;
3274 
3275   if ((ulonglong) byte_count > current_thd->variables.max_allowed_packet)
3276   {
3277     push_warning_printf(current_thd, Sql_condition::WARN_LEVEL_WARN,
3278 			ER_WARN_ALLOWED_PACKET_OVERFLOWED,
3279 			ER(ER_WARN_ALLOWED_PACKET_OVERFLOWED),
3280 			func_name(), current_thd->variables.max_allowed_packet);
3281     goto err;
3282   }
3283 
3284   if (args[2]->null_value || !pad_char_length ||
3285       str->alloc((uint32) byte_count))
3286     goto err;
3287 
3288   str->length(0);
3289   str->set_charset(collation.collation);
3290   count-= res_char_length;
3291   while (count >= pad_char_length)
3292   {
3293     str->append(*pad);
3294     count-= pad_char_length;
3295   }
3296   if (count > 0)
3297     str->append(pad->ptr(), pad->charpos((int) count), collation.collation);
3298 
3299   str->append(*res);
3300   null_value= 0;
3301   return str;
3302 
3303 err:
3304   null_value= 1;
3305   return 0;
3306 }
3307 
3308 
val_str(String * str)3309 String *Item_func_conv::val_str(String *str)
3310 {
3311   DBUG_ASSERT(fixed == 1);
3312   String *res= args[0]->val_str(str);
3313   char *endptr,ans[65],*ptr;
3314   longlong dec;
3315   int from_base= (int) args[1]->val_int();
3316   int to_base= (int) args[2]->val_int();
3317   int err;
3318 
3319   // Note that abs(INT_MIN) is undefined.
3320   if (args[0]->null_value || args[1]->null_value || args[2]->null_value ||
3321       from_base == INT_MIN || to_base == INT_MIN ||
3322       abs(to_base) > 36 || abs(to_base) < 2 ||
3323       abs(from_base) > 36 || abs(from_base) < 2 || !(res->length()))
3324   {
3325     null_value= 1;
3326     return NULL;
3327   }
3328   null_value= 0;
3329   unsigned_flag= !(from_base < 0);
3330 
3331   if (args[0]->field_type() == MYSQL_TYPE_BIT)
3332   {
3333     /*
3334      Special case: The string representation of BIT doesn't resemble the
3335      decimal representation, so we shouldn't change it to string and then to
3336      decimal.
3337     */
3338     dec= args[0]->val_int();
3339   }
3340   else
3341   {
3342     if (from_base < 0)
3343       dec= my_strntoll(res->charset(), res->ptr(), res->length(),
3344                        -from_base, &endptr, &err);
3345     else
3346       dec= (longlong) my_strntoull(res->charset(), res->ptr(), res->length(),
3347                                    from_base, &endptr, &err);
3348   }
3349 
3350   if (!(ptr= longlong2str(dec, ans, to_base)) ||
3351       str->copy(ans, (uint32) (ptr - ans), default_charset()))
3352   {
3353     null_value= 1;
3354     return NULL;
3355   }
3356   return str;
3357 }
3358 
3359 
val_str(String * str)3360 String *Item_func_conv_charset::val_str(String *str)
3361 {
3362   DBUG_ASSERT(fixed == 1);
3363   if (use_cached_value)
3364     return null_value ? 0 : &str_value;
3365   String *arg= args[0]->val_str(str);
3366   uint dummy_errors;
3367   if (!arg)
3368   {
3369     null_value=1;
3370     return 0;
3371   }
3372   null_value= tmp_value.copy(arg->ptr(), arg->length(), arg->charset(),
3373                              conv_charset, &dummy_errors);
3374   return null_value ? 0 : check_well_formed_result(&tmp_value,
3375                                                    false, // send warning
3376                                                    true); // truncate
3377 }
3378 
fix_length_and_dec()3379 void Item_func_conv_charset::fix_length_and_dec()
3380 {
3381   collation.set(conv_charset, DERIVATION_IMPLICIT);
3382   fix_char_length(args[0]->max_char_length());
3383 }
3384 
print(String * str,enum_query_type query_type)3385 void Item_func_conv_charset::print(String *str, enum_query_type query_type)
3386 {
3387   str->append(STRING_WITH_LEN("convert("));
3388   args[0]->print(str, query_type);
3389   str->append(STRING_WITH_LEN(" using "));
3390   str->append(conv_charset->csname);
3391   str->append(')');
3392 }
3393 
val_str(String * str)3394 String *Item_func_set_collation::val_str(String *str)
3395 {
3396   DBUG_ASSERT(fixed == 1);
3397   str=args[0]->val_str(str);
3398   if ((null_value=args[0]->null_value))
3399     return 0;
3400   str->set_charset(collation.collation);
3401   return str;
3402 }
3403 
fix_length_and_dec()3404 void Item_func_set_collation::fix_length_and_dec()
3405 {
3406   CHARSET_INFO *set_collation;
3407   const char *colname;
3408   String tmp, *str= args[1]->val_str(&tmp);
3409   colname= str->c_ptr();
3410   if (colname == binary_keyword)
3411     set_collation= get_charset_by_csname(args[0]->collation.collation->csname,
3412 					 MY_CS_BINSORT,MYF(0));
3413   else
3414   {
3415     if (!(set_collation= mysqld_collation_get_by_name(colname)))
3416       return;
3417   }
3418 
3419   if (!set_collation ||
3420       !my_charset_same(args[0]->collation.collation,set_collation))
3421   {
3422     my_error(ER_COLLATION_CHARSET_MISMATCH, MYF(0),
3423              colname, args[0]->collation.collation->csname);
3424     return;
3425   }
3426   collation.set(set_collation, DERIVATION_EXPLICIT,
3427                 args[0]->collation.repertoire);
3428   max_length= args[0]->max_length;
3429 }
3430 
3431 
eq(const Item * item,bool binary_cmp) const3432 bool Item_func_set_collation::eq(const Item *item, bool binary_cmp) const
3433 {
3434   /* Assume we don't have rtti */
3435   if (this == item)
3436     return 1;
3437   if (item->type() != FUNC_ITEM)
3438     return 0;
3439   Item_func *item_func=(Item_func*) item;
3440   if (arg_count != item_func->arg_count ||
3441       functype() != item_func->functype())
3442     return 0;
3443   Item_func_set_collation *item_func_sc=(Item_func_set_collation*) item;
3444   if (collation.collation != item_func_sc->collation.collation)
3445     return 0;
3446   for (uint i=0; i < arg_count ; i++)
3447     if (!args[i]->eq(item_func_sc->args[i], binary_cmp))
3448       return 0;
3449   return 1;
3450 }
3451 
3452 
print(String * str,enum_query_type query_type)3453 void Item_func_set_collation::print(String *str, enum_query_type query_type)
3454 {
3455   str->append('(');
3456   args[0]->print(str, query_type);
3457   str->append(STRING_WITH_LEN(" collate "));
3458   DBUG_ASSERT(args[1]->basic_const_item() &&
3459               args[1]->type() == Item::STRING_ITEM);
3460   args[1]->str_value.print(str);
3461   str->append(')');
3462 }
3463 
val_str(String * str)3464 String *Item_func_charset::val_str(String *str)
3465 {
3466   DBUG_ASSERT(fixed == 1);
3467   uint dummy_errors;
3468 
3469   const CHARSET_INFO *cs= args[0]->charset_for_protocol();
3470   null_value= 0;
3471   str->copy(cs->csname, (uint) strlen(cs->csname),
3472 	    &my_charset_latin1, collation.collation, &dummy_errors);
3473   return str;
3474 }
3475 
val_str(String * str)3476 String *Item_func_collation::val_str(String *str)
3477 {
3478   DBUG_ASSERT(fixed == 1);
3479   uint dummy_errors;
3480   const CHARSET_INFO *cs= args[0]->charset_for_protocol();
3481 
3482   null_value= 0;
3483   str->copy(cs->name, (uint) strlen(cs->name),
3484 	    &my_charset_latin1, collation.collation, &dummy_errors);
3485   return str;
3486 }
3487 
3488 
fix_length_and_dec()3489 void Item_func_weight_string::fix_length_and_dec()
3490 {
3491   const CHARSET_INFO *cs= args[0]->collation.collation;
3492   collation.set(&my_charset_bin, args[0]->collation.derivation);
3493   flags= my_strxfrm_flag_normalize(flags, cs->levels_for_order);
3494   field= args[0]->type() == FIELD_ITEM && args[0]->is_temporal() ?
3495          ((Item_field *) (args[0]))->field : (Field *) NULL;
3496   /*
3497     Use result_length if it was given explicitly in constructor,
3498     otherwise calculate max_length using argument's max_length
3499     and "nweights".
3500   */
3501   max_length= field ? field->pack_length() :
3502               result_length ? result_length :
3503               cs->mbmaxlen * max(args[0]->max_length, nweights);
3504   maybe_null= 1;
3505 }
3506 
3507 
3508 /* Return a weight_string according to collation */
val_str(String * str)3509 String *Item_func_weight_string::val_str(String *str)
3510 {
3511   String *res;
3512   const CHARSET_INFO *cs= args[0]->collation.collation;
3513   uint tmp_length, frm_length;
3514   DBUG_ASSERT(fixed == 1);
3515 
3516   if (args[0]->result_type() != STRING_RESULT ||
3517       !(res= args[0]->val_str(str)))
3518     goto nl;
3519 
3520   /*
3521     Use result_length if it was given in constructor
3522     explicitly, otherwise calculate result length
3523     from argument and "nweights".
3524   */
3525   tmp_length= field ? field->pack_length() :
3526               result_length ? result_length :
3527               cs->coll->strnxfrmlen(cs, cs->mbmaxlen *
3528                                     max(res->length(), nweights));
3529 
3530   if(tmp_length > current_thd->variables.max_allowed_packet)
3531   {
3532     push_warning_printf(current_thd, Sql_condition::WARN_LEVEL_WARN,
3533                         ER_WARN_ALLOWED_PACKET_OVERFLOWED,
3534                         ER(ER_WARN_ALLOWED_PACKET_OVERFLOWED), func_name(),
3535                         current_thd->variables.max_allowed_packet);
3536     goto nl;
3537   }
3538 
3539   if (tmp_value.alloc(tmp_length))
3540     goto nl;
3541 
3542   if (field)
3543   {
3544     frm_length= field->pack_length();
3545     field->make_sort_key((uchar *) tmp_value.ptr(), tmp_length);
3546   }
3547   else
3548     frm_length= cs->coll->strnxfrm(cs,
3549                                    (uchar *) tmp_value.ptr(), tmp_length,
3550                                    nweights ? nweights : tmp_length,
3551                                    (const uchar *) res->ptr(), res->length(),
3552                                    flags);
3553   DBUG_ASSERT(frm_length <= tmp_length);
3554 
3555   tmp_value.length(frm_length);
3556   null_value= 0;
3557   return &tmp_value;
3558 
3559 nl:
3560   null_value= 1;
3561   return 0;
3562 }
3563 
3564 
val_str_ascii(String * str)3565 String *Item_func_hex::val_str_ascii(String *str)
3566 {
3567   String *res;
3568   DBUG_ASSERT(fixed == 1);
3569   if (args[0]->result_type() != STRING_RESULT)
3570   {
3571     ulonglong dec;
3572     char ans[65],*ptr;
3573     /* Return hex of unsigned longlong value */
3574     if (args[0]->result_type() == REAL_RESULT ||
3575         args[0]->result_type() == DECIMAL_RESULT)
3576     {
3577       double val= args[0]->val_real();
3578       if ((val <= (double) LONGLONG_MIN) ||
3579           (val >= (double) (ulonglong) ULONGLONG_MAX))
3580         dec=  ~(longlong) 0;
3581       else
3582         dec= (ulonglong) (val + (val > 0 ? 0.5 : -0.5));
3583     }
3584     else
3585       dec= (ulonglong) args[0]->val_int();
3586 
3587     if ((null_value= args[0]->null_value))
3588       return 0;
3589 
3590     if (!(ptr= longlong2str(dec, ans, 16)) ||
3591         str->copy(ans,(uint32) (ptr - ans),
3592         &my_charset_numeric))
3593       return make_empty_result();		// End of memory
3594     return str;
3595   }
3596 
3597   /* Convert given string to a hex string, character by character */
3598   res= args[0]->val_str(str);
3599   if (!res || tmp_value.alloc(res->length()*2+1))
3600   {
3601     null_value=1;
3602     return 0;
3603   }
3604   null_value=0;
3605   tmp_value.length(res->length()*2);
3606   tmp_value.set_charset(&my_charset_latin1);
3607 
3608   octet2hex((char*) tmp_value.ptr(), res->ptr(), res->length());
3609   return &tmp_value;
3610 }
3611 
3612   /** Convert given hex string to a binary string. */
3613 
val_str(String * str)3614 String *Item_func_unhex::val_str(String *str)
3615 {
3616   const char *from, *end;
3617   char *to;
3618   String *res;
3619   uint length;
3620   DBUG_ASSERT(fixed == 1);
3621 
3622   res= args[0]->val_str(str);
3623   if (!res || tmp_value.alloc(length= (1+res->length())/2))
3624   {
3625     null_value=1;
3626     return 0;
3627   }
3628 
3629   from= res->ptr();
3630   null_value= 0;
3631   tmp_value.length(length);
3632   to= (char*) tmp_value.ptr();
3633   if (res->length() % 2)
3634   {
3635     int hex_char;
3636     *to++= hex_char= hexchar_to_int(*from++);
3637     if ((null_value= (hex_char == -1)))
3638       return 0;
3639   }
3640   for (end=res->ptr()+res->length(); from < end ; from+=2, to++)
3641   {
3642     int hex_char;
3643     *to= (hex_char= hexchar_to_int(from[0])) << 4;
3644     if ((null_value= (hex_char == -1)))
3645       return 0;
3646     *to|= hex_char= hexchar_to_int(from[1]);
3647     if ((null_value= (hex_char == -1)))
3648       return 0;
3649   }
3650   return &tmp_value;
3651 }
3652 
3653 
3654 #ifndef DBUG_OFF
val_str(String * str)3655 String *Item_func_like_range::val_str(String *str)
3656 {
3657   DBUG_ASSERT(fixed == 1);
3658   longlong nbytes= args[1]->val_int();
3659   String *res= args[0]->val_str(str);
3660   size_t min_len, max_len;
3661   const CHARSET_INFO *cs= collation.collation;
3662 
3663   if (!res || args[0]->null_value || args[1]->null_value ||
3664       nbytes < 0 || nbytes > MAX_BLOB_WIDTH ||
3665       min_str.alloc(nbytes) || max_str.alloc(nbytes))
3666     goto err;
3667   null_value=0;
3668 
3669   if (cs->coll->like_range(cs, res->ptr(), res->length(),
3670                            '\\', '_', '%', nbytes,
3671                            (char*) min_str.ptr(), (char*) max_str.ptr(),
3672                            &min_len, &max_len))
3673     goto err;
3674 
3675   min_str.set_charset(collation.collation);
3676   max_str.set_charset(collation.collation);
3677   min_str.length(min_len);
3678   max_str.length(max_len);
3679 
3680   return is_min ? &min_str : &max_str;
3681 
3682 err:
3683   null_value= 1;
3684   return 0;
3685 }
3686 #endif
3687 
3688 
eq(const Item * item,bool binary_cmp) const3689 bool Item_char_typecast::eq(const Item *item, bool binary_cmp) const
3690 {
3691   if (this == item)
3692     return 1;
3693   if (item->type() != FUNC_ITEM ||
3694       functype() != ((Item_func*)item)->functype())
3695     return 0;
3696 
3697   Item_char_typecast *cast= (Item_char_typecast*)item;
3698   if (cast_length != cast->cast_length ||
3699       cast_cs     != cast->cast_cs)
3700     return 0;
3701 
3702   if (!args[0]->eq(cast->args[0], binary_cmp))
3703       return 0;
3704   return 1;
3705 }
3706 
3707 
print(String * str,enum_query_type query_type)3708 void Item_char_typecast::print(String *str, enum_query_type query_type)
3709 {
3710   str->append(STRING_WITH_LEN("cast("));
3711   args[0]->print(str, query_type);
3712   str->append(STRING_WITH_LEN(" as char"));
3713   if (cast_length >= 0)
3714     str->append_parenthesized(cast_length);
3715   if (cast_cs)
3716   {
3717     str->append(STRING_WITH_LEN(" charset "));
3718     str->append(cast_cs->csname);
3719   }
3720   str->append(')');
3721 }
3722 
3723 
val_str(String * str)3724 String *Item_char_typecast::val_str(String *str)
3725 {
3726   DBUG_ASSERT(fixed == 1);
3727   String *res;
3728   uint32 length;
3729 
3730   if (cast_length >= 0 &&
3731       ((unsigned) cast_length) > current_thd->variables.max_allowed_packet)
3732   {
3733     push_warning_printf(current_thd, Sql_condition::WARN_LEVEL_WARN,
3734 			ER_WARN_ALLOWED_PACKET_OVERFLOWED,
3735 			ER(ER_WARN_ALLOWED_PACKET_OVERFLOWED),
3736 			cast_cs == &my_charset_bin ?
3737                         "cast_as_binary" : func_name(),
3738                         current_thd->variables.max_allowed_packet);
3739     null_value= 1;
3740     return 0;
3741   }
3742 
3743   if (!charset_conversion)
3744   {
3745     if (!(res= args[0]->val_str(str)))
3746     {
3747       null_value= 1;
3748       return 0;
3749     }
3750   }
3751   else
3752   {
3753     // Convert character set if differ
3754     uint dummy_errors;
3755     if (!(res= args[0]->val_str(str)) ||
3756         tmp_value.copy(res->ptr(), res->length(), from_cs,
3757                        cast_cs, &dummy_errors))
3758     {
3759       null_value= 1;
3760       return 0;
3761     }
3762     res= &tmp_value;
3763   }
3764 
3765   res->set_charset(cast_cs);
3766 
3767   /*
3768     Cut the tail if cast with length
3769     and the result is longer than cast length, e.g.
3770     CAST('string' AS CHAR(1))
3771   */
3772   if (cast_length >= 0)
3773   {
3774     if (res->length() > (length= (uint32) res->charpos(cast_length)))
3775     {                                           // Safe even if const arg
3776       char char_type[40];
3777       my_snprintf(char_type, sizeof(char_type), "%s(%lu)",
3778                   cast_cs == &my_charset_bin ? "BINARY" : "CHAR",
3779                   (ulong) length);
3780 
3781       if (!res->alloced_length())
3782       {                                         // Don't change const str
3783         str_value= *res;                        // Not malloced string
3784         res= &str_value;
3785       }
3786       ErrConvString err(res);
3787       push_warning_printf(current_thd, Sql_condition::WARN_LEVEL_WARN,
3788                           ER_TRUNCATED_WRONG_VALUE,
3789                           ER(ER_TRUNCATED_WRONG_VALUE), char_type,
3790                           err.ptr());
3791       res->length((uint) length);
3792     }
3793     else if (cast_cs == &my_charset_bin && res->length() < (uint) cast_length)
3794     {
3795       if (res->alloced_length() < (uint) cast_length)
3796       {
3797         str_value.alloc(cast_length);
3798         str_value.copy(*res);
3799         res= &str_value;
3800       }
3801       memset(const_cast<char*>(res->ptr() + res->length()), 0,
3802              cast_length - res->length());
3803       res->length(cast_length);
3804     }
3805   }
3806   null_value= 0;
3807   return res;
3808 }
3809 
3810 
fix_length_and_dec()3811 void Item_char_typecast::fix_length_and_dec()
3812 {
3813   /*
3814     If we convert between two ASCII compatible character sets and the
3815     argument repertoire is MY_REPERTOIRE_ASCII then from_cs is set to cast_cs.
3816     This allows just to take over the args[0]->val_str() result
3817     and thus avoid unnecessary character set conversion.
3818   */
3819   from_cs= args[0]->collation.repertoire == MY_REPERTOIRE_ASCII &&
3820            my_charset_is_ascii_based(cast_cs) &&
3821            my_charset_is_ascii_based(args[0]->collation.collation) ?
3822            cast_cs : args[0]->collation.collation;
3823 
3824 
3825   collation.set(cast_cs, DERIVATION_IMPLICIT);
3826   fix_char_length(cast_length >= 0 ? cast_length :
3827                   cast_cs == &my_charset_bin ? args[0]->max_length :
3828                   args[0]->max_char_length());
3829 
3830   /*
3831      We always force character set conversion if cast_cs
3832      is a multi-byte character set. It garantees that the
3833      result of CAST is a well-formed string.
3834      For single-byte character sets we allow just to copy from the argument.
3835      A single-byte character sets string is always well-formed.
3836   */
3837   charset_conversion= (cast_cs->mbmaxlen > 1) ||
3838                       (!my_charset_same(from_cs, cast_cs) &&
3839                        from_cs != &my_charset_bin &&
3840                        cast_cs != &my_charset_bin);
3841 }
3842 
3843 
print(String * str,enum_query_type query_type)3844 void Item_func_binary::print(String *str, enum_query_type query_type)
3845 {
3846   str->append(STRING_WITH_LEN("cast("));
3847   args[0]->print(str, query_type);
3848   str->append(STRING_WITH_LEN(" as binary)"));
3849 }
3850 
3851 
3852 #include <my_dir.h>				// For my_stat
3853 
val_str(String * str)3854 String *Item_load_file::val_str(String *str)
3855 {
3856   DBUG_ASSERT(fixed == 1);
3857   String *file_name;
3858   File file;
3859   MY_STAT stat_info;
3860   char path[FN_REFLEN];
3861   DBUG_ENTER("load_file");
3862 
3863   if (!(file_name= args[0]->val_str(str))
3864 #ifndef NO_EMBEDDED_ACCESS_CHECKS
3865       || !(current_thd->security_ctx->master_access & FILE_ACL)
3866 #endif
3867       )
3868     goto err;
3869 
3870   (void) fn_format(path, file_name->c_ptr_safe(), mysql_real_data_home, "",
3871 		   MY_RELATIVE_PATH | MY_UNPACK_FILENAME);
3872 
3873   /* Read only allowed from within dir specified by secure_file_priv */
3874   if (!is_secure_file_path(path))
3875     goto err;
3876 
3877   if (!mysql_file_stat(key_file_loadfile, path, &stat_info, MYF(0)))
3878     goto err;
3879 
3880   if (!(stat_info.st_mode & S_IROTH))
3881   {
3882     /* my_error(ER_TEXTFILE_NOT_READABLE, MYF(0), file_name->c_ptr()); */
3883     goto err;
3884   }
3885   if (stat_info.st_size > (long) current_thd->variables.max_allowed_packet)
3886   {
3887     push_warning_printf(current_thd, Sql_condition::WARN_LEVEL_WARN,
3888 			ER_WARN_ALLOWED_PACKET_OVERFLOWED,
3889 			ER(ER_WARN_ALLOWED_PACKET_OVERFLOWED),
3890 			func_name(), current_thd->variables.max_allowed_packet);
3891     goto err;
3892   }
3893   if (tmp_value.alloc(stat_info.st_size))
3894     goto err;
3895   if ((file= mysql_file_open(key_file_loadfile,
3896                              file_name->ptr(), O_RDONLY, MYF(0))) < 0)
3897     goto err;
3898   if (mysql_file_read(file, (uchar*) tmp_value.ptr(), stat_info.st_size,
3899                       MYF(MY_NABP)))
3900   {
3901     mysql_file_close(file, MYF(0));
3902     goto err;
3903   }
3904   tmp_value.length(stat_info.st_size);
3905   mysql_file_close(file, MYF(0));
3906   null_value = 0;
3907   DBUG_RETURN(&tmp_value);
3908 
3909 err:
3910   null_value = 1;
3911   DBUG_RETURN(0);
3912 }
3913 
3914 
val_str(String * str)3915 String* Item_func_export_set::val_str(String* str)
3916 {
3917   DBUG_ASSERT(fixed == 1);
3918   String yes_buf, no_buf, sep_buf;
3919   const ulonglong the_set = (ulonglong) args[0]->val_int();
3920   const String *yes= args[1]->val_str(&yes_buf);
3921   const String *no= args[2]->val_str(&no_buf);
3922   const String *sep= NULL;
3923 
3924   uint num_set_values = 64;
3925   str->length(0);
3926   str->set_charset(collation.collation);
3927 
3928   /* Check if some argument is a NULL value */
3929   if (args[0]->null_value || args[1]->null_value || args[2]->null_value)
3930   {
3931     null_value= true;
3932     return NULL;
3933   }
3934   /*
3935     Arg count can only be 3, 4 or 5 here. This is guaranteed from the
3936     grammar for EXPORT_SET()
3937   */
3938   switch(arg_count) {
3939   case 5:
3940     num_set_values = (uint) args[4]->val_int();
3941     if (num_set_values > 64)
3942       num_set_values=64;
3943     if (args[4]->null_value)
3944     {
3945       null_value= true;
3946       return NULL;
3947     }
3948     /* Fall through */
3949   case 4:
3950     if (!(sep = args[3]->val_str(&sep_buf)))	// Only true if NULL
3951     {
3952       null_value= true;
3953       return NULL;
3954     }
3955     break;
3956   case 3:
3957     {
3958       /* errors is not checked - assume "," can always be converted */
3959       uint errors;
3960       sep_buf.copy(STRING_WITH_LEN(","), &my_charset_bin,
3961                    collation.collation, &errors);
3962       sep = &sep_buf;
3963     }
3964     break;
3965   default:
3966     DBUG_ASSERT(0); // cannot happen
3967   }
3968   null_value= false;
3969 
3970   const ulong max_allowed_packet= current_thd->variables.max_allowed_packet;
3971   const uint num_separators= num_set_values > 0 ? num_set_values - 1 : 0;
3972   const ulonglong max_total_length=
3973     num_set_values * max(yes->length(), no->length()) +
3974     num_separators * sep->length();
3975 
3976   if (unlikely(max_total_length > max_allowed_packet))
3977   {
3978     push_warning_printf(current_thd, Sql_condition::WARN_LEVEL_WARN,
3979                         ER_WARN_ALLOWED_PACKET_OVERFLOWED,
3980                         ER(ER_WARN_ALLOWED_PACKET_OVERFLOWED),
3981                         func_name(), max_allowed_packet);
3982     null_value= true;
3983     return NULL;
3984   }
3985 
3986   uint ix;
3987   ulonglong mask;
3988   for (ix= 0, mask=0x1; ix < num_set_values; ++ix, mask = (mask << 1))
3989   {
3990     if (the_set & mask)
3991       str->append(*yes);
3992     else
3993       str->append(*no);
3994     if (ix != num_separators)
3995       str->append(*sep);
3996   }
3997   return str;
3998 }
3999 
fix_length_and_dec()4000 void Item_func_export_set::fix_length_and_dec()
4001 {
4002   uint32 length= max(args[1]->max_char_length(), args[2]->max_char_length());
4003   uint32 sep_length= (arg_count > 3 ? args[3]->max_char_length() : 1);
4004 
4005   if (agg_arg_charsets_for_string_result(collation,
4006                                          args + 1, min(4U, arg_count) - 1))
4007     return;
4008   fix_char_length(length * 64 + sep_length * 63);
4009 }
4010 
4011 
4012 #define get_esc_bit(mask, num) (1 & (*((mask) + ((num) >> 3))) >> ((num) & 7))
4013 
4014 /**
4015   QUOTE() function returns argument string in single quotes suitable for
4016   using in a SQL statement.
4017 
4018   Adds a \\ before all characters that needs to be escaped in a SQL string.
4019   We also escape '^Z' (END-OF-FILE in windows) to avoid probelms when
4020   running commands from a file in windows.
4021 
4022   This function is very useful when you want to generate SQL statements.
4023 
4024   @note
4025     QUOTE(NULL) returns the string 'NULL' (4 letters, without quotes).
4026 
4027   @retval
4028     str	   Quoted string
4029   @retval
4030     NULL	   Out of memory.
4031 */
4032 
val_str(String * str)4033 String *Item_func_quote::val_str(String *str)
4034 {
4035   DBUG_ASSERT(fixed == 1);
4036   /*
4037     Bit mask that has 1 for set for the position of the following characters:
4038     0, \, ' and ^Z
4039   */
4040 
4041   static uchar escmask[32]=
4042   {
4043     0x01, 0x00, 0x00, 0x04, 0x80, 0x00, 0x00, 0x00,
4044     0x00, 0x00, 0x00, 0x10, 0x00, 0x00, 0x00, 0x00,
4045     0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
4046     0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
4047   };
4048 
4049   char *from, *to, *end, *start;
4050   String *arg= args[0]->val_str(str);
4051   uint arg_length, new_length;
4052   if (!arg)					// Null argument
4053   {
4054     /* Return the string 'NULL' */
4055     str->copy(STRING_WITH_LEN("NULL"), collation.collation);
4056     null_value= 0;
4057     return str;
4058   }
4059 
4060   arg_length= arg->length();
4061 
4062   if (collation.collation->mbmaxlen == 1)
4063   {
4064     new_length= arg_length + 2; /* for beginning and ending ' signs */
4065     for (from= (char*) arg->ptr(), end= from + arg_length; from < end; from++)
4066       new_length+= get_esc_bit(escmask, (uchar) *from);
4067   }
4068   else
4069   {
4070     new_length= (arg_length * 2) +  /* For string characters */
4071                 (2 * collation.collation->mbmaxlen); /* For quotes */
4072   }
4073 
4074   if (tmp_value.alloc(new_length))
4075     goto null;
4076 
4077   if (collation.collation->mbmaxlen > 1)
4078   {
4079     const CHARSET_INFO *cs= collation.collation;
4080     int mblen;
4081     uchar *to_end;
4082     to= (char*) tmp_value.ptr();
4083     to_end= (uchar*) to + new_length;
4084 
4085     /* Put leading quote */
4086     if ((mblen= cs->cset->wc_mb(cs, '\'', (uchar *) to, to_end)) <= 0)
4087       goto null;
4088     to+= mblen;
4089 
4090     for (start= (char*) arg->ptr(), end= start + arg_length; start < end; )
4091     {
4092       my_wc_t wc;
4093       bool escape;
4094       if ((mblen= cs->cset->mb_wc(cs, &wc, (uchar*) start, (uchar*) end)) <= 0)
4095         goto null;
4096       start+= mblen;
4097       switch (wc) {
4098         case 0:      escape= 1; wc= '0'; break;
4099         case '\032': escape= 1; wc= 'Z'; break;
4100         case '\'':   escape= 1; break;
4101         case '\\':   escape= 1; break;
4102         default:     escape= 0; break;
4103       }
4104       if (escape)
4105       {
4106         if ((mblen= cs->cset->wc_mb(cs, '\\', (uchar*) to, to_end)) <= 0)
4107           goto null;
4108         to+= mblen;
4109       }
4110       if ((mblen= cs->cset->wc_mb(cs, wc, (uchar*) to, to_end)) <= 0)
4111         goto null;
4112       to+= mblen;
4113     }
4114 
4115     /* Put trailing quote */
4116     if ((mblen= cs->cset->wc_mb(cs, '\'', (uchar *) to, to_end)) <= 0)
4117       goto null;
4118     to+= mblen;
4119     new_length= to - tmp_value.ptr();
4120     goto ret;
4121   }
4122 
4123   /*
4124     We replace characters from the end to the beginning
4125   */
4126   to= (char*) tmp_value.ptr() + new_length - 1;
4127   *to--= '\'';
4128   for (start= (char*) arg->ptr(),end= start + arg_length; end-- != start; to--)
4129   {
4130     /*
4131       We can't use the bitmask here as we want to replace \O and ^Z with 0
4132       and Z
4133     */
4134     switch (*end)  {
4135     case 0:
4136       *to--= '0';
4137       *to=   '\\';
4138       break;
4139     case '\032':
4140       *to--= 'Z';
4141       *to=   '\\';
4142       break;
4143     case '\'':
4144     case '\\':
4145       *to--= *end;
4146       *to=   '\\';
4147       break;
4148     default:
4149       *to= *end;
4150       break;
4151     }
4152   }
4153   *to= '\'';
4154 
4155 ret:
4156   if (new_length > current_thd->variables.max_allowed_packet)
4157   {
4158     push_warning_printf(current_thd, Sql_condition::WARN_LEVEL_WARN,
4159                         ER_WARN_ALLOWED_PACKET_OVERFLOWED,
4160                         ER_THD(current_thd, ER_WARN_ALLOWED_PACKET_OVERFLOWED),
4161                         func_name(),
4162                         current_thd->variables.max_allowed_packet);
4163     null_value= true;
4164     return NULL;
4165   }
4166 
4167   tmp_value.length(new_length);
4168   tmp_value.set_charset(collation.collation);
4169   null_value= 0;
4170   return &tmp_value;
4171 
4172 null:
4173   null_value= 1;
4174   return 0;
4175 }
4176 
val_int()4177 longlong Item_func_uncompressed_length::val_int()
4178 {
4179   DBUG_ASSERT(fixed == 1);
4180   String *res= args[0]->val_str(&value);
4181   if (!res)
4182   {
4183     null_value=1;
4184     return 0; /* purecov: inspected */
4185   }
4186   null_value=0;
4187   if (res->is_empty()) return 0;
4188 
4189   /*
4190     If length is <= 4 bytes, data is corrupt. This is the best we can do
4191     to detect garbage input without decompressing it.
4192   */
4193   if (res->length() <= 4)
4194   {
4195     push_warning_printf(current_thd, Sql_condition::WARN_LEVEL_WARN,
4196                         ER_ZLIB_Z_DATA_ERROR,
4197                         ER(ER_ZLIB_Z_DATA_ERROR));
4198     null_value= 1;
4199     return 0;
4200   }
4201 
4202  /*
4203     res->ptr() using is safe because we have tested that string is at least
4204     5 bytes long.
4205     res->c_ptr() is not used because:
4206       - we do not need \0 terminated string to get first 4 bytes
4207       - c_ptr() tests simbol after string end (uninitialiozed memory) which
4208         confuse valgrind
4209   */
4210   return uint4korr(res->ptr()) & 0x3FFFFFFF;
4211 }
4212 
val_int()4213 longlong Item_func_crc32::val_int()
4214 {
4215   DBUG_ASSERT(fixed == 1);
4216   String *res=args[0]->val_str(&value);
4217   if (!res)
4218   {
4219     null_value=1;
4220     return 0; /* purecov: inspected */
4221   }
4222   null_value=0;
4223   return (longlong) crc32(0L, (uchar*)res->ptr(), res->length());
4224 }
4225 
4226 #ifdef HAVE_COMPRESS
4227 #include "zlib.h"
4228 
val_str(String * str)4229 String *Item_func_compress::val_str(String *str)
4230 {
4231   int err= Z_OK, code;
4232   ulong new_size;
4233   String *res;
4234   Byte *body;
4235   char *tmp, *last_char;
4236   DBUG_ASSERT(fixed == 1);
4237 
4238   if (!(res= args[0]->val_str(str)))
4239   {
4240     null_value= 1;
4241     return 0;
4242   }
4243   null_value= 0;
4244   if (res->is_empty()) return res;
4245 
4246   /*
4247     Citation from zlib.h (comment for compress function):
4248 
4249     Compresses the source buffer into the destination buffer.  sourceLen is
4250     the byte length of the source buffer. Upon entry, destLen is the total
4251     size of the destination buffer, which must be at least 0.1% larger than
4252     sourceLen plus 12 bytes.
4253     We assume here that the buffer can't grow more than .25 %.
4254   */
4255   new_size= res->length() + res->length() / 5 + 12;
4256 
4257   // Check new_size overflow: new_size <= res->length()
4258   if (((uint32) (new_size+5) <= res->length()) ||
4259       buffer.realloc((uint32) new_size + 4 + 1))
4260   {
4261     null_value= 1;
4262     return 0;
4263   }
4264 
4265   body= ((Byte*)buffer.ptr()) + 4;
4266 
4267   // As far as we have checked res->is_empty() we can use ptr()
4268   if ((err= compress(body, &new_size,
4269 		     (const Bytef*)res->ptr(), res->length())) != Z_OK)
4270   {
4271     code= err==Z_MEM_ERROR ? ER_ZLIB_Z_MEM_ERROR : ER_ZLIB_Z_BUF_ERROR;
4272     push_warning(current_thd,Sql_condition::WARN_LEVEL_WARN,code,ER(code));
4273     null_value= 1;
4274     return 0;
4275   }
4276 
4277   tmp= (char*)buffer.ptr(); // int4store is a macro; avoid side effects
4278   int4store(tmp, res->length() & 0x3FFFFFFF);
4279 
4280   /* This is to ensure that things works for CHAR fields, which trim ' ': */
4281   last_char= ((char*)body)+new_size-1;
4282   if (*last_char == ' ')
4283   {
4284     *++last_char= '.';
4285     new_size++;
4286   }
4287 
4288   buffer.length((uint32)new_size + 4);
4289   return &buffer;
4290 }
4291 
4292 
val_str(String * str)4293 String *Item_func_uncompress::val_str(String *str)
4294 {
4295   DBUG_ASSERT(fixed == 1);
4296   String *res= args[0]->val_str(str);
4297   ulong new_size;
4298   int err;
4299   uint code;
4300 
4301   if (!res)
4302     goto err;
4303   null_value= 0;
4304   if (res->is_empty())
4305     return res;
4306 
4307   /* If length is less than 4 bytes, data is corrupt */
4308   if (res->length() <= 4)
4309   {
4310     push_warning_printf(current_thd,Sql_condition::WARN_LEVEL_WARN,
4311 			ER_ZLIB_Z_DATA_ERROR,
4312 			ER(ER_ZLIB_Z_DATA_ERROR));
4313     goto err;
4314   }
4315 
4316   /* Size of uncompressed data is stored as first 4 bytes of field */
4317   new_size= uint4korr(res->ptr()) & 0x3FFFFFFF;
4318   if (new_size > current_thd->variables.max_allowed_packet)
4319   {
4320     push_warning_printf(current_thd,Sql_condition::WARN_LEVEL_WARN,
4321 			ER_TOO_BIG_FOR_UNCOMPRESS,
4322 			ER(ER_TOO_BIG_FOR_UNCOMPRESS),
4323                         static_cast<int>(current_thd->variables.
4324                                          max_allowed_packet));
4325     goto err;
4326   }
4327   if (buffer.realloc((uint32)new_size))
4328     goto err;
4329 
4330   if ((err= uncompress((Byte*)buffer.ptr(), &new_size,
4331 		       ((const Bytef*)res->ptr())+4,res->length())) == Z_OK)
4332   {
4333     buffer.length((uint32) new_size);
4334     return &buffer;
4335   }
4336 
4337   code= ((err == Z_BUF_ERROR) ? ER_ZLIB_Z_BUF_ERROR :
4338 	 ((err == Z_MEM_ERROR) ? ER_ZLIB_Z_MEM_ERROR : ER_ZLIB_Z_DATA_ERROR));
4339   push_warning(current_thd,Sql_condition::WARN_LEVEL_WARN,code,ER(code));
4340 
4341 err:
4342   null_value= 1;
4343   return 0;
4344 }
4345 #endif
4346 
4347 /*
4348   UUID, as in
4349     DCE 1.1: Remote Procedure Call,
4350     Open Group Technical Standard Document Number C706, October 1997,
4351     (supersedes C309 DCE: Remote Procedure Call 8/1994,
4352     which was basis for ISO/IEC 11578:1996 specification)
4353 */
4354 
4355 static struct rand_struct uuid_rand;
4356 static uint nanoseq;
4357 static ulonglong uuid_time=0;
4358 static char clock_seq_and_node_str[]="-0000-000000000000";
4359 
4360 /**
4361   number of 100-nanosecond intervals between
4362   1582-10-15 00:00:00.00 and 1970-01-01 00:00:00.00.
4363 */
4364 #define UUID_TIME_OFFSET ((ulonglong) 141427 * 24 * 60 * 60 * \
4365                           1000 * 1000 * 10)
4366 
4367 #define UUID_VERSION      0x1000
4368 #define UUID_VARIANT      0x8000
4369 
tohex(char * to,uint from,uint len)4370 static void tohex(char *to, uint from, uint len)
4371 {
4372   to+= len;
4373   while (len--)
4374   {
4375     *--to= _dig_vec_lower[from & 15];
4376     from >>= 4;
4377   }
4378 }
4379 
set_clock_seq_str()4380 static void set_clock_seq_str()
4381 {
4382   uint16 clock_seq= ((uint)(my_rnd(&uuid_rand)*16383)) | UUID_VARIANT;
4383   tohex(clock_seq_and_node_str+1, clock_seq, 4);
4384   nanoseq= 0;
4385 }
4386 
val_str(String * str)4387 String *Item_func_uuid::val_str(String *str)
4388 {
4389   DBUG_ASSERT(fixed == 1);
4390   char *s;
4391   THD *thd= current_thd;
4392 
4393   mysql_mutex_lock(&LOCK_uuid_generator);
4394   if (! uuid_time) /* first UUID() call. initializing data */
4395   {
4396     ulong tmp=sql_rnd_with_mutex();
4397     uchar mac[6];
4398     int i;
4399     if (my_gethwaddr(mac))
4400     {
4401       /* purecov: begin inspected */
4402       /*
4403         generating random "hardware addr"
4404         and because specs explicitly specify that it should NOT correlate
4405         with a clock_seq value (initialized random below), we use a separate
4406         randominit() here
4407       */
4408       randominit(&uuid_rand, tmp + (ulong) thd, tmp + (ulong)global_query_id);
4409       for (i=0; i < (int)sizeof(mac); i++)
4410         mac[i]=(uchar)(my_rnd(&uuid_rand)*255);
4411       /* purecov: end */
4412     }
4413     s=clock_seq_and_node_str+sizeof(clock_seq_and_node_str)-1;
4414     for (i=sizeof(mac)-1 ; i>=0 ; i--)
4415     {
4416       *--s=_dig_vec_lower[mac[i] & 15];
4417       *--s=_dig_vec_lower[mac[i] >> 4];
4418     }
4419     randominit(&uuid_rand, tmp + (ulong) server_start_time,
4420 	       tmp + (ulong) thd->status_var.bytes_sent);
4421     set_clock_seq_str();
4422   }
4423 
4424   ulonglong tv= my_getsystime() + UUID_TIME_OFFSET + nanoseq;
4425 
4426   if (likely(tv > uuid_time))
4427   {
4428     /*
4429       Current time is ahead of last timestamp, as it should be.
4430       If we "borrowed time", give it back, just as long as we
4431       stay ahead of the previous timestamp.
4432     */
4433     if (nanoseq)
4434     {
4435       DBUG_ASSERT((tv > uuid_time) && (nanoseq > 0));
4436       /*
4437         -1 so we won't make tv= uuid_time for nanoseq >= (tv - uuid_time)
4438       */
4439       ulong delta= min<ulong>(nanoseq, (ulong) (tv - uuid_time -1));
4440       tv-= delta;
4441       nanoseq-= delta;
4442     }
4443   }
4444   else
4445   {
4446     if (unlikely(tv == uuid_time))
4447     {
4448       /*
4449         For low-res system clocks. If several requests for UUIDs
4450         end up on the same tick, we add a nano-second to make them
4451         different.
4452         ( current_timestamp + nanoseq * calls_in_this_period )
4453         may end up > next_timestamp; this is OK. Nonetheless, we'll
4454         try to unwind nanoseq when we get a chance to.
4455         If nanoseq overflows, we'll start over with a new numberspace
4456         (so the if() below is needed so we can avoid the ++tv and thus
4457         match the follow-up if() if nanoseq overflows!).
4458       */
4459       if (likely(++nanoseq))
4460         ++tv;
4461     }
4462 
4463     if (unlikely(tv <= uuid_time))
4464     {
4465       /*
4466         If the admin changes the system clock (or due to Daylight
4467         Saving Time), the system clock may be turned *back* so we
4468         go through a period once more for which we already gave out
4469         UUIDs.  To avoid duplicate UUIDs despite potentially identical
4470         times, we make a new random component.
4471         We also come here if the nanoseq "borrowing" overflows.
4472         In either case, we throw away any nanoseq borrowing since it's
4473         irrelevant in the new numberspace.
4474       */
4475       set_clock_seq_str();
4476       tv= my_getsystime() + UUID_TIME_OFFSET;
4477       nanoseq= 0;
4478       DBUG_PRINT("uuid",("making new numberspace"));
4479     }
4480   }
4481 
4482   uuid_time=tv;
4483   mysql_mutex_unlock(&LOCK_uuid_generator);
4484 
4485   uint32 time_low=            (uint32) (tv & 0xFFFFFFFF);
4486   uint16 time_mid=            (uint16) ((tv >> 32) & 0xFFFF);
4487   uint16 time_hi_and_version= (uint16) ((tv >> 48) | UUID_VERSION);
4488 
4489   str->realloc(UUID_LENGTH+1);
4490   str->length(UUID_LENGTH);
4491   str->set_charset(system_charset_info);
4492   s=(char *) str->ptr();
4493   s[8]=s[13]='-';
4494   tohex(s, time_low, 8);
4495   tohex(s+9, time_mid, 4);
4496   tohex(s+14, time_hi_and_version, 4);
4497   strmov(s+18, clock_seq_and_node_str);
4498   DBUG_EXECUTE_IF("force_fake_uuid",
4499                   strmov(s, "a2d00942-b69c-11e4-a696-0020ff6fcbe6");
4500                   );
4501   return str;
4502 }
4503 
4504 
fix_length_and_dec()4505 void Item_func_gtid_subtract::fix_length_and_dec()
4506 {
4507   maybe_null= args[0]->maybe_null || args[1]->maybe_null;
4508   collation.set(default_charset(), DERIVATION_COERCIBLE, MY_REPERTOIRE_ASCII);
4509   /*
4510     In the worst case, the string grows after subtraction. This
4511     happens when a GTID in args[0] is split by a GTID in args[1],
4512     e.g., UUID:1-6 minus UUID:3-4 becomes UUID:1-2,5-6.  The worst
4513     case is UUID:1-100 minus UUID:9, where the two characters ":9" in
4514     args[1] yield the five characters "-8,10" in the result.
4515   */
4516   fix_char_length_ulonglong(args[0]->max_length +
4517                             max<ulonglong>(args[1]->max_length -
4518                                            Uuid::TEXT_LENGTH, 0) * 5 / 2);
4519 }
4520 
4521 
val_str_ascii(String * str)4522 String *Item_func_gtid_subtract::val_str_ascii(String *str)
4523 {
4524   DBUG_ENTER("Item_func_gtid_subtract::val_str_ascii");
4525   String *str1, *str2;
4526   const char *charp1, *charp2;
4527   enum_return_status status;
4528   /*
4529     We must execute args[*]->val_str_ascii() before checking
4530     args[*]->null_value to ensure that them are updated when
4531     this function is executed inside a stored procedure.
4532   */
4533   if ((str1= args[0]->val_str_ascii(&buf1)) != NULL &&
4534       (charp1= str1->c_ptr_safe()) != NULL &&
4535       (str2= args[1]->val_str_ascii(&buf2)) != NULL &&
4536       (charp2= str2->c_ptr_safe()) != NULL &&
4537       !args[0]->null_value && !args[1]->null_value)
4538   {
4539     Sid_map sid_map(NULL/*no rwlock*/);
4540     // compute sets while holding locks
4541     Gtid_set set1(&sid_map, charp1, &status);
4542     if (status == RETURN_STATUS_OK)
4543     {
4544       Gtid_set set2(&sid_map, charp2, &status);
4545       int length;
4546       // subtract, save result, return result
4547       if (status == RETURN_STATUS_OK &&
4548           set1.remove_gtid_set(&set2) == 0 &&
4549           !str->realloc((length= set1.get_string_length()) + 1))
4550       {
4551         null_value= false;
4552         set1.to_string((char *)str->ptr());
4553         str->length(length);
4554         DBUG_RETURN(str);
4555       }
4556     }
4557   }
4558   null_value= true;
4559   DBUG_RETURN(NULL);
4560 }
4561