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
20
#include <drizzled/server_includes.h>
21
#include <drizzled/authentication.h>
22
#include <drizzled/drizzled_error_messages.h>
24
#define MIN_HANDSHAKE_SIZE 6
27
Get structure for logging connection data for the current user
30
char *ip_to_hostname(struct sockaddr_storage *in, int addrLen)
35
char hostname_buff[NI_MAXHOST];
37
/* Historical comparison for 127.0.0.1 */
38
gxi_error= getnameinfo((struct sockaddr *)in, addrLen,
39
hostname_buff, NI_MAXHOST,
40
NULL, 0, NI_NUMERICHOST);
46
if (!(name= my_strdup(hostname_buff, MYF(0))))
55
Check if user exist and password supplied is correct.
57
@param thd thread handle, thd->security_ctx->{host,user,ip} are used
58
@param command originator of the check: now check_user is called
59
during connect and change user procedures; used for
61
@param passwd scrambled password received from client
62
@param passwd_len length of scrambled password
63
@param db database name to connect to, may be NULL
64
@param check_count true if establishing a new connection. In this case
65
check that we have not exceeded the global
66
max_connections limist
68
@note Host, user and passwd may point to communication buffer.
69
Current implementation does not depend on that, but future changes
70
should be done with this in mind; 'thd' is INOUT, all other params
74
@retval 1 error, e.g. access denied or handshake error, not sent to
75
the client. A message is pushed into the error stack.
79
check_user(THD *thd, enum enum_server_command command,
81
uint passwd_len, const char *db,
84
LEX_STRING db_str= { (char *) db, db ? strlen(db) : 0 };
85
bool is_authenticated;
88
Clear thd->db as it points to something, that will be freed when
89
connection is closed. We don't want to accidentally free a wrong
90
pointer if connect failed. Also in case of 'CHANGE USER' failure,
91
current database will be switched to 'no database selected'.
93
thd->reset_db(NULL, 0);
95
if (passwd_len != 0 && passwd_len != SCRAMBLE_LENGTH)
97
my_error(ER_HANDSHAKE_ERROR, MYF(0), thd->main_security_ctx.ip);
101
is_authenticated= authenticate_user(thd, passwd);
103
if (is_authenticated != true)
105
my_error(ER_ACCESS_DENIED_ERROR, MYF(0),
106
thd->main_security_ctx.user,
107
thd->main_security_ctx.ip,
108
passwd_len ? ER(ER_YES) : ER(ER_NO));
115
thd->security_ctx->skip_grants();
116
memset(&ur, 0, sizeof(USER_RESOURCES));
120
pthread_mutex_lock(&LOCK_connection_count);
121
bool count_ok= connection_count <= max_connections;
122
VOID(pthread_mutex_unlock(&LOCK_connection_count));
125
{ // too many connections
126
my_error(ER_CON_COUNT_ERROR, MYF(0));
132
Log the command before authentication checks, so that the user can
133
check the log for the tried login tried and also to detect
136
general_log_print(thd, command,
137
((char*) "%s@%s on %s"),
138
thd->main_security_ctx.user,
139
thd->main_security_ctx.ip,
140
db ? db : (char*) "");
142
/* Change database if necessary */
145
if (mysql_change_db(thd, &db_str, false))
147
/* mysql_change_db() has pushed the error message. */
152
thd->password= test(passwd_len); // remember for error messages
153
/* Ready to handle queries */
159
Check for maximum allowable user connections, if the mysqld server is
160
started with corresponding variable that is greater then 0.
163
extern "C" uchar *get_key_conn(user_conn *buff, size_t *length,
164
bool not_used __attribute__((unused)))
167
return (uchar*) buff->user;
171
extern "C" void free_user(struct user_conn *uc)
173
my_free((char*) uc,MYF(0));
176
void thd_init_client_charset(THD *thd, uint cs_number)
179
Use server character set and collation if
180
- opt_character_set_client_handshake is not set
181
- client has not specified a character set
182
- client character set is the same as the servers
183
- client character set doesn't exists in server
185
if (!opt_character_set_client_handshake ||
186
!(thd->variables.character_set_client= get_charset(cs_number, MYF(0))) ||
187
!my_strcasecmp(&my_charset_latin1,
188
global_system_variables.character_set_client->name,
189
thd->variables.character_set_client->name))
191
thd->variables.character_set_client=
192
global_system_variables.character_set_client;
193
thd->variables.collation_connection=
194
global_system_variables.collation_connection;
195
thd->variables.character_set_results=
196
global_system_variables.character_set_results;
200
thd->variables.character_set_results=
201
thd->variables.collation_connection=
202
thd->variables.character_set_client;
208
Initialize connection threads
211
bool init_new_connection_handler_thread()
213
pthread_detach_this_thread();
214
/* Win32 calls this in pthread_create */
215
if (my_thread_init())
221
Perform handshake, authorize client and update thd ACL variables.
228
0 success, OK is sent to user, thd is updated.
229
-1 error, which is sent to user
230
> 0 error code (not sent to user)
233
static int check_connection(THD *thd)
239
#ifdef SIGNAL_WITH_VIO_CLOSE
240
thd->set_active_vio(net->vio);
247
if (vio_peer_addr(net->vio, ip, &thd->peer_port, NI_MAXHOST))
249
my_error(ER_BAD_HOST_ERROR, MYF(0), thd->main_security_ctx.ip);
252
if (!(thd->main_security_ctx.ip= my_strdup(ip,MYF(MY_WME))))
253
return 1; /* The error is set by my_strdup(). */
255
vio_keepalive(net->vio, true);
257
uint32_t server_capabilites;
259
/* buff[] needs to big enough to hold the server_version variable */
260
char buff[SERVER_VERSION_LENGTH + SCRAMBLE_LENGTH + 64];
261
server_capabilites= CLIENT_BASIC_FLAGS;
263
if (opt_using_transactions)
264
server_capabilites|= CLIENT_TRANSACTIONS;
266
server_capabilites|= CLIENT_COMPRESS;
267
#endif /* HAVE_COMPRESS */
269
end= stpncpy(buff, server_version, SERVER_VERSION_LENGTH) + 1;
270
int4store((uchar*) end, thd->thread_id);
273
So as check_connection is the only entry point to authorization
274
procedure, scramble is set here. This gives us new scramble for
277
create_random_string(thd->scramble, SCRAMBLE_LENGTH, &thd->rand);
279
Old clients does not understand long scrambles, but can ignore packet
280
tail: that's why first part of the scramble is placed here, and second
281
part at the end of packet.
283
end= strmake(end, thd->scramble, SCRAMBLE_LENGTH_323) + 1;
285
int2store(end, server_capabilites);
286
/* write server characteristics: up to 16 bytes allowed */
287
end[2]=(char) default_charset_info->number;
288
int2store(end+3, thd->server_status);
289
memset(end+5, 0, 13);
291
/* write scramble tail */
292
end= strmake(end, thd->scramble + SCRAMBLE_LENGTH_323,
293
SCRAMBLE_LENGTH - SCRAMBLE_LENGTH_323) + 1;
295
/* At this point we write connection message and read reply */
296
if (net_write_command(net, (uchar) protocol_version, (uchar*) "", 0,
297
(uchar*) buff, (size_t) (end-buff)) ||
298
(pkt_len= my_net_read(net)) == packet_error ||
299
pkt_len < MIN_HANDSHAKE_SIZE)
301
my_error(ER_HANDSHAKE_ERROR, MYF(0),
302
thd->main_security_ctx.ip);
306
if (thd->packet.alloc(thd->variables.net_buffer_length))
307
return 1; /* The error is set by alloc(). */
309
thd->client_capabilities= uint2korr(net->read_pos);
312
thd->client_capabilities|= ((uint32_t) uint2korr(net->read_pos+2)) << 16;
313
thd->max_client_packet_length= uint4korr(net->read_pos+4);
314
thd_init_client_charset(thd, (uint) net->read_pos[8]);
315
thd->update_charset();
316
end= (char*) net->read_pos+32;
319
Disable those bits which are not supported by the server.
320
This is a precautionary measure, if the client lies. See Bug#27944.
322
thd->client_capabilities&= server_capabilites;
324
if (thd->client_capabilities & CLIENT_IGNORE_SPACE)
325
thd->variables.sql_mode|= MODE_IGNORE_SPACE;
327
if (end >= (char*) net->read_pos+ pkt_len +2)
330
my_error(ER_HANDSHAKE_ERROR, MYF(0), thd->main_security_ctx.ip);
334
if (thd->client_capabilities & CLIENT_INTERACTIVE)
335
thd->variables.net_wait_timeout= thd->variables.net_interactive_timeout;
336
if ((thd->client_capabilities & CLIENT_TRANSACTIONS) &&
337
opt_using_transactions)
338
net->return_status= &thd->server_status;
341
char *passwd= strend(user)+1;
342
uint user_len= passwd - user - 1;
344
char db_buff[NAME_LEN + 1]; // buffer to store db in utf8
345
char user_buff[USERNAME_LENGTH + 1]; // buffer to store user in utf8
349
Old clients send null-terminated string as password; new clients send
350
the size (1 byte) + string (not null-terminated). Hence in case of empty
351
password both send '\0'.
353
This strlen() can't be easily deleted without changing protocol.
355
Cast *passwd to an unsigned char, so that it doesn't extend the sign for
356
*passwd > 127 and become 2**32-127+ after casting to uint.
358
uint passwd_len= thd->client_capabilities & CLIENT_SECURE_CONNECTION ?
359
(uchar)(*passwd++) : strlen(passwd);
360
db= thd->client_capabilities & CLIENT_CONNECT_WITH_DB ?
361
db + passwd_len + 1 : 0;
362
/* strlen() can't be easily deleted without changing protocol */
363
uint db_len= db ? strlen(db) : 0;
365
if (passwd + passwd_len + db_len > (char *)net->read_pos + pkt_len)
367
my_error(ER_HANDSHAKE_ERROR, MYF(0), thd->main_security_ctx.ip);
371
/* Since 4.1 all database names are stored in utf8 */
374
db_buff[copy_and_convert(db_buff, sizeof(db_buff)-1,
377
thd->charset(), &dummy_errors)]= 0;
381
user_buff[user_len= copy_and_convert(user_buff, sizeof(user_buff)-1,
382
system_charset_info, user, user_len,
383
thd->charset(), &dummy_errors)]= '\0';
386
/* If username starts and ends in "'", chop them off */
387
if (user_len > 1 && user[0] == '\'' && user[user_len - 1] == '\'')
394
if (thd->main_security_ctx.user)
395
x_free(thd->main_security_ctx.user);
396
if (!(thd->main_security_ctx.user= my_strdup(user, MYF(MY_WME))))
397
return 1; /* The error is set by my_strdup(). */
398
return check_user(thd, COM_CONNECT, passwd, passwd_len, db, true);
403
Setup thread to be used with the current thread
406
bool setup_connection_thread_globals()
407
thd Thread/connection handler
411
1 Error (out of memory)
412
In this case we will close the connection and increment status
415
bool setup_connection_thread_globals(THD *thd)
417
if (thd->store_globals())
419
close_connection(thd, ER_OUT_OF_RESOURCES, 1);
420
statistic_increment(aborted_connects,&LOCK_status);
421
thread_scheduler.end_thread(thd, 0);
429
Autenticate user, with error reporting
436
Connection is not closed in case of errors
444
bool login_connection(THD *thd)
449
/* Use "connect_timeout" value during connection phase */
450
my_net_set_read_timeout(net, connect_timeout);
451
my_net_set_write_timeout(net, connect_timeout);
455
error= check_connection(thd);
456
net_end_statement(thd);
459
{ // Wrong permissions
460
statistic_increment(aborted_connects,&LOCK_status);
463
/* Connect completed, set read/write timeouts back to default */
464
my_net_set_read_timeout(net, thd->variables.net_read_timeout);
465
my_net_set_write_timeout(net, thd->variables.net_write_timeout);
471
Close an established connection
474
This mainly updates status variables
477
void end_connection(THD *thd)
480
plugin_thdvar_cleanup(thd);
482
if (thd->killed || (net->error && net->vio != 0))
484
statistic_increment(aborted_threads,&LOCK_status);
487
if (net->error && net->vio != 0)
489
if (!thd->killed && thd->variables.log_warnings > 1)
491
Security_context *sctx= thd->security_ctx;
493
sql_print_warning(ER(ER_NEW_ABORTING_CONNECTION),
494
thd->thread_id,(thd->db ? thd->db : "unconnected"),
495
sctx->user ? sctx->user : "unauthenticated",
497
(thd->main_da.is_error() ? thd->main_da.message() :
498
ER(ER_UNKNOWN_ERROR)));
505
Initialize THD to handle queries
508
void prepare_new_connection_state(THD* thd)
510
Security_context *sctx= thd->security_ctx;
512
if (thd->variables.max_join_size == HA_POS_ERROR)
513
thd->options |= OPTION_BIG_SELECTS;
514
if (thd->client_capabilities & CLIENT_COMPRESS)
515
thd->net.compress=1; // Use compression
518
Much of this is duplicated in create_embedded_thd() for the
519
embedded server library.
520
TODO: refactor this to avoid code duplication there
522
thd->version= refresh_version;
524
thd->command= COM_SLEEP;
526
thd->init_for_queries();
528
/* In the past this would only run of the user did not have SUPER_ACL */
529
if (sys_init_connect.value_length)
531
execute_init_command(thd, &sys_init_connect, &LOCK_sys_init_connect);
534
thd->killed= THD::KILL_CONNECTION;
535
sql_print_warning(ER(ER_NEW_ABORTING_CONNECTION),
536
thd->thread_id,(thd->db ? thd->db : "unconnected"),
537
sctx->user ? sctx->user : "unauthenticated",
538
sctx->ip, "init_connect command failed");
539
sql_print_warning("%s", thd->main_da.message());
543
thd->init_for_queries();
549
Thread handler for a connection
552
handle_one_connection()
553
arg Connection object (THD)
556
This function (normally) does the following:
558
- Initialize THD to be used with this thread
560
- Execute all queries sent on the connection
561
- Take connection down
562
- End thread / Handle next connection using thread from thread cache
565
pthread_handler_t handle_one_connection(void *arg)
567
THD *thd= (THD*) arg;
568
uint32_t launch_time= (uint32_t) ((thd->thr_create_utime= my_micro_time()) -
571
if (thread_scheduler.init_new_connection_thread())
573
close_connection(thd, ER_OUT_OF_RESOURCES, 1);
574
statistic_increment(aborted_connects,&LOCK_status);
575
thread_scheduler.end_thread(thd,0);
578
if (launch_time >= slow_launch_time*1000000L)
579
statistic_increment(slow_launch_threads,&LOCK_status);
582
handle_one_connection() is normally the only way a thread would
583
start and would always be on the very high end of the stack ,
584
therefore, the thread stack always starts at the address of the
585
first local variable of handle_one_connection, which is thd. We
586
need to know the start of the stack so that we could check for
589
thd->thread_stack= (char*) &thd;
590
if (setup_connection_thread_globals(thd))
597
if (login_connection(thd))
600
prepare_new_connection_state(thd);
602
while (!net->error && net->vio != 0 &&
603
!(thd->killed == THD::KILL_CONNECTION))
611
close_connection(thd, 0, 1);
612
if (thread_scheduler.end_thread(thd,1))
613
return 0; // Probably no-threads
616
If end_thread() returns, we are either running with
617
thread-handler=no-threads or this thread has been schedule to
618
handle the next connection.
621
thd->thread_stack= (char*) &thd;