~drizzle-trunk/drizzle/development

« back to all changes in this revision

Viewing changes to drizzled/sql_connect.cc

  • Committer: Brian Aker
  • Date: 2009-02-10 00:14:40 UTC
  • Revision ID: brian@tangent.org-20090210001440-qjg8eofh3h93064b
Adding Multi-threaded Scheduler into the system.

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
/* -*- mode: c++; c-basic-offset: 2; indent-tabs-mode: nil; -*-
 
2
 *  vim:expandtab:shiftwidth=2:tabstop=2:smarttab:
 
3
 *
 
4
 *  Copyright (C) 2008 Sun Microsystems
 
5
 *
 
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.
 
9
 *
 
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.
 
14
 *
 
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
 
18
 */
 
19
 
 
20
 
 
21
/*
 
22
  Functions to autenticate and handle reqests for a connection
 
23
*/
 
24
#include <drizzled/server_includes.h>
 
25
#include <netdb.h>
 
26
 
 
27
#include <drizzled/authentication.h>
 
28
#include <drizzled/db.h>
 
29
#include <drizzled/error.h>
 
30
#include <drizzled/sql_parse.h>
 
31
#include <drizzled/plugin_scheduling.h>
 
32
#include <drizzled/session.h>
 
33
#include <drizzled/data_home.h>
 
34
 
 
35
extern scheduling_st thread_scheduler;
 
36
 
 
37
#define MIN_HANDSHAKE_SIZE      6
 
38
 
 
39
/**
 
40
  Check if user exist and password supplied is correct.
 
41
 
 
42
  @param  session         thread handle, session->security_ctx->{host,user,ip} are used
 
43
  @param  command     originator of the check: now check_user is called
 
44
                      during connect and change user procedures; used for
 
45
                      logging.
 
46
  @param  passwd      scrambled password received from client
 
47
  @param  passwd_len  length of scrambled password
 
48
  @param  db          database name to connect to, may be NULL
 
49
 
 
50
  @note Host, user and passwd may point to communication buffer.
 
51
  Current implementation does not depend on that, but future changes
 
52
  should be done with this in mind; 'session' is INOUT, all other params
 
53
  are 'IN'.
 
54
 
 
55
  @retval  0  OK
 
56
  @retval  1  error, e.g. access denied or handshake error, not sent to
 
57
              the client. A message is pushed into the error stack.
 
58
*/
 
59
 
 
60
int
 
61
check_user(Session *session, const char *passwd,
 
62
           uint32_t passwd_len, const char *db)
 
63
{
 
64
  LEX_STRING db_str= { (char *) db, db ? strlen(db) : 0 };
 
65
  bool is_authenticated;
 
66
 
 
67
  /*
 
68
    Clear session->db as it points to something, that will be freed when
 
69
    connection is closed. We don't want to accidentally free a wrong
 
70
    pointer if connect failed. Also in case of 'CHANGE USER' failure,
 
71
    current database will be switched to 'no database selected'.
 
72
  */
 
73
  session->reset_db(NULL, 0);
 
74
 
 
75
  if (passwd_len != 0 && passwd_len != SCRAMBLE_LENGTH)
 
76
  {
 
77
    my_error(ER_HANDSHAKE_ERROR, MYF(0), session->security_ctx.ip.c_str());
 
78
    return(1);
 
79
  }
 
80
 
 
81
  is_authenticated= authenticate_user(session, passwd);
 
82
 
 
83
  if (is_authenticated != true)
 
84
  {
 
85
    my_error(ER_ACCESS_DENIED_ERROR, MYF(0),
 
86
             session->security_ctx.user.c_str(),
 
87
             session->security_ctx.ip.c_str(),
 
88
             passwd_len ? ER(ER_YES) : ER(ER_NO));
 
89
 
 
90
    return 1;
 
91
  }
 
92
 
 
93
 
 
94
  session->security_ctx.skip_grants();
 
95
 
 
96
  /* Change database if necessary */
 
97
  if (db && db[0])
 
98
  {
 
99
    if (mysql_change_db(session, &db_str, false))
 
100
    {
 
101
      /* mysql_change_db() has pushed the error message. */
 
102
      return(1);
 
103
    }
 
104
  }
 
105
  session->my_ok();
 
106
  session->password= test(passwd_len);          // remember for error messages
 
107
  /* Ready to handle queries */
 
108
  return(0);
 
109
}
 
