~drizzle-trunk/drizzle/development

« back to all changes in this revision

Viewing changes to drizzled/sql_connect.cc

  • Committer: Brian Aker
  • Date: 2009-01-07 21:26:58 UTC
  • Revision ID: brian@tangent.org-20090107212658-2fh0s2uwh10w68y2
Committing fix lock_multi

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