~drizzle-trunk/drizzle/development

« back to all changes in this revision

Viewing changes to plugin/oldlibdrizzle/oldlibdrizzle.cc

  • Committer: Brian Aker
  • Date: 2009-08-18 07:19:56 UTC
  • mfrom: (1116.1.3 stewart)
  • mto: This revision was merged to the branch mainline in revision 1118.
  • Revision ID: brian@gaz-20090818071956-nfpoe9rp3i7p50kx
Merge my branch from Stewart into one branch

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