110
 
 
111
 
 
112
/*
 
113
  Check for maximum allowable user connections, if the mysqld server is
 
114
  started with corresponding variable that is greater then 0.
 
115
*/
 
116
 
 
117
extern "C" unsigned char *get_key_conn(user_conn *buff, size_t *length,
 
118
                               bool )
 
119
{
 
120
  *length= buff->len;
 
121
  return (unsigned char*) buff->user;
 
122
}
 
123
 
 
124
 
 
125
extern "C" void free_user(struct user_conn *uc)
 
126
{
 
127
  free((char*) uc);
 
128
}
 
129
 
 
130
/*
 
131
  Initialize connection threads
 
132
*/
 
133
 
 
134
bool init_new_connection_handler_thread()
 
135
{
 
136
  if (my_thread_init())
 
137
    return 1;
 
138
  return 0;
 
139
}
 
140
 
 
141
/*
 
142
  Perform handshake, authorize client and update session ACL variables.
 
143
 
 
144
  SYNOPSIS
 
145
    check_connection()
 
146
    session  thread handle
 
147
 
 
148
  RETURN
 
149
     0  success, OK is sent to user, session is updated.
 
150
    -1  error, which is sent to user
 
151
   > 0  error code (not sent to user)
 
152
*/
 
153
 
 
154
static int check_connection(Session *session)
 
