~drizzle-trunk/drizzle/development

« back to all changes in this revision

Viewing changes to plugin/oldlibdrizzle/oldlibdrizzle.cc

  • Committer: devananda
  • Date: 2009-07-01 17:38:47 UTC
  • mto: (1093.1.7 captain)
  • mto: This revision was merged to the branch mainline in revision 1095.
  • Revision ID: devananda.vdv@gmail.com-20090701173847-3n3mbtessg5ff35e
refactored function/benchmark into plugin/benchmark

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