~drizzle-trunk/drizzle/development

« back to all changes in this revision

Viewing changes to drizzled/sql_connect.cc

  • Committer: Monty Taylor
  • Date: 2009-03-08 23:45:12 UTC
  • mto: (923.2.1 mordred)
  • mto: This revision was merged to the branch mainline in revision 921.
  • Revision ID: mordred@inaugust.com-20090308234512-tqkygxtu1iaig23s
Removed C99 isnan() usage, which allows us to remove the util/math.{cc,h} workarounds. Yay for standards!

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