155
{
 
156
  NET *net= &session->net;
 
157
  uint32_t pkt_len= 0;
 
158
  char *end;
 
159
 
 
160
  // TCP/IP connection
 
161
  {
 
162
    char ip[NI_MAXHOST];
 
163
 
 
164
    if (drizzleclient_net_peer_addr(net, ip, &session->peer_port, NI_MAXHOST))
 
165
    {
 
166
      my_error(ER_BAD_HOST_ERROR, MYF(0), session->security_ctx.ip.c_str());
 
167
      return 1;
 
168
    }
 
169
 
 
170
    session->security_ctx.ip.assign(ip);
 
171
  }
 
172
  drizzleclient_net_keepalive(net, true);
 
173
 
 
174
  uint32_t server_capabilites;
 
175
  {
 
176
    /* buff[] needs to big enough to hold the server_version variable */
 
177
    char buff[SERVER_VERSION_LENGTH + SCRAMBLE_LENGTH + 64];
 
178
    server_capabilites= CLIENT_BASIC_FLAGS;
 
179
 
 
180
    if (opt_using_transactions)
 
181
      server_capabilites|= CLIENT_TRANSACTIONS;
 
182
#ifdef HAVE_COMPRESS
 
183
    server_capabilites|= CLIENT_COMPRESS;
 
184
#endif /* HAVE_COMPRESS */
 
185
 
 
186
    end= buff + strlen(server_version);
 
187
    if ((end - buff) >= SERVER_VERSION_LENGTH)
 
188
      end= buff + (SERVER_VERSION_LENGTH - 1);
 
189
    memcpy(buff, server_version, end - buff);
 
190
    *end= 0;
 
191
    end++;
 
192
 
 
193
    int4store((unsigned char*) end, session->thread_id);
 
194
    end+= 4;
 
195
    /*
 
196
      So as check_connection is the only entry point to authorization
 
197
      procedure, scramble is set here. This gives us new scramble for
 
198
      each handshake.
 
199
    */
 
200
    drizzleclient_create_random_string(session->scramble, SCRAMBLE_LENGTH, &session->rand);
 
201
    /*
 
202
      Old clients does not understand long scrambles, but can ignore packet
 
203
      tail: that's why first part of the scramble is placed here, and second
 
204
      part at the end of packet.
 
205
    */
 
206
    end= strncpy(end, session->scramble, SCRAMBLE_LENGTH_323);
 
207
    end+= SCRAMBLE_LENGTH_323 + 1;
 
208
 
 
209
    int2store(end, server_capabilites);
 
210
    /* write server characteristics: up to 16 bytes allowed */
 
211
    end[2]=(char) default_charset_info->number;
 
212
    int2store(end+3, session->server_status);
 
213
    memset(end+5, 0, 13);
 
214
    end+= 18;
 
215
    /* write scramble tail */
 
216
    size_t scramble_len= SCRAMBLE_LENGTH - SCRAMBLE_LENGTH_323;
 
217
    end= strncpy(end, session->scramble + SCRAMBLE_LENGTH_323, scramble_len);
 
218
    end+= scramble_len + 1;
 
219
 
 
220
    /* At this point we write connection message and read reply */
 
221
    if (drizzleclient_net_write_command(net, (unsigned char) protocol_version, (unsigned char*) "", 0,
 
222
                          (unsigned char*) buff, (size_t) (end-buff)) ||
 
223
        (pkt_len= drizzleclient_net_read(net)) == packet_error ||
 
224
        pkt_len < MIN_HANDSHAKE_SIZE)
 
225
    {
 
226
      my_error(ER_HANDSHAKE_ERROR, MYF(0),
 
227
               session->security_ctx.ip.c_str());
 
228
      return 1;
 
229
    }
 
230
  }
 
231
  if (session->packet.alloc(session->variables.net_buffer_length))
 
232
    return 1; /* The error is set by alloc(). */
 
233
 
 
234
  session->client_capabilities= uint2korr(net->read_pos);
 
235
 
 
236
 
 
237
  session->client_capabilities|= ((uint32_t) uint2korr(net->read_pos+2)) << 16;
 
238
  session->max_client_packet_length= uint4korr(net->read_pos+4);
 
239
  session->update_charset();
 
240
  end= (char*) net->read_pos+32;
 
241
 
 
242
  /*
 
243
    Disable those bits which are not supported by the server.
 
244
    This is a precautionary measure, if the client lies. See Bug#27944.
 
245
  */
 
246
  session->client_capabilities&= server_capabilites;
 
247
 
 
248
  if (end >= (char*) net->read_pos+ pkt_len +2)
 
249
  {
 
250
 
 
251
    my_error(ER_HANDSHAKE_ERROR, MYF(0), session->security_ctx.ip.c_str());
 
252
    return 1;
 
253
  }
 
254
 
 
255
  if (session->client_capabilities & CLIENT_INTERACTIVE)
 
256
    session->variables.net_wait_timeout= session->variables.net_interactive_timeout;
 
257
  if ((session->client_capabilities & CLIENT_TRANSACTIONS) &&
 
258
      opt_using_transactions)
 
259
    net->return_status= &session->server_status;
 
260
 
 
261
  char *user= end;
 
262
  char *passwd= strchr(user, '\0')+1;
 
263
  uint32_t user_len= passwd - user - 1;
 
264
  char *db= passwd;
 
265
  char db_buff[NAME_LEN + 1];           // buffer to store db in utf8
 
266
  char user_buff[USERNAME_LENGTH + 1];  // buffer to store user in utf8
 
267
  uint32_t dummy_errors;
 
268
 
 
269
  /*
 
270
    Old clients send null-terminated string as password; new clients send
 
271
    the size (1 byte) + string (not null-terminated). Hence in case of empty
 
272
    password both send '\0'.
 
273
 
 
274
    This strlen() can't be easily deleted without changing protocol.
 
275
 
 
276
    Cast *passwd to an unsigned char, so that it doesn't extend the sign for
 
277
    *passwd > 127 and become 2**32-127+ after casting to uint.
 
278
  */
 
279
  uint32_t passwd_len= session->client_capabilities & CLIENT_SECURE_CONNECTION ?
 
280
    (unsigned char)(*passwd++) : strlen(passwd);
 
281
  db= session->client_capabilities & CLIENT_CONNECT_WITH_DB ?
 
282
    db + passwd_len + 1 : 0;
 
283
  /* strlen() can't be easily deleted without changing protocol */
 
284
  uint32_t db_len= db ? strlen(db) : 0;
 
285
 
 
286
  if (passwd + passwd_len + db_len > (char *)net->read_pos + pkt_len)
 
287
  {
 
288
    my_error(ER_HANDSHAKE_ERROR, MYF(0), session->security_ctx.ip.c_str());
 
289
    return 1;
 
290
  }
 
291
 
 
292
  /* Since 4.1 all database names are stored in utf8 */
 
293
  if (db)
 
294
  {
 
295
    db_buff[copy_and_convert(db_buff, sizeof(db_buff)-1,
 
296
                             system_charset_info,
 
297
                             db, db_len,
 
298
                             session->charset(), &dummy_errors)]= 0;
 
299
    db= db_buff;
 
300
  }
 
301
 
 
302
  user_buff[user_len= copy_and_convert(user_buff, sizeof(user_buff)-1,
 
303
                                       system_charset_info, user, user_len,
 
304
                                       session->charset(), &dummy_errors)]= '\0';
 
305
  user= user_buff;
 
306
 
 
307
  /* If username starts and ends in "'", chop them off */
 
308
  if (user_len > 1 && user[0] == '\'' && user[user_len - 1] == '\'')
 
309
  {
 
310
    user[user_len-1]= 0;
 
311
    user++;
 
312
    user_len-= 2;
 
313
  }
 
314
 
 
315
  session->security_ctx.user.assign(user);
 
316
 
 
317
  return check_user(session, passwd, passwd_len, db);
 
318
}
 
