1
/* -*- mode: c++; c-basic-offset: 2; indent-tabs-mode: nil; -*-
2
* vim:expandtab:shiftwidth=2:tabstop=2:smarttab:
4
* Copyright (C) 2008 Sun Microsystems
6
* This program is free software; you can redistribute it and/or modify
7
* it under the terms of the GNU General Public License as published by
8
* the Free Software Foundation; version 2 of the License.
10
* This program is distributed in the hope that it will be useful,
11
* but WITHOUT ANY WARRANTY; without even the implied warranty of
12
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13
* GNU General Public License for more details.
15
* You should have received a copy of the GNU General Public License
16
* along with this program; if not, write to the Free Software
17
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
22
Functions to autenticate and handle reqests for a connection
24
#include <drizzled/server_includes.h>
27
#include <drizzled/authentication.h>
28
#include <drizzled/db.h>
29
#include <drizzled/error.h>
30
#include <drizzled/sql_parse.h>
31
#include <drizzled/scheduler.h>
32
#include <drizzled/session.h>
34
extern scheduler_functions thread_scheduler;
36
#define MIN_HANDSHAKE_SIZE 6
39
Get structure for logging connection data for the current user
42
char *ip_to_hostname(struct sockaddr_storage *in, int addrLen)
47
char hostname_buff[NI_MAXHOST];
49
/* Historical comparison for 127.0.0.1 */
50
gxi_error= getnameinfo((struct sockaddr *)in, addrLen,
51
hostname_buff, NI_MAXHOST,
52
NULL, 0, NI_NUMERICHOST);
58
if (!(name= my_strdup(hostname_buff, MYF(0))))
67
Check if user exist and password supplied is correct.
69
@param session thread handle, session->security_ctx->{host,user,ip} are used
70
@param command originator of the check: now check_user is called
71
during connect and change user procedures; used for
73
@param passwd scrambled password received from client
74
@param passwd_len length of scrambled password
75
@param db database name to connect to, may be NULL
76
@param check_count true if establishing a new connection. In this case
77
check that we have not exceeded the global
78
max_connections limist
80
@note Host, user and passwd may point to communication buffer.
81
Current implementation does not depend on that, but future changes
82
should be done with this in mind; 'session' is INOUT, all other params
86
@retval 1 error, e.g. access denied or handshake error, not sent to
87
the client. A message is pushed into the error stack.
91
check_user(Session *session, const char *passwd,
92
uint32_t passwd_len, const char *db,
95
LEX_STRING db_str= { (char *) db, db ? strlen(db) : 0 };
96
bool is_authenticated;
99
Clear session->db as it points to something, that will be freed when
100
connection is closed. We don't want to accidentally free a wrong
101
pointer if connect failed. Also in case of 'CHANGE USER' failure,
102
current database will be switched to 'no database selected'.
104
session->reset_db(NULL, 0);
106
if (passwd_len != 0 && passwd_len != SCRAMBLE_LENGTH)
108
my_error(ER_HANDSHAKE_ERROR, MYF(0), session->main_security_ctx.ip);
112
is_authenticated= authenticate_user(session, passwd);
114
if (is_authenticated != true)
116
my_error(ER_ACCESS_DENIED_ERROR, MYF(0),
117
session->main_security_ctx.user,
118
session->main_security_ctx.ip,
119
passwd_len ? ER(ER_YES) : ER(ER_NO));
126
session->security_ctx->skip_grants();
127
memset(&ur, 0, sizeof(USER_RESOURCES));
131
pthread_mutex_lock(&LOCK_connection_count);
132
bool count_ok= connection_count <= max_connections;
133
pthread_mutex_unlock(&LOCK_connection_count);
136
{ // too many connections
137
my_error(ER_CON_COUNT_ERROR, MYF(0));
142
/* Change database if necessary */
145
if (mysql_change_db(session, &db_str, false))
147
/* mysql_change_db() has pushed the error message. */
152
session->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" unsigned char *get_key_conn(user_conn *buff, size_t *length,
164
bool not_used __attribute__((unused)))
167
return (unsigned char*) buff->user;
171
extern "C" void free_user(struct user_conn *uc)
176
void session_init_client_charset(Session *session, uint32_t 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
!(session->variables.character_set_client= get_charset(cs_number, MYF(0))) ||
187
!my_strcasecmp(&my_charset_utf8_general_ci,
188
global_system_variables.character_set_client->name,
189
session->variables.character_set_client->name))
191
session->variables.character_set_client=
192
global_system_variables.character_set_client;
193
session->variables.collation_connection=
194
global_system_variables.collation_connection;
195
session->variables.character_set_results=
196
global_system_variables.character_set_results;
200
session->variables.character_set_results=
201
session->variables.collation_connection=
202
session->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 session ACL variables.
225
session thread handle
228
0 success, OK is sent to user, session is updated.
229
-1 error, which is sent to user
230
> 0 error code (not sent to user)
233
static int check_connection(Session *session)
235
NET *net= &session->net;
243
if (net_peer_addr(net, ip, &session->peer_port, NI_MAXHOST))
245
my_error(ER_BAD_HOST_ERROR, MYF(0), session->main_security_ctx.ip);
248
if (!(session->main_security_ctx.ip= my_strdup(ip,MYF(MY_WME))))
249
return 1; /* The error is set by my_strdup(). */
251
net_keepalive(net, true);
253
uint32_t server_capabilites;
255
/* buff[] needs to big enough to hold the server_version variable */
256
char buff[SERVER_VERSION_LENGTH + SCRAMBLE_LENGTH + 64];
257
server_capabilites= CLIENT_BASIC_FLAGS;
259
if (opt_using_transactions)
260
server_capabilites|= CLIENT_TRANSACTIONS;
262
server_capabilites|= CLIENT_COMPRESS;
263
#endif /* HAVE_COMPRESS */
265
end= my_stpncpy(buff, server_version, SERVER_VERSION_LENGTH) + 1;
266
int4store((unsigned char*) end, session->thread_id);
269
So as check_connection is the only entry point to authorization
270
procedure, scramble is set here. This gives us new scramble for
273
create_random_string(session->scramble, SCRAMBLE_LENGTH, &session->rand);
275
Old clients does not understand long scrambles, but can ignore packet
276
tail: that's why first part of the scramble is placed here, and second
277
part at the end of packet.
279
end= strmake(end, session->scramble, SCRAMBLE_LENGTH_323) + 1;
281
int2store(end, server_capabilites);
282
/* write server characteristics: up to 16 bytes allowed */
283
end[2]=(char) default_charset_info->number;
284
int2store(end+3, session->server_status);
285
memset(end+5, 0, 13);
287
/* write scramble tail */
288
end= strmake(end, session->scramble + SCRAMBLE_LENGTH_323,
289
SCRAMBLE_LENGTH - SCRAMBLE_LENGTH_323) + 1;
291
/* At this point we write connection message and read reply */
292
if (net_write_command(net, (unsigned char) protocol_version, (unsigned char*) "", 0,
293
(unsigned char*) buff, (size_t) (end-buff)) ||
294
(pkt_len= my_net_read(net)) == packet_error ||
295
pkt_len < MIN_HANDSHAKE_SIZE)
297
my_error(ER_HANDSHAKE_ERROR, MYF(0),
298
session->main_security_ctx.ip);
302
if (session->packet.alloc(session->variables.net_buffer_length))
303
return 1; /* The error is set by alloc(). */
305
session->client_capabilities= uint2korr(net->read_pos);
308
session->client_capabilities|= ((uint32_t) uint2korr(net->read_pos+2)) << 16;
309
session->max_client_packet_length= uint4korr(net->read_pos+4);
310
session_init_client_charset(session, (uint) net->read_pos[8]);
311
session->update_charset();
312
end= (char*) net->read_pos+32;
315
Disable those bits which are not supported by the server.
316
This is a precautionary measure, if the client lies. See Bug#27944.
318
session->client_capabilities&= server_capabilites;
320
if (end >= (char*) net->read_pos+ pkt_len +2)
323
my_error(ER_HANDSHAKE_ERROR, MYF(0), session->main_security_ctx.ip);
327
if (session->client_capabilities & CLIENT_INTERACTIVE)
328
session->variables.net_wait_timeout= session->variables.net_interactive_timeout;
329
if ((session->client_capabilities & CLIENT_TRANSACTIONS) &&
330
opt_using_transactions)
331
net->return_status= &session->server_status;
334
char *passwd= strchr(user, '\0')+1;
335
uint32_t user_len= passwd - user - 1;
337
char db_buff[NAME_LEN + 1]; // buffer to store db in utf8
338
char user_buff[USERNAME_LENGTH + 1]; // buffer to store user in utf8
339
uint32_t dummy_errors;
342
Old clients send null-terminated string as password; new clients send
343
the size (1 byte) + string (not null-terminated). Hence in case of empty
344
password both send '\0'.
346
This strlen() can't be easily deleted without changing protocol.
348
Cast *passwd to an unsigned char, so that it doesn't extend the sign for
349
*passwd > 127 and become 2**32-127+ after casting to uint.
351
uint32_t passwd_len= session->client_capabilities & CLIENT_SECURE_CONNECTION ?
352
(unsigned char)(*passwd++) : strlen(passwd);
353
db= session->client_capabilities & CLIENT_CONNECT_WITH_DB ?
354
db + passwd_len + 1 : 0;
355
/* strlen() can't be easily deleted without changing protocol */
356
uint32_t db_len= db ? strlen(db) : 0;
358
if (passwd + passwd_len + db_len > (char *)net->read_pos + pkt_len)
360
my_error(ER_HANDSHAKE_ERROR, MYF(0), session->main_security_ctx.ip);
364
/* Since 4.1 all database names are stored in utf8 */
367
db_buff[copy_and_convert(db_buff, sizeof(db_buff)-1,
370
session->charset(), &dummy_errors)]= 0;
374
user_buff[user_len= copy_and_convert(user_buff, sizeof(user_buff)-1,
375
system_charset_info, user, user_len,
376
session->charset(), &dummy_errors)]= '\0';
379
/* If username starts and ends in "'", chop them off */
380
if (user_len > 1 && user[0] == '\'' && user[user_len - 1] == '\'')
387
if (session->main_security_ctx.user)
388
if (session->main_security_ctx.user)
389
free(session->main_security_ctx.user);
390
if (!(session->main_security_ctx.user= my_strdup(user, MYF(MY_WME))))
391
return 1; /* The error is set by my_strdup(). */
392
return check_user(session, passwd, passwd_len, db, true);
397
Setup thread to be used with the current thread
400
bool setup_connection_thread_globals()
401
session Thread/connection handler
405
1 Error (out of memory)
406
In this case we will close the connection and increment status
409
bool setup_connection_thread_globals(Session *session)
411
if (session->store_globals())
413
close_connection(session, ER_OUT_OF_RESOURCES, 1);
414
statistic_increment(aborted_connects,&LOCK_status);
415
thread_scheduler.end_thread(session, 0);
423
Autenticate user, with error reporting
427
session Thread handler
430
Connection is not closed in case of errors
438
bool login_connection(Session *session)
440
NET *net= &session->net;
443
/* Use "connect_timeout" value during connection phase */
444
my_net_set_read_timeout(net, connect_timeout);
445
my_net_set_write_timeout(net, connect_timeout);
449
error= check_connection(session);
450
net_end_statement(session);
453
{ // Wrong permissions
454
statistic_increment(aborted_connects,&LOCK_status);
457
/* Connect completed, set read/write timeouts back to default */
458
my_net_set_read_timeout(net, session->variables.net_read_timeout);
459
my_net_set_write_timeout(net, session->variables.net_write_timeout);
465
Close an established connection
468
This mainly updates status variables
471
void end_connection(Session *session)
473
NET *net= &session->net;
474
plugin_sessionvar_cleanup(session);
476
if (session->killed || (net->error && net->vio != 0))
478
statistic_increment(aborted_threads,&LOCK_status);
481
if (net->error && net->vio != 0)
483
if (!session->killed && session->variables.log_warnings > 1)
485
Security_context *sctx= session->security_ctx;
487
sql_print_warning(ER(ER_NEW_ABORTING_CONNECTION),
488
session->thread_id,(session->db ? session->db : "unconnected"),
489
sctx->user ? sctx->user : "unauthenticated",
491
(session->main_da.is_error() ? session->main_da.message() :
492
ER(ER_UNKNOWN_ERROR)));
499
Initialize Session to handle queries
502
void prepare_new_connection_state(Session* session)
504
Security_context *sctx= session->security_ctx;
506
if (session->variables.max_join_size == HA_POS_ERROR)
507
session->options |= OPTION_BIG_SELECTS;
508
if (session->client_capabilities & CLIENT_COMPRESS)
509
session->net.compress=1; // Use compression
512
Much of this is duplicated in create_embedded_session() for the
513
embedded server library.
514
TODO: refactor this to avoid code duplication there
516
session->version= refresh_version;
517
session->set_proc_info(0);
518
session->command= COM_SLEEP;
520
session->init_for_queries();
522
/* In the past this would only run of the user did not have SUPER_ACL */
523
if (sys_init_connect.value_length)
525
execute_init_command(session, &sys_init_connect, &LOCK_sys_init_connect);
526
if (session->is_error())
528
session->killed= Session::KILL_CONNECTION;
529
sql_print_warning(ER(ER_NEW_ABORTING_CONNECTION),
530
session->thread_id,(session->db ? session->db : "unconnected"),
531
sctx->user ? sctx->user : "unauthenticated",
532
sctx->ip, "init_connect command failed");
533
sql_print_warning("%s", session->main_da.message());
535
session->set_proc_info(0);
537
session->init_for_queries();
543
Thread handler for a connection
546
handle_one_connection()
547
arg Connection object (Session)
550
This function (normally) does the following:
552
- Initialize Session to be used with this thread
554
- Execute all queries sent on the connection
555
- Take connection down
556
- End thread / Handle next connection using thread from thread cache
559
pthread_handler_t handle_one_connection(void *arg)
561
Session *session= (Session*) arg;
562
uint32_t launch_time= (uint32_t) ((session->thr_create_utime= my_micro_time()) -
563
session->connect_utime);
565
if (thread_scheduler.init_new_connection_thread())
567
close_connection(session, ER_OUT_OF_RESOURCES, 1);
568
statistic_increment(aborted_connects,&LOCK_status);
569
thread_scheduler.end_thread(session,0);
572
if (launch_time >= slow_launch_time*1000000L)
573
statistic_increment(slow_launch_threads,&LOCK_status);
576
handle_one_connection() is normally the only way a thread would
577
start and would always be on the very high end of the stack ,
578
therefore, the thread stack always starts at the address of the
579
first local variable of handle_one_connection, which is session. We
580
need to know the start of the stack so that we could check for
583
session->thread_stack= (char*) &session;
584
if (setup_connection_thread_globals(session))
589
NET *net= &session->net;
591
if (login_connection(session))
594
prepare_new_connection_state(session);
596
while (!net->error && net->vio != 0 &&
597
!(session->killed == Session::KILL_CONNECTION))
599
if (do_command(session))
602
end_connection(session);
605
close_connection(session, 0, 1);
606
if (thread_scheduler.end_thread(session,1))
607
return 0; // Probably no-threads
610
If end_thread() returns, we are either running with
611
thread-handler=no-threads or this thread has been schedule to
612
handle the next connection.
614
session= current_session;
615
session->thread_stack= (char*) &session;