~drizzle-trunk/drizzle/development

« back to all changes in this revision

Viewing changes to drizzled/protocol.cc

  • Committer: Monty Taylor
  • Date: 2008-12-18 07:24:54 UTC
  • mto: This revision was merged to the branch mainline in revision 714.
  • Revision ID: monty@bitters-20081218072454-8pnep622damjgqli
Fixed one more my_time thing.

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
/* - mode: c; c-basic-offset: 2; indent-tabs-mode: nil; -*-
2
 
 *  vim:expandtab:shiftwidth=2:tabstop=2:smarttab:
3
 
 *
4
 
 *  Copyright (C) 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
19
 
 */
20
 
 
21
 
 
22
 
#include "config.h"
23
 
#include <drizzled/gettext.h>
 
1
/* Copyright (C) 2000-2003 MySQL AB
 
2
 
 
3
   This program is free software; you can redistribute it and/or modify
 
4
   it under the terms of the GNU General Public License as published by
 
5
   the Free Software Foundation; version 2 of the License.
 
6
 
 
7
   This program is distributed in the hope that it will be useful,
 
8
   but WITHOUT ANY WARRANTY; without even the implied warranty of
 
9
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 
10
   GNU General Public License for more details.
 
11
 
 
12
   You should have received a copy of the GNU General Public License
 
13
   along with this program; if not, write to the Free Software
 
14
   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA */
 
15
 
 
16
/**
 
17
  @file
 
18
 
 
19
  Low level functions for storing data to be send to the MySQL client.
 
20
  The actual communction is handled by the net_xxx functions in net_serv.cc
 
21
*/
 
22
#include <drizzled/server_includes.h>
24
23
#include <drizzled/error.h>
25
 
#include <drizzled/query_id.h>
 
24
#include <drizzled/sql_state.h>
 
25
#include <libdrizzle/pack.h>
 
26
#include <drizzled/protocol.h>
26
27
#include <drizzled/session.h>
27
 
#include "drizzled/internal/my_sys.h"
28
 
#include "drizzled/internal/m_string.h"
29
 
#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
 
 
36
 
namespace po= boost::program_options;
37
 
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
 
{
59
 
}
60
 
 
61
 
in_port_t ListenDrizzleProtocol::getPort(void) const
62
 
{
63
 
  return port;
64
 
}
65
 
 
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())
79
 
    return true;
80
 
 
81
 
  return false;
82
 
}
83
 
 
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);
 
28
 
 
29
static const unsigned int PACKET_BUFFER_EXTRA_ALLOC= 1024;
 
30
/* Declared non-static only because of the embedded library. */
 
31
static void net_send_error_packet(Session *session, uint32_t sql_errno, const char *err);
 
32
static void write_eof_packet(Session *session, NET *net,
 
33
                             uint32_t server_status, uint32_t total_warn_count);
 
34
 
 
35
bool Protocol::net_store_data(const unsigned char *from, size_t length)
 
36
{
 
37
  size_t packet_length= packet->length();
 
38
  /*
 
39
     The +9 comes from that strings of length longer than 16M require
 
40
     9 bytes to be stored (see net_store_length).
 
41
  */
 
42
  if (packet_length+9+length > packet->alloced_length() &&
 
43
      packet->realloc(packet_length+9+length))
 
44
    return 1;
 
45
  unsigned char *to= net_store_length((unsigned char*) packet->ptr()+packet_length, length);
 
46
  memcpy(to,from,length);
 
47
  packet->length((size_t) (to+length-(unsigned char*) packet->ptr()));
 
48
  return 0;
 
49
}
 
50
 
 
51
 
 
52
 
 
53
 
 
54
/*
 
55
  net_store_data() - extended version with character set conversion.
 
56
 
 
57
  It is optimized for short strings whose length after
 
58
  conversion is garanteed to be less than 251, which accupies
 
59
  exactly one byte to store length. It allows not to use
 
60
  the "convert" member as a temporary buffer, conversion
 
61
  is done directly to the "packet" member.
 
62
  The limit 251 is good enough to optimize send_fields()
 
63
  because column, table, database names fit into this limit.
 
64
*/
 
65
 
 
66
bool Protocol::net_store_data(const unsigned char *from, size_t length,
 
67
                              const CHARSET_INFO * const from_cs,
 
68
                                                          const CHARSET_INFO * const to_cs)
 
