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
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>
26
#include "drizzled/internal/m_string.h"
31
#include "oldlibdrizzle.h"
35
using namespace drizzled;
37
#define PROTOCOL_VERSION 10
41
extern uint32_t global_thread_id;
44
static const unsigned int PACKET_BUFFER_EXTRA_ALLOC= 1024;
46
static uint32_t connect_timeout;
47
static uint32_t read_timeout;
48
static uint32_t write_timeout;
49
static uint32_t retry_count;
50
static uint32_t buffer_length;
51
static char* bind_address;
53
const char* ListenMySQLProtocol::getHost(void) const
58
in_port_t ListenMySQLProtocol::getPort(void) const
60
return (in_port_t) port;
63
plugin::Client *ListenMySQLProtocol::getClient(int fd)
66
new_fd= acceptTcp(fd);
70
return new (nothrow) ClientMySQLProtocol(new_fd, using_mysql41_protocol);
73
ClientMySQLProtocol::ClientMySQLProtocol(int fd, bool using_mysql41_protocol_arg):
74
using_mysql41_protocol(using_mysql41_protocol_arg)
81
if (drizzleclient_net_init_sock(&net, fd, 0, buffer_length))
84
drizzleclient_net_set_read_timeout(&net, read_timeout);
85
drizzleclient_net_set_write_timeout(&net, write_timeout);
86
net.retry_count=retry_count;
89
ClientMySQLProtocol::~ClientMySQLProtocol()
92
drizzleclient_vio_close(net.vio);
95
int ClientMySQLProtocol::getFileDescriptor(void)
97
return drizzleclient_net_get_sd(&net);
100
bool ClientMySQLProtocol::isConnected()
105
bool ClientMySQLProtocol::isReading(void)
107
return net.reading_or_writing == 1;
110
bool ClientMySQLProtocol::isWriting(void)
112
return net.reading_or_writing == 2;
115
bool ClientMySQLProtocol::flush()
119
bool ret= drizzleclient_net_write(&net, (unsigned char*) packet.ptr(),
125
void ClientMySQLProtocol::close(void)
129
drizzleclient_net_close(&net);
130
drizzleclient_net_end(&net);
134
bool ClientMySQLProtocol::authenticate()
136
bool connection_is_valid;
138
/* Use "connect_timeout" value during connection phase */
139
drizzleclient_net_set_read_timeout(&net, connect_timeout);
140
drizzleclient_net_set_write_timeout(&net, connect_timeout);
142
connection_is_valid= checkConnection();
144
if (connection_is_valid)
148
sendError(session->main_da.sql_errno(), session->main_da.message());
152
/* Connect completed, set read/write timeouts back to default */
153
drizzleclient_net_set_read_timeout(&net, read_timeout);
154
drizzleclient_net_set_write_timeout(&net, write_timeout);
158
bool ClientMySQLProtocol::readCommand(char **l_packet, uint32_t *packet_length)
161
This thread will do a blocking read from the client which
162
will be interrupted when the next command is received from
163
the client, the connection is closed or "net_wait_timeout"
164
number of seconds has passed
167
/* We can do this much more efficiently with poll timeouts or watcher thread,
168
disabling for now, which means net_wait_timeout == read_timeout. */
169
drizzleclient_net_set_read_timeout(&net,
170
session->variables.net_wait_timeout);
175
*packet_length= drizzleclient_net_read(&net);
176
if (*packet_length == packet_error)
178
/* Check if we can continue without closing the connection */
180
if(net.last_errno== CR_NET_PACKET_TOO_LARGE)
181
my_error(ER_NET_PACKET_TOO_LARGE, MYF(0));
182
if (session->main_da.status() == Diagnostics_area::DA_ERROR)
183
sendError(session->main_da.sql_errno(), session->main_da.message());
188
return false; // We have to close it.
195
*l_packet= (char*) net.read_pos;
198
'packet_length' contains length of data, as it was stored in packet
199
header. In case of malformed header, drizzleclient_net_read returns zero.
200
If packet_length is not zero, drizzleclient_net_read ensures that the returned
201
number of bytes was actually read from network.
202
There is also an extra safety measure in drizzleclient_net_read:
203
it sets packet[packet_length]= 0, but only for non-zero packets.
206
if (*packet_length == 0) /* safety */
208
/* Initialize with COM_SLEEP packet */
209
(*l_packet)[0]= (unsigned char) COM_SLEEP;
212
else if (using_mysql41_protocol)
214
/* Map from MySQL commands to Drizzle commands. */
215
switch ((int)(*l_packet)[0])
219
case 2: /* INIT_DB */
223
case 8: /* SHUTDOWN */
224
(*l_packet)[0]= (unsigned char) COM_SHUTDOWN;
228
(*l_packet)[0]= (unsigned char) COM_PING;
233
/* Just drop connection for MySQL commands we don't support. */
234
(*l_packet)[0]= (unsigned char) COM_QUIT;
240
/* Do not rely on drizzleclient_net_read, extra safety against programming errors. */
241
(*l_packet)[*packet_length]= '\0'; /* safety */
244
/* See comment above. */
245
/* Restore read timeout value */
246
drizzleclient_net_set_read_timeout(&net,
247
session->variables.net_read_timeout);
254
Return ok to the client.
256
The ok packet has the following structure:
258
- 0 : Marker (1 byte)
259
- affected_rows : Stored in 1-9 bytes
260
- id : Stored in 1-9 bytes
261
- server_status : Copy of session->server_status; Can be used by client
262
to check if we are inside an transaction.
264
- warning_count : Stored in 2 bytes; New in 4.1 client
265
- message : Stored as packed length (1-9 bytes) + message.
266
Is not stored if no message.
268
@param session Thread handler
269
@param affected_rows Number of rows changed by statement
270
@param id Auto_increment id for first row (if used)
271
@param message Message to send to the client (Used by mysql_status)
274
void ClientMySQLProtocol::sendOK()
276
unsigned char buff[DRIZZLE_ERRMSG_SIZE+10],*pos;
277
const char *message= NULL;
280
if (!net.vio) // hack for re-parsing queries
285
buff[0]=0; // No fields
286
if (session->main_da.status() == Diagnostics_area::DA_OK)
288
if (client_capabilities & CLIENT_FOUND_ROWS && session->main_da.found_rows())
289
pos=drizzleclient_net_store_length(buff+1,session->main_da.found_rows());
291
pos=drizzleclient_net_store_length(buff+1,session->main_da.affected_rows());
292
pos=drizzleclient_net_store_length(pos, session->main_da.last_insert_id());
293
int2store(pos, session->main_da.server_status());
295
tmp= min(session->main_da.total_warn_count(), (uint32_t)65535);
296
message= session->main_da.message();
300
pos=drizzleclient_net_store_length(buff+1,0);
301
pos=drizzleclient_net_store_length(pos, 0);
302
int2store(pos, session->server_status);
304
tmp= min(session->total_warn_count, (uint32_t)65535);
307
/* We can only return up to 65535 warnings in two bytes */
311
session->main_da.can_overwrite_status= true;
313
if (message && message[0])
315
size_t length= strlen(message);
316
pos=drizzleclient_net_store_length(pos,length);
317
memcpy(pos,(unsigned char*) message,length);
320
drizzleclient_net_write(&net, buff, (size_t) (pos-buff));
321
drizzleclient_net_flush(&net);
323
session->main_da.can_overwrite_status= false;
327
Send eof (= end of result set) to the client.
329
The eof packet has the following structure:
331
- 254 (DRIZZLE_PROTOCOL_NO_MORE_DATA) : Marker (1 byte)
332
- warning_count : Stored in 2 bytes; New in 4.1 client
333
- status_flag : Stored in 2 bytes;
334
For flags like SERVER_MORE_RESULTS_EXISTS.
336
Note that the warning count will not be sent if 'no_flush' is set as
337
we don't want to report the warning count until all data is sent to the
341
void ClientMySQLProtocol::sendEOF()
343
/* Set to true if no active vio, to work well in case of --init-file */
346
session->main_da.can_overwrite_status= true;
347
writeEOFPacket(session->main_da.server_status(),
348
session->main_da.total_warn_count());
349
drizzleclient_net_flush(&net);
350
session->main_da.can_overwrite_status= false;
352
packet.shrink(buffer_length);
356
void ClientMySQLProtocol::sendError(uint32_t sql_errno, const char *err)
360
buff[]: sql_errno:2 + ('#':1 + SQLSTATE_LENGTH:5) + DRIZZLE_ERRMSG_SIZE:512
362
unsigned char buff[2+1+SQLSTATE_LENGTH+DRIZZLE_ERRMSG_SIZE], *pos;
365
assert(err && err[0]);
368
It's one case when we can push an error even though there
369
is an OK or EOF already.
371
session->main_da.can_overwrite_status= true;
373
/* Abort multi-result sets */
374
session->server_status&= ~SERVER_MORE_RESULTS_EXISTS;
377
Send a error string to client.
379
For SIGNAL/RESIGNAL and GET DIAGNOSTICS functionality it's
380
critical that every error that can be intercepted is issued in one
381
place only, my_message_sql.
389
int2store(buff,sql_errno);
392
/* The first # is to make the client backward compatible */
394
pos= (unsigned char*) strcpy((char*) buff+3, drizzle_errno_to_sqlstate(sql_errno));
395
pos+= strlen(drizzle_errno_to_sqlstate(sql_errno));
397
char *tmp= strncpy((char*)pos, err, DRIZZLE_ERRMSG_SIZE-1);
398
tmp+= strlen((char*)pos);
400
length= (uint32_t)(tmp-(char*)buff);
403
drizzleclient_net_write_command(&net,(unsigned char) 255, (unsigned char*) "", 0, (unsigned char*) err, length);
405
session->main_da.can_overwrite_status= false;
409
Send name and type of result to client.
411
Sum fields has table name empty and field_name.
413
@param Session Thread data object
414
@param list List of items to send to client
415
@param flag Bit mask with the following functions:
416
- 1 send number of rows
417
- 2 send default values
418
- 4 don't write eof packet
423
1 Error (Note that in this case the error is not sent to the
426
bool ClientMySQLProtocol::sendFields(List<Item> *list)
428
List_iterator_fast<Item> it(*list);
430
unsigned char buff[80];
431
String tmp((char*) buff,sizeof(buff),&my_charset_bin);
433
unsigned char *row_pos= drizzleclient_net_store_length(buff, list->elements);
434
(void) drizzleclient_net_write(&net, buff, (size_t) (row_pos-buff));
440
item->make_field(&field);
444
if (store(STRING_WITH_LEN("def")) ||
445
store(field.db_name) ||
446
store(field.table_name) ||
447
store(field.org_table_name) ||
448
store(field.col_name) ||
449
store(field.org_col_name) ||
450
packet.realloc(packet.length()+12))
453
/* Store fixed length fields */
454
pos= (char*) packet.ptr()+packet.length();
455
*pos++= 12; // Length of packed fields
457
int2store(pos, field.charsetnr);
458
int4store(pos+2, field.length);
460
if (using_mysql41_protocol)
462
/* Switch to MySQL field numbering. */
465
case DRIZZLE_TYPE_LONG:
469
case DRIZZLE_TYPE_DOUBLE:
473
case DRIZZLE_TYPE_NULL:
477
case DRIZZLE_TYPE_TIMESTAMP:
481
case DRIZZLE_TYPE_LONGLONG:
485
case DRIZZLE_TYPE_DATETIME:
489
case DRIZZLE_TYPE_DATE:
493
case DRIZZLE_TYPE_VARCHAR:
497
case DRIZZLE_TYPE_DECIMAL:
501
case DRIZZLE_TYPE_ENUM:
505
case DRIZZLE_TYPE_BLOB:
512
/* Add one to compensate for tinyint removal from enum. */
513
pos[6]= field.type + 1;
516
int2store(pos+7,field.flags);
517
pos[9]= (char) field.decimals;
518
pos[10]= 0; // For the future
519
pos[11]= 0; // For the future
522
packet.length((uint32_t) (pos - packet.ptr()));
528
Mark the end of meta-data result set, and store session->server_status,
529
to show that there is no cursor.
530
Send no warning information, as it will be sent at statement end.
532
writeEOFPacket(session->server_status, session->total_warn_count);
536
my_message(ER_OUT_OF_RESOURCES, ER(ER_OUT_OF_RESOURCES),
541
bool ClientMySQLProtocol::store(Field *from)
545
char buff[MAX_FIELD_WIDTH];
546
String str(buff,sizeof(buff), &my_charset_bin);
550
return netStoreData((const unsigned char *)str.ptr(), str.length());
553
bool ClientMySQLProtocol::store(void)
557
return packet.append(buff, sizeof(buff), PACKET_BUFFER_EXTRA_ALLOC);
560
bool ClientMySQLProtocol::store(int32_t from)
563
return netStoreData((unsigned char*) buff,
564
(size_t) (internal::int10_to_str(from, buff, -10) - buff));
567
bool ClientMySQLProtocol::store(uint32_t from)
570
return netStoreData((unsigned char*) buff,
571
(size_t) (internal::int10_to_str(from, buff, 10) - buff));
574
bool ClientMySQLProtocol::store(int64_t from)
577
return netStoreData((unsigned char*) buff,
578
(size_t) (internal::int64_t10_to_str(from, buff, -10) - buff));
581
bool ClientMySQLProtocol::store(uint64_t from)
584
return netStoreData((unsigned char*) buff,
585
(size_t) (internal::int64_t10_to_str(from, buff, 10) - buff));
588
bool ClientMySQLProtocol::store(double from, uint32_t decimals, String *buffer)
590
buffer->set_real(from, decimals, session->charset());
591
return netStoreData((unsigned char*) buffer->ptr(), buffer->length());
594
bool ClientMySQLProtocol::store(const char *from, size_t length)
596
return netStoreData((const unsigned char *)from, length);
599
bool ClientMySQLProtocol::wasAborted(void)
601
return net.error && net.vio != 0;
604
bool ClientMySQLProtocol::haveMoreData(void)
606
return drizzleclient_net_more_data(&net);
609
bool ClientMySQLProtocol::haveError(void)
611
return net.error || net.vio == 0;
614
bool ClientMySQLProtocol::checkConnection(void)
624
if (drizzleclient_net_peer_addr(&net, ip, &peer_port, NI_MAXHOST))
626
my_error(ER_BAD_HOST_ERROR, MYF(0), session->getSecurityContext().getIp().c_str());
630
session->getSecurityContext().setIp(ip);
632
drizzleclient_net_keepalive(&net, true);
634
uint32_t server_capabilites;
636
/* buff[] needs to big enough to hold the server_version variable */
637
char buff[SERVER_VERSION_LENGTH + SCRAMBLE_LENGTH + 64];
639
server_capabilites= CLIENT_BASIC_FLAGS;
641
if (using_mysql41_protocol)
642
server_capabilites|= CLIENT_PROTOCOL_MYSQL41;
645
server_capabilites|= CLIENT_COMPRESS;
646
#endif /* HAVE_COMPRESS */
648
end= buff + strlen(VERSION);
649
if ((end - buff) >= SERVER_VERSION_LENGTH)
650
end= buff + (SERVER_VERSION_LENGTH - 1);
651
memcpy(buff, VERSION, end - buff);
655
int4store((unsigned char*) end, global_thread_id);
658
/* We don't use scramble anymore. */
659
memset(end, 'X', SCRAMBLE_LENGTH_323);
660
end+= SCRAMBLE_LENGTH_323;
661
*end++= 0; /* an empty byte for some reason */
663
int2store(end, server_capabilites);
664
/* write server characteristics: up to 16 bytes allowed */
665
end[2]=(char) default_charset_info->number;
666
int2store(end+3, session->server_status);
667
memset(end+5, 0, 13);
670
/* Write scramble tail. */
671
memset(end, 'X', SCRAMBLE_LENGTH - SCRAMBLE_LENGTH_323);
672
end+= (SCRAMBLE_LENGTH - SCRAMBLE_LENGTH_323);
673
*end++= 0; /* an empty byte for some reason */
675
/* At this point we write connection message and read reply */
676
if (drizzleclient_net_write_command(&net
677
, (unsigned char) PROTOCOL_VERSION
678
, (unsigned char*) ""
680
, (unsigned char*) buff
681
, (size_t) (end-buff))
682
|| (pkt_len= drizzleclient_net_read(&net)) == packet_error
683
|| pkt_len < MIN_HANDSHAKE_SIZE)
685
my_error(ER_HANDSHAKE_ERROR, MYF(0), session->getSecurityContext().getIp().c_str());
689
if (packet.alloc(buffer_length))
690
return false; /* The error is set by alloc(). */
692
client_capabilities= uint2korr(net.read_pos);
695
client_capabilities|= ((uint32_t) uint2korr(net.read_pos + 2)) << 16;
696
session->max_client_packet_length= uint4korr(net.read_pos + 4);
697
end= (char*) net.read_pos + 32;
700
Disable those bits which are not supported by the server.
701
This is a precautionary measure, if the client lies. See Bug#27944.
703
client_capabilities&= server_capabilites;
705
if (end >= (char*) net.read_pos + pkt_len + 2)
707
my_error(ER_HANDSHAKE_ERROR, MYF(0), session->getSecurityContext().getIp().c_str());
711
net.return_status= &session->server_status;
714
char *passwd= strchr(user, '\0')+1;
715
uint32_t user_len= passwd - user - 1;
719
Old clients send null-terminated string as password; new clients send
720
the size (1 byte) + string (not null-terminated). Hence in case of empty
721
password both send '\0'.
723
This strlen() can't be easily deleted without changing client.
725
Cast *passwd to an unsigned char, so that it doesn't extend the sign for
726
*passwd > 127 and become 2**32-127+ after casting to uint.
728
uint32_t passwd_len= client_capabilities & CLIENT_SECURE_CONNECTION ?
729
(unsigned char)(*passwd++) : strlen(passwd);
730
l_db= client_capabilities & CLIENT_CONNECT_WITH_DB ? l_db + passwd_len + 1 : 0;
732
/* strlen() can't be easily deleted without changing client */
733
uint32_t db_len= l_db ? strlen(l_db) : 0;
735
if (passwd + passwd_len + db_len > (char *) net.read_pos + pkt_len)
737
my_error(ER_HANDSHAKE_ERROR, MYF(0), session->getSecurityContext().getIp().c_str());
741
/* If username starts and ends in "'", chop them off */
742
if (user_len > 1 && user[0] == '\'' && user[user_len - 1] == '\'')
749
session->getSecurityContext().setUser(user);
751
return session->checkUser(passwd, passwd_len, l_db);
754
bool ClientMySQLProtocol::netStoreData(const unsigned char *from, size_t length)
756
size_t packet_length= packet.length();
758
The +9 comes from that strings of length longer than 16M require
759
9 bytes to be stored (see drizzleclient_net_store_length).
761
if (packet_length+9+length > packet.alloced_length() &&
762
packet.realloc(packet_length+9+length))
764
unsigned char *to= drizzleclient_net_store_length((unsigned char*) packet.ptr()+packet_length, length);
765
memcpy(to,from,length);
766
packet.length((size_t) (to+length-(unsigned char*) packet.ptr()));
771
Format EOF packet according to the current client and
772
write it to the network output buffer.
775
void ClientMySQLProtocol::writeEOFPacket(uint32_t server_status,
776
uint32_t total_warn_count)
778
unsigned char buff[5];
780
Don't send warn count during SP execution, as the warn_list
781
is cleared between substatements, and mysqltest gets confused
783
uint32_t tmp= min(total_warn_count, (uint32_t)65535);
784
buff[0]= DRIZZLE_PROTOCOL_NO_MORE_DATA;
785
int2store(buff+1, tmp);
787
The following test should never be true, but it's better to do it
788
because if 'is_fatal_error' is set the server is not going to execute
789
other queries (see the if test in dispatch_command / COM_QUERY)
791
if (session->is_fatal_error)
792
server_status&= ~SERVER_MORE_RESULTS_EXISTS;
793
int2store(buff + 3, server_status);
794
drizzleclient_net_write(&net, buff, 5);
797
static ListenMySQLProtocol *listen_obj= NULL;
799
static int init(drizzled::plugin::Registry ®istry)
801
listen_obj= new ListenMySQLProtocol("mysql_protocol", true);
802
registry.add(listen_obj);
806
static int deinit(drizzled::plugin::Registry ®istry)
808
registry.remove(listen_obj);
813
static DRIZZLE_SYSVAR_UINT(port, port, PLUGIN_VAR_RQCMDARG,
814
N_("Port number to use for connection or 0 for default to with MySQL "
816
NULL, NULL, 3306, 0, 65535, 0);
817
static DRIZZLE_SYSVAR_UINT(connect_timeout, connect_timeout,
818
PLUGIN_VAR_RQCMDARG, N_("Connect Timeout."),
819
NULL, NULL, 10, 1, 300, 0);
820
static DRIZZLE_SYSVAR_UINT(read_timeout, read_timeout, PLUGIN_VAR_RQCMDARG,
821
N_("Read Timeout."), NULL, NULL, 30, 1, 300, 0);
822
static DRIZZLE_SYSVAR_UINT(write_timeout, write_timeout, PLUGIN_VAR_RQCMDARG,
823
N_("Write Timeout."), NULL, NULL, 60, 1, 300, 0);
824
static DRIZZLE_SYSVAR_UINT(retry_count, retry_count, PLUGIN_VAR_RQCMDARG,
825
N_("Retry Count."), NULL, NULL, 10, 1, 100, 0);
826
static DRIZZLE_SYSVAR_UINT(buffer_length, buffer_length, PLUGIN_VAR_RQCMDARG,
827
N_("Buffer length."), NULL, NULL, 16384, 1024,
829
static DRIZZLE_SYSVAR_STR(bind_address, bind_address, PLUGIN_VAR_READONLY,
830
N_("Address to bind to."), NULL, NULL, NULL);
832
static drizzle_sys_var* sys_variables[]= {
833
DRIZZLE_SYSVAR(port),
834
DRIZZLE_SYSVAR(connect_timeout),
835
DRIZZLE_SYSVAR(read_timeout),
836
DRIZZLE_SYSVAR(write_timeout),
837
DRIZZLE_SYSVAR(retry_count),
838
DRIZZLE_SYSVAR(buffer_length),
839
DRIZZLE_SYSVAR(bind_address),
843
DRIZZLE_DECLARE_PLUGIN
849
"MySQL Protocol Module",
851
init, /* Plugin Init */
852
deinit, /* Plugin Deinit */
853
sys_variables, /* system variables */
854
NULL /* config options */
856
DRIZZLE_DECLARE_PLUGIN_END;