~drizzle-trunk/drizzle/development

« back to all changes in this revision

Viewing changes to plugin/drizzle_protocol/drizzle_protocol.cc

  • Committer: lbieber
  • Date: 2010-09-07 22:29:56 UTC
  • mfrom: (1747.1.3 build)
  • Revision ID: lbieber@orisndriz03-20100907222956-d60u695b7hx3zs0d
Merge Andrew - bug 597778 - Timestamp cannot reliably store leap seconds, so don't try. Leave that to datetime only
Merge Andrew - bug 621862 - Add / clean-up error messages for unireg_abort
Merge Andrew - bug 629563 - Drop the broken --mysql options and Change the --protocol option to accept 'mysql' or 'drizzle' ('mysql' currently default)

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
/* - mode: c; c-basic-offset: 2; indent-tabs-mode: nil; -*-
 
1
/* -*- mode: c++; c-basic-offset: 2; indent-tabs-mode: nil; -*-
2
2
 *  vim:expandtab:shiftwidth=2:tabstop=2:smarttab:
3
3
 *
4
 
 *  Copyright (C) 2010 Brian Aker
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; either version 2 of the License, or
9
 
 *  (at your option) any later version.
10
 
 *
11
 
 *  This program is distributed in the hope that it will be useful,
12
 
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
13
 
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14
 
 *  GNU General Public License for more details.
15
 
 *
16
 
 *  You should have received a copy of the GNU General Public License
17
 
 *  along with this program; if not, write to the Free Software
18
 
 *  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 
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., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
19
18
 */
20
19
 
21
 
 
22
20
#include "config.h"
23
21
#include <drizzled/gettext.h>
24
22
#include <drizzled/error.h>
31
29
#include <iostream>
32
30
#include <boost/program_options.hpp>
33
31
#include <drizzled/module/option_map.h>
34
 
#include "drizzled/util/tokenize.h"
 
32
#include "pack.h"
 
33
#include "errmsg.h"
35
34
#include "drizzle_protocol.h"
36
 
#include "plugin/drizzle_protocol/status_table.h"
 
35
#include "options.h"
 
36
 
 
37
#define PROTOCOL_VERSION 10
37
38
 
38
39
namespace po= boost::program_options;
39
40
using namespace drizzled;
40
41
using namespace std;
41
42
 
42
 
namespace drizzle_plugin
43
 