69
{
 
70
  uint32_t dummy_errors;
 
71
  /* Calculate maxumum possible result length */
 
72
  uint32_t conv_length= to_cs->mbmaxlen * length / from_cs->mbminlen;
 
73
  if (conv_length > 250)
 
74
  {
 
75
    /*
 
76
      For strings with conv_length greater than 250 bytes
 
77
      we don't know how many bytes we will need to store length: one or two,
 
78
      because we don't know result length until conversion is done.
 
79
      For example, when converting from utf8 (mbmaxlen=3) to latin1,
 
80
      conv_length=300 means that the result length can vary between 100 to 300.
 
81
      length=100 needs one byte, length=300 needs to bytes.
 
82
 
 
83
      Thus conversion directly to "packet" is not worthy.
 
84
      Let's use "convert" as a temporary buffer.
 
85
    */
 
86
    return (convert->copy((const char*) from, length, from_cs,
 
87
                          to_cs, &dummy_errors) ||
 
88
            net_store_data((const unsigned char*) convert->ptr(), convert->length()));
 
89
  }
 
90
 
 
91
  size_t packet_length= packet->length();
 
92
  size_t new_length= packet_length + conv_length + 1;
 
93
 
 
94
  if (new_length > packet->alloced_length() && packet->realloc(new_length))
 
95
    return 1;
 
96
 
 
97
  char *length_pos= (char*) packet->ptr() + packet_length;
 
98
  char *to= length_pos + 1;
 
99
 
 
100
  to+= copy_and_convert(to, conv_length, to_cs,
 
101
                        (const char*) from, length, from_cs, &dummy_errors);
 
102
 
 
103
  net_store_length((unsigned char*) length_pos, to - length_pos - 1);
 
104
  packet->length((uint) (to - packet->ptr()));
 
105
  return 0;
 
106
}
 
107
 
 
108
 
 
109
/**
 
110
  Send a error string to client.
 
111
 
 
112
  Design note:
 
113
  net_printf_error and net_send_error are low-level functions
 
114
  that shall be used only when a new connection is being
 
115
  established or at server startup.
 
116
 
 
117
  For SIGNAL/RESIGNAL and GET DIAGNOSTICS functionality it's
 
118
  critical that every error that can be intercepted is issued in one
 
119
  place only, my_message_sql.
 
120
*/
 
121
void net_send_error(Session *session, uint32_t sql_errno, const char *err)
 
122
{
 
123
  assert(sql_errno);
 
124
  assert(err && err[0]);
 
125
 
 
126
  /*
 
127
    It's one case when we can push an error even though there
 
128
    is an OK or EOF already.
 
129
  */
 
130
  session->main_da.can_overwrite_status= true;
 
131
 
 
132
  /* Abort multi-result sets */
 
133
  session->server_status&= ~SERVER_MORE_RESULTS_EXISTS;
 
134
 
 
135
  net_send_error_packet(session, sql_errno, err);
 
136
 
 
137
  session->main_da.can_overwrite_status= false;
 
138
}
 
139
 
 
140
/**
 
141
  Return ok to the client.
 
142
 
 
143
  The ok packet has the following structure:
 
144
 
 
145
  - 0               : Marker (1 byte)
 
146
  - affected_rows       : Stored in 1-9 bytes
 
147
  - id          : Stored in 1-9 bytes
 
148
  - server_status       : Copy of session->server_status;  Can be used by client
 
149
  to check if we are inside an transaction.
 
150
  New in 4.0 protocol
 
151
  - warning_count       : Stored in 2 bytes; New in 4.1 protocol
 
152
  - message             : Stored as packed length (1-9 bytes) + message.
 
153
  Is not stored if no message.
 
154
 
 
155
  @param session                   Thread handler
 
156
  @param affected_rows     Number of rows changed by statement
 
157
  @param id                Auto_increment id for first row (if used)
 
158
  @param message           Message to send to the client (Used by mysql_status)
 
159
*/
 
160
 
 
161
static void
 
162
net_send_ok(Session *session,
 
163
            uint32_t server_status, uint32_t total_warn_count,
 
164
            ha_rows affected_rows, uint64_t id, const char *message)
 
