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, const char *passwd,
80
uint32_t passwd_len, const char *db,
83
LEX_STRING db_str= { (char *) db, db ? strlen(db) : 0 };
84
bool is_authenticated;
87
Clear thd->db as it points to something, that will be freed when
88
connection is closed. We don't want to accidentally free a wrong
89
pointer if connect failed. Also in case of 'CHANGE USER' failure,
90
current database will be switched to 'no database selected'.
92
thd->reset_db(NULL, 0);
94
if (passwd_len != 0 && passwd_len != SCRAMBLE_LENGTH)
96
my_error(ER_HANDSHAKE_ERROR, MYF(0), thd->main_security_ctx.ip);
100
is_authenticated= authenticate_user(thd, passwd);
102
if (is_authenticated != true)
104
my_error(ER_ACCESS_DENIED_ERROR, MYF(0),
105
thd->main_security_ctx.user,
106
thd->main_security_ctx.ip,
107
passwd_len ? ER(ER_YES) : ER(ER_NO));
114
thd->security_ctx->skip_grants();
115
memset(&ur, 0, sizeof(USER_RESOURCES));
119
pthread_mutex_lock(&LOCK_connection_count);
120
bool count_ok= connection_count <= max_connections;
121
pthread_mutex_unlock(&LOCK_connection_count);
124
{ // too many connections
125
my_error(ER_CON_COUNT_ERROR, MYF(0));
130
/* Change database if necessary */
133
if (mysql_change_db(thd, &db_str, false))
135
/* mysql_change_db() has pushed the error message. */
140
thd->password= test(passwd_len); // remember for error messages
141
/* Ready to handle queries */
147
Check for maximum allowable user connections, if the mysqld server is
148
started with corresponding variable that is greater then 0.
151
extern "C" unsigned char *get_key_conn(user_conn *buff, size_t *length,
152
bool not_used __attribute__((unused)))
155
return (unsigned char*) buff->user;
159
extern "C" void free_user(struct user_conn *uc)
164
void thd_init_client_charset(THD *thd, uint32_t cs_number)
167
Use server character set and collation if
168
- opt_character_set_client_handshake is not set
169
- client has not specified a character set
170
- client character set is the same as the servers
171
- client character set doesn't exists in server
173
if (!opt_character_set_client_handshake ||
174
!(thd->variables.character_set_client= get_charset(cs_number, MYF(0))) ||
175
!my_strcasecmp(&my_charset_utf8_general_ci,
176
global_system_variables.character_set_client->name,
177
thd->variables.character_set_client->name))
179
thd->variables.character_set_client=
180
global_system_variables.character_set_client;
181
thd->variables.collation_connection=
182
global_system_variables.collation_connection;
183
thd->variables.character_set_results=
184
global_system_variables.character_set_results;
188
thd->variables.character_set_results=
189
thd->variables.collation_connection=
190
thd->variables.character_set_client;
196
Initialize connection threads
199
bool init_new_connection_handler_thread()
201
pthread_detach_this_thread();
202
/* Win32 calls this in pthread_create */
203
if (my_thread_init())
209
Perform handshake, authorize client and update thd ACL variables.
216
0 success, OK is sent to user, thd is updated.
217
-1 error, which is sent to user
218
> 0 error code (not sent to user)
221
static int check_connection(THD *thd)
231
if (net_peer_addr(net, ip, &thd->peer_port, NI_MAXHOST))
233
my_error(ER_BAD_HOST_ERROR, MYF(0), thd->main_security_ctx.ip);
236
if (!(thd->main_security_ctx.ip= my_strdup(ip,MYF(MY_WME))))
237
return 1; /* The error is set by my_strdup(). */
239
net_keepalive(net, true);
241
uint32_t server_capabilites;
243
/* buff[] needs to big enough to hold the server_version variable */
244
char buff[SERVER_VERSION_LENGTH + SCRAMBLE_LENGTH + 64];
245
server_capabilites= CLIENT_BASIC_FLAGS;
247
if (opt_using_transactions)
248
server_capabilites|= CLIENT_TRANSACTIONS;
250
server_capabilites|= CLIENT_COMPRESS;
251
#endif /* HAVE_COMPRESS */
253
end= my_stpncpy(buff, server_version, SERVER_VERSION_LENGTH) + 1;
254
int4store((unsigned char*) end, thd->thread_id);
257
So as check_connection is the only entry point to authorization
258
procedure, scramble is set here. This gives us new scramble for
261
create_random_string(thd->scramble, SCRAMBLE_LENGTH, &thd->rand);
263
Old clients does not understand long scrambles, but can ignore packet
264
tail: that's why first part of the scramble is placed here, and second
265
part at the end of packet.
267
end= strmake(end, thd->scramble, SCRAMBLE_LENGTH_323) + 1;
269
int2store(end, server_capabilites);
270
/* write server characteristics: up to 16 bytes allowed */
271
end[2]=(char) default_charset_info->number;
272
int2store(end+3, thd->server_status);
273
memset(end+5, 0, 13);
275
/* write scramble tail */
276
end= strmake(end, thd->scramble + SCRAMBLE_LENGTH_323,
277
SCRAMBLE_LENGTH - SCRAMBLE_LENGTH_323) + 1;
279
/* At this point we write connection message and read reply */
280
if (net_write_command(net, (unsigned char) protocol_version, (unsigned char*) "", 0,
281
(unsigned char*) buff, (size_t) (end-buff)) ||
282
(pkt_len= my_net_read(net)) == packet_error ||
283
pkt_len < MIN_HANDSHAKE_SIZE)
285
my_error(ER_HANDSHAKE_ERROR, MYF(0),
286
thd->main_security_ctx.ip);
290
if (thd->packet.alloc(thd->variables.net_buffer_length))
291
return 1; /* The error is set by alloc(). */
293
thd->client_capabilities= uint2korr(net->read_pos);
296
thd->client_capabilities|= ((uint32_t) uint2korr(net->read_pos+2)) << 16;
297
thd->max_client_packet_length= uint4korr(net->read_pos+4);
298
thd_init_client_charset(thd, (uint) net->read_pos[8]);
299
thd->update_charset();
300
end= (char*) net->read_pos+32;
303
Disable those bits which are not supported by the server.
304
This is a precautionary measure, if the client lies. See Bug#27944.
306
thd->client_capabilities&= server_capabilites;
308
if (end >= (char*) net->read_pos+ pkt_len +2)
311
my_error(ER_HANDSHAKE_ERROR, MYF(0), thd->main_security_ctx.ip);
315
if (thd->client_capabilities & CLIENT_INTERACTIVE)
316
thd->variables.net_wait_timeout= thd->variables.net_interactive_timeout;
317
if ((thd->client_capabilities & CLIENT_TRANSACTIONS) &&
318
opt_using_transactions)
319
net->return_status= &thd->server_status;
322
char *passwd= strchr(user, '\0')+1;
323
uint32_t user_len= passwd - user - 1;
325
char db_buff[NAME_LEN + 1]; // buffer to store db in utf8
326
char user_buff[USERNAME_LENGTH + 1]; // buffer to store user in utf8
327
uint32_t dummy_errors;
330
Old clients send null-terminated string as password; new clients send
331
the size (1 byte) + string (not null-terminated). Hence in case of empty
332
password both send '\0'.
334
This strlen() can't be easily deleted without changing protocol.
336
Cast *passwd to an unsigned char, so that it doesn't extend the sign for
337
*passwd > 127 and become 2**32-127+ after casting to uint.
339
uint32_t passwd_len= thd->client_capabilities & CLIENT_SECURE_CONNECTION ?
340
(unsigned char)(*passwd++) : strlen(passwd);
341
db= thd->client_capabilities & CLIENT_CONNECT_WITH_DB ?
342
db + passwd_len + 1 : 0;
343
/* strlen() can't be easily deleted without changing protocol */
344
uint32_t db_len= db ? strlen(db) : 0;
346
if (passwd + passwd_len + db_len > (char *)net->read_pos + pkt_len)
348
my_error(ER_HANDSHAKE_ERROR, MYF(0), thd->main_security_ctx.ip);
352
/* Since 4.1 all database names are stored in utf8 */
355
db_buff[copy_and_convert(db_buff, sizeof(db_buff)-1,
358
thd->charset(), &dummy_errors)]= 0;
362
user_buff[user_len= copy_and_convert(user_buff, sizeof(user_buff)-1,
363
system_charset_info, user, user_len,
364
thd->charset(), &dummy_errors)]= '\0';
367
/* If username starts and ends in "'", chop them off */
368
if (user_len > 1 && user[0] == '\'' && user[user_len - 1] == '\'')
375
if (thd->main_security_ctx.user)
376
if (thd->main_security_ctx.user)
377
free(thd->main_security_ctx.user);
378
if (!(thd->main_security_ctx.user= my_strdup(user, MYF(MY_WME))))
379
return 1; /* The error is set by my_strdup(). */
380
return check_user(thd, passwd, passwd_len, db, true);
385
Setup thread to be used with the current thread
388
bool setup_connection_thread_globals()
389
thd Thread/connection handler
393
1 Error (out of memory)
394
In this case we will close the connection and increment status
397
bool setup_connection_thread_globals(THD *thd)
399
if (thd->store_globals())
401
close_connection(thd, ER_OUT_OF_RESOURCES, 1);
402
statistic_increment(aborted_connects,&LOCK_status);
403
thread_scheduler.end_thread(thd, 0);
411
Autenticate user, with error reporting
418
Connection is not closed in case of errors
426
bool login_connection(THD *thd)
431
/* Use "connect_timeout" value during connection phase */
432
my_net_set_read_timeout(net, connect_timeout);
433
my_net_set_write_timeout(net, connect_timeout);
437
error= check_connection(thd);
438
net_end_statement(thd);
441
{ // Wrong permissions
442
statistic_increment(aborted_connects,&LOCK_status);
445
/* Connect completed, set read/write timeouts back to default */
446
my_net_set_read_timeout(net, thd->variables.net_read_timeout);
447
my_net_set_write_timeout(net, thd->variables.net_write_timeout);
453
Close an established connection
456
This mainly updates status variables
459
void end_connection(THD *thd)
462
plugin_thdvar_cleanup(thd);
464
if (thd->killed || (net->error && net->vio != 0))
466
statistic_increment(aborted_threads,&LOCK_status);
469
if (net->error && net->vio != 0)
471
if (!thd->killed && thd->variables.log_warnings > 1)
473
Security_context *sctx= thd->security_ctx;
475
sql_print_warning(ER(ER_NEW_ABORTING_CONNECTION),
476
thd->thread_id,(thd->db ? thd->db : "unconnected"),
477
sctx->user ? sctx->user : "unauthenticated",
479
(thd->main_da.is_error() ? thd->main_da.message() :
480
ER(ER_UNKNOWN_ERROR)));
487
Initialize THD to handle queries
490
void prepare_new_connection_state(THD* thd)
492
Security_context *sctx= thd->security_ctx;
494
if (thd->variables.max_join_size == HA_POS_ERROR)
495
thd->options |= OPTION_BIG_SELECTS;
496
if (thd->client_capabilities & CLIENT_COMPRESS)
497
thd->net.compress=1; // Use compression
500
Much of this is duplicated in create_embedded_thd() for the
501
embedded server library.
502
TODO: refactor this to avoid code duplication there
504
thd->version= refresh_version;
505
thd->set_proc_info(0);
506
thd->command= COM_SLEEP;
508
thd->init_for_queries();
510
/* In the past this would only run of the user did not have SUPER_ACL */
511
if (sys_init_connect.value_length)
513
execute_init_command(thd, &sys_init_connect, &LOCK_sys_init_connect);
516
thd->killed= THD::KILL_CONNECTION;
517
sql_print_warning(ER(ER_NEW_ABORTING_CONNECTION),
518
thd->thread_id,(thd->db ? thd->db : "unconnected"),
519
sctx->user ? sctx->user : "unauthenticated",
520
sctx->ip, "init_connect command failed");
521
sql_print_warning("%s", thd->main_da.message());
523
thd->set_proc_info(0);
525
thd->init_for_queries();
531
Thread handler for a connection
534
handle_one_connection()
535
arg Connection object (THD)
538
This function (normally) does the following:
540
- Initialize THD to be used with this thread
542
- Execute all queries sent on the connection
543
- Take connection down
544
- End thread / Handle next connection using thread from thread cache
547
pthread_handler_t handle_one_connection(void *arg)
549
THD *thd= (THD*) arg;
550
uint32_t launch_time= (uint32_t) ((thd->thr_create_utime= my_micro_time()) -
553
if (thread_scheduler.init_new_connection_thread())
555
close_connection(thd, ER_OUT_OF_RESOURCES, 1);
556
statistic_increment(aborted_connects,&LOCK_status);
557
thread_scheduler.end_thread(thd,0);
560
if (launch_time >= slow_launch_time*1000000L)
561
statistic_increment(slow_launch_threads,&LOCK_status);
564
handle_one_connection() is normally the only way a thread would
565
start and would always be on the very high end of the stack ,
566
therefore, the thread stack always starts at the address of the
567
first local variable of handle_one_connection, which is thd. We
568
need to know the start of the stack so that we could check for
571
thd->thread_stack= (char*) &thd;
572
if (setup_connection_thread_globals(thd))
579
if (login_connection(thd))
582
prepare_new_connection_state(thd);
584
while (!net->error && net->vio != 0 &&
585
!(thd->killed == THD::KILL_CONNECTION))
593
close_connection(thd, 0, 1);
594
if (thread_scheduler.end_thread(thd,1))
595
return 0; // Probably no-threads
598
If end_thread() returns, we are either running with
599
thread-handler=no-threads or this thread has been schedule to
600
handle the next connection.
603
thd->thread_stack= (char*) &thd;