319
 
 
320
 
 
321
/*
 
322
  Setup thread to be used with the current thread
 
323
 
 
324
  SYNOPSIS
 
325
    bool setup_connection_thread_globals()
 
326
    session    Thread/connection handler
 
327
 
 
328
  RETURN
 
329
    0   ok
 
330
    1   Error (out of memory)
 
331
        In this case we will close the connection and increment status
 
332
*/
 
333
 
 
334
bool setup_connection_thread_globals(Session *session)
 
335
{
 
336
  if (session->store_globals())
 
337
  {
 
338
    session->close_connection(ER_OUT_OF_RESOURCES, true);
 
339
    statistic_increment(aborted_connects,&LOCK_status);
 
340
    thread_scheduler.end_thread(session, 0);
 
341
    return 1;                                   // Error
 
342
  }
 
343
  return 0;
 
344
}
 
345
 
 
346
 
 
347
/*
 
348
  Autenticate user, with error reporting
 
349
 
 
350
  SYNOPSIS
 
351
   login_connection()
 
352
   session        Thread handler
 
353
 
 
354
  NOTES
 
355
    Connection is not closed in case of errors
 
356
 
 
357
  RETURN
 
358
    0    ok
 
359
    1    error
 
360
*/
 
361
 
 
362
 
 
363
bool login_connection(Session *session)
 
364
{
 
365
  NET *net= &session->net;
 
366
  int error;
 
367
 
 
368
  /* Use "connect_timeout" value during connection phase */
 
369
  drizzleclient_net_set_read_timeout(net, connect_timeout);
 
370
  drizzleclient_net_set_write_timeout(net, connect_timeout);
 
371
 
 
372
  lex_start(session);
 
373
 
 
374
  error= check_connection(session);
 
375
  drizzleclient_net_end_statement(session);
 
376
 
 
377
  if (error)
 
378
  {                                             // Wrong permissions
 
379
    statistic_increment(aborted_connects,&LOCK_status);
 
380
    return(1);
 
381
  }
 
382
  /* Connect completed, set read/write timeouts back to default */
 
383
  drizzleclient_net_set_read_timeout(net, session->variables.net_read_timeout);
 
384
  drizzleclient_net_set_write_timeout(net, session->variables.net_write_timeout);
 
385
  return(0);
 
386
}
 
387
 
 
388
 
 
389
/*
 
390
  Close an established connection
 
391
 
 
392
  NOTES
 
393
    This mainly updates status variables
 
394
*/
 
395
 
 
396
void end_connection(Session *session)
 
397
{
 
398
  NET *net= &session->net;
 
399
  plugin_sessionvar_cleanup(session);
 
400
 
 
401
  if (session->killed || (net->error && net->vio != 0))
 
402
  {
 
403
    statistic_increment(aborted_threads,&LOCK_status);
 
404
  }
 
405
 
 
406
  if (net->error && net->vio != 0)
 
407
  {
 
408
    if (!session->killed && session->variables.log_warnings > 1)
 
409
    {
 
410
      Security_context *sctx= &session->security_ctx;
 
411
 
 
412
      errmsg_printf(ERRMSG_LVL_WARN, ER(ER_NEW_ABORTING_CONNECTION),
 
413
                        session->thread_id,(session->db ? session->db : "unconnected"),
 
414
                        sctx->user.empty() == false ? sctx->user.c_str() : "unauthenticated",
 
415
                        sctx->ip.c_str(),
 
416
                        (session->main_da.is_error() ? session->main_da.message() :
 
417
                         ER(ER_UNKNOWN_ERROR)));
 
418
    }
 
419
  }
 
420
}
 
421
 
 
422
 
 
423
/*
 
424
  Initialize Session to handle queries
 
425
*/
 
426
 
 
427
void prepare_new_connection_state(Session* session)
 