165
{
 
166
  NET *net= &session->net;
 
167
  unsigned char buff[DRIZZLE_ERRMSG_SIZE+10],*pos;
 
168
 
 
169
  if (! net->vio)       // hack for re-parsing queries
 
170
  {
 
171
    return;
 
172
  }
 
173
 
 
174
  buff[0]=0;                                    // No fields
 
175
  pos=net_store_length(buff+1,affected_rows);
 
176
  pos=net_store_length(pos, id);
 
177
 
 
178
  int2store(pos, server_status);
 
179
  pos+=2;
 
180
 
 
181
  /* We can only return up to 65535 warnings in two bytes */
 
182
  uint32_t tmp= cmin(total_warn_count, (uint)65535);
 
183
  int2store(pos, tmp);
 
184
  pos+= 2;
 
185
 
 
186
  session->main_da.can_overwrite_status= true;
 
187
 
 
188
  if (message && message[0])
 
189
    pos= net_store_data(pos, (unsigned char*) message, strlen(message));
 
190
  my_net_write(net, buff, (size_t) (pos-buff));
 
191
  net_flush(net);
 
192
 
 
193
  session->main_da.can_overwrite_status= false;
 
194
}
 
195
 
 
196
/**
 
197
  Send eof (= end of result set) to the client.
 
198
 
 
199
  The eof packet has the following structure:
 
200
 
 
201
  - 254 (DRIZZLE_PROTOCOL_NO_MORE_DATA) : Marker (1 byte)
 
202
  - warning_count       : Stored in 2 bytes; New in 4.1 protocol
 
203
  - status_flag : Stored in 2 bytes;
 
204
  For flags like SERVER_MORE_RESULTS_EXISTS.
 
205
 
 
206
  Note that the warning count will not be sent if 'no_flush' is set as
 
207
  we don't want to report the warning count until all data is sent to the
 
208
  client.
 
209
 
 
210
  @param session                Thread handler
 
211
  @param no_flush       Set to 1 if there will be more data to the client,
 
212
                    like in send_fields().
 
213
*/
 
214
 
 
215
static void
 
216
net_send_eof(Session *session, uint32_t server_status, uint32_t total_warn_count)
 
217
{
 
218
  NET *net= &session->net;
 
219
  /* Set to true if no active vio, to work well in case of --init-file */
 
220
  if (net->vio != 0)
 
221
  {
 
222
    session->main_da.can_overwrite_status= true;
 
223
    write_eof_packet(session, net, server_status, total_warn_count);
 
224
    net_flush(net);
 
225
    session->main_da.can_overwrite_status= false;
 
226
  }
 
227
}
 
228
 
 
229
 
 
230
/**
 
231
  Format EOF packet according to the current protocol and
 
232
  write it to the network output buffer.
 
233
*/
 
234
 
 
235
static void write_eof_packet(Session *session, NET *net,
 
236
                             uint32_t server_status,
 
237
                             uint32_t total_warn_count)
 
238
{
 
239
  unsigned char buff[5];
 
240
  /*
 
241
    Don't send warn count during SP execution, as the warn_list
 
242
    is cleared between substatements, and mysqltest gets confused
 
243
  */
 
244
  uint32_t tmp= cmin(total_warn_count, (uint)65535);
 
245
  buff[0]= DRIZZLE_PROTOCOL_NO_MORE_DATA;
 
246
  int2store(buff+1, tmp);
 
247
  /*
 
248
    The following test should never be true, but it's better to do it
 
249
    because if 'is_fatal_error' is set the server is not going to execute
 
250
    other queries (see the if test in dispatch_command / COM_QUERY)
 
251
  */
 
252
  if (session->is_fatal_error)
 
253
    server_status&= ~SERVER_MORE_RESULTS_EXISTS;
 
254
  int2store(buff + 3, server_status);
 
255
  my_net_write(net, buff, 5);
 
256
}
 
257
 
 
258
void net_send_error_packet(Session *session, uint32_t sql_errno, const char *err)
 
259
{
 
260
  NET *net= &session->net;
 
261
  uint32_t length;
 
262
  /*
 
263
    buff[]: sql_errno:2 + ('#':1 + SQLSTATE_LENGTH:5) + DRIZZLE_ERRMSG_SIZE:512
 
264
  */
 
265
  unsigned char buff[2+1+SQLSTATE_LENGTH+DRIZZLE_ERRMSG_SIZE], *pos;
 
266
 
 
267
  if (net->vio == 0)
 
268
  {
 
269
    return;
 
270
  }
 
271
 
 
272
  int2store(buff,sql_errno);
 
273
  pos= buff+2;
 
274
 
 
275
  /* The first # is to make the protocol backward compatible */
 
276
  buff[2]= '#';
 
277
  pos= (unsigned char*) strcpy((char*) buff+3, drizzle_errno_to_sqlstate(sql_errno));
 
278
  pos+= strlen(drizzle_errno_to_sqlstate(sql_errno));
 
279
 
 
280
  char *tmp= strncpy((char*)pos, err, DRIZZLE_ERRMSG_SIZE-1);
 
281
  tmp+= strlen((char*)pos);
 
282
  tmp[0]= '\0';
 
283
  length= (uint32_t)(tmp-(char*)buff);
 
284
  err= (char*) buff;
 
285
 
 
286
  net_write_command(net,(unsigned char) 255, (unsigned char*) "", 0, (unsigned char*) err, length);
 
287
  return;
 
288
}
 
