~drizzle-trunk/drizzle/development

« back to all changes in this revision

Viewing changes to drizzled/sql_connect.cc

  • Committer: Brian Aker
  • Date: 2009-01-24 09:43:35 UTC
  • Revision ID: brian@gir-3.local-20090124094335-6qdtvc35gl5fvivz
Adding in an example singe thread scheduler

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