428
{
 
429
  Security_context *sctx= &session->security_ctx;
 
430
 
 
431
  if (session->variables.max_join_size == HA_POS_ERROR)
 
432
    session->options |= OPTION_BIG_SELECTS;
 
433
  if (session->client_capabilities & CLIENT_COMPRESS)
 
434
    session->net.compress=1;                            // Use compression
 
435
 
 
436
  /*
 
437
    Much of this is duplicated in create_embedded_session() for the
 
438
    embedded server library.
 
439
    TODO: refactor this to avoid code duplication there
 
440
  */
 
441
  session->version= refresh_version;
 
442
  session->set_proc_info(0);
 
443
  session->command= COM_SLEEP;
 
444
  session->set_time();
 
445
  session->init_for_queries();
 
446
 
 
447
  /* In the past this would only run of the user did not have SUPER_ACL */
 
448
  if (sys_init_connect.value_length)
 
449
  {
 
450
    execute_init_command(session, &sys_init_connect, &LOCK_sys_init_connect);
 
451
    if (session->is_error())
 
452
    {
 
453
      session->killed= Session::KILL_CONNECTION;
 
454
      errmsg_printf(ERRMSG_LVL_WARN, ER(ER_NEW_ABORTING_CONNECTION),
 
455
                        session->thread_id,(session->db ? session->db : "unconnected"),
 
456
                        sctx->user.empty() == false ? sctx->user.c_str() : "unauthenticated",
 
457
                        sctx->ip.c_str(), "init_connect command failed");
 
458
      errmsg_printf(ERRMSG_LVL_WARN, "%s", session->main_da.message());
 
459
    }
 
460
    session->set_proc_info(0);
 
461
    session->set_time();
 
462
    session->init_for_queries();
 
463
  }
 
464
}
 
465
 
 
466
 
 
467
/*
 
468
  Thread handler for a connection
 
469
 
 
470
  SYNOPSIS
 
471
    handle_one_connection()
 
472
    arg         Connection object (Session)
 
473
 
 
474
  IMPLEMENTATION
 
475
    This function (normally) does the following:
 
476
    - Initialize thread
 
477
    - Initialize Session to be used with this thread
 
478
    - Authenticate user
 
479
    - Execute all queries sent on the connection
 
480
    - Take connection down
 
481
    - End thread  / Handle next connection using thread from thread cache
 
482
*/
 
483
 
 
484
pthread_handler_t handle_one_connection(void *arg)
 
485
{
 
486
  Session *session= (Session*) arg;
 
487
  uint32_t launch_time= (uint32_t) ((session->thr_create_utime= my_micro_time()) -
 
488
                              session->connect_utime);
 
489
 
 
490
  if (thread_scheduler.init_new_connection_thread())
 
491
  {
 
492
    session->close_connection(ER_OUT_OF_RESOURCES, true);
 
493
    statistic_increment(aborted_connects,&LOCK_status);
 
494
    thread_scheduler.end_thread(session,0);
 
495
    return 0;
 
496
  }
 
497
  if (launch_time >= slow_launch_time*1000000L)
 
498
    statistic_increment(slow_launch_threads,&LOCK_status);
 
499
 
 
500
  /*
 
501
    handle_one_connection() is normally the only way a thread would
 
502
    start and would always be on the very high end of the stack ,
 
503
    therefore, the thread stack always starts at the address of the
 
504
    first local variable of handle_one_connection, which is session. We
 
505
    need to know the start of the stack so that we could check for
 
506
    stack overruns.
 
507
  */
 
508
  session->thread_stack= (char*) &session;
 
509
  if (setup_connection_thread_globals(session))
 
510
    return 0;
 
511
 
 
512
  for (;;)
 
513
  {
 
514
    NET *net= &session->net;
 
515
 
 
516
    if (login_connection(session))
 
517
      goto end_thread;
 
518
 
 
519
    prepare_new_connection_state(session);
 
520
 
 
521
    while (!net->error && net->vio != 0 &&
 
522
           !(session->killed == Session::KILL_CONNECTION))
 
523
    {
 
524
      if (do_command(session))
 
525
        break;
 
526
    }
 
527
    end_connection(session);
 
528
 
 
529
end_thread:
 
530
    session->close_connection(0, true);
 
531
    if (thread_scheduler.end_thread(session, 1))
 
532
      return 0;                                 // Probably no-threads
 
533
 
 
534
    /*
 
535
      If end_thread() returns, we are either running with
 
536
      thread-handler=no-threads or this thread has been schedule to
 
537
      handle the next connection.
 
538
    */
 
539
    session= current_session;
 
540
    session->thread_stack= (char*) &session;
 
541
  }
 
542
}