289
 
 
290
 
 
291
/**
 
292
  Faster net_store_length when we know that length is less than 65536.
 
293
  We keep a separate version for that range because it's widely used in
 
294
  libmysql.
 
295
 
 
296
  uint32_t is used as agrument type because of MySQL type conventions:
 
297
  - uint32_t for 0..65536
 
298
  - ulong for 0..4294967296
 
299
  - uint64_t for bigger numbers.
 
300
*/
 
301
 
 
302
static unsigned char *net_store_length_fast(unsigned char *packet, uint32_t length)
 
303
{
 
304
  if (length < 251)
 
305
  {
 
306
    *packet=(unsigned char) length;
 
307
    return packet+1;
 
308
  }
 
309
  *packet++=252;
 
310
  int2store(packet,(uint32_t) length);
 
311
 
 
312
  return packet+2;
 
313
}
 
314
 
 
315
/**
 
316
  Send the status of the current statement execution over network.
 
317
 
 
318
  @param  session   in fact, carries two parameters, NET for the transport and
 
319
                Diagnostics_area as the source of status information.
 
320
 
 
321
  In MySQL, there are two types of SQL statements: those that return
 
322
  a result set and those that return status information only.
 
323
 
 
324
  If a statement returns a result set, it consists of 3 parts:
 
325
  - result set meta-data
 
326
  - variable number of result set rows (can be 0)
 
327
  - followed and terminated by EOF or ERROR packet
 
328
 
 
329
  Once the  client has seen the meta-data information, it always
 
330
  expects an EOF or ERROR to terminate the result set. If ERROR is
 
331
  received, the result set rows are normally discarded (this is up
 
332
  to the client implementation, libmysql at least does discard them).
 
333
  EOF, on the contrary, means "successfully evaluated the entire
 
334
  result set". Since we don't know how many rows belong to a result
 
335
  set until it's evaluated, EOF/ERROR is the indicator of the end
 
336
  of the row stream. Note, that we can not buffer result set rows
 
337
  on the server -- there may be an arbitrary number of rows. But
 
338
  we do buffer the last packet (EOF/ERROR) in the Diagnostics_area and
 
339
  delay sending it till the very end of execution (here), to be able to
 
340
  change EOF to an ERROR if commit failed or some other error occurred
 
341
  during the last cleanup steps taken after execution.
 
342
 
 
343
  A statement that does not return a result set doesn't send result
 
344
  set meta-data either. Instead it returns one of:
 
345
  - OK packet
 
346
  - ERROR packet.
 
347
  Similarly to the EOF/ERROR of the previous statement type, OK/ERROR
 
348
  packet is "buffered" in the diagnostics area and sent to the client
 
349
  in the end of statement.
 
350
 
 
351
  @pre  The diagnostics area is assigned or disabled. It can not be empty
 
352
        -- we assume that every SQL statement or COM_* command
 
353
        generates OK, ERROR, or EOF status.
 
354
 
 
355
  @post The status information is encoded to protocol format and sent to the
 
356
        client.
 
357
 
 
358
  @return We conventionally return void, since the only type of error
 
359
          that can happen here is a NET (transport) error, and that one
 
360
          will become visible when we attempt to read from the NET the
 
361
          next command.
 
362
          Diagnostics_area::is_sent is set for debugging purposes only.
 
363
*/
 
364
 
 
365
void net_end_statement(Session *session)
 
