mySQL 5.0.11 sources for tomato
[tomato.git] / release / src / router / mysql / sql / sql_connect.cc
blobe7aa48c94f57346dc4a26fb7cadc178dac4b0c71
1 /*
2 Copyright (c) 2007, 2012, Oracle and/or its affiliates. All rights reserved.
4 This program is free software; you can redistribute it and/or modify
5 it under the terms of the GNU General Public License as published by
6 the Free Software Foundation; version 2 of the License.
8 This program is distributed in the hope that it will be useful,
9 but WITHOUT ANY WARRANTY; without even the implied warranty of
10 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 GNU General Public License for more details.
13 You should have received a copy of the GNU General Public License
14 along with this program; if not, write to the Free Software
15 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
19 Functions to autenticate and handle reqests for a connection
22 #include "mysql_priv.h"
24 /** Size of the header fields of an authentication packet. */
25 #define AUTH_PACKET_HEADER_SIZE_PROTO_41 32
26 #define AUTH_PACKET_HEADER_SIZE_PROTO_40 5
27 #define AUTH_PACKET_HEADER_SIZE_CONNJ_SSL 4
29 #ifdef __WIN__
30 extern void win_install_sigabrt_handler();
31 #endif
34 Get structure for logging connection data for the current user
37 #ifndef NO_EMBEDDED_ACCESS_CHECKS
38 static HASH hash_user_connections;
40 static int get_or_create_user_conn(THD *thd, const char *user,
41 const char *host,
42 USER_RESOURCES *mqh)
44 int return_val= 0;
45 size_t temp_len, user_len;
46 char temp_user[USER_HOST_BUFF_SIZE];
47 struct user_conn *uc;
49 DBUG_ASSERT(user != 0);
50 DBUG_ASSERT(host != 0);
52 user_len= strlen(user);
53 temp_len= (strmov(strmov(temp_user, user)+1, host) - temp_user)+1;
54 (void) pthread_mutex_lock(&LOCK_user_conn);
55 if (!(uc = (struct user_conn *) hash_search(&hash_user_connections,
56 (uchar*) temp_user, temp_len)))
58 /* First connection for user; Create a user connection object */
59 if (!(uc= ((struct user_conn*)
60 my_malloc(sizeof(struct user_conn) + temp_len+1,
61 MYF(MY_WME)))))
63 /* MY_WME ensures an error is set in THD. */
64 return_val= 1;
65 goto end;
67 uc->user=(char*) (uc+1);
68 memcpy(uc->user,temp_user,temp_len+1);
69 uc->host= uc->user + user_len + 1;
70 uc->len= temp_len;
71 uc->connections= uc->questions= uc->updates= uc->conn_per_hour= 0;
72 uc->user_resources= *mqh;
73 uc->reset_utime= thd->thr_create_utime;
74 if (my_hash_insert(&hash_user_connections, (uchar*) uc))
76 /* The only possible error is out of memory, MY_WME sets an error. */
77 my_free((char*) uc,0);
78 return_val= 1;
79 goto end;
82 thd->user_connect=uc;
83 uc->connections++;
84 end:
85 (void) pthread_mutex_unlock(&LOCK_user_conn);
86 return return_val;
92 check if user has already too many connections
94 SYNOPSIS
95 check_for_max_user_connections()
96 thd Thread handle
97 uc User connect object
99 NOTES
100 If check fails, we decrease user connection count, which means one
101 shouldn't call decrease_user_connections() after this function.
103 RETURN
104 0 ok
105 1 error
108 static
109 int check_for_max_user_connections(THD *thd, USER_CONN *uc)
111 int error=0;
112 DBUG_ENTER("check_for_max_user_connections");
114 (void) pthread_mutex_lock(&LOCK_user_conn);
115 if (max_user_connections && !uc->user_resources.user_conn &&
116 max_user_connections < (uint) uc->connections)
118 my_error(ER_TOO_MANY_USER_CONNECTIONS, MYF(0), uc->user);
119 error=1;
120 goto end;
122 time_out_user_resource_limits(thd, uc);
123 if (uc->user_resources.user_conn &&
124 uc->user_resources.user_conn < uc->connections)
126 my_error(ER_USER_LIMIT_REACHED, MYF(0), uc->user,
127 "max_user_connections",
128 (long) uc->user_resources.user_conn);
129 error= 1;
130 goto end;
132 if (uc->user_resources.conn_per_hour &&
133 uc->user_resources.conn_per_hour <= uc->conn_per_hour)
135 my_error(ER_USER_LIMIT_REACHED, MYF(0), uc->user,
136 "max_connections_per_hour",
137 (long) uc->user_resources.conn_per_hour);
138 error=1;
139 goto end;
141 uc->conn_per_hour++;
143 end:
144 if (error)
145 uc->connections--; // no need for decrease_user_connections() here
146 (void) pthread_mutex_unlock(&LOCK_user_conn);
147 DBUG_RETURN(error);
152 Decrease user connection count
154 SYNOPSIS
155 decrease_user_connections()
156 uc User connection object
158 NOTES
159 If there is a n user connection object for a connection
160 (which only happens if 'max_user_connections' is defined or
161 if someone has created a resource grant for a user), then
162 the connection count is always incremented on connect.
164 The user connect object is not freed if some users has
165 'max connections per hour' defined as we need to be able to hold
166 count over the lifetime of the connection.
169 void decrease_user_connections(USER_CONN *uc)
171 DBUG_ENTER("decrease_user_connections");
172 (void) pthread_mutex_lock(&LOCK_user_conn);
173 DBUG_ASSERT(uc->connections);
174 if (!--uc->connections && !mqh_used)
176 /* Last connection for user; Delete it */
177 (void) hash_delete(&hash_user_connections,(uchar*) uc);
179 (void) pthread_mutex_unlock(&LOCK_user_conn);
180 DBUG_VOID_RETURN;
185 Reset per-hour user resource limits when it has been more than
186 an hour since they were last checked
188 SYNOPSIS:
189 time_out_user_resource_limits()
190 thd Thread handler
191 uc User connection details
193 NOTE:
194 This assumes that the LOCK_user_conn mutex has been acquired, so it is
195 safe to test and modify members of the USER_CONN structure.
198 void time_out_user_resource_limits(THD *thd, USER_CONN *uc)
200 ulonglong check_time= thd->start_utime;
201 DBUG_ENTER("time_out_user_resource_limits");
203 /* If more than a hour since last check, reset resource checking */
204 if (check_time - uc->reset_utime >= LL(3600000000))
206 uc->questions=1;
207 uc->updates=0;
208 uc->conn_per_hour=0;
209 uc->reset_utime= check_time;
212 DBUG_VOID_RETURN;
216 Check if maximum queries per hour limit has been reached
217 returns 0 if OK.
220 bool check_mqh(THD *thd, uint check_command)
222 bool error= 0;
223 USER_CONN *uc=thd->user_connect;
224 DBUG_ENTER("check_mqh");
225 DBUG_ASSERT(uc != 0);
227 (void) pthread_mutex_lock(&LOCK_user_conn);
229 time_out_user_resource_limits(thd, uc);
231 /* Check that we have not done too many questions / hour */
232 if (uc->user_resources.questions &&
233 uc->questions++ >= uc->user_resources.questions)
235 my_error(ER_USER_LIMIT_REACHED, MYF(0), uc->user, "max_questions",
236 (long) uc->user_resources.questions);
237 error=1;
238 goto end;
240 if (check_command < (uint) SQLCOM_END)
242 /* Check that we have not done too many updates / hour */
243 if (uc->user_resources.updates &&
244 (sql_command_flags[check_command] & CF_CHANGES_DATA) &&
245 uc->updates++ >= uc->user_resources.updates)
247 my_error(ER_USER_LIMIT_REACHED, MYF(0), uc->user, "max_updates",
248 (long) uc->user_resources.updates);
249 error=1;
250 goto end;
253 end:
254 (void) pthread_mutex_unlock(&LOCK_user_conn);
255 DBUG_RETURN(error);
258 #endif /* NO_EMBEDDED_ACCESS_CHECKS */
262 Check if user exist and password supplied is correct.
264 @param thd thread handle, thd->security_ctx->{host,user,ip} are used
265 @param command originator of the check: now check_user is called
266 during connect and change user procedures; used for
267 logging.
268 @param passwd scrambled password received from client
269 @param passwd_len length of scrambled password
270 @param db database name to connect to, may be NULL
271 @param check_count TRUE if establishing a new connection. In this case
272 check that we have not exceeded the global
273 max_connections limist
275 @note Host, user and passwd may point to communication buffer.
276 Current implementation does not depend on that, but future changes
277 should be done with this in mind; 'thd' is INOUT, all other params
278 are 'IN'.
280 @retval 0 OK; thd->security_ctx->user/master_access/priv_user/db_access and
281 thd->db are updated; OK is sent to the client.
282 @retval 1 error, e.g. access denied or handshake error, not sent to
283 the client. A message is pushed into the error stack.
287 check_user(THD *thd, enum enum_server_command command,
288 const char *passwd, uint passwd_len, const char *db,
289 bool check_count)
291 DBUG_ENTER("check_user");
292 LEX_STRING db_str= { (char *) db, db ? strlen(db) : 0 };
295 Clear thd->db as it points to something, that will be freed when
296 connection is closed. We don't want to accidentally free a wrong
297 pointer if connect failed. Also in case of 'CHANGE USER' failure,
298 current database will be switched to 'no database selected'.
300 thd->reset_db(NULL, 0);
302 #ifdef NO_EMBEDDED_ACCESS_CHECKS
303 thd->main_security_ctx.master_access= GLOBAL_ACLS; // Full rights
304 /* Change database if necessary */
305 if (db && db[0])
307 if (mysql_change_db(thd, &db_str, FALSE))
308 DBUG_RETURN(1);
310 my_ok(thd);
311 DBUG_RETURN(0);
312 #else
314 my_bool opt_secure_auth_local;
315 pthread_mutex_lock(&LOCK_global_system_variables);
316 opt_secure_auth_local= opt_secure_auth;
317 pthread_mutex_unlock(&LOCK_global_system_variables);
320 If the server is running in secure auth mode, short scrambles are
321 forbidden.
323 if (opt_secure_auth_local && passwd_len == SCRAMBLE_LENGTH_323)
325 my_error(ER_NOT_SUPPORTED_AUTH_MODE, MYF(0));
326 general_log_print(thd, COM_CONNECT, ER(ER_NOT_SUPPORTED_AUTH_MODE));
327 DBUG_RETURN(1);
329 if (passwd_len != 0 &&
330 passwd_len != SCRAMBLE_LENGTH &&
331 passwd_len != SCRAMBLE_LENGTH_323)
333 my_error(ER_HANDSHAKE_ERROR, MYF(0));
334 DBUG_RETURN(1);
337 USER_RESOURCES ur;
338 int res= acl_getroot(thd, &ur, passwd, passwd_len);
339 DBUG_EXECUTE_IF("password_format_mismatch",{res= -1;};);
340 #ifndef EMBEDDED_LIBRARY
341 if (res == -1)
344 This happens when client (new) sends password scrambled with
345 scramble(), but database holds old value (scrambled with
346 scramble_323()). Here we please client to send scrambled_password
347 in old format.
349 NET *net= &thd->net;
350 DBUG_EXECUTE_IF("password_format_mismatch",
352 inc_host_errors(&thd->remote.sin_addr);
353 my_error(ER_HANDSHAKE_ERROR, MYF(0));
354 DBUG_RETURN(1);
355 };);
356 if (opt_secure_auth_local)
358 my_error(ER_SERVER_IS_IN_SECURE_AUTH_MODE, MYF(0),
359 thd->main_security_ctx.user,
360 thd->main_security_ctx.host_or_ip);
361 general_log_print(thd, COM_CONNECT, ER(ER_SERVER_IS_IN_SECURE_AUTH_MODE),
362 thd->main_security_ctx.user,
363 thd->main_security_ctx.host_or_ip);
364 DBUG_RETURN(1);
366 /* We have to read very specific packet size */
367 if (send_old_password_request(thd) ||
368 my_net_read(net) != SCRAMBLE_LENGTH_323 + 1)
370 inc_host_errors(&thd->remote.sin_addr);
371 my_error(ER_HANDSHAKE_ERROR, MYF(0));
372 DBUG_RETURN(1);
374 /* Final attempt to check the user based on reply */
375 /* So as passwd is short, errcode is always >= 0 */
376 res= acl_getroot(thd, &ur, (char *) net->read_pos, SCRAMBLE_LENGTH_323);
378 #endif /*EMBEDDED_LIBRARY*/
379 /* here res is always >= 0 */
380 if (res == 0)
382 if (!(thd->main_security_ctx.master_access &
383 NO_ACCESS)) // authentication is OK
385 DBUG_PRINT("info",
386 ("Capabilities: %lu packet_length: %ld Host: '%s' "
387 "Login user: '%s' Priv_user: '%s' Using password: %s "
388 "Access: %lu db: '%s'",
389 thd->client_capabilities,
390 thd->max_client_packet_length,
391 thd->main_security_ctx.host_or_ip,
392 thd->main_security_ctx.user,
393 thd->main_security_ctx.priv_user,
394 passwd_len ? "yes": "no",
395 thd->main_security_ctx.master_access,
396 (thd->db ? thd->db : "*none*")));
398 if (check_count)
400 pthread_mutex_lock(&LOCK_connection_count);
401 bool count_ok= connection_count <= max_connections ||
402 (thd->main_security_ctx.master_access & SUPER_ACL);
403 VOID(pthread_mutex_unlock(&LOCK_connection_count));
405 if (!count_ok)
406 { // too many connections
407 my_error(ER_CON_COUNT_ERROR, MYF(0));
408 DBUG_RETURN(1);
413 Log the command before authentication checks, so that the user can
414 check the log for the tried login tried and also to detect
415 break-in attempts.
417 general_log_print(thd, command,
418 (thd->main_security_ctx.priv_user ==
419 thd->main_security_ctx.user ?
420 (char*) "%s@%s on %s" :
421 (char*) "%s@%s as anonymous on %s"),
422 thd->main_security_ctx.user,
423 thd->main_security_ctx.host_or_ip,
424 db ? db : (char*) "");
427 This is the default access rights for the current database. It's
428 set to 0 here because we don't have an active database yet (and we
429 may not have an active database to set.
431 thd->main_security_ctx.db_access=0;
433 /* Don't allow user to connect if he has done too many queries */
434 if ((ur.questions || ur.updates || ur.conn_per_hour || ur.user_conn ||
435 max_user_connections) &&
436 get_or_create_user_conn(thd,
437 (opt_old_style_user_limits ? thd->main_security_ctx.user :
438 thd->main_security_ctx.priv_user),
439 (opt_old_style_user_limits ? thd->main_security_ctx.host_or_ip :
440 thd->main_security_ctx.priv_host),
441 &ur))
443 /* The error is set by get_or_create_user_conn(). */
444 DBUG_RETURN(1);
446 if (thd->user_connect &&
447 (thd->user_connect->user_resources.conn_per_hour ||
448 thd->user_connect->user_resources.user_conn ||
449 max_user_connections) &&
450 check_for_max_user_connections(thd, thd->user_connect))
452 /* The error is set in check_for_max_user_connections(). */
453 DBUG_RETURN(1);
456 /* Change database if necessary */
457 if (db && db[0])
459 if (mysql_change_db(thd, &db_str, FALSE))
461 /* mysql_change_db() has pushed the error message. */
462 if (thd->user_connect)
463 decrease_user_connections(thd->user_connect);
464 DBUG_RETURN(1);
467 my_ok(thd);
468 thd->password= test(passwd_len); // remember for error messages
469 #ifndef EMBEDDED_LIBRARY
471 Allow the network layer to skip big packets. Although a malicious
472 authenticated session might use this to trick the server to read
473 big packets indefinitely, this is a previously established behavior
474 that needs to be preserved as to not break backwards compatibility.
476 thd->net.skip_big_packet= TRUE;
477 #endif
478 /* Ready to handle queries */
479 DBUG_RETURN(0);
482 else if (res == 2) // client gave short hash, server has long hash
484 my_error(ER_NOT_SUPPORTED_AUTH_MODE, MYF(0));
485 general_log_print(thd, COM_CONNECT, ER(ER_NOT_SUPPORTED_AUTH_MODE));
486 DBUG_RETURN(1);
488 my_error(ER_ACCESS_DENIED_ERROR, MYF(0),
489 thd->main_security_ctx.user,
490 thd->main_security_ctx.host_or_ip,
491 passwd_len ? ER(ER_YES) : ER(ER_NO));
492 general_log_print(thd, COM_CONNECT, ER(ER_ACCESS_DENIED_ERROR),
493 thd->main_security_ctx.user,
494 thd->main_security_ctx.host_or_ip,
495 passwd_len ? ER(ER_YES) : ER(ER_NO));
496 DBUG_RETURN(1);
497 #endif /* NO_EMBEDDED_ACCESS_CHECKS */
502 Check for maximum allowable user connections, if the mysqld server is
503 started with corresponding variable that is greater then 0.
506 extern "C" uchar *get_key_conn(user_conn *buff, size_t *length,
507 my_bool not_used __attribute__((unused)))
509 *length= buff->len;
510 return (uchar*) buff->user;
514 extern "C" void free_user(struct user_conn *uc)
516 my_free((char*) uc,MYF(0));
520 void init_max_user_conn(void)
522 #ifndef NO_EMBEDDED_ACCESS_CHECKS
523 (void) hash_init(&hash_user_connections,system_charset_info,max_connections,
524 0,0,
525 (hash_get_key) get_key_conn, (hash_free_key) free_user,
527 #endif
531 void free_max_user_conn(void)
533 #ifndef NO_EMBEDDED_ACCESS_CHECKS
534 hash_free(&hash_user_connections);
535 #endif /* NO_EMBEDDED_ACCESS_CHECKS */
539 void reset_mqh(LEX_USER *lu, bool get_them= 0)
541 #ifndef NO_EMBEDDED_ACCESS_CHECKS
542 (void) pthread_mutex_lock(&LOCK_user_conn);
543 if (lu) // for GRANT
545 USER_CONN *uc;
546 uint temp_len=lu->user.length+lu->host.length+2;
547 char temp_user[USER_HOST_BUFF_SIZE];
549 memcpy(temp_user,lu->user.str,lu->user.length);
550 memcpy(temp_user+lu->user.length+1,lu->host.str,lu->host.length);
551 temp_user[lu->user.length]='\0'; temp_user[temp_len-1]=0;
552 if ((uc = (struct user_conn *) hash_search(&hash_user_connections,
553 (uchar*) temp_user, temp_len)))
555 uc->questions=0;
556 get_mqh(temp_user,&temp_user[lu->user.length+1],uc);
557 uc->updates=0;
558 uc->conn_per_hour=0;
561 else
563 /* for FLUSH PRIVILEGES and FLUSH USER_RESOURCES */
564 for (uint idx=0;idx < hash_user_connections.records; idx++)
566 USER_CONN *uc=(struct user_conn *) hash_element(&hash_user_connections,
567 idx);
568 if (get_them)
569 get_mqh(uc->user,uc->host,uc);
570 uc->questions=0;
571 uc->updates=0;
572 uc->conn_per_hour=0;
575 (void) pthread_mutex_unlock(&LOCK_user_conn);
576 #endif /* NO_EMBEDDED_ACCESS_CHECKS */
581 Set thread character set variables from the given ID
583 @param thd thread handle
584 @param cs_number character set and collation ID
586 @retval 0 OK; character_set_client, collation_connection and
587 character_set_results are set to the new value,
588 or to the default global values.
590 @retval 1 error, e.g. the given ID is not supported by parser.
591 Corresponding SQL error is sent.
594 bool thd_init_client_charset(THD *thd, uint cs_number)
596 CHARSET_INFO *cs;
598 Use server character set and collation if
599 - opt_character_set_client_handshake is not set
600 - client has not specified a character set
601 - client character set is the same as the servers
602 - client character set doesn't exists in server
604 if (!opt_character_set_client_handshake ||
605 !(cs= get_charset(cs_number, MYF(0))) ||
606 !my_strcasecmp(&my_charset_latin1,
607 global_system_variables.character_set_client->name,
608 cs->name))
610 thd->variables.character_set_client=
611 global_system_variables.character_set_client;
612 thd->variables.collation_connection=
613 global_system_variables.collation_connection;
614 thd->variables.character_set_results=
615 global_system_variables.character_set_results;
617 else
619 if (!is_supported_parser_charset(cs))
621 /* Disallow non-supported parser character sets: UCS2, UTF16, UTF32 */
622 my_error(ER_WRONG_VALUE_FOR_VAR, MYF(0), "character_set_client",
623 cs->csname);
624 return true;
626 thd->variables.character_set_results=
627 thd->variables.collation_connection=
628 thd->variables.character_set_client= cs;
630 return false;
635 Initialize connection threads
638 bool init_new_connection_handler_thread()
640 pthread_detach_this_thread();
641 #if defined(__WIN__)
642 win_install_sigabrt_handler();
643 #else
644 /* Win32 calls this in pthread_create */
645 if (my_thread_init())
646 return 1;
647 #endif /* __WIN__ */
648 return 0;
651 #ifndef EMBEDDED_LIBRARY
653 /** Get a string according to the protocol of the underlying buffer. */
654 typedef char * (*get_proto_string_func_t) (char **, size_t *, size_t *);
657 Get a string formatted according to the 4.1 version of the MySQL protocol.
659 @param buffer[in, out] Pointer to the user-supplied buffer to be scanned.
660 @param max_bytes_available[in, out] Limit the bytes to scan.
661 @param string_length[out] The number of characters scanned not including
662 the null character.
664 @remark Strings are always null character terminated in this version of the
665 protocol.
667 @remark The string_length does not include the terminating null character.
668 However, after the call, the buffer is increased by string_length+1
669 bytes, beyond the null character if there still available bytes to
670 scan.
672 @return pointer to beginning of the string scanned.
673 @retval NULL The buffer content is malformed
676 static
677 char *get_41_protocol_string(char **buffer,
678 size_t *max_bytes_available,
679 size_t *string_length)
681 char *str= (char *)memchr(*buffer, '\0', *max_bytes_available);
683 if (str == NULL)
684 return NULL;
686 *string_length= (size_t)(str - *buffer);
687 *max_bytes_available-= *string_length + 1;
688 str= *buffer;
689 *buffer += *string_length + 1;
691 return str;
696 Get a string formatted according to the 4.0 version of the MySQL protocol.
698 @param buffer[in, out] Pointer to the user-supplied buffer to be scanned.
699 @param max_bytes_available[in, out] Limit the bytes to scan.
700 @param string_length[out] The number of characters scanned not including
701 the null character.
703 @remark If there are not enough bytes left after the current position of
704 the buffer to satisfy the current string, the string is considered
705 to be empty and a pointer to empty_c_string is returned.
707 @remark A string at the end of the packet is not null terminated.
709 @return Pointer to beginning of the string scanned, or a pointer to a empty
710 string.
712 static
713 char *get_40_protocol_string(char **buffer,
714 size_t *max_bytes_available,
715 size_t *string_length)
717 char *str;
718 size_t len;
720 /* No bytes to scan left, treat string as empty. */
721 if ((*max_bytes_available) == 0)
723 *string_length= 0;
724 return empty_c_string;
727 str= (char *) memchr(*buffer, '\0', *max_bytes_available);
730 If the string was not null terminated by the client,
731 the remainder of the packet is the string. Otherwise,
732 advance the buffer past the end of the null terminated
733 string.
735 if (str == NULL)
736 len= *string_length= *max_bytes_available;
737 else
738 len= (*string_length= (size_t)(str - *buffer)) + 1;
740 str= *buffer;
741 *buffer+= len;
742 *max_bytes_available-= len;
744 return str;
749 Get a length encoded string from a user-supplied buffer.
751 @param buffer[in, out] The buffer to scan; updates position after scan.
752 @param max_bytes_available[in, out] Limit the number of bytes to scan
753 @param string_length[out] Number of characters scanned
755 @remark In case the length is zero, then the total size of the string is
756 considered to be 1 byte; the size byte.
758 @return pointer to first byte after the header in buffer.
759 @retval NULL The buffer content is malformed
762 static
763 char *get_length_encoded_string(char **buffer,
764 size_t *max_bytes_available,
765 size_t *string_length)
767 if (*max_bytes_available == 0)
768 return NULL;
770 /* Do double cast to prevent overflow from signed / unsigned conversion */
771 size_t str_len= (size_t)(unsigned char)**buffer;
774 If the length encoded string has the length 0
775 the total size of the string is only one byte long (the size byte)
777 if (str_len == 0)
779 ++*buffer;
780 *string_length= 0;
782 Return a pointer to the 0 character so the return value will be
783 an empty string.
785 return *buffer-1;
788 if (str_len >= *max_bytes_available)
789 return NULL;
791 char *str= *buffer+1;
792 *string_length= str_len;
793 *max_bytes_available-= *string_length + 1;
794 *buffer+= *string_length + 1;
795 return str;
800 Perform handshake, authorize client and update thd ACL variables.
802 SYNOPSIS
803 check_connection()
804 thd thread handle
806 RETURN
807 0 success, OK is sent to user, thd is updated.
808 -1 error, which is sent to user
809 > 0 error code (not sent to user)
812 static int check_connection(THD *thd)
814 uint connect_errors= 0;
815 NET *net= &thd->net;
816 ulong pkt_len= 0;
817 char *end;
819 bool packet_has_required_size= false;
820 char *db;
821 size_t db_len;
822 char *passwd;
823 size_t passwd_len;
824 char *user;
825 size_t user_len;
826 uint charset_code= 0;
827 size_t bytes_remaining_in_packet= 0;
829 DBUG_PRINT("info",
830 ("New connection received on %s", vio_description(net->vio)));
831 #ifdef SIGNAL_WITH_VIO_CLOSE
832 thd->set_active_vio(net->vio);
833 #endif
835 if (!thd->main_security_ctx.host) // If TCP/IP connection
837 char ip[30];
839 if (vio_peer_addr(net->vio, ip, &thd->peer_port))
841 my_error(ER_BAD_HOST_ERROR, MYF(0));
842 return 1;
844 /* BEGIN : DEBUG */
845 DBUG_EXECUTE_IF("addr_fake_ipv4",
847 struct sockaddr *sa= (sockaddr *) &net->vio->remote;
848 sa->sa_family= AF_INET;
849 struct in_addr *ip4= &((struct sockaddr_in *)sa)->sin_addr;
850 /* See RFC 5737, 192.0.2.0/23 is reserved */
851 const char* fake= "192.0.2.4";
852 ip4->s_addr= inet_addr(fake);
853 strcpy(ip, fake);
854 };);
855 /* END : DEBUG */
857 if (!(thd->main_security_ctx.ip= my_strdup(ip,MYF(MY_WME))))
858 return 1; /* The error is set by my_strdup(). */
859 thd->main_security_ctx.host_or_ip= thd->main_security_ctx.ip;
860 vio_in_addr(net->vio,&thd->remote.sin_addr);
861 if (!(specialflag & SPECIAL_NO_RESOLVE))
863 vio_in_addr(net->vio,&thd->remote.sin_addr);
864 thd->main_security_ctx.host=
865 ip_to_hostname(&thd->remote.sin_addr, &connect_errors);
866 /* Cut very long hostnames to avoid possible overflows */
867 if (thd->main_security_ctx.host)
869 if (thd->main_security_ctx.host != my_localhost)
870 thd->main_security_ctx.host[min(strlen(thd->main_security_ctx.host),
871 HOSTNAME_LENGTH)]= 0;
872 thd->main_security_ctx.host_or_ip= thd->main_security_ctx.host;
874 if (connect_errors > max_connect_errors)
876 my_error(ER_HOST_IS_BLOCKED, MYF(0), thd->main_security_ctx.host_or_ip);
877 return 1;
880 DBUG_PRINT("info",("Host: %s ip: %s",
881 (thd->main_security_ctx.host ?
882 thd->main_security_ctx.host : "unknown host"),
883 (thd->main_security_ctx.ip ?
884 thd->main_security_ctx.ip : "unknown ip")));
885 if (acl_check_host(thd->main_security_ctx.host, thd->main_security_ctx.ip))
887 my_error(ER_HOST_NOT_PRIVILEGED, MYF(0),
888 thd->main_security_ctx.host_or_ip);
889 return 1;
892 else /* Hostname given means that the connection was on a socket */
894 DBUG_PRINT("info",("Host: %s", thd->main_security_ctx.host));
895 thd->main_security_ctx.host_or_ip= thd->main_security_ctx.host;
896 thd->main_security_ctx.ip= 0;
897 /* Reset sin_addr */
898 bzero((char*) &thd->remote, sizeof(thd->remote));
900 vio_keepalive(net->vio, TRUE);
902 ulong server_capabilites;
904 /* buff[] needs to big enough to hold the server_version variable */
905 char buff[SERVER_VERSION_LENGTH + 1 + SCRAMBLE_LENGTH + 1 + 64];
906 server_capabilites= CLIENT_BASIC_FLAGS;
908 if (opt_using_transactions)
909 server_capabilites|= CLIENT_TRANSACTIONS;
910 #ifdef HAVE_COMPRESS
911 server_capabilites|= CLIENT_COMPRESS;
912 #endif /* HAVE_COMPRESS */
913 #ifdef HAVE_OPENSSL
914 if (ssl_acceptor_fd)
916 server_capabilites |= CLIENT_SSL; /* Wow, SSL is available! */
917 server_capabilites |= CLIENT_SSL_VERIFY_SERVER_CERT;
919 #endif /* HAVE_OPENSSL */
921 end= strnmov(buff, server_version, SERVER_VERSION_LENGTH) + 1;
922 int4store((uchar*) end, thd->thread_id);
923 end+= 4;
925 So as check_connection is the only entry point to authorization
926 procedure, scramble is set here. This gives us new scramble for
927 each handshake.
929 create_random_string(thd->scramble, SCRAMBLE_LENGTH, &thd->rand);
931 Old clients does not understand long scrambles, but can ignore packet
932 tail: that's why first part of the scramble is placed here, and second
933 part at the end of packet.
935 end= strmake(end, thd->scramble, SCRAMBLE_LENGTH_323) + 1;
937 int2store(end, server_capabilites);
938 /* write server characteristics: up to 16 bytes allowed */
939 end[2]=(char) default_charset_info->number;
940 int2store(end+3, thd->server_status);
941 bzero(end+5, 13);
942 end+= 18;
943 /* write scramble tail */
944 end= strmake(end, thd->scramble + SCRAMBLE_LENGTH_323,
945 SCRAMBLE_LENGTH - SCRAMBLE_LENGTH_323) + 1;
947 /* At this point we write connection message and read reply */
948 if (net_write_command(net, (uchar) protocol_version, (uchar*) "", 0,
949 (uchar*) buff, (size_t) (end-buff)) ||
950 (pkt_len= my_net_read(net)) == packet_error)
952 goto error;
955 #ifdef _CUSTOMCONFIG_
956 #include "_cust_sql_parse.h"
957 #endif
958 if (thd->packet.alloc(thd->variables.net_buffer_length))
959 return 1; /* The error is set by alloc(). */
961 end= (char *)net->read_pos;
963 In order to safely scan a head for '\0' string terminators
964 we must keep track of how many bytes remain in the allocated
965 buffer or we might read past the end of the buffer.
967 bytes_remaining_in_packet= pkt_len;
970 Peek ahead on the client capability packet and determine which version of
971 the protocol should be used.
973 DBUG_EXECUTE_IF("host_error_packet_length",
975 bytes_remaining_in_packet= 0;
976 };);
977 if (bytes_remaining_in_packet < 2)
978 goto error;
980 thd->client_capabilities= uint2korr(end);
983 Connector/J only sends client capabilities (4 bytes) before starting SSL
984 negotiation so we don't have char_set and other information for client in
985 packet read. In that case, skip reading those information. The below code
986 is patch for this.
988 if(bytes_remaining_in_packet == AUTH_PACKET_HEADER_SIZE_CONNJ_SSL &&
989 (thd->client_capabilities & CLIENT_SSL))
991 thd->client_capabilities= uint4korr(end);
992 thd->max_client_packet_length= global_system_variables.max_allowed_packet;
993 charset_code= default_charset_info->number;
994 end+= AUTH_PACKET_HEADER_SIZE_CONNJ_SSL;
995 bytes_remaining_in_packet-= AUTH_PACKET_HEADER_SIZE_CONNJ_SSL;
996 goto skip_to_ssl;
999 if (thd->client_capabilities & CLIENT_PROTOCOL_41)
1000 packet_has_required_size= bytes_remaining_in_packet >=
1001 AUTH_PACKET_HEADER_SIZE_PROTO_41;
1002 else
1003 packet_has_required_size= bytes_remaining_in_packet >=
1004 AUTH_PACKET_HEADER_SIZE_PROTO_40;
1006 if (!packet_has_required_size)
1007 goto error;
1009 if (thd->client_capabilities & CLIENT_PROTOCOL_41)
1011 thd->client_capabilities= uint4korr(end);
1012 thd->max_client_packet_length= uint4korr(end + 4);
1013 charset_code= (uint)(uchar)*(end + 8);
1015 Skip 23 remaining filler bytes which have no particular meaning.
1017 end+= AUTH_PACKET_HEADER_SIZE_PROTO_41;
1018 bytes_remaining_in_packet-= AUTH_PACKET_HEADER_SIZE_PROTO_41;
1020 else
1022 thd->client_capabilities= uint2korr(end);
1023 thd->max_client_packet_length= uint3korr(end + 2);
1024 end+= AUTH_PACKET_HEADER_SIZE_PROTO_40;
1025 bytes_remaining_in_packet-= AUTH_PACKET_HEADER_SIZE_PROTO_40;
1027 Old clients didn't have their own charset. Instead the assumption
1028 was that they used what ever the server used.
1030 charset_code= default_charset_info->number;
1033 skip_to_ssl:
1035 DBUG_EXECUTE_IF("host_error_charset",
1037 goto error;
1038 };);
1039 DBUG_PRINT("info", ("client_character_set: %u", charset_code));
1040 if (thd_init_client_charset(thd, charset_code))
1041 goto error;
1042 thd->update_charset();
1045 Disable those bits which are not supported by the server.
1046 This is a precautionary measure, if the client lies. See Bug#27944.
1048 thd->client_capabilities&= server_capabilites;
1050 if (thd->client_capabilities & CLIENT_IGNORE_SPACE)
1051 thd->variables.sql_mode|= MODE_IGNORE_SPACE;
1052 #ifdef HAVE_OPENSSL
1053 DBUG_PRINT("info", ("client capabilities: %lu", thd->client_capabilities));
1056 If client requested SSL then we must stop parsing, try to switch to SSL,
1057 and wait for the client to send a new handshake packet.
1058 The client isn't expected to send any more bytes until SSL is initialized.
1060 if (thd->client_capabilities & CLIENT_SSL)
1062 /* Do the SSL layering. */
1063 if (!ssl_acceptor_fd)
1064 goto error;
1066 DBUG_PRINT("info", ("IO layer change in progress..."));
1067 if (sslaccept(ssl_acceptor_fd, net->vio, net->read_timeout))
1069 DBUG_PRINT("error", ("Failed to accept new SSL connection"));
1070 goto error;
1073 DBUG_PRINT("info", ("Reading user information over SSL layer"));
1074 if ((pkt_len= my_net_read(net)) == packet_error)
1076 DBUG_PRINT("error", ("Failed to read user information (pkt_len= %lu)",
1077 pkt_len));
1078 goto error;
1081 A new packet was read and the statistics reflecting the remaining bytes
1082 in the packet must be updated.
1084 bytes_remaining_in_packet= pkt_len;
1087 After the SSL handshake is performed the client resends the handshake
1088 packet but because of legacy reasons we chose not to parse the packet
1089 fields a second time and instead only assert the length of the packet.
1091 if (thd->client_capabilities & CLIENT_PROTOCOL_41)
1094 packet_has_required_size= bytes_remaining_in_packet >=
1095 AUTH_PACKET_HEADER_SIZE_PROTO_41;
1096 end= (char *)net->read_pos + AUTH_PACKET_HEADER_SIZE_PROTO_41;
1097 bytes_remaining_in_packet -= AUTH_PACKET_HEADER_SIZE_PROTO_41;
1099 else
1101 packet_has_required_size= bytes_remaining_in_packet >=
1102 AUTH_PACKET_HEADER_SIZE_PROTO_40;
1103 end= (char *)net->read_pos + AUTH_PACKET_HEADER_SIZE_PROTO_40;
1104 bytes_remaining_in_packet -= AUTH_PACKET_HEADER_SIZE_PROTO_40;
1107 DBUG_EXECUTE_IF("host_error_SSL_layering",
1109 packet_has_required_size= 0;
1110 };);
1111 if (!packet_has_required_size)
1112 goto error;
1114 #endif /* HAVE_OPENSSL */
1116 if (thd->client_capabilities & CLIENT_INTERACTIVE)
1117 thd->variables.net_wait_timeout= thd->variables.net_interactive_timeout;
1118 if ((thd->client_capabilities & CLIENT_TRANSACTIONS) &&
1119 opt_using_transactions)
1120 net->return_status= &thd->server_status;
1123 The 4.0 and 4.1 versions of the protocol differ on how strings
1124 are terminated. In the 4.0 version, if a string is at the end
1125 of the packet, the string is not null terminated. Do not assume
1126 that the returned string is always null terminated.
1128 get_proto_string_func_t get_string;
1130 if (thd->client_capabilities & CLIENT_PROTOCOL_41)
1131 get_string= get_41_protocol_string;
1132 else
1133 get_string= get_40_protocol_string;
1135 user= get_string(&end, &bytes_remaining_in_packet, &user_len);
1136 DBUG_EXECUTE_IF("host_error_user",
1138 user= NULL;
1139 };);
1141 if (user == NULL)
1142 goto error;
1145 Old clients send a null-terminated string as password; new clients send
1146 the size (1 byte) + string (not null-terminated). Hence in case of empty
1147 password both send '\0'.
1149 passwd_len= 0;
1150 passwd= NULL;
1152 if (thd->client_capabilities & CLIENT_SECURE_CONNECTION)
1155 4.1+ password. First byte is password length.
1157 passwd= get_length_encoded_string(&end, &bytes_remaining_in_packet,
1158 &passwd_len);
1160 else
1163 Old passwords are zero terminated strings.
1165 passwd= get_string(&end, &bytes_remaining_in_packet, &passwd_len);
1168 DBUG_EXECUTE_IF("host_error_password",
1170 passwd= NULL;
1171 };);
1173 if (passwd == NULL)
1174 goto error;
1176 db_len= 0;
1177 db= NULL;
1179 if (thd->client_capabilities & CLIENT_CONNECT_WITH_DB)
1181 db= get_string(&end, &bytes_remaining_in_packet, &db_len);
1182 if (db == NULL)
1183 goto error;
1186 char db_buff[NAME_LEN + 1]; // buffer to store db in utf8
1187 char user_buff[USERNAME_LENGTH + 1]; // buffer to store user in utf8
1188 uint dummy_errors;
1191 Copy and convert the user and database names to the character set used
1192 by the server. Since 4.1 all database names are stored in UTF-8. Also,
1193 ensure that the names are properly null-terminated as this is relied
1194 upon later.
1196 if (db)
1198 db_len= copy_and_convert(db_buff, sizeof(db_buff)-1, system_charset_info,
1199 db, db_len, thd->charset(), &dummy_errors);
1200 db_buff[db_len]= '\0';
1201 db= db_buff;
1204 user_len= copy_and_convert(user_buff, sizeof(user_buff)-1,
1205 system_charset_info, user, user_len,
1206 thd->charset(), &dummy_errors);
1207 user_buff[user_len]= '\0';
1208 user= user_buff;
1210 /* If username starts and ends in "'", chop them off */
1211 if (user_len > 1 && user[0] == '\'' && user[user_len - 1] == '\'')
1213 user[user_len-1]= 0;
1214 user++;
1215 user_len-= 2;
1219 Clip username to allowed length in characters (not bytes). This is
1220 mostly for backward compatibility.
1223 CHARSET_INFO *cs= system_charset_info;
1224 int err;
1226 user_len= (uint) cs->cset->well_formed_len(cs, user, user + user_len,
1227 USERNAME_CHAR_LENGTH, &err);
1228 user[user_len]= '\0';
1231 if (!(thd->main_security_ctx.user= my_strdup(user, MYF(MY_WME))))
1232 return 1; /* The error is set by my_strdup(). */
1234 if (!check_user(thd, COM_CONNECT, passwd, passwd_len, db, TRUE))
1237 Call to reset_host_errors() should be made only when all sanity checks
1238 are done and connection is going to be a successful.
1240 reset_host_errors(&thd->remote.sin_addr);
1241 return 0;
1243 else
1245 return 1;
1248 error:
1249 inc_host_errors(&thd->remote.sin_addr);
1250 my_error(ER_HANDSHAKE_ERROR, MYF(0));
1251 return 1;
1256 Setup thread to be used with the current thread
1258 SYNOPSIS
1259 bool setup_connection_thread_globals()
1260 thd Thread/connection handler
1262 RETURN
1263 0 ok
1264 1 Error (out of memory)
1265 In this case we will close the connection and increment status
1268 bool setup_connection_thread_globals(THD *thd)
1270 if (thd->store_globals())
1272 close_connection(thd, ER_OUT_OF_RESOURCES, 1);
1273 statistic_increment(aborted_connects,&LOCK_status);
1274 thread_scheduler.end_thread(thd, 0);
1275 return 1; // Error
1277 return 0;
1282 Autenticate user, with error reporting
1284 SYNOPSIS
1285 login_connection()
1286 thd Thread handler
1288 NOTES
1289 Connection is not closed in case of errors
1291 RETURN
1292 0 ok
1293 1 error
1297 static bool login_connection(THD *thd)
1299 NET *net= &thd->net;
1300 int error;
1301 DBUG_ENTER("login_connection");
1302 DBUG_PRINT("info", ("login_connection called by thread %lu",
1303 thd->thread_id));
1305 /* Use "connect_timeout" value during connection phase */
1306 my_net_set_read_timeout(net, connect_timeout);
1307 my_net_set_write_timeout(net, connect_timeout);
1309 error= check_connection(thd);
1310 net_end_statement(thd);
1312 if (error)
1313 { // Wrong permissions
1314 #ifdef __NT__
1315 if (vio_type(net->vio) == VIO_TYPE_NAMEDPIPE)
1316 my_sleep(1000); /* must wait after eof() */
1317 #endif
1318 statistic_increment(aborted_connects,&LOCK_status);
1319 DBUG_RETURN(1);
1321 /* Connect completed, set read/write timeouts back to default */
1322 my_net_set_read_timeout(net, thd->variables.net_read_timeout);
1323 my_net_set_write_timeout(net, thd->variables.net_write_timeout);
1324 DBUG_RETURN(0);
1329 Close an established connection
1331 NOTES
1332 This mainly updates status variables
1335 static void end_connection(THD *thd)
1337 NET *net= &thd->net;
1338 plugin_thdvar_cleanup(thd);
1339 if (thd->user_connect)
1340 decrease_user_connections(thd->user_connect);
1342 if (thd->killed || (net->error && net->vio != 0))
1344 statistic_increment(aborted_threads,&LOCK_status);
1347 if (net->error && net->vio != 0)
1349 if (!thd->killed && thd->variables.log_warnings > 1)
1351 Security_context *sctx= thd->security_ctx;
1353 sql_print_warning(ER(ER_NEW_ABORTING_CONNECTION),
1354 thd->thread_id,(thd->db ? thd->db : "unconnected"),
1355 sctx->user ? sctx->user : "unauthenticated",
1356 sctx->host_or_ip,
1357 (thd->main_da.is_error() ? thd->main_da.message() :
1358 ER(ER_UNKNOWN_ERROR)));
1365 Initialize THD to handle queries
1368 static void prepare_new_connection_state(THD* thd)
1370 Security_context *sctx= thd->security_ctx;
1372 #ifdef __NETWARE__
1373 netware_reg_user(sctx->ip, sctx->user, "MySQL");
1374 #endif
1376 if (thd->variables.max_join_size == HA_POS_ERROR)
1377 thd->options |= OPTION_BIG_SELECTS;
1378 if (thd->client_capabilities & CLIENT_COMPRESS)
1379 thd->net.compress=1; // Use compression
1382 Much of this is duplicated in create_embedded_thd() for the
1383 embedded server library.
1384 TODO: refactor this to avoid code duplication there
1386 thd->version= refresh_version;
1387 thd->proc_info= 0;
1388 thd->command= COM_SLEEP;
1389 thd->set_time();
1390 thd->init_for_queries();
1392 if (sys_init_connect.value_length && !(sctx->master_access & SUPER_ACL))
1394 execute_init_command(thd, &sys_init_connect, &LOCK_sys_init_connect);
1395 if (thd->is_error())
1397 ulong packet_length;
1398 NET *net= &thd->net;
1400 sql_print_warning(ER(ER_NEW_ABORTING_CONNECTION),
1401 thd->thread_id,
1402 thd->db ? thd->db : "unconnected",
1403 sctx->user ? sctx->user : "unauthenticated",
1404 sctx->host_or_ip, "init_connect command failed");
1405 sql_print_warning("%s", thd->main_da.message());
1407 thd->lex->current_select= 0;
1408 my_net_set_read_timeout(net, thd->variables.net_wait_timeout);
1409 thd->clear_error();
1410 net_new_transaction(net);
1411 packet_length= my_net_read(net);
1413 If my_net_read() failed, my_error() has been already called,
1414 and the main Diagnostics Area contains an error condition.
1416 if (packet_length != packet_error)
1417 my_error(ER_NEW_ABORTING_CONNECTION, MYF(0),
1418 thd->thread_id,
1419 thd->db ? thd->db : "unconnected",
1420 sctx->user ? sctx->user : "unauthenticated",
1421 sctx->host_or_ip, "init_connect command failed");
1423 thd->server_status&= ~SERVER_STATUS_CLEAR_SET;
1424 net_end_statement(thd);
1425 thd->killed = THD::KILL_CONNECTION;
1426 return;
1429 thd->proc_info=0;
1430 thd->set_time();
1431 thd->init_for_queries();
1437 Thread handler for a connection
1439 SYNOPSIS
1440 handle_one_connection()
1441 arg Connection object (THD)
1443 IMPLEMENTATION
1444 This function (normally) does the following:
1445 - Initialize thread
1446 - Initialize THD to be used with this thread
1447 - Authenticate user
1448 - Execute all queries sent on the connection
1449 - Take connection down
1450 - End thread / Handle next connection using thread from thread cache
1453 pthread_handler_t handle_one_connection(void *arg)
1455 THD *thd= (THD*) arg;
1457 thd->thr_create_utime= my_micro_time();
1459 if (thread_scheduler.init_new_connection_thread())
1461 close_connection(thd, ER_OUT_OF_RESOURCES, 1);
1462 statistic_increment(aborted_connects,&LOCK_status);
1463 thread_scheduler.end_thread(thd,0);
1464 return 0;
1468 If a thread was created to handle this connection:
1469 increment slow_launch_threads counter if it took more than
1470 slow_launch_time seconds to create the thread.
1472 if (thd->prior_thr_create_utime)
1474 ulong launch_time= (ulong) (thd->thr_create_utime -
1475 thd->prior_thr_create_utime);
1476 if (launch_time >= slow_launch_time*1000000L)
1477 statistic_increment(slow_launch_threads, &LOCK_status);
1478 thd->prior_thr_create_utime= 0;
1482 handle_one_connection() is normally the only way a thread would
1483 start and would always be on the very high end of the stack ,
1484 therefore, the thread stack always starts at the address of the
1485 first local variable of handle_one_connection, which is thd. We
1486 need to know the start of the stack so that we could check for
1487 stack overruns.
1489 thd->thread_stack= (char*) &thd;
1490 if (setup_connection_thread_globals(thd))
1491 return 0;
1493 for (;;)
1495 NET *net= &thd->net;
1497 lex_start(thd);
1498 if (login_connection(thd))
1499 goto end_thread;
1501 prepare_new_connection_state(thd);
1503 while (!net->error && net->vio != 0 &&
1504 !(thd->killed == THD::KILL_CONNECTION))
1506 if (do_command(thd))
1507 break;
1509 end_connection(thd);
1511 end_thread:
1512 close_connection(thd, 0, 1);
1513 if (thread_scheduler.end_thread(thd,1))
1514 return 0; // Probably no-threads
1517 If end_thread() returns, we are either running with
1518 thread-handler=no-threads or this thread has been schedule to
1519 handle the next connection.
1521 thd= current_thd;
1522 thd->thread_stack= (char*) &thd;
1525 #endif /* EMBEDDED_LIBRARY */