~drizzle-trunk/drizzle/development

« back to all changes in this revision

Viewing changes to plugin/drizzle_protocol/drizzle_protocol.cc

  • Committer: Brian Aker
  • Date: 2010-07-09 21:43:25 UTC
  • mfrom: (1643.5.1 dr-bug-600624)
  • Revision ID: brian@gaz-20100709214325-4rllc5yyo6bku5sh
Merge Prafulla Tekawade

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