366
{
 
367
  assert(! session->main_da.is_sent);
 
368
 
 
369
  /* Can not be true, but do not take chances in production. */
 
370
  if (session->main_da.is_sent)
 
371
    return;
 
372
 
 
373
  switch (session->main_da.status()) {
 
374
  case Diagnostics_area::DA_ERROR:
 
375
    /* The query failed, send error to log and abort bootstrap. */
 
376
    net_send_error(session,
 
377
                   session->main_da.sql_errno(),
 
378
                   session->main_da.message());
 
379
    break;
 
380
  case Diagnostics_area::DA_EOF:
 
381
    net_send_eof(session,
 
382
                 session->main_da.server_status(),
 
383
                 session->main_da.total_warn_count());
 
384
    break;
 
385
  case Diagnostics_area::DA_OK:
 
386
    net_send_ok(session,
 
387
                session->main_da.server_status(),
 
388
                session->main_da.total_warn_count(),
 
389
                session->main_da.affected_rows(),
 
390
                session->main_da.last_insert_id(),
 
391
                session->main_da.message());
 
392
    break;
 
393
  case Diagnostics_area::DA_DISABLED:
 
394
    break;
 
395
  case Diagnostics_area::DA_EMPTY:
 
396
  default:
 
397
    assert(0);
 
398
    net_send_ok(session, session->server_status, session->total_warn_count,
 
399
                0, 0, NULL);
 
400
    break;
 
401
  }
 
402
  session->main_da.is_sent= true;
 
403
}
 
404
 
 
405
 
 
406
/****************************************************************************
 
407
  Functions used by the protocol functions (like net_send_ok) to store
 
408
  strings and numbers in the header result packet.
 
409
****************************************************************************/
 
410
 
 
411
/* The following will only be used for short strings < 65K */
 
412
 
 
413
unsigned char *net_store_data(unsigned char *to, const unsigned char *from, size_t length)
 
414
{
 
415
  to=net_store_length_fast(to,length);
 
416
  memcpy(to,from,length);
 
417
  return to+length;
 
418
}
 
419
 
 
420
unsigned char *net_store_data(unsigned char *to,int32_t from)
 
421
{
 
422
  char buff[20];
 
423
  uint32_t length=(uint) (int10_to_str(from,buff,10)-buff);
 
424
  to=net_store_length_fast(to,length);
 
425
  memcpy(to,buff,length);
 
426
  return to+length;
 
427
}
 
428
 
 
429
unsigned char *net_store_data(unsigned char *to,int64_t from)
 
430
{
 
431
  char buff[22];
 
432
  uint32_t length=(uint) (int64_t10_to_str(from,buff,10)-buff);
 
433
  to=net_store_length_fast(to,length);
 
434
  memcpy(to,buff,length);
 
435
  return to+length;
 
436
}
 
437
 
 
438
 
 
439
/*****************************************************************************
 
440
  Default Protocol functions
 
441
*****************************************************************************/
 
442
 
 
443
void Protocol::init(Session *session_arg)
 
444
{
 
445
  session=session_arg;
 
446
  packet= &session->packet;
 
447
  convert= &session->convert_buffer;
 
448
}
 
449
 
 
450
/**
 
451
  Finish the result set with EOF packet, as is expected by the client,
 
452
  if there is an error evaluating the next row and a continue handler
 
453
  for the error.
 
454
*/
 
455
 
 
456
void Protocol::end_partial_result_set(Session *session)
 
457
{
 
458
  net_send_eof(session, session->server_status, 0 /* no warnings, we're inside SP */);
 
459
}
 
460
 
 
461
 
 
462
bool Protocol::flush()
 
463
{
 
464
  return net_flush(&session->net);
 
465
}
 
466
 
 
467
 
 
468
/**
 
469
  Send name and type of result to client.
 
470
 
 
471
  Sum fields has table name empty and field_name.
 
472
 
 
473
  @param Session                Thread data object
 
474
  @param list           List of items to send to client
 
475
  @param flag           Bit mask with the following functions:
 
476
                        - 1 send number of rows
 
477
                        - 2 send default values
 
478
                        - 4 don't write eof packet
 
479
 
 
480
  @retval
 
481
    0   ok
 
482
  @retval
 
483
    1   Error  (Note that in this case the error is not sent to the
 
484
    client)
 
485
*/
 
486
bool Protocol::send_fields(List<Item> *list, uint32_t flags)
 
