1
/* Copyright (C) 2007 MySQL AB
3
This program is free software; you can redistribute it and/or modify
4
it under the terms of the GNU General Public License as published by
5
the Free Software Foundation; version 2 of the License.
7
This program is distributed in the hope that it will be useful,
8
but WITHOUT ANY WARRANTY; without even the implied warranty of
9
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
10
GNU General Public License for more details.
12
You should have received a copy of the GNU General Public License
13
along with this program; if not, write to the Free Software
14
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */
18
Functions to autenticate and handle reqests for a connection
21
#include "mysql_priv.h"
23
#define MIN_HANDSHAKE_SIZE 6
26
Get structure for logging connection data for the current user
29
char *ip_to_hostname(struct sockaddr_storage *in, int addrLen)
34
char hostname_buff[NI_MAXHOST];
36
/* Historical comparison for 127.0.0.1 */
37
gxi_error= getnameinfo((struct sockaddr *)in, addrLen,
38
hostname_buff, NI_MAXHOST,
39
NULL, 0, NI_NUMERICHOST);
42
DBUG_PRINT("error",("getnameinfo returned %d", gxi_error));
45
DBUG_PRINT("info",("resolved: %s", hostname_buff));
47
if (!(name= my_strdup(hostname_buff, MYF(0))))
49
DBUG_PRINT("error",("out of memory"));
57
Check if user exist and password supplied is correct.
59
@param thd thread handle, thd->security_ctx->{host,user,ip} are used
60
@param command originator of the check: now check_user is called
61
during connect and change user procedures; used for
63
@param passwd scrambled password received from client
64
@param passwd_len length of scrambled password
65
@param db database name to connect to, may be NULL
66
@param check_count TRUE if establishing a new connection. In this case
67
check that we have not exceeded the global
68
max_connections limist
70
@note Host, user and passwd may point to communication buffer.
71
Current implementation does not depend on that, but future changes
72
should be done with this in mind; 'thd' is INOUT, all other params
75
@retval 0 OK; thd->security_ctx->user/master_access/priv_user/db_access and
76
thd->db are updated; OK is sent to the client.
77
@retval 1 error, e.g. access denied or handshake error, not sent to
78
the client. A message is pushed into the error stack.
82
check_user(THD *thd, enum enum_server_command command,
83
const char *passwd, uint passwd_len, const char *db,
86
DBUG_ENTER("check_user");
87
LEX_STRING db_str= { (char *) db, db ? strlen(db) : 0 };
90
Clear thd->db as it points to something, that will be freed when
91
connection is closed. We don't want to accidentally free a wrong
92
pointer if connect failed. Also in case of 'CHANGE USER' failure,
93
current database will be switched to 'no database selected'.
95
thd->reset_db(NULL, 0);
97
my_bool opt_secure_auth_local;
98
pthread_mutex_lock(&LOCK_global_system_variables);
99
opt_secure_auth_local= opt_secure_auth;
100
pthread_mutex_unlock(&LOCK_global_system_variables);
103
If the server is running in secure auth mode, short scrambles are
106
if (opt_secure_auth_local && passwd_len == SCRAMBLE_LENGTH_323)
108
my_error(ER_NOT_SUPPORTED_AUTH_MODE, MYF(0));
109
general_log_print(thd, COM_CONNECT, ER(ER_NOT_SUPPORTED_AUTH_MODE));
112
if (passwd_len != 0 &&
113
passwd_len != SCRAMBLE_LENGTH &&
114
passwd_len != SCRAMBLE_LENGTH_323)
116
my_error(ER_HANDSHAKE_ERROR, MYF(0), thd->main_security_ctx.host_or_ip);
121
thd->security_ctx->skip_grants();
122
memset(&ur, 0, sizeof(USER_RESOURCES));
125
("Capabilities: %lu packet_length: %ld Host: '%s' "
126
"Login user: '%s' Priv_user: '%s' Using password: %s "
128
thd->client_capabilities,
129
thd->max_client_packet_length,
130
thd->main_security_ctx.host_or_ip,
131
thd->main_security_ctx.user,
132
thd->main_security_ctx.priv_user,
133
passwd_len ? "yes": "no",
134
(thd->db ? thd->db : "*none*")));
138
pthread_mutex_lock(&LOCK_connection_count);
139
bool count_ok= connection_count <= max_connections;
140
VOID(pthread_mutex_unlock(&LOCK_connection_count));
143
{ // too many connections
144
my_error(ER_CON_COUNT_ERROR, MYF(0));
150
Log the command before authentication checks, so that the user can
151
check the log for the tried login tried and also to detect
154
general_log_print(thd, command,
155
(thd->main_security_ctx.priv_user ==
156
thd->main_security_ctx.user ?
157
(char*) "%s@%s on %s" :
158
(char*) "%s@%s as anonymous on %s"),
159
thd->main_security_ctx.user,
160
thd->main_security_ctx.host_or_ip,
161
db ? db : (char*) "");
164
This is the default access rights for the current database. It's
165
set to 0 here because we don't have an active database yet (and we
166
may not have an active database to set.
168
thd->main_security_ctx.db_access=0;
170
/* Change database if necessary */
173
if (mysql_change_db(thd, &db_str, FALSE))
175
/* mysql_change_db() has pushed the error message. */
180
thd->password= test(passwd_len); // remember for error messages
181
/* Ready to handle queries */
187
Check for maximum allowable user connections, if the mysqld server is
188
started with corresponding variable that is greater then 0.
191
extern "C" uchar *get_key_conn(user_conn *buff, size_t *length,
192
my_bool not_used __attribute__((unused)))
195
return (uchar*) buff->user;
199
extern "C" void free_user(struct user_conn *uc)
201
my_free((char*) uc,MYF(0));
204
void thd_init_client_charset(THD *thd, uint cs_number)
207
Use server character set and collation if
208
- opt_character_set_client_handshake is not set
209
- client has not specified a character set
210
- client character set is the same as the servers
211
- client character set doesn't exists in server
213
if (!opt_character_set_client_handshake ||
214
!(thd->variables.character_set_client= get_charset(cs_number, MYF(0))) ||
215
!my_strcasecmp(&my_charset_latin1,
216
global_system_variables.character_set_client->name,
217
thd->variables.character_set_client->name))
219
thd->variables.character_set_client=
220
global_system_variables.character_set_client;
221
thd->variables.collation_connection=
222
global_system_variables.collation_connection;
223
thd->variables.character_set_results=
224
global_system_variables.character_set_results;
228
thd->variables.character_set_results=
229
thd->variables.collation_connection=
230
thd->variables.character_set_client;
236
Initialize connection threads
239
bool init_new_connection_handler_thread()
241
pthread_detach_this_thread();
242
/* Win32 calls this in pthread_create */
243
if (my_thread_init())
249
Perform handshake, authorize client and update thd ACL variables.
256
0 success, OK is sent to user, thd is updated.
257
-1 error, which is sent to user
258
> 0 error code (not sent to user)
261
static int check_connection(THD *thd)
268
("New connection received on %s", vio_description(net->vio)));
269
#ifdef SIGNAL_WITH_VIO_CLOSE
270
thd->set_active_vio(net->vio);
273
if (!thd->main_security_ctx.host) // If TCP/IP connection
277
if (vio_peer_addr(net->vio, ip, &thd->peer_port, NI_MAXHOST))
279
my_error(ER_BAD_HOST_ERROR, MYF(0), thd->main_security_ctx.host_or_ip);
282
if (!(thd->main_security_ctx.ip= my_strdup(ip,MYF(MY_WME))))
283
return 1; /* The error is set by my_strdup(). */
284
thd->main_security_ctx.host_or_ip= thd->main_security_ctx.ip;
285
thd->main_security_ctx.host= ip_to_hostname(&net->vio->remote,
287
thd->main_security_ctx.host_or_ip= thd->main_security_ctx.host;
288
DBUG_PRINT("info",("Host: %s ip: %s",
289
(thd->main_security_ctx.host ?
290
thd->main_security_ctx.host : "unknown host"),
291
(thd->main_security_ctx.ip ?
292
thd->main_security_ctx.ip : "unknown ip")));
294
else /* Hostname given means that the connection was on a socket */
296
DBUG_PRINT("info",("Host: %s", thd->main_security_ctx.host));
297
thd->main_security_ctx.host_or_ip= thd->main_security_ctx.host;
298
thd->main_security_ctx.ip= 0;
300
bzero((char*) &net->vio->remote, sizeof(net->vio->remote));
302
vio_keepalive(net->vio, TRUE);
304
ulong server_capabilites;
306
/* buff[] needs to big enough to hold the server_version variable */
307
char buff[SERVER_VERSION_LENGTH + SCRAMBLE_LENGTH + 64];
308
server_capabilites= CLIENT_BASIC_FLAGS;
310
if (opt_using_transactions)
311
server_capabilites|= CLIENT_TRANSACTIONS;
313
server_capabilites|= CLIENT_COMPRESS;
314
#endif /* HAVE_COMPRESS */
316
end= strnmov(buff, server_version, SERVER_VERSION_LENGTH) + 1;
317
int4store((uchar*) end, thd->thread_id);
320
So as check_connection is the only entry point to authorization
321
procedure, scramble is set here. This gives us new scramble for
324
create_random_string(thd->scramble, SCRAMBLE_LENGTH, &thd->rand);
326
Old clients does not understand long scrambles, but can ignore packet
327
tail: that's why first part of the scramble is placed here, and second
328
part at the end of packet.
330
end= strmake(end, thd->scramble, SCRAMBLE_LENGTH_323) + 1;
332
int2store(end, server_capabilites);
333
/* write server characteristics: up to 16 bytes allowed */
334
end[2]=(char) default_charset_info->number;
335
int2store(end+3, thd->server_status);
338
/* write scramble tail */
339
end= strmake(end, thd->scramble + SCRAMBLE_LENGTH_323,
340
SCRAMBLE_LENGTH - SCRAMBLE_LENGTH_323) + 1;
342
/* At this point we write connection message and read reply */
343
if (net_write_command(net, (uchar) protocol_version, (uchar*) "", 0,
344
(uchar*) buff, (size_t) (end-buff)) ||
345
(pkt_len= my_net_read(net)) == packet_error ||
346
pkt_len < MIN_HANDSHAKE_SIZE)
348
my_error(ER_HANDSHAKE_ERROR, MYF(0),
349
thd->main_security_ctx.host_or_ip);
353
#ifdef _CUSTOMCONFIG_
354
#include "_cust_sql_parse.h"
356
if (thd->packet.alloc(thd->variables.net_buffer_length))
357
return 1; /* The error is set by alloc(). */
359
thd->client_capabilities= uint2korr(net->read_pos);
360
if (thd->client_capabilities & CLIENT_PROTOCOL_41)
362
thd->client_capabilities|= ((ulong) uint2korr(net->read_pos+2)) << 16;
363
thd->max_client_packet_length= uint4korr(net->read_pos+4);
364
DBUG_PRINT("info", ("client_character_set: %d", (uint) net->read_pos[8]));
365
thd_init_client_charset(thd, (uint) net->read_pos[8]);
366
thd->update_charset();
367
end= (char*) net->read_pos+32;
371
thd->max_client_packet_length= uint3korr(net->read_pos+2);
372
end= (char*) net->read_pos+5;
375
Disable those bits which are not supported by the server.
376
This is a precautionary measure, if the client lies. See Bug#27944.
378
thd->client_capabilities&= server_capabilites;
380
if (thd->client_capabilities & CLIENT_IGNORE_SPACE)
381
thd->variables.sql_mode|= MODE_IGNORE_SPACE;
383
if (end >= (char*) net->read_pos+ pkt_len +2)
386
my_error(ER_HANDSHAKE_ERROR, MYF(0), thd->main_security_ctx.host_or_ip);
390
if (thd->client_capabilities & CLIENT_INTERACTIVE)
391
thd->variables.net_wait_timeout= thd->variables.net_interactive_timeout;
392
if ((thd->client_capabilities & CLIENT_TRANSACTIONS) &&
393
opt_using_transactions)
394
net->return_status= &thd->server_status;
397
char *passwd= strend(user)+1;
398
uint user_len= passwd - user - 1;
400
char db_buff[NAME_LEN + 1]; // buffer to store db in utf8
401
char user_buff[USERNAME_LENGTH + 1]; // buffer to store user in utf8
405
Old clients send null-terminated string as password; new clients send
406
the size (1 byte) + string (not null-terminated). Hence in case of empty
407
password both send '\0'.
409
This strlen() can't be easily deleted without changing protocol.
411
Cast *passwd to an unsigned char, so that it doesn't extend the sign for
412
*passwd > 127 and become 2**32-127+ after casting to uint.
414
uint passwd_len= thd->client_capabilities & CLIENT_SECURE_CONNECTION ?
415
(uchar)(*passwd++) : strlen(passwd);
416
db= thd->client_capabilities & CLIENT_CONNECT_WITH_DB ?
417
db + passwd_len + 1 : 0;
418
/* strlen() can't be easily deleted without changing protocol */
419
uint db_len= db ? strlen(db) : 0;
421
if (passwd + passwd_len + db_len > (char *)net->read_pos + pkt_len)
423
my_error(ER_HANDSHAKE_ERROR, MYF(0), thd->main_security_ctx.host_or_ip);
427
/* Since 4.1 all database names are stored in utf8 */
430
db_buff[copy_and_convert(db_buff, sizeof(db_buff)-1,
433
thd->charset(), &dummy_errors)]= 0;
437
user_buff[user_len= copy_and_convert(user_buff, sizeof(user_buff)-1,
438
system_charset_info, user, user_len,
439
thd->charset(), &dummy_errors)]= '\0';
442
/* If username starts and ends in "'", chop them off */
443
if (user_len > 1 && user[0] == '\'' && user[user_len - 1] == '\'')
450
if (thd->main_security_ctx.user)
451
x_free(thd->main_security_ctx.user);
452
if (!(thd->main_security_ctx.user= my_strdup(user, MYF(MY_WME))))
453
return 1; /* The error is set by my_strdup(). */
454
return check_user(thd, COM_CONNECT, passwd, passwd_len, db, TRUE);
459
Setup thread to be used with the current thread
462
bool setup_connection_thread_globals()
463
thd Thread/connection handler
467
1 Error (out of memory)
468
In this case we will close the connection and increment status
471
bool setup_connection_thread_globals(THD *thd)
473
if (thd->store_globals())
475
close_connection(thd, ER_OUT_OF_RESOURCES, 1);
476
statistic_increment(aborted_connects,&LOCK_status);
477
thread_scheduler.end_thread(thd, 0);
485
Autenticate user, with error reporting
492
Connection is not closed in case of errors
500
bool login_connection(THD *thd)
504
DBUG_ENTER("login_connection");
505
DBUG_PRINT("info", ("login_connection called by thread %lu",
508
/* Use "connect_timeout" value during connection phase */
509
my_net_set_read_timeout(net, connect_timeout);
510
my_net_set_write_timeout(net, connect_timeout);
514
error= check_connection(thd);
515
net_end_statement(thd);
518
{ // Wrong permissions
519
statistic_increment(aborted_connects,&LOCK_status);
522
/* Connect completed, set read/write timeouts back to default */
523
my_net_set_read_timeout(net, thd->variables.net_read_timeout);
524
my_net_set_write_timeout(net, thd->variables.net_write_timeout);
530
Close an established connection
533
This mainly updates status variables
536
void end_connection(THD *thd)
539
plugin_thdvar_cleanup(thd);
541
if (thd->killed || (net->error && net->vio != 0))
543
statistic_increment(aborted_threads,&LOCK_status);
546
if (net->error && net->vio != 0)
548
if (!thd->killed && thd->variables.log_warnings > 1)
550
Security_context *sctx= thd->security_ctx;
552
sql_print_warning(ER(ER_NEW_ABORTING_CONNECTION),
553
thd->thread_id,(thd->db ? thd->db : "unconnected"),
554
sctx->user ? sctx->user : "unauthenticated",
556
(thd->main_da.is_error() ? thd->main_da.message() :
557
ER(ER_UNKNOWN_ERROR)));
564
Initialize THD to handle queries
567
void prepare_new_connection_state(THD* thd)
569
Security_context *sctx= thd->security_ctx;
571
if (thd->variables.max_join_size == HA_POS_ERROR)
572
thd->options |= OPTION_BIG_SELECTS;
573
if (thd->client_capabilities & CLIENT_COMPRESS)
574
thd->net.compress=1; // Use compression
577
Much of this is duplicated in create_embedded_thd() for the
578
embedded server library.
579
TODO: refactor this to avoid code duplication there
581
thd->version= refresh_version;
583
thd->command= COM_SLEEP;
585
thd->init_for_queries();
587
/* In the past this would only run of the user did not have SUPER_ACL */
588
if (sys_init_connect.value_length)
590
execute_init_command(thd, &sys_init_connect, &LOCK_sys_init_connect);
593
thd->killed= THD::KILL_CONNECTION;
594
sql_print_warning(ER(ER_NEW_ABORTING_CONNECTION),
595
thd->thread_id,(thd->db ? thd->db : "unconnected"),
596
sctx->user ? sctx->user : "unauthenticated",
597
sctx->host_or_ip, "init_connect command failed");
598
sql_print_warning("%s", thd->main_da.message());
602
thd->init_for_queries();
608
Thread handler for a connection
611
handle_one_connection()
612
arg Connection object (THD)
615
This function (normally) does the following:
617
- Initialize THD to be used with this thread
619
- Execute all queries sent on the connection
620
- Take connection down
621
- End thread / Handle next connection using thread from thread cache
624
pthread_handler_t handle_one_connection(void *arg)
626
THD *thd= (THD*) arg;
627
ulong launch_time= (ulong) ((thd->thr_create_utime= my_micro_time()) -
630
if (thread_scheduler.init_new_connection_thread())
632
close_connection(thd, ER_OUT_OF_RESOURCES, 1);
633
statistic_increment(aborted_connects,&LOCK_status);
634
thread_scheduler.end_thread(thd,0);
637
if (launch_time >= slow_launch_time*1000000L)
638
statistic_increment(slow_launch_threads,&LOCK_status);
641
handle_one_connection() is normally the only way a thread would
642
start and would always be on the very high end of the stack ,
643
therefore, the thread stack always starts at the address of the
644
first local variable of handle_one_connection, which is thd. We
645
need to know the start of the stack so that we could check for
648
thd->thread_stack= (char*) &thd;
649
if (setup_connection_thread_globals(thd))
656
if (login_connection(thd))
659
prepare_new_connection_state(thd);
661
while (!net->error && net->vio != 0 &&
662
!(thd->killed == THD::KILL_CONNECTION))
670
close_connection(thd, 0, 1);
671
if (thread_scheduler.end_thread(thd,1))
672
return 0; // Probably no-threads
675
If end_thread() returns, we are either running with
676
thread-handler=no-threads or this thread has been schedule to
677
handle the next connection.
680
thd->thread_stack= (char*) &thd;