1
/* -*- mode: c++; c-basic-offset: 2; indent-tabs-mode: nil; -*-
2
* vim:expandtab:shiftwidth=2:tabstop=2:smarttab:
4
* Copyright (C) 2008 Sun Microsystems
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.
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.
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
20
#include <drizzled/server_includes.h>
21
#include <drizzled/gettext.h>
22
#include <drizzled/error.h>
23
#include <drizzled/query_id.h>
24
#include <drizzled/sql_state.h>
25
#include <drizzled/session.h>
30
#include "oldlibdrizzle.h"
34
using namespace drizzled;
36
#define PROTOCOL_VERSION 10
38
static const unsigned int PACKET_BUFFER_EXTRA_ALLOC= 1024;
40
static uint32_t connect_timeout;
41
static uint32_t read_timeout;
42
static uint32_t write_timeout;
43
static uint32_t retry_count;
44
static uint32_t buffer_length;
45
static char* bind_address;
47
const char* ListenMySQLProtocol::getHost(void) const
52
in_port_t ListenMySQLProtocol::getPort(void) const
54
return (in_port_t) port;
57
plugin::Client *ListenMySQLProtocol::getClient(int fd)
60
new_fd= acceptTcp(fd);
64
return new (nothrow) ClientMySQLProtocol(new_fd, using_mysql41_protocol);
67
ClientMySQLProtocol::ClientMySQLProtocol(int fd, bool using_mysql41_protocol_arg):
68
using_mysql41_protocol(using_mysql41_protocol_arg)
75
if (drizzleclient_net_init_sock(&net, fd, 0, buffer_length))
78
drizzleclient_net_set_read_timeout(&net, read_timeout);
79
drizzleclient_net_set_write_timeout(&net, write_timeout);
80
net.retry_count=retry_count;
83
ClientMySQLProtocol::~ClientMySQLProtocol()
86
drizzleclient_vio_close(net.vio);
89
int ClientMySQLProtocol::getFileDescriptor(void)
91
return drizzleclient_net_get_sd(&net);
94
bool ClientMySQLProtocol::isConnected()
99
bool ClientMySQLProtocol::isReading(void)
101
return net.reading_or_writing == 1;
104
bool ClientMySQLProtocol::isWriting(void)
106
return net.reading_or_writing == 2;
109
bool ClientMySQLProtocol::flush()
113
bool ret= drizzleclient_net_write(&net, (unsigned char*) packet.ptr(),
119
void ClientMySQLProtocol::close(void)
123
drizzleclient_net_close(&net);
124
drizzleclient_net_end(&net);
128
bool ClientMySQLProtocol::authenticate()
130
bool connection_is_valid;
132
/* Use "connect_timeout" value during connection phase */
133
drizzleclient_net_set_read_timeout(&net, connect_timeout);
134
drizzleclient_net_set_write_timeout(&net, connect_timeout);
136
connection_is_valid= checkConnection();
138
if (connection_is_valid)
142
sendError(session->main_da.sql_errno(), session->main_da.message());
146
/* Connect completed, set read/write timeouts back to default */
147
drizzleclient_net_set_read_timeout(&net, read_timeout);
148
drizzleclient_net_set_write_timeout(&net, write_timeout);
152
bool ClientMySQLProtocol::readCommand(char **l_packet, uint32_t *packet_length)
155
This thread will do a blocking read from the client which
156
will be interrupted when the next command is received from
157
the client, the connection is closed or "net_wait_timeout"
158
number of seconds has passed
161
/* We can do this much more efficiently with poll timeouts or watcher thread,
162
disabling for now, which means net_wait_timeout == read_timeout. */
163
drizzleclient_net_set_read_timeout(&net,
164
session->variables.net_wait_timeout);
169
*packet_length= drizzleclient_net_read(&net);
170
if (*packet_length == packet_error)
172
/* Check if we can continue without closing the connection */
174
if(net.last_errno== CR_NET_PACKET_TOO_LARGE)
175
my_error(ER_NET_PACKET_TOO_LARGE, MYF(0));
176
if (session->main_da.status() == Diagnostics_area::DA_ERROR)
177
sendError(session->main_da.sql_errno(), session->main_da.message());
182
return false; // We have to close it.
189
*l_packet= (char*) net.read_pos;
192
'packet_length' contains length of data, as it was stored in packet
193
header. In case of malformed header, drizzleclient_net_read returns zero.
194
If packet_length is not zero, drizzleclient_net_read ensures that the returned
195
number of bytes was actually read from network.
196
There is also an extra safety measure in drizzleclient_net_read:
197
it sets packet[packet_length]= 0, but only for non-zero packets.
200
if (*packet_length == 0) /* safety */
202
/* Initialize with COM_SLEEP packet */
203
(*l_packet)[0]= (unsigned char) COM_SLEEP;
206
else if (using_mysql41_protocol)
208
/* Map from MySQL commands to Drizzle commands. */
209
switch ((int)(*l_packet)[0])
213
case 2: /* INIT_DB */
217
case 8: /* SHUTDOWN */
218
(*l_packet)[0]= (unsigned char) COM_SHUTDOWN;
222
(*l_packet)[0]= (unsigned char) COM_SHUTDOWN;
227
/* Just drop connection for MySQL commands we don't support. */
228
(*l_packet)[0]= (unsigned char) COM_QUIT;
234
/* Do not rely on drizzleclient_net_read, extra safety against programming errors. */
235
(*l_packet)[*packet_length]= '\0'; /* safety */
238
/* See comment above. */
239
/* Restore read timeout value */
240
drizzleclient_net_set_read_timeout(&net,
241
session->variables.net_read_timeout);
248
Return ok to the client.
250
The ok packet has the following structure:
252
- 0 : Marker (1 byte)
253
- affected_rows : Stored in 1-9 bytes
254
- id : Stored in 1-9 bytes
255
- server_status : Copy of session->server_status; Can be used by client
256
to check if we are inside an transaction.
258
- warning_count : Stored in 2 bytes; New in 4.1 client
259
- message : Stored as packed length (1-9 bytes) + message.
260
Is not stored if no message.
262
@param session Thread handler
263
@param affected_rows Number of rows changed by statement
264
@param id Auto_increment id for first row (if used)
265
@param message Message to send to the client (Used by mysql_status)
268
void ClientMySQLProtocol::sendOK()
270
unsigned char buff[DRIZZLE_ERRMSG_SIZE+10],*pos;
271
const char *message= NULL;
274
if (!net.vio) // hack for re-parsing queries
279
buff[0]=0; // No fields
280
if (session->main_da.status() == Diagnostics_area::DA_OK)
282
if (client_capabilities & CLIENT_FOUND_ROWS && session->main_da.found_rows())
283
pos=drizzleclient_net_store_length(buff+1,session->main_da.found_rows());
285
pos=drizzleclient_net_store_length(buff+1,session->main_da.affected_rows());
286
pos=drizzleclient_net_store_length(pos, session->main_da.last_insert_id());
287
int2store(pos, session->main_da.server_status());
289
tmp= min(session->main_da.total_warn_count(), (uint32_t)65535);
290
message= session->main_da.message();
294
pos=drizzleclient_net_store_length(buff+1,0);
295
pos=drizzleclient_net_store_length(pos, 0);
296
int2store(pos, session->server_status);
298
tmp= min(session->total_warn_count, (uint32_t)65535);
301
/* We can only return up to 65535 warnings in two bytes */
305
session->main_da.can_overwrite_status= true;
307
if (message && message[0])
309
size_t length= strlen(message);
310
pos=drizzleclient_net_store_length(pos,length);
311
memcpy(pos,(unsigned char*) message,length);
314
drizzleclient_net_write(&net, buff, (size_t) (pos-buff));
315
drizzleclient_net_flush(&net);
317
session->main_da.can_overwrite_status= false;
321
Send eof (= end of result set) to the client.
323
The eof packet has the following structure:
325
- 254 (DRIZZLE_PROTOCOL_NO_MORE_DATA) : Marker (1 byte)
326
- warning_count : Stored in 2 bytes; New in 4.1 client
327
- status_flag : Stored in 2 bytes;
328
For flags like SERVER_MORE_RESULTS_EXISTS.
330
Note that the warning count will not be sent if 'no_flush' is set as
331
we don't want to report the warning count until all data is sent to the
335
void ClientMySQLProtocol::sendEOF()
337
/* Set to true if no active vio, to work well in case of --init-file */
340
session->main_da.can_overwrite_status= true;
341
writeEOFPacket(session->main_da.server_status(),
342
session->main_da.total_warn_count());
343
drizzleclient_net_flush(&net);
344
session->main_da.can_overwrite_status= false;
346
packet.shrink(buffer_length);
350
void ClientMySQLProtocol::sendError(uint32_t sql_errno, const char *err)
354
buff[]: sql_errno:2 + ('#':1 + SQLSTATE_LENGTH:5) + DRIZZLE_ERRMSG_SIZE:512
356
unsigned char buff[2+1+SQLSTATE_LENGTH+DRIZZLE_ERRMSG_SIZE], *pos;
359
assert(err && err[0]);
362
It's one case when we can push an error even though there
363
is an OK or EOF already.
365
session->main_da.can_overwrite_status= true;
367
/* Abort multi-result sets */
368
session->server_status&= ~SERVER_MORE_RESULTS_EXISTS;
371
Send a error string to client.
373
For SIGNAL/RESIGNAL and GET DIAGNOSTICS functionality it's
374
critical that every error that can be intercepted is issued in one
375
place only, my_message_sql.
383
int2store(buff,sql_errno);
386
/* The first # is to make the client backward compatible */
388
pos= (unsigned char*) strcpy((char*) buff+3, drizzle_errno_to_sqlstate(sql_errno));
389
pos+= strlen(drizzle_errno_to_sqlstate(sql_errno));
391
char *tmp= strncpy((char*)pos, err, DRIZZLE_ERRMSG_SIZE-1);
392
tmp+= strlen((char*)pos);
394
length= (uint32_t)(tmp-(char*)buff);
397
drizzleclient_net_write_command(&net,(unsigned char) 255, (unsigned char*) "", 0, (unsigned char*) err, length);
399
session->main_da.can_overwrite_status= false;
403
Send name and type of result to client.
405
Sum fields has table name empty and field_name.
407
@param Session Thread data object
408
@param list List of items to send to client
409
@param flag Bit mask with the following functions:
410
- 1 send number of rows
411
- 2 send default values
412
- 4 don't write eof packet
417
1 Error (Note that in this case the error is not sent to the
420
bool ClientMySQLProtocol::sendFields(List<Item> *list)
422
List_iterator_fast<Item> it(*list);
424
unsigned char buff[80];
425
String tmp((char*) buff,sizeof(buff),&my_charset_bin);
427
unsigned char *row_pos= drizzleclient_net_store_length(buff, list->elements);
428
(void) drizzleclient_net_write(&net, buff, (size_t) (row_pos-buff));
434
item->make_field(&field);
438
if (store(STRING_WITH_LEN("def")) ||
439
store(field.db_name) ||
440
store(field.table_name) ||
441
store(field.org_table_name) ||
442
store(field.col_name) ||
443
store(field.org_col_name) ||
444
packet.realloc(packet.length()+12))
447
/* Store fixed length fields */
448
pos= (char*) packet.ptr()+packet.length();
449
*pos++= 12; // Length of packed fields
451
int2store(pos, field.charsetnr);
452
int4store(pos+2, field.length);
454
if (using_mysql41_protocol)
456
/* Switch to MySQL field numbering. */
459
case DRIZZLE_TYPE_LONG:
463
case DRIZZLE_TYPE_DOUBLE:
467
case DRIZZLE_TYPE_NULL:
471
case DRIZZLE_TYPE_TIMESTAMP:
475
case DRIZZLE_TYPE_LONGLONG:
479
case DRIZZLE_TYPE_DATETIME:
483
case DRIZZLE_TYPE_DATE:
487
case DRIZZLE_TYPE_VARCHAR:
491
case DRIZZLE_TYPE_NEWDECIMAL:
495
case DRIZZLE_TYPE_ENUM:
499
case DRIZZLE_TYPE_BLOB:
506
/* Add one to compensate for tinyint removal from enum. */
507
pos[6]= field.type + 1;
510
int2store(pos+7,field.flags);
511
pos[9]= (char) field.decimals;
512
pos[10]= 0; // For the future
513
pos[11]= 0; // For the future
516
packet.length((uint32_t) (pos - packet.ptr()));
522
Mark the end of meta-data result set, and store session->server_status,
523
to show that there is no cursor.
524
Send no warning information, as it will be sent at statement end.
526
writeEOFPacket(session->server_status, session->total_warn_count);
530
my_message(ER_OUT_OF_RESOURCES, ER(ER_OUT_OF_RESOURCES),
535
bool ClientMySQLProtocol::store(Field *from)
539
char buff[MAX_FIELD_WIDTH];
540
String str(buff,sizeof(buff), &my_charset_bin);
544
return netStoreData((const unsigned char *)str.ptr(), str.length());
547
bool ClientMySQLProtocol::store(void)
551
return packet.append(buff, sizeof(buff), PACKET_BUFFER_EXTRA_ALLOC);
554
bool ClientMySQLProtocol::store(int32_t from)
557
return netStoreData((unsigned char*) buff,
558
(size_t) (int10_to_str(from, buff, -10) - buff));
561
bool ClientMySQLProtocol::store(uint32_t from)
564
return netStoreData((unsigned char*) buff,
565
(size_t) (int10_to_str(from, buff, 10) - buff));
568
bool ClientMySQLProtocol::store(int64_t from)
571
return netStoreData((unsigned char*) buff,
572
(size_t) (int64_t10_to_str(from, buff, -10) - buff));
575
bool ClientMySQLProtocol::store(uint64_t from)
578
return netStoreData((unsigned char*) buff,
579
(size_t) (int64_t10_to_str(from, buff, 10) - buff));
582
bool ClientMySQLProtocol::store(double from, uint32_t decimals, String *buffer)
584
buffer->set_real(from, decimals, session->charset());
585
return netStoreData((unsigned char*) buffer->ptr(), buffer->length());
588
bool ClientMySQLProtocol::store(const char *from, size_t length)
590
return netStoreData((const unsigned char *)from, length);
593
bool ClientMySQLProtocol::wasAborted(void)
595
return net.error && net.vio != 0;
598
bool ClientMySQLProtocol::haveMoreData(void)
600
return drizzleclient_net_more_data(&net);
603
bool ClientMySQLProtocol::haveError(void)
605
return net.error || net.vio == 0;
608
bool ClientMySQLProtocol::checkConnection(void)
618
if (drizzleclient_net_peer_addr(&net, ip, &peer_port, NI_MAXHOST))
620
my_error(ER_BAD_HOST_ERROR, MYF(0), session->security_ctx.ip.c_str());
624
session->security_ctx.ip.assign(ip);
626
drizzleclient_net_keepalive(&net, true);
628
uint32_t server_capabilites;
630
/* buff[] needs to big enough to hold the server_version variable */
631
char buff[SERVER_VERSION_LENGTH + SCRAMBLE_LENGTH + 64];
633
server_capabilites= CLIENT_BASIC_FLAGS;
635
if (using_mysql41_protocol)
636
server_capabilites|= CLIENT_PROTOCOL_MYSQL41;
639
server_capabilites|= CLIENT_COMPRESS;
640
#endif /* HAVE_COMPRESS */
642
end= buff + strlen(VERSION);
643
if ((end - buff) >= SERVER_VERSION_LENGTH)
644
end= buff + (SERVER_VERSION_LENGTH - 1);
645
memcpy(buff, VERSION, end - buff);
649
int4store((unsigned char*) end, global_thread_id);
652
/* We don't use scramble anymore. */
653
memset(end, 'X', SCRAMBLE_LENGTH_323);
654
end+= SCRAMBLE_LENGTH_323;
655
*end++= 0; /* an empty byte for some reason */
657
int2store(end, server_capabilites);
658
/* write server characteristics: up to 16 bytes allowed */
659
end[2]=(char) default_charset_info->number;
660
int2store(end+3, session->server_status);
661
memset(end+5, 0, 13);
664
/* Write scramble tail. */
665
memset(end, 'X', SCRAMBLE_LENGTH - SCRAMBLE_LENGTH_323);
666
end+= (SCRAMBLE_LENGTH - SCRAMBLE_LENGTH_323);
667
*end++= 0; /* an empty byte for some reason */
669
/* At this point we write connection message and read reply */
670
if (drizzleclient_net_write_command(&net
671
, (unsigned char) PROTOCOL_VERSION
672
, (unsigned char*) ""
674
, (unsigned char*) buff
675
, (size_t) (end-buff))
676
|| (pkt_len= drizzleclient_net_read(&net)) == packet_error
677
|| pkt_len < MIN_HANDSHAKE_SIZE)
679
my_error(ER_HANDSHAKE_ERROR, MYF(0), session->security_ctx.ip.c_str());
683
if (packet.alloc(buffer_length))
684
return false; /* The error is set by alloc(). */
686
client_capabilities= uint2korr(net.read_pos);
689
client_capabilities|= ((uint32_t) uint2korr(net.read_pos + 2)) << 16;
690
session->max_client_packet_length= uint4korr(net.read_pos + 4);
691
end= (char*) net.read_pos + 32;
694
Disable those bits which are not supported by the server.
695
This is a precautionary measure, if the client lies. See Bug#27944.
697
client_capabilities&= server_capabilites;
699
if (end >= (char*) net.read_pos + pkt_len + 2)
701
my_error(ER_HANDSHAKE_ERROR, MYF(0), session->security_ctx.ip.c_str());
705
net.return_status= &session->server_status;
708
char *passwd= strchr(user, '\0')+1;
709
uint32_t user_len= passwd - user - 1;
713
Old clients send null-terminated string as password; new clients send
714
the size (1 byte) + string (not null-terminated). Hence in case of empty
715
password both send '\0'.
717
This strlen() can't be easily deleted without changing client.
719
Cast *passwd to an unsigned char, so that it doesn't extend the sign for
720
*passwd > 127 and become 2**32-127+ after casting to uint.
722
uint32_t passwd_len= client_capabilities & CLIENT_SECURE_CONNECTION ?
723
(unsigned char)(*passwd++) : strlen(passwd);
724
l_db= client_capabilities & CLIENT_CONNECT_WITH_DB ? l_db + passwd_len + 1 : 0;
726
/* strlen() can't be easily deleted without changing client */
727
uint32_t db_len= l_db ? strlen(l_db) : 0;
729
if (passwd + passwd_len + db_len > (char *) net.read_pos + pkt_len)
731
my_error(ER_HANDSHAKE_ERROR, MYF(0), session->security_ctx.ip.c_str());
735
/* If username starts and ends in "'", chop them off */
736
if (user_len > 1 && user[0] == '\'' && user[user_len - 1] == '\'')
743
session->security_ctx.user.assign(user);
745
return session->checkUser(passwd, passwd_len, l_db);
748
bool ClientMySQLProtocol::netStoreData(const unsigned char *from, size_t length)
750
size_t packet_length= packet.length();
752
The +9 comes from that strings of length longer than 16M require
753
9 bytes to be stored (see drizzleclient_net_store_length).
755
if (packet_length+9+length > packet.alloced_length() &&
756
packet.realloc(packet_length+9+length))
758
unsigned char *to= drizzleclient_net_store_length((unsigned char*) packet.ptr()+packet_length, length);
759
memcpy(to,from,length);
760
packet.length((size_t) (to+length-(unsigned char*) packet.ptr()));
765
Format EOF packet according to the current client and
766
write it to the network output buffer.
769
void ClientMySQLProtocol::writeEOFPacket(uint32_t server_status,
770
uint32_t total_warn_count)
772
unsigned char buff[5];
774
Don't send warn count during SP execution, as the warn_list
775
is cleared between substatements, and mysqltest gets confused
777
uint32_t tmp= min(total_warn_count, (uint32_t)65535);
778
buff[0]= DRIZZLE_PROTOCOL_NO_MORE_DATA;
779
int2store(buff+1, tmp);
781
The following test should never be true, but it's better to do it
782
because if 'is_fatal_error' is set the server is not going to execute
783
other queries (see the if test in dispatch_command / COM_QUERY)
785
if (session->is_fatal_error)
786
server_status&= ~SERVER_MORE_RESULTS_EXISTS;
787
int2store(buff + 3, server_status);
788
drizzleclient_net_write(&net, buff, 5);
791
static ListenMySQLProtocol *listen_obj= NULL;
793
static int init(drizzled::plugin::Registry ®istry)
795
listen_obj= new ListenMySQLProtocol("mysql_protocol", true);
796
registry.add(listen_obj);
800
static int deinit(drizzled::plugin::Registry ®istry)
802
registry.remove(listen_obj);
807
static DRIZZLE_SYSVAR_UINT(port, port, PLUGIN_VAR_RQCMDARG,
808
N_("Port number to use for connection or 0 for default to with MySQL "
810
NULL, NULL, 3306, 0, 65535, 0);
811
static DRIZZLE_SYSVAR_UINT(connect_timeout, connect_timeout,
812
PLUGIN_VAR_RQCMDARG, N_("Connect Timeout."),
813
NULL, NULL, 10, 1, 300, 0);
814
static DRIZZLE_SYSVAR_UINT(read_timeout, read_timeout, PLUGIN_VAR_RQCMDARG,
815
N_("Read Timeout."), NULL, NULL, 30, 1, 300, 0);
816
static DRIZZLE_SYSVAR_UINT(write_timeout, write_timeout, PLUGIN_VAR_RQCMDARG,
817
N_("Write Timeout."), NULL, NULL, 60, 1, 300, 0);
818
static DRIZZLE_SYSVAR_UINT(retry_count, retry_count, PLUGIN_VAR_RQCMDARG,
819
N_("Retry Count."), NULL, NULL, 10, 1, 100, 0);
820
static DRIZZLE_SYSVAR_UINT(buffer_length, buffer_length, PLUGIN_VAR_RQCMDARG,
821
N_("Buffer length."), NULL, NULL, 16384, 1024,
823
static DRIZZLE_SYSVAR_STR(bind_address, bind_address, PLUGIN_VAR_READONLY,
824
N_("Address to bind to."), NULL, NULL, NULL);
826
static struct st_mysql_sys_var* system_variables[]= {
827
DRIZZLE_SYSVAR(port),
828
DRIZZLE_SYSVAR(connect_timeout),
829
DRIZZLE_SYSVAR(read_timeout),
830
DRIZZLE_SYSVAR(write_timeout),
831
DRIZZLE_SYSVAR(retry_count),
832
DRIZZLE_SYSVAR(buffer_length),
833
DRIZZLE_SYSVAR(bind_address),
837
drizzle_declare_plugin(mysql_protocol)
842
"MySQL Protocol Module",
844
init, /* Plugin Init */
845
deinit, /* Plugin Deinit */
846
NULL, /* status variables */
847
system_variables, /* system variables */
848
NULL /* config options */
850
drizzle_declare_plugin_end;