487
{
 
488
  List_iterator_fast<Item> it(*list);
 
489
  Item *item;
 
490
  unsigned char buff[80];
 
491
  String tmp((char*) buff,sizeof(buff),&my_charset_bin);
 
492
  Protocol_text prot(session);
 
493
  String *local_packet= prot.storage_packet();
 
494
  const CHARSET_INFO * const session_charset= session->variables.character_set_results;
 
495
 
 
496
  if (flags & SEND_NUM_ROWS)
 
497
  {                             // Packet with number of elements
 
498
    unsigned char *pos= net_store_length(buff, list->elements);
 
499
    (void) my_net_write(&session->net, buff, (size_t) (pos-buff));
 
500
  }
 
501
 
 
502
  while ((item=it++))
 
503
  {
 
504
    char *pos;
 
505
    const CHARSET_INFO * const cs= system_charset_info;
 
506
    Send_field field;
 
507
    item->make_field(&field);
 
508
 
 
509
    prot.prepare_for_resend();
 
510
 
 
511
 
 
512
    if (prot.store(STRING_WITH_LEN("def"), cs, session_charset) ||
 
513
        prot.store(field.db_name, (uint) strlen(field.db_name),
 
514
                   cs, session_charset) ||
 
515
        prot.store(field.table_name, (uint) strlen(field.table_name),
 
516
                   cs, session_charset) ||
 
517
        prot.store(field.org_table_name, (uint) strlen(field.org_table_name),
 
518
                   cs, session_charset) ||
 
519
        prot.store(field.col_name, (uint) strlen(field.col_name),
 
520
                   cs, session_charset) ||
 
521
        prot.store(field.org_col_name, (uint) strlen(field.org_col_name),
 
522
                   cs, session_charset) ||
 
523
        local_packet->realloc(local_packet->length()+12))
 
524
      goto err;
 
525
 
 
526
    /* Store fixed length fields */
 
527
    pos= (char*) local_packet->ptr()+local_packet->length();
 
528
    *pos++= 12;                         // Length of packed fields
 
529
    if (item->collation.collation == &my_charset_bin || session_charset == NULL)
 
530
    {
 
531
      /* No conversion */
 
532
      int2store(pos, field.charsetnr);
 
533
      int4store(pos+2, field.length);
 
534
    }
 
535
    else
 
536
    {
 
537
      /* With conversion */
 
538
      uint32_t max_char_len;
 
539
      int2store(pos, session_charset->number);
 
540
      /*
 
541
        For TEXT/BLOB columns, field_length describes the maximum data
 
542
        length in bytes. There is no limit to the number of characters
 
543
        that a TEXT column can store, as long as the data fits into
 
544
        the designated space.
 
545
        For the rest of textual columns, field_length is evaluated as
 
546
        char_count * mbmaxlen, where character count is taken from the
 
547
        definition of the column. In other words, the maximum number
 
548
        of characters here is limited by the column definition.
 
549
      */
 
550
      max_char_len= field.length / item->collation.collation->mbmaxlen;
 
551
      int4store(pos+2, max_char_len * session_charset->mbmaxlen);
 
552
    }
 
553
    pos[6]= field.type;
 
554
    int2store(pos+7,field.flags);
 
555
    pos[9]= (char) field.decimals;
 
556
    pos[10]= 0;                         // For the future
 
557
    pos[11]= 0;                         // For the future
 
558
    pos+= 12;
 
559
 
 
560
    local_packet->length((uint) (pos - local_packet->ptr()));
 
561
    if (flags & SEND_DEFAULTS)
 
562
      item->send(&prot, &tmp);                  // Send default value
 
563
    if (prot.write())
 
564
      break;                                    /* purecov: inspected */
 
565
  }
 
566
 
 
567
  if (flags & SEND_EOF)
 
568
  {
 
569
    /*
 
570
      Mark the end of meta-data result set, and store session->server_status,
 
571
      to show that there is no cursor.
 
572
      Send no warning information, as it will be sent at statement end.
 
573
    */
 
574
    write_eof_packet(session, &session->net, session->server_status, session->total_warn_count);
 
575
  }
 
576
  return(prepare_for_send(list));
 
577
 
 
578
err:
 
579
  my_message(ER_OUT_OF_RESOURCES, ER(ER_OUT_OF_RESOURCES),
 
580
             MYF(0));   /* purecov: inspected */
 
581
  return(1);                            /* purecov: inspected */
 
582
}
 
583
 
 
584
 
 
585
bool Protocol::write()
 
586
{
 
587
  return(my_net_write(&session->net, (unsigned char*) packet->ptr(),
 
588
                           packet->length()));
 
589
}
 
590
 
 
591
 
 
592
/**
 
593
  Send \\0 end terminated string.
 
594
 
 
595
  @param from   NULL or \\0 terminated string
 
596
 
 
597
  @note
 
598
    In most cases one should use store(from, length) instead of this function
 
599
 
 
600
  @retval
 
601
    0           ok
 
602
  @retval
 
603
    1           error
 
604
*/
 