{
44
43
namespace drizzle_protocol
45
44
{
46
45
 
47
 
std::vector<std::string> ClientDrizzleProtocol::drizzle_admin_ip_addresses;
48
 
static port_constraint port;
49
 
static timeout_constraint connect_timeout;
50
 
static timeout_constraint read_timeout;
51
 
static timeout_constraint write_timeout;
52
 
static retry_constraint retry_count;
53
 
static buffer_constraint buffer_length;
54
46
 
55
47
static const uint32_t DRIZZLE_TCP_PORT= 4427;
56
 
 
57
 
ProtocolCounters *ListenDrizzleProtocol::drizzle_counters= new ProtocolCounters();
 
48
static const unsigned int PACKET_BUFFER_EXTRA_ALLOC= 1024;
 
49
static uint32_t port;
 
50
static uint32_t connect_timeout;
 
51
static uint32_t read_timeout;
 
52
static uint32_t write_timeout;
 
53
static uint32_t retry_count;
 
54
static uint32_t buffer_length;
 
55
static char* bind_address= NULL;
58
56
 
59
57
ListenDrizzleProtocol::~ListenDrizzleProtocol()
60
58
{
 
59
  /* This is strdup'd from the options */
 
60
  free(bind_address);
 
61
}
 
62
 
 
63
const char* ListenDrizzleProtocol::getHost(void) const
 
64
{
 
65
  return bind_address;
61
66
}
62
67
 
63
68
in_port_t ListenDrizzleProtocol::getPort(void) const
64
69
{
65
 
  return port;
66
 
}
 
70
  char *env;
67
71
 
68
 
void ClientDrizzleProtocol::drizzle_compose_ip_addresses(vector<string> options)
69
 
{
70
 
  for (vector<string>::iterator it= options.begin();
71
 
       it != options.end();
72
 
       ++it)
 
72
  if (port == 0)
73
73
  {
74
 
    tokenize(*it, drizzle_admin_ip_addresses, ",", true);
 
74
    port= DRIZZLE_TCP_PORT;
 
75
 
 
76
    if ((env = getenv("DRIZZLE_TCP_PORT")))
 
77
      port= (uint32_t) atoi(env);
 
78
 
 
79
    assert(port != 0);
75
80
  }
76
 
}
77
 
 
78
 
bool ClientDrizzleProtocol::isAdminAllowed(void)
79
 
{
80
 
  if (std::find(drizzle_admin_ip_addresses.begin(), drizzle_admin_ip_addresses.end(), session->user()->address()) != drizzle_admin_ip_addresses.end())
81
 
    return true;
82
 
 
83
 
  return false;
 
81
 
 
82
  return (in_port_t) port;
84
83
}
85
84
 
86
85
plugin::Client *ListenDrizzleProtocol::getClient(int fd)
90
89
  if (new_fd == -1)
91
90
    return NULL;
92
91
 
93
 
  return new ClientDrizzleProtocol(new_fd, getCounters());
94
 
}
95
 
 
96
 
static int init(drizzled::module::Context &context)
97
 
{  
 
92
  return new (nothrow) ClientDrizzleProtocol(new_fd, using_mysql41_protocol);
 
93
}
 
94
 
 
95
ClientDrizzleProtocol::ClientDrizzleProtocol(int fd, bool using_mysql41_protocol_arg):
 
96
  using_mysql41_protocol(using_mysql41_protocol_arg)
 
97
{
 
98
  net.vio= 0;
 
99
 
 
100
  if (fd == -1)
 
101
    return;
 
102
 
 
103
  if (drizzleclient_net_init_sock(&net, fd, 0, buffer_length))
 
104
    throw bad_alloc();
 
105
 
 
106
  drizzleclient_net_set_read_timeout(&net, read_timeout);
 
107
  drizzleclient_net_set_write_timeout(&net, write_timeout);
 
108
  net.retry_count=retry_count;
 
109
}
 
110
 
 
111
ClientDrizzleProtocol::~ClientDrizzleProtocol()
 
112
{
 
113
  if (net.vio)
 
114
    drizzleclient_vio_close(net.vio);
 
115
}
 
116
 
 
117
int ClientDrizzleProtocol::getFileDescriptor(void)
 
118
{
 
119
  return drizzleclient_net_get_sd(&net);
 
120
}
 
121
 
 
122
bool ClientDrizzleProtocol::isConnected()
 
123
{
 
124
  return net.vio != 0;
 
125
}
 
126
 
 
127
bool ClientDrizzleProtocol::isReading(void)
 
128
{
 
129
  return net.reading_or_writing == 1;
 
130
}
 
131
 
 
132
bool ClientDrizzleProtocol::isWriting(void)
 
133
{
 
134
  return net.reading_or_writing == 2;
 
135
}
 
136
 
 
137
bool ClientDrizzleProtocol::flush()
 
138
{
 
139
  if (net.vio == NULL)
 
140
    return false;
 
141
  bool ret= drizzleclient_net_write(&net, (unsigned char*) packet.ptr(),
 
142
                           packet.length());
 
143
  packet.length(0);
 
144
  return ret;
 
145
}
 
146
 
 
147
void ClientDrizzleProtocol::close(void)
 
148
{
 
149
  if (net.vio)
 
150
  { 
 
151
    drizzleclient_net_close(&net);
 
152
    drizzleclient_net_end(&net);
 
153
  }
 
154
}
 
155
 
 
156
bool ClientDrizzleProtocol::authenticate()
 
157
{
 
158
  bool connection_is_valid;
 
159
 
 
160
  /* Use "connect_timeout" value during connection phase */
 
161
  drizzleclient_net_set_read_timeout(&net, connect_timeout);
 
162
  drizzleclient_net_set_write_timeout(&net, connect_timeout);
 
163
 
 
164
  connection_is_valid= checkConnection();
 
165
 
 
166
  if (connection_is_valid)
 
167
    sendOK();
 
168
  else
 
169
  {
 
170
    sendError(session->main_da.sql_errno(), session->main_da.message());
 
171
    return false;
 
172
  }
 
173
 
 
174
  /* Connect completed, set read/write timeouts back to default */
 
175
  drizzleclient_net_set_read_timeout(&net, read_timeout);
 
176
  drizzleclient_net_set_write_timeout(&net, write_timeout);
 
177
  return true;
 
178
}
 
179
 
 
180
bool ClientDrizzleProtocol::readCommand(char **l_packet, uint32_t *packet_length)
 
181
{
 
182
  /*
 
183
    This thread will do a blocking read from the client which
 
184
    will be interrupted when the next command is received from
 
185
    the client, the connection is closed or "net_wait_timeout"
 
186
    number of seconds has passed
 
187
  */
 
188
#ifdef NEVER
 
189
  /* We can do this much more efficiently with poll timeouts or watcher thread,
 
190
     disabling for now, which means net_wait_timeout == read_timeout. */
 
191
  drizzleclient_net_set_read_timeout(&net,
 
192
                                     session->variables.net_wait_timeout);
 
193
#endif
 
194
 
 
195
  net.pkt_nr=0;
 
196
 
 
197
  *packet_length= drizzleclient_net_read(&net);
 
198
  if (*packet_length == packet_error)
 
199
  {
 
200
    /* Check if we can continue without closing the connection */
 
201
 
 
202
    if(net.last_errno== CR_NET_PACKET_TOO_LARGE)
 
203
      my_error(ER_NET_PACKET_TOO_LARGE, MYF(0));
 
204
    if (session->main_da.status() == Diagnostics_area::DA_ERROR)
 
205
      sendError(session->main_da.sql_errno(), session->main_da.message());
 
206
    else
 
207
      sendOK();
 
208
 
 
209
    if (net.error != 3)
 
210
      return false;                       // We have to close it.
 
211
 
 
212
    net.error= 0;
 
213
    *packet_length= 0;
 
214
    return true;
 
215
  }
 
216
 
 
217
  *l_packet= (char*) net.read_pos;
 
218
 
 
219
  /*
 
220
    'packet_length' contains length of data, as it was stored in packet
 
221
    header. In case of malformed header, drizzleclient_net_read returns zero.
 
222
    If packet_length is not zero, drizzleclient_net_read ensures that the returned
 
223
    number of bytes was actually read from network.
 
224
    There is also an extra safety measure in drizzleclient_net_read:
 
225
    it sets packet[packet_length]= 0, but only for non-zero packets.
 
226
  */
 
227
 
 
228
  if (*packet_length == 0)                       /* safety */
 
229
  {
 
230
    /* Initialize with COM_SLEEP packet */
 
231
    (*l_packet)[0]= (unsigned char) COM_SLEEP;
 
232
    *packet_length= 1;
 
233
  }
 
234
  else if (using_mysql41_protocol)
 
235
  {
 
236
    /* Map from MySQL commands to Drizzle commands. */
 
237
    switch ((int)(*l_packet)[0])
 
238
    {
 
239
    case 0: /* SLEEP */
 
240
    case 1: /* QUIT */
 
241
    case 2: /* INIT_DB */
 
242
    case 3: /* QUERY */
 
243
      break;
 
244
 
 
245
    case 8: /* SHUTDOWN */
 
246
      (*l_packet)[0]= (unsigned char) COM_SHUTDOWN;
 
247
      break;
 
248
 
 
249
    case 14: /* PING */
 
250
      (*l_packet)[0]= (unsigned char) COM_SHUTDOWN;
 
251
      break;
 
252
 
 
253
 
 
254
    default:
 
255
      /* Just drop connection for MySQL commands we don't support. */
 
256
      (*l_packet)[0]= (unsigned char) COM_QUIT;
 
257
      *packet_length= 1;
 
258
      break;
 
259
    }
 
260
  }
 
261
 
 
262
  /* Do not rely on drizzleclient_net_read, extra safety against programming errors. */
 
263
  (*l_packet)[*packet_length]= '\0';                  /* safety */
 
264
 
 
265
#ifdef NEVER
 
266
  /* See comment above. */
 
267
  /* Restore read timeout value */
 
268
  drizzleclient_net_set_read_timeout(&net,
 
269
                                     session->variables.net_read_timeout);
 
270
#endif
 
271
 
 
272
  return true;
 
273
}
 
274
 
 
275
/**
 
276
  Return ok to the client.
 
277
 
 
278
  The ok packet has the following structure:
 
279
 
 
280
  - 0               : Marker (1 byte)
 
281
  - affected_rows    : Stored in 1-9 bytes
 
282
  - id        : Stored in 1-9 bytes
 
283
  - server_status    : Copy of session->server_status;  Can be used by client
 
284
  to check if we are inside an transaction.
 
285
  New in 4.0 client
 
286
  - warning_count    : Stored in 2 bytes; New in 4.1 client
 
287
  - message        : Stored as packed length (1-9 bytes) + message.
 
288
  Is not stored if no message.
 
289
 
 
290
  @param session           Thread handler
 
291
  @param affected_rows       Number of rows changed by statement
 
292
  @param id           Auto_increment id for first row (if used)
 
293
  @param message       Message to send to the client (Used by mysql_status)
 
294
*/
 
295
 
 
296
void ClientDrizzleProtocol::sendOK()
 
297
{
 
298
  unsigned char buff[DRIZZLE_ERRMSG_SIZE+10],*pos;
 
299
  const char *message= NULL;
 
300
  uint32_t tmp;
 
301
 
 
302
  if (!net.vio)    // hack for re-parsing queries
 
303
  {
 
304
    return;
 
305
  }
 
306
 
 
307
  buff[0]=0;                    // No fields
 
308
  if (session->main_da.status() == Diagnostics_area::DA_OK)
 
309
  {
 
310
    if (client_capabilities & CLIENT_FOUND_ROWS && session->main_da.found_rows())
 
311
      pos=drizzleclient_net_store_length(buff+1,session->main_da.found_rows());
 
312
    else
 
313
      pos=drizzleclient_net_store_length(buff+1,session->main_da.affected_rows());
 
314
    pos=drizzleclient_net_store_length(pos, session->main_da.last_insert_id());
 
315
    int2store(pos, session->main_da.server_status());
 
316
    pos+=2;
 
317
    tmp= min(session->main_da.total_warn_count(), (uint32_t)65535);
 
318
    message= session->main_da.message();
 
319
  }
 
320
  else
 
321
  {
 
322
    pos=drizzleclient_net_store_length(buff+1,0);
 
323
    pos=drizzleclient_net_store_length(pos, 0);
 
324
    int2store(pos, session->server_status);
 
325
    pos+=2;
 
326
    tmp= min(session->total_warn_count, (uint32_t)65535);
 
327
  }
 
328
 
 
329
  /* We can only return up to 65535 warnings in two bytes */
 
330
  int2store(pos, tmp);
 
331
  pos+= 2;
 
332
 
 
333
  session->main_da.can_overwrite_status= true;
 
334
 
 
335
  if (message && message[0])
 
336
  {
 
337
    size_t length= strlen(message);
 
338
    pos=drizzleclient_net_store_length(pos,length);
 
339
    memcpy(pos,(unsigned char*) message,length);
 
340
    pos+=length;
 
341
  }
 
342
  drizzleclient_net_write(&net, buff, (size_t) (pos-buff));
 
343
  drizzleclient_net_flush(&net);
 
344
 
 
345
  session->main_da.can_overwrite_status= false;
 
346
}
 
347
 
 
348
/**
 
349
  Send eof (= end of result set) to the client.
 
350
 
 
351
  The eof packet has the following structure:
 
352
 
 
353
  - 254    (DRIZZLE_PROTOCOL_NO_MORE_DATA)    : Marker (1 byte)
 
354
  - warning_count    : Stored in 2 bytes; New in 4.1 client
 
355
  - status_flag    : Stored in 2 bytes;
 
356
  For flags like SERVER_MORE_RESULTS_EXISTS.
 
357
 
 
358
  Note that the warning count will not be sent if 'no_flush' is set as
 
359
  we don't want to report the warning count until all data is sent to the
 
360
  client.
 
361
*/
 
362
 
 
363
void ClientDrizzleProtocol::sendEOF()
 
364
{
 
365
  /* Set to true if no active vio, to work well in case of --init-file */
 
366
  if (net.vio != 0)
 
367
  {
 
368
    session->main_da.can_overwrite_status= true;
 
369
    writeEOFPacket(session->main_da.server_status(),
 
370
                   session->main_da.total_warn_count());
 
371
    drizzleclient_net_flush(&net);
 
372
    session->main_da.can_overwrite_status= false;
 
373
  }
 
374
  packet.shrink(buffer_length);
 
375
}
 
376
 
 
377
 
 
378
void ClientDrizzleProtocol::sendError(uint32_t sql_errno, const char *err)
 
379
{
 
380
  uint32_t length;
 
381
  /*
 
382
    buff[]: sql_errno:2 + ('#':1 + SQLSTATE_LENGTH:5) + DRIZZLE_ERRMSG_SIZE:512
 
383
  */
 
384
  unsigned char buff[2+1+SQLSTATE_LENGTH+DRIZZLE_ERRMSG_SIZE], *pos;
 
385
 
 
386
  assert(sql_errno);
 
387
  assert(err && err[0]);
 
388
 
 
389
  /*
 
390
    It's one case when we can push an error even though there
 
391
    is an OK or EOF already.
 
392
  */
 
393
  session->main_da.can_overwrite_status= true;
 
394
 
 
395
  /* Abort multi-result sets */
 
396
  session->server_status&= ~SERVER_MORE_RESULTS_EXISTS;
 
397
 
 
398
  /**
 
399
    Send a error string to client.
 
400
 
 
401
    For SIGNAL/RESIGNAL and GET DIAGNOSTICS functionality it's
 
402
    critical that every error that can be intercepted is issued in one
 
403
    place only, my_message_sql.
 
404
  */
 
405
 
 
406
  if (net.vio == 0)
 
407
  {
 
408
    return;
 
409
  }
 
410
 
 
411
  int2store(buff,sql_errno);
 
412
  pos= buff+2;
 
413
 
 
414
  /* The first # is to make the client backward compatible */
 
415
  buff[2]= '#';
 
416
  pos= (unsigned char*) strcpy((char*) buff+3, drizzle_errno_to_sqlstate(sql_errno));
 
417
  pos+= strlen(drizzle_errno_to_sqlstate(sql_errno));
 
418
 
 
419
  char *tmp= strncpy((char*)pos, err, DRIZZLE_ERRMSG_SIZE-1);
 
420
  tmp+= strlen((char*)pos);
 
421
  tmp[0]= '\0';
 
422
  length= (uint32_t)(tmp-(char*)buff);
 
423
  err= (char*) buff;
 
424
 
 
425
  drizzleclient_net_write_command(&net,(unsigned char) 255, (unsigned char*) "", 0, (unsigned char*) err, length);
 
426
 
 
427
  session->main_da.can_overwrite_status= false;
 
428
}
 
429
 
 
430
/**
 
431
  Send name and type of result to client.
 
432
 
 
433
  Sum fields has table name empty and field_name.
 
434
 
 
435
  @param Session        Thread data object
 
436
  @param list            List of items to send to client
 
437
  @param flag            Bit mask with the following functions:
 
438
                        - 1 send number of rows
 
439
                        - 2 send default values
 
440
                        - 4 don't write eof packet
 
441
 
 
442
  @retval
 
443
    0    ok
 
444
  @retval
 
445
    1    Error  (Note that in this case the error is not sent to the
 
446
    client)
 
447
*/
 
448
bool ClientDrizzleProtocol::sendFields(List<Item> *list)
 
449
{
 
450
  List_iterator_fast<Item> it(*list);
 
451
  Item *item;
 
452
  unsigned char buff[80];
 
453
  String tmp((char*) buff,sizeof(buff),&my_charset_bin);
 
454
 
 
455
  unsigned char *row_pos= drizzleclient_net_store_length(buff, list->elements);
 
456
  (void) drizzleclient_net_write(&net, buff, (size_t) (row_pos-buff));
 
457
 
 
458
  while ((item=it++))
 
459
  {
 
460
    char *pos;
 
461
    SendField field;
 
462
    item->make_field(&field);
 
463
 
 
464
    packet.length(0);
 
465
 
 
466
    if (store(STRING_WITH_LEN("def")) ||
 
467
        store(field.db_name) ||
 
468
        store(field.table_name) ||
 
469
        store(field.org_table_name) ||
 
470
        store(field.col_name) ||
 
471
        store(field.org_col_name) ||
 
472
        packet.realloc(packet.length()+12))
 
473
      goto err;
 
474
 
 
475
    /* Store fixed length fields */
 
476
    pos= (char*) packet.ptr()+packet.length();
 
477
    *pos++= 12;                // Length of packed fields
 
478
    /* No conversion */
 
479
    int2store(pos, field.charsetnr);
 
480
    int4store(pos+2, field.length);
 
481
 
 
482
    if (using_mysql41_protocol)
 
483
    {
 
484
      /* Switch to MySQL field numbering. */
 
485
      switch (field.type)
 
486
      {
 
487
      case DRIZZLE_TYPE_LONG:
 
488
        pos[6]= 3;
 
489
        break;
 
490
 
 
491
      case DRIZZLE_TYPE_DOUBLE:
 
492
        pos[6]= 5;
 
493
        break;
 
494
 
 
495
      case DRIZZLE_TYPE_NULL:
 
496
        pos[6]= 6;
 
497
        break;
 
498
 
 
499
      case DRIZZLE_TYPE_TIMESTAMP:
 
500
        pos[6]= 7;
 
501
        break;
 
502
 
 
503
      case DRIZZLE_TYPE_LONGLONG:
 
504
        pos[6]= 8;
 
505
        break;
 
506
 
 
507
      case DRIZZLE_TYPE_DATETIME:
 
508
        pos[6]= 12;
 
509
        break;
 
510
 
 
511
      case DRIZZLE_TYPE_DATE:
 
512
        pos[6]= 14;
 
513
        break;
 
514
 
 
515
      case DRIZZLE_TYPE_VARCHAR:
 
516
        pos[6]= 15;
 
517
        break;
 
518
 
 
519
      case DRIZZLE_TYPE_DECIMAL:
 
520
        pos[6]= (char)246;
 
521
        break;
 
522
 
 
523
      case DRIZZLE_TYPE_ENUM:
 
524
        pos[6]= (char)247;
 
525
        break;
 
526
 
 
527
      case DRIZZLE_TYPE_BLOB:
 
528
        pos[6]= (char)252;
 
529
        break;
 
530
      }
 
531
    }
 
532
    else
 
533
    {
 
534
      /* Add one to compensate for tinyint removal from enum. */
 
535
      pos[6]= field.type + 1;
 
536
    }
 
537
 
 
538
    int2store(pos+7,field.flags);
 
539
    pos[9]= (char) field.decimals;
 
540
    pos[10]= 0;                // For the future
 
541
    pos[11]= 0;                // For the future
 
542
    pos+= 12;
 
543
 
 
544
    packet.length((uint32_t) (pos - packet.ptr()));
 
545
    if (flush())
 
546
      break;
 
547
  }
 
548
 
 
549
  /*
 
550
    Mark the end of meta-data result set, and store session->server_status,
 
551
    to show that there is no cursor.
 
552
    Send no warning information, as it will be sent at statement end.
 
553
  */
 
554
  writeEOFPacket(session->server_status, session->total_warn_count);
 
555
  return 0;
 
556
 
 
557
err:
 
558
  my_message(ER_OUT_OF_RESOURCES, ER(ER_OUT_OF_RESOURCES),
 
559
             MYF(0));
 
560
  return 1;
 
561
}
 
562
 
 
563
bool ClientDrizzleProtocol::store(Field *from)
 
564
{
 
565
  if (from->is_null())
 
566
    return store();
 
567
  char buff[MAX_FIELD_WIDTH];
 
568
  String str(buff,sizeof(buff), &my_charset_bin);
 
569
 
 
570
  from->val_str(&str);
 
571
 
 
572
  return netStoreData((const unsigned char *)str.ptr(), str.length());
 
573
}
 
574
 
 
575
bool ClientDrizzleProtocol::store(void)
 
576
{
 
577
  char buff[1];
 
578
  buff[0]= (char)251;
 
579
  return packet.append(buff, sizeof(buff), PACKET_BUFFER_EXTRA_ALLOC);
 
580
}
 
581
 
 
582
bool ClientDrizzleProtocol::store(int32_t from)
 
583
{
 
584
  char buff[12];
 
585
  return netStoreData((unsigned char*) buff,
 
586
                      (size_t) (internal::int10_to_str(from, buff, -10) - buff));
 
587
}
 
588
 
 
589
bool ClientDrizzleProtocol::store(uint32_t from)
 
590
{
 
591
  char buff[11];
 
592
  return netStoreData((unsigned char*) buff,
 
593
                      (size_t) (internal::int10_to_str(from, buff, 10) - buff));
 
594
}
 
595
 
 
596
bool ClientDrizzleProtocol::store(int64_t from)
 
597
{
 
598
  char buff[22];
 
599
  return netStoreData((unsigned char*) buff,
 
600
                      (size_t) (internal::int64_t10_to_str(from, buff, -10) - buff));
 
601
}
 
602
 
 
603
bool ClientDrizzleProtocol::store(uint64_t from)
 
604
{
 
605
  char buff[21];
 
606
  return netStoreData((unsigned char*) buff,
 
607
                      (size_t) (internal::int64_t10_to_str(from, buff, 10) - buff));
 
608
}
 
609
 
 
610
bool ClientDrizzleProtocol::store(double from, uint32_t decimals, String *buffer)
 
611
{
 
612
  buffer->set_real(from, decimals, session->charset());
 
613
  return netStoreData((unsigned char*) buffer->ptr(), buffer->length());
 
614
}
 
615
 
 
616
bool ClientDrizzleProtocol::store(const char *from, size_t length)
 
617
{
 
618
  return netStoreData((const unsigned char *)from, length);
 
619
}
 
620
 
 
621
bool ClientDrizzleProtocol::wasAborted(void)
 
622
{
 
623
  return net.error && net.vio != 0;
 
624
}
 
625
 
 
626
bool ClientDrizzleProtocol::haveMoreData(void)
 
627
{
 
628
  return drizzleclient_net_more_data(&net);
 
629
}
 
630
 
 
631
bool ClientDrizzleProtocol::haveError(void)
 
632
{
 
633
  return net.error || net.vio == 0;
 
634
}
 
635
 
 
636
bool ClientDrizzleProtocol::checkConnection(void)
 
637
{
 
638
  uint32_t pkt_len= 0;
 
639
  char *end;
 
640
 
 
641
  // TCP/IP connection
 
642
  {
 
643
    char ip[NI_MAXHOST];
 
644
    uint16_t peer_port;
 
645
 
 
646
    if (drizzleclient_net_peer_addr(&net, ip, &peer_port, NI_MAXHOST))
 
647
    {
 
648
      my_error(ER_BAD_HOST_ERROR, MYF(0), session->getSecurityContext().getIp().c_str());
 
649
      return false;
 
650
    }
 
651
 
 
652
    session->getSecurityContext().setIp(ip);
 
653
  }
 
654
  drizzleclient_net_keepalive(&net, true);
 
655
 
 
656
  uint32_t server_capabilites;
 
657
  {
 
658
    /* buff[] needs to big enough to hold the server_version variable */
 
659
    char buff[SERVER_VERSION_LENGTH + SCRAMBLE_LENGTH + 64];
 
660
 
 
661
    server_capabilites= CLIENT_BASIC_FLAGS;
 
662
 
 
663
    if (using_mysql41_protocol)
 
664
      server_capabilites|= CLIENT_PROTOCOL_MYSQL41;
 
665
 
 
666
#ifdef HAVE_COMPRESS
 
667
    server_capabilites|= CLIENT_COMPRESS;
 
668
#endif /* HAVE_COMPRESS */
 
669
 
 
670
    end= buff + strlen(PANDORA_RELEASE_VERSION);
 
671
    if ((end - buff) >= SERVER_VERSION_LENGTH)
 
672
      end= buff + (SERVER_VERSION_LENGTH - 1);
 
673
    memcpy(buff, PANDORA_RELEASE_VERSION, end - buff);
 
674
    *end= 0;
 
675
    end++;
 
676
 
 
677
    int4store((unsigned char*) end, session->variables.pseudo_thread_id);
 
678
    end+= 4;
 
679
 
 
680
    /* We don't use scramble anymore. */
 
681
    memset(end, 'X', SCRAMBLE_LENGTH_323);
 
682
    end+= SCRAMBLE_LENGTH_323;
 
683
    *end++= 0; /* an empty byte for some reason */
 
684
 
 
685
    int2store(end, server_capabilites);
 
686
    /* write server characteristics: up to 16 bytes allowed */
 
687
    end[2]=(char) default_charset_info->number;
 
688
    int2store(end+3, session->server_status);
 
689
    memset(end+5, 0, 13);
 
690
    end+= 18;
 
691
 
 
692
    /* Write scramble tail. */
 
693
    memset(end, 'X', SCRAMBLE_LENGTH - SCRAMBLE_LENGTH_323);
 
694
    end+= (SCRAMBLE_LENGTH - SCRAMBLE_LENGTH_323);
 
695
    *end++= 0; /* an empty byte for some reason */
 
696
 
 
697
    /* At this point we write connection message and read reply */
 
698
    if (drizzleclient_net_write_command(&net
 
699
          , (unsigned char) PROTOCOL_VERSION
 
700
          , (unsigned char*) ""
 
701
          , 0
 
702
          , (unsigned char*) buff
 
703
          , (size_t) (end-buff)) 
 
704
        ||    (pkt_len= drizzleclient_net_read(&net)) == packet_error 
 
705
        || pkt_len < MIN_HANDSHAKE_SIZE)
 
706
    {
 
707
      my_error(ER_HANDSHAKE_ERROR, MYF(0), session->getSecurityContext().getIp().c_str());
 
708
      return false;
 
709
    }
 
710
  }
 
711
  if (packet.alloc(buffer_length))
 
712
    return false; /* The error is set by alloc(). */
 
713
 
 
714
  client_capabilities= uint2korr(net.read_pos);
 
715
 
 
716
 
 
717
  client_capabilities|= ((uint32_t) uint2korr(net.read_pos + 2)) << 16;
 
718
  session->max_client_packet_length= uint4korr(net.read_pos + 4);
 
719
  end= (char*) net.read_pos + 32;
 
720
 
 
721
  /*
 
722
    Disable those bits which are not supported by the server.
 
723
    This is a precautionary measure, if the client lies. See Bug#27944.
 
724
  */
 
725
  client_capabilities&= server_capabilites;
 
726
 
 
727
  if (end >= (char*) net.read_pos + pkt_len + 2)
 
728
  {
 
729
    my_error(ER_HANDSHAKE_ERROR, MYF(0), session->getSecurityContext().getIp().c_str());
 
730
    return false;
 
731
  }
 
732
 
 
733
  net.return_status= &session->server_status;
 
734
 
 
735
  char *user= end;
 
736
  char *passwd= strchr(user, '\0')+1;
 
737
  uint32_t user_len= passwd - user - 1;
 
738
  char *l_db= passwd;
 
739
 
 
740
  /*
 
741
    Old clients send null-terminated string as password; new clients send
 
742
    the size (1 byte) + string (not null-terminated). Hence in case of empty
 
743
    password both send '\0'.
 
744
 
 
745
    This strlen() can't be easily deleted without changing client.
 
746
 
 
747
    Cast *passwd to an unsigned char, so that it doesn't extend the sign for
 
748
    *passwd > 127 and become 2**32-127+ after casting to uint.
 
749
  */
 
750
  uint32_t passwd_len= client_capabilities & CLIENT_SECURE_CONNECTION ?
 
751
    (unsigned char)(*passwd++) : strlen(passwd);
 
752
  l_db= client_capabilities & CLIENT_CONNECT_WITH_DB ? l_db + passwd_len + 1 : 0;
 
753
 
 
754
  /* strlen() can't be easily deleted without changing client */
 
755
  uint32_t db_len= l_db ? strlen(l_db) : 0;
 
756
 
 
757
  if (passwd + passwd_len + db_len > (char *) net.read_pos + pkt_len)
 
758
  {
 
759
    my_error(ER_HANDSHAKE_ERROR, MYF(0), session->getSecurityContext().getIp().c_str());
 
760
    return false;
 
761
  }
 
762
 
 
763
  /* If username starts and ends in "'", chop them off */
 
764
  if (user_len > 1 && user[0] == '\'' && user[user_len - 1] == '\'')
 
765
  {
 
766
    user[user_len-1]= 0;
 
767
    user++;
 
768
    user_len-= 2;
 
769
  }
 
770
 
 
771
  session->getSecurityContext().setUser(user);
 
772
 
 
773
  return session->checkUser(passwd, passwd_len, l_db);
 
774
}
 
775
 
 
776
bool ClientDrizzleProtocol::netStoreData(const unsigned char *from, size_t length)
 
777
{
 
778
  size_t packet_length= packet.length();
 
779
  /*
 
780
     The +9 comes from that strings of length longer than 16M require
 
781
     9 bytes to be stored (see drizzleclient_net_store_length).
 
782
  */
 
783
  if (packet_length+9+length > packet.alloced_length() &&
 
784
      packet.realloc(packet_length+9+length))
 
785
    return 1;
 
786
  unsigned char *to= drizzleclient_net_store_length((unsigned char*) packet.ptr()+packet_length, length);
 
787
  memcpy(to,from,length);
 
788
  packet.length((size_t) (to+length-(unsigned char*) packet.ptr()));
 
789
  return 0;
 
790
}
 
791
 
 
792
/**
 
793
  Format EOF packet according to the current client and
 
794
  write it to the network output buffer.
 
795
*/
 
796
 
 
797
void ClientDrizzleProtocol::writeEOFPacket(uint32_t server_status,
 
798
                                         uint32_t total_warn_count)
 
799
{
 
800
  unsigned char buff[5];
 
801
  /*
 
802
    Don't send warn count during SP execution, as the warn_list
 
803
    is cleared between substatements, and mysqltest gets confused
 
804
  */
 
805
  uint32_t tmp= min(total_warn_count, (uint32_t)65535);
 
806
  buff[0]= DRIZZLE_PROTOCOL_NO_MORE_DATA;
 
807
  int2store(buff+1, tmp);
 
808
  /*
 
809
    The following test should never be true, but it's better to do it
 
810
    because if 'is_fatal_error' is set the server is not going to execute
 
811
    other queries (see the if test in dispatch_command / COM_QUERY)
 
812
  */
 
813
  if (session->is_fatal_error)
 
814
    server_status&= ~SERVER_MORE_RESULTS_EXISTS;
 
815
  int2store(buff + 3, server_status);
 
816
  drizzleclient_net_write(&net, buff, 5);
 
817
}
 
818
 
 
819
static int init(module::Context &context)
 
820
{
98
821
  const module::option_map &vm= context.getOptions();
99
 
 
100
 
  context.add(new StatusTable);
101
 
  context.add(new ListenDrizzleProtocol("drizzle_protocol", vm["bind-address"].as<std::string>(), true));
102
 
  context.registerVariable(new sys_var_constrained_value_readonly<in_port_t>("port", port));
103
 
  context.registerVariable(new sys_var_constrained_value_readonly<uint32_t>("connect_timeout", connect_timeout));
104
 
  context.registerVariable(new sys_var_constrained_value_readonly<uint32_t>("read_timeout", read_timeout));
105
 
  context.registerVariable(new sys_var_constrained_value_readonly<uint32_t>("write_timeout", write_timeout));
106
 
  context.registerVariable(new sys_var_constrained_value_readonly<uint32_t>("retry_count", retry_count));
107
 
  context.registerVariable(new sys_var_constrained_value_readonly<uint32_t>("buffer_length", buffer_length));
108
 
  context.registerVariable(new sys_var_const_string_val("bind_address",
109
 
                                                        vm["bind-address"].as<std::string>()));
110
 
 
111
 
  context.registerVariable(new sys_var_uint32_t_ptr("max-connections", &ListenDrizzleProtocol::drizzle_counters->max_connections));
112
 
 
 
822
  if (vm.count("port"))
 
823
  { 
 
824
    if (port > 65535)
 
825
    {
 
826
      errmsg_printf(ERRMSG_LVL_ERROR, _("Invalid value of port\n"));
 
827
      exit(-1);
 
828
    }
 
829
  }
 
830
 
 
831
  if (vm.count("connect-timeout"))
 
832
  {
 
833
    if (connect_timeout < 1 || connect_timeout > 300)
 
834
    {
 
835
      errmsg_printf(ERRMSG_LVL_ERROR, _("Invalid value for connect_timeout\n"));
 
836
      exit(-1);
 
837
    }
 
838
  }
 
839
 
 
840
  if (vm.count("read-timeout"))
 
841
  {
 
842
    if (read_timeout < 1 || read_timeout > 300)
 
843
    {
 
844
      errmsg_printf(ERRMSG_LVL_ERROR, _("Invalid value for read_timeout\n"));
 
845
      exit(-1);
 
846
    }
 
847
  }
 
848
 
 
849
  if (vm.count("write-timeout"))
 
850
  {
 
851
    if (write_timeout < 1 || write_timeout > 300)
 
852
    {
 
853
      errmsg_printf(ERRMSG_LVL_ERROR, _("Invalid value for write_timeout\n"));
 
854
      exit(-1);
 
855
    }
 
856
  }
 
857
 
 
858
  if (vm.count("retry-count"))
 
859
  {
 
860
    if (retry_count < 1 || retry_count > 100)
 
861
    {
 
862
      errmsg_printf(ERRMSG_LVL_ERROR, _("Invalid value for retry_count\n"));
 
863
      exit(-1);
 
864
    }
 
865
  }
 
866
 
 
867
  if (vm.count("buffer-length"))
 
868
  {
 
869
    if (buffer_length < 1024 || buffer_length > 1024*1024)
 
870
    {
 
871
      errmsg_printf(ERRMSG_LVL_ERROR, _("Invalid value for buffer_length\n"));
 
872
      exit(-1);
 
873
    }
 
874
  }
 
875
 
 
876
  if (vm.count("bind-address"))
 
877
  {
 
878
    bind_address= strdup(vm["bind-address"].as<string>().c_str());
 
879
  }
 
880
 
 
881
  else
 
882
  {
 
883
    bind_address= NULL;
 
884
  }
 
885
  
 
886
  context.add(new ListenDrizzleProtocol("drizzle_protocol", false)); 
113
887
  return 0;
114
888
}
115
889
 
 
890
static DRIZZLE_SYSVAR_UINT(port, port, PLUGIN_VAR_RQCMDARG,
 
891
                           N_("Port number to use for connection or 0 for "
 
892
                              "default to, in order of "
 
893
                              "preference, drizzle.cnf, $DRIZZLE_TCP_PORT, "
 
894
                              "built-in default (4427)."),
 
895
                           NULL, NULL, 0, 0, 65535, 0);
 
896
static DRIZZLE_SYSVAR_UINT(connect_timeout, connect_timeout,
 
897
                           PLUGIN_VAR_RQCMDARG, N_("Connect Timeout."),
 
898
                           NULL, NULL, 10, 1, 300, 0);
 
899
static DRIZZLE_SYSVAR_UINT(read_timeout, read_timeout, PLUGIN_VAR_RQCMDARG,
 
900
                           N_("Read Timeout."), NULL, NULL, 30, 1, 300, 0);
 
901
static DRIZZLE_SYSVAR_UINT(write_timeout, write_timeout, PLUGIN_VAR_RQCMDARG,
 
902
                           N_("Write Timeout."), NULL, NULL, 60, 1, 300, 0);
 
903
static DRIZZLE_SYSVAR_UINT(retry_count, retry_count, PLUGIN_VAR_RQCMDARG,
 
904
                           N_("Retry Count."), NULL, NULL, 10, 1, 100, 0);
 
905
static DRIZZLE_SYSVAR_UINT(buffer_length, buffer_length, PLUGIN_VAR_RQCMDARG,
 
906
                           N_("Buffer length."), NULL, NULL, 16384, 1024,
 
907
                           1024*1024, 0);
 
908
static DRIZZLE_SYSVAR_STR(bind_address, bind_address, PLUGIN_VAR_READONLY,
 
909
                          N_("Address to bind to."), NULL, NULL, NULL);
116
910
 
117
911
static void init_options(drizzled::module::option_context &context)
118
912
{
119
913
  context("port",
120
 
          po::value<port_constraint>(&port)->default_value(DRIZZLE_TCP_PORT),
121
 
          N_("Port number to use for connection or 0 for default to with Drizzle/MySQL protocol."));
 
914
          po::value<uint32_t>(&port)->default_value(0),
 
915
          N_("Port number to use for connection or 0 for "
 
916
                              "default to, in order of "
 
917
                              "preference, drizzle.cnf, $DRIZZLE_TCP_PORT, "
 
918
                              "built-in default (4427)."));
122
919
  context("connect-timeout",
123
 
          po::value<timeout_constraint>(&connect_timeout)->default_value(10),
 
920
          po::value<uint32_t>(&connect_timeout)->default_value(10),
124
921
          N_("Connect Timeout."));
125
922
  context("read-timeout",
126
 
          po::value<timeout_constraint>(&read_timeout)->default_value(30),
 
923
          po::value<uint32_t>(&read_timeout)->default_value(30),
127
924
          N_("Read Timeout."));
128
925
  context("write-timeout",
129
 
          po::value<timeout_constraint>(&write_timeout)->default_value(60),
 
926
          po::value<uint32_t>(&write_timeout)->default_value(60),
130
927
          N_("Write Timeout."));
131
928
  context("retry-count",
132
 
          po::value<retry_constraint>(&retry_count)->default_value(10),
 
929
          po::value<uint32_t>(&retry_count)->default_value(10),
133
930
          N_("Retry Count."));
134
931
  context("buffer-length",
135
 
          po::value<buffer_constraint>(&buffer_length)->default_value(16384),
 
932
          po::value<uint32_t>(&buffer_length)->default_value(16384),
136
933
          N_("Buffer length."));
137
934
  context("bind-address",
138
 
          po::value<std::string>()->default_value(""),
 
935
          po::value<string>(),
139
936
          N_("Address to bind to."));
140
 
  context("max-connections",
141
 
          po::value<uint32_t>(&ListenDrizzleProtocol::drizzle_counters->max_connections)->default_value(1000),
142
 
          N_("Maximum simultaneous connections."));
143
 
  context("admin-ip-addresses",
144
 
          po::value<vector<string> >()->composing()->notifier(&ClientDrizzleProtocol::drizzle_compose_ip_addresses),
145
 
          N_("A restrictive IP address list for incoming admin connections."));
146
937
}
147
938
 
 
939
static drizzle_sys_var* sys_variables[]= {
 
940
  DRIZZLE_SYSVAR(port),
 
941
  DRIZZLE_SYSVAR(connect_timeout),
 
942
  DRIZZLE_SYSVAR(read_timeout),
 
943
  DRIZZLE_SYSVAR(write_timeout),
 
944
  DRIZZLE_SYSVAR(retry_count),
 
945
  DRIZZLE_SYSVAR(buffer_length),
 
946
  DRIZZLE_SYSVAR(bind_address),
 
947
  NULL
 
948
};
 
949
 
148
950
} /* namespace drizzle_protocol */
149
 
} /* namespace drizzle_plugin */
150
951
 
151
 
DRIZZLE_PLUGIN(drizzle_plugin::drizzle_protocol::init, NULL, drizzle_plugin::drizzle_protocol::init_options);
 
952
DRIZZLE_PLUGIN(drizzle_protocol::init, drizzle_protocol::sys_variables, drizzle_protocol::init_options);