605
 
 
606
bool Protocol::store(const char *from, const CHARSET_INFO * const cs)
 
607
{
 
608
  if (!from)
 
609
    return store_null();
 
610
  uint32_t length= strlen(from);
 
611
  return store(from, length, cs);
 
612
}
 
613
 
 
614
 
 
615
/**
 
616
  Send a set of strings as one long string with ',' in between.
 
617
*/
 
618
 
 
619
bool Protocol::store(I_List<i_string>* str_list)
 
620
{
 
621
  char buf[256];
 
622
  String tmp(buf, sizeof(buf), &my_charset_bin);
 
623
  uint32_t len;
 
624
  I_List_iterator<i_string> it(*str_list);
 
625
  i_string* s;
 
626
 
 
627
  tmp.length(0);
 
628
  while ((s=it++))
 
629
  {
 
630
    tmp.append(s->ptr);
 
631
    tmp.append(',');
 
632
  }
 
633
  if ((len= tmp.length()))
 
634
    len--;                                      // Remove last ','
 
635
  return store((char*) tmp.ptr(), len,  tmp.charset());
 
636
}
 
637
 
 
638
 
 
639
bool Protocol::store(String *str)
 
640
{
 
641
  return store((char*) str->ptr(), str->length(), str->charset());
 
642
}
 
643
 
 
644
void Protocol::free()
 
645
{
 
646
  packet->free();
 
647
}
 
648
 
 
649
 
 
650
/****************************************************************************
 
651
  Functions to handle the simple (default) protocol where everything is
 
652
  This protocol is the one that is used by default between the MySQL server
 
653
  and client when you are not using prepared statements.
 
654
 
 
655
  All data are sent as 'packed-string-length' followed by 'string-data'
 
656
****************************************************************************/
 
657
 
 
658
void Protocol_text::prepare_for_resend()
 
659
{
 
660
  packet->length(0);
 
661
}
 
662
 
 
663
bool Protocol_text::store_null()
 
664
{
 
665
  char buff[1];
 
666
  buff[0]= (char)251;
 
667
  return packet->append(buff, sizeof(buff), PACKET_BUFFER_EXTRA_ALLOC);
 
668
}
 
669
 
 
670
 
 
671
/**
 
672
  Auxilary function to convert string to the given character set
 
673
  and store in network buffer.
 
674
*/
 
675
 
 
676
bool Protocol::store_string_aux(const char *from, size_t length,
 
677
                                const CHARSET_INFO * const fromcs,
 
678
                                                                const CHARSET_INFO * const tocs)
 
679
{
 
680
  /* 'tocs' is set 0 when client issues SET character_set_results=NULL */
 
681
  if (tocs && !my_charset_same(fromcs, tocs) &&
 
682
      fromcs != &my_charset_bin &&
 
683
      tocs != &my_charset_bin)
 
684
  {
 
685
    /* Store with conversion */
 
686
    return net_store_data((unsigned char*) from, length, fromcs, tocs);
 
687
  }
 
688
  /* Store without conversion */
 
689
  return net_store_data((unsigned char*) from, length);
 
690
}
 
691
 
 
692
 
 
693
bool Protocol_text::store(const char *from, size_t length,
 
694
                          const CHARSET_INFO * const fromcs,
 
695
                                                  const CHARSET_INFO * const tocs)
 
696
{
 
697
  return store_string_aux(from, length, fromcs, tocs);
 
698
}
 
699
 
 
700
 
 
701
bool Protocol_text::store(const char *from, size_t length,
 
702
                          const CHARSET_INFO * const fromcs)
 
703
{
 
704
  const CHARSET_INFO * const tocs= this->session->variables.character_set_results;
 
705
  return store_string_aux(from, length, fromcs, tocs);
 
706
}
 
707
 
 
708
 
 
709
bool Protocol_text::store_tiny(int64_t from)
 
710
{
 
711
  char buff[20];
 
712
  return net_store_data((unsigned char*) buff,
 
713
                        (size_t) (int10_to_str((int) from, buff, -10) - buff));
 
714
}
 
715
 
 
716
 
 
717
bool Protocol_text::store_short(int64_t from)
 
718
{
 
719
  char buff[20];
 
720
  return net_store_data((unsigned char*) buff,
 
721
                        (size_t) (int10_to_str((int) from, buff, -10) -
 
722
                                  buff));
 
723
}
 
724
 
 
725
 
 
726
bool Protocol_text::store_long(int64_t from)
 
727
{
 
728
  char buff[20];
 
729
  return net_store_data((unsigned char*) buff,
 
730
                        (size_t) (int10_to_str((long int)from, buff,
 
731
                                               (from <0)?-10:10)-buff));
 
732
}
 
733
 
 
734
 
 
735
bool Protocol_text::store_int64_t(int64_t from, bool unsigned_flag)
 
736
{
 
737
  char buff[22];
 
738
  return net_store_data((unsigned char*) buff,
 
739
                        (size_t) (int64_t10_to_str(from,buff,
 
740
                                                    unsigned_flag ? 10 : -10)-
 
741
                                  buff));
 
742
}
 
743
 
 
744
 
 
745
bool Protocol_text::store_decimal(const my_decimal *d)
 
746
{
 
747
  char buff[DECIMAL_MAX_STR_LENGTH];
 
748
  String str(buff, sizeof(buff), &my_charset_bin);
 
749
  (void) my_decimal2string(E_DEC_FATAL_ERROR, d, 0, 0, 0, &str);
 
750
  return net_store_data((unsigned char*) str.ptr(), str.length());
 
751
}
 
752
 
 
753
 
 
754
bool Protocol_text::store(float from, uint32_t decimals, String *buffer)
 
755
{
 
756
  buffer->set_real((double) from, decimals, session->charset());
 
757
  return net_store_data((unsigned char*) buffer->ptr(), buffer->length());
 
758
}
 
759
 
 
760
 
 
761
bool Protocol_text::store(double from, uint32_t decimals, String *buffer)
 
762
{
 
763
  buffer->set_real(from, decimals, session->charset());
 
764
  return net_store_data((unsigned char*) buffer->ptr(), buffer->length());
 
765
}
 
766
 
 
767
 
 
768
bool Protocol_text::store(Field *field)
 
769
{
 
770
  if (field->is_null())
 
771
    return store_null();
 
772
  char buff[MAX_FIELD_WIDTH];
 
773
  String str(buff,sizeof(buff), &my_charset_bin);
 
774
  const CHARSET_INFO * const tocs= this->session->variables.character_set_results;
 
775
 
 
776
  field->val_str(&str);
 
777
 
 
778
  return store_string_aux(str.ptr(), str.length(), str.charset(), tocs);
 
779
}
 
780
 
 
781
 
 
782
/**
 
783
  @todo
 
784
    Second_part format ("%06") needs to change when
 
785
    we support 0-6 decimals for time.
 
786
*/
 
787
 
 
788
bool Protocol_text::store(DRIZZLE_TIME *tm)
 
789
{
 
790
  char buff[40];
 
791
  uint32_t length;
 
792
  length= sprintf(buff, "%04d-%02d-%02d %02d:%02d:%02d",
 
793
                           (int) tm->year,
 
794
                           (int) tm->month,
 
795
                           (int) tm->day,
 
796
                           (int) tm->hour,
 
797
                           (int) tm->minute,
 
798
                           (int) tm->second);
 
799
  if (tm->second_part)
 
800
    length+= sprintf(buff+length, ".%06d",
 
801
                                     (int)tm->second_part);
 
802
  return net_store_data((unsigned char*) buff, length);
 
803
}
 
804
 
 
805
 
 
806
bool Protocol_text::store_date(DRIZZLE_TIME *tm)
 
807
{
 
808
  char buff[MAX_DATE_STRING_REP_LENGTH];
 
809
  size_t length= my_date_to_str(tm, buff);
 
810
  return net_store_data((unsigned char*) buff, length);
 
811
}
 
812
 
 
813
 
 
814
/**
 
815
  @todo
 
816
    Second_part format ("%06") needs to change when
 
817
    we support 0-6 decimals for time.
 
818
*/
 
819
 
 
820
bool Protocol_text::store_time(DRIZZLE_TIME *tm)
 
821
{
 
822
  char buff[40];
 
823
  uint32_t length;
 
824
  uint32_t day= (tm->year || tm->month) ? 0 : tm->day;
 
825
  length= sprintf(buff, "%s%02ld:%02d:%02d",
 
826
                           tm->neg ? "-" : "",
 
827
                           (long) day*24L+(long) tm->hour,
 
828
                           (int) tm->minute,
 
829
                           (int) tm->second);
 
830
  if (tm->second_part)
 
831
    length+= sprintf(buff+length, ".%06d", (int)tm->second_part);
 
832
  return net_store_data((unsigned char*) buff, length);
 
833
}
 
834