91
return new ClientDrizzleProtocol(new_fd, getCounters());
94
static int init(drizzled::module::Context &context)
96
const module::option_map &vm= context.getOptions();
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>()));
110
context.registerVariable(new sys_var_uint32_t_ptr("max-connections", &ListenDrizzleProtocol::drizzle_counters->max_connections));
116
static void init_options(drizzled::module::option_context &context)
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),
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("localhost"),
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."));
147
} /* namespace drizzle_protocol */
148
} /* namespace drizzle_plugin */
150
DRIZZLE_PLUGIN(drizzle_plugin::drizzle_protocol::init, NULL, drizzle_plugin::drizzle_protocol::init_options);
85
return new (nothrow) ClientDrizzleProtocol(new_fd, using_mysql41_protocol);
88
ClientDrizzleProtocol::ClientDrizzleProtocol(int fd, bool using_mysql41_protocol_arg):
89
using_mysql41_protocol(using_mysql41_protocol_arg)
96
if (drizzleclient_net_init_sock(&net, fd, 0, buffer_length))
99
drizzleclient_net_set_read_timeout(&net, read_timeout);
100
drizzleclient_net_set_write_timeout(&net, write_timeout);
101
net.retry_count=retry_count;
104
ClientDrizzleProtocol::~ClientDrizzleProtocol()
107
drizzleclient_vio_close(net.vio);
110
int ClientDrizzleProtocol::getFileDescriptor(void)
112
return drizzleclient_net_get_sd(&net);
115
bool ClientDrizzleProtocol::isConnected()
120
bool ClientDrizzleProtocol::isReading(void)
122
return net.reading_or_writing == 1;
125
bool ClientDrizzleProtocol::isWriting(void)
127
return net.reading_or_writing == 2;
130
bool ClientDrizzleProtocol::flush()
134
bool ret= drizzleclient_net_write(&net, (unsigned char*) packet.ptr(),
140
void ClientDrizzleProtocol::close(void)
144
drizzleclient_net_close(&net);
145
drizzleclient_net_end(&net);
149
bool ClientDrizzleProtocol::authenticate()
151
bool connection_is_valid;
153
/* Use "connect_timeout" value during connection phase */
154
drizzleclient_net_set_read_timeout(&net, connect_timeout);
155
drizzleclient_net_set_write_timeout(&net, connect_timeout);
157
connection_is_valid= checkConnection();
159
if (connection_is_valid)
163
sendError(session->main_da.sql_errno(), session->main_da.message());
167
/* Connect completed, set read/write timeouts back to default */
168
drizzleclient_net_set_read_timeout(&net, read_timeout);
169
drizzleclient_net_set_write_timeout(&net, write_timeout);
173
bool ClientDrizzleProtocol::readCommand(char **l_packet, uint32_t *packet_length)
176
This thread will do a blocking read from the client which
177
will be interrupted when the next command is received from
178
the client, the connection is closed or "net_wait_timeout"
179
number of seconds has passed
182
/* We can do this much more efficiently with poll timeouts or watcher thread,
183
disabling for now, which means net_wait_timeout == read_timeout. */
184
drizzleclient_net_set_read_timeout(&net,
185
session->variables.net_wait_timeout);
190
*packet_length= drizzleclient_net_read(&net);
191
if (*packet_length == packet_error)
193
/* Check if we can continue without closing the connection */
195
if(net.last_errno== CR_NET_PACKET_TOO_LARGE)
196
my_error(ER_NET_PACKET_TOO_LARGE, MYF(0));
197
if (session->main_da.status() == Diagnostics_area::DA_ERROR)
198
sendError(session->main_da.sql_errno(), session->main_da.message());
203
return false; // We have to close it.
210
*l_packet= (char*) net.read_pos;
213
'packet_length' contains length of data, as it was stored in packet
214
header. In case of malformed header, drizzleclient_net_read returns zero.
215
If packet_length is not zero, drizzleclient_net_read ensures that the returned
216
number of bytes was actually read from network.
217
There is also an extra safety measure in drizzleclient_net_read:
218
it sets packet[packet_length]= 0, but only for non-zero packets.
221
if (*packet_length == 0) /* safety */
223
/* Initialize with COM_SLEEP packet */
224
(*l_packet)[0]= (unsigned char) COM_SLEEP;
227
else if (using_mysql41_protocol)
229
/* Map from MySQL commands to Drizzle commands. */
230
switch ((int)(*l_packet)[0])
234
case 2: /* INIT_DB */
238
case 8: /* SHUTDOWN */
239
(*l_packet)[0]= (unsigned char) COM_SHUTDOWN;
243
(*l_packet)[0]= (unsigned char) COM_SHUTDOWN;
248
/* Just drop connection for MySQL commands we don't support. */
249
(*l_packet)[0]= (unsigned char) COM_QUIT;
255
/* Do not rely on drizzleclient_net_read, extra safety against programming errors. */
256
(*l_packet)[*packet_length]= '\0'; /* safety */
259
/* See comment above. */
260
/* Restore read timeout value */
261
drizzleclient_net_set_read_timeout(&net,
262
session->variables.net_read_timeout);
269
Return ok to the client.
271
The ok packet has the following structure:
273
- 0 : Marker (1 byte)
274
- affected_rows : Stored in 1-9 bytes
275
- id : Stored in 1-9 bytes
276
- server_status : Copy of session->server_status; Can be used by client
277
to check if we are inside an transaction.
279
- warning_count : Stored in 2 bytes; New in 4.1 client
280
- message : Stored as packed length (1-9 bytes) + message.
281
Is not stored if no message.
283
@param session Thread handler
284
@param affected_rows Number of rows changed by statement
285
@param id Auto_increment id for first row (if used)
286
@param message Message to send to the client (Used by mysql_status)
289
void ClientDrizzleProtocol::sendOK()
291
unsigned char buff[DRIZZLE_ERRMSG_SIZE+10],*pos;
292
const char *message= NULL;
295
if (!net.vio) // hack for re-parsing queries
300
buff[0]=0; // No fields
301
if (session->main_da.status() == Diagnostics_area::DA_OK)
303
if (client_capabilities & CLIENT_FOUND_ROWS && session->main_da.found_rows())
304
pos=drizzleclient_net_store_length(buff+1,session->main_da.found_rows());
306
pos=drizzleclient_net_store_length(buff+1,session->main_da.affected_rows());
307
pos=drizzleclient_net_store_length(pos, session->main_da.last_insert_id());
308
int2store(pos, session->main_da.server_status());
310
tmp= min(session->main_da.total_warn_count(), (uint32_t)65535);
311
message= session->main_da.message();
315
pos=drizzleclient_net_store_length(buff+1,0);
316
pos=drizzleclient_net_store_length(pos, 0);
317
int2store(pos, session->server_status);
319
tmp= min(session->total_warn_count, (uint32_t)65535);
322
/* We can only return up to 65535 warnings in two bytes */
326
session->main_da.can_overwrite_status= true;
328
if (message && message[0])
330
size_t length= strlen(message);
331
pos=drizzleclient_net_store_length(pos,length);
332
memcpy(pos,(unsigned char*) message,length);
335
drizzleclient_net_write(&net, buff, (size_t) (pos-buff));
336
drizzleclient_net_flush(&net);
338
session->main_da.can_overwrite_status= false;
342
Send eof (= end of result set) to the client.
344
The eof packet has the following structure:
346
- 254 (DRIZZLE_PROTOCOL_NO_MORE_DATA) : Marker (1 byte)
347
- warning_count : Stored in 2 bytes; New in 4.1 client
348
- status_flag : Stored in 2 bytes;
349
For flags like SERVER_MORE_RESULTS_EXISTS.
351
Note that the warning count will not be sent if 'no_flush' is set as
352
we don't want to report the warning count until all data is sent to the
356
void ClientDrizzleProtocol::sendEOF()
358
/* Set to true if no active vio, to work well in case of --init-file */
361
session->main_da.can_overwrite_status= true;
362
writeEOFPacket(session->main_da.server_status(),
363
session->main_da.total_warn_count());
364
drizzleclient_net_flush(&net);
365
session->main_da.can_overwrite_status= false;
367
packet.shrink(buffer_length);
371
void ClientDrizzleProtocol::sendError(uint32_t sql_errno, const char *err)
375
buff[]: sql_errno:2 + ('#':1 + SQLSTATE_LENGTH:5) + DRIZZLE_ERRMSG_SIZE:512
377
unsigned char buff[2+1+SQLSTATE_LENGTH+DRIZZLE_ERRMSG_SIZE], *pos;
380
assert(err && err[0]);
383
It's one case when we can push an error even though there
384
is an OK or EOF already.
386
session->main_da.can_overwrite_status= true;
388
/* Abort multi-result sets */
389
session->server_status&= ~SERVER_MORE_RESULTS_EXISTS;
392
Send a error string to client.
394
For SIGNAL/RESIGNAL and GET DIAGNOSTICS functionality it's
395
critical that every error that can be intercepted is issued in one
396
place only, my_message_sql.
404
int2store(buff,sql_errno);
407
/* The first # is to make the client backward compatible */
409
pos= (unsigned char*) strcpy((char*) buff+3, drizzle_errno_to_sqlstate(sql_errno));
410
pos+= strlen(drizzle_errno_to_sqlstate(sql_errno));
412
char *tmp= strncpy((char*)pos, err, DRIZZLE_ERRMSG_SIZE-1);
413
tmp+= strlen((char*)pos);
415
length= (uint32_t)(tmp-(char*)buff);
418
drizzleclient_net_write_command(&net,(unsigned char) 255, (unsigned char*) "", 0, (unsigned char*) err, length);
420
session->main_da.can_overwrite_status= false;
424
Send name and type of result to client.
426
Sum fields has table name empty and field_name.
428
@param Session Thread data object
429
@param list List of items to send to client
430
@param flag Bit mask with the following functions:
431
- 1 send number of rows
432
- 2 send default values
433
- 4 don't write eof packet
438
1 Error (Note that in this case the error is not sent to the
441
bool ClientDrizzleProtocol::sendFields(List<Item> *list)
443
List_iterator_fast<Item> it(*list);
445
unsigned char buff[80];
446
String tmp((char*) buff,sizeof(buff),&my_charset_bin);
448
unsigned char *row_pos= drizzleclient_net_store_length(buff, list->elements);
449
(void) drizzleclient_net_write(&net, buff, (size_t) (row_pos-buff));
455
item->make_field(&field);
459
if (store(STRING_WITH_LEN("def")) ||
460
store(field.db_name) ||
461
store(field.table_name) ||
462
store(field.org_table_name) ||
463
store(field.col_name) ||
464
store(field.org_col_name) ||
465
packet.realloc(packet.length()+12))
468
/* Store fixed length fields */
469
pos= (char*) packet.ptr()+packet.length();
470
*pos++= 12; // Length of packed fields
472
int2store(pos, field.charsetnr);
473
int4store(pos+2, field.length);
475
if (using_mysql41_protocol)
477
/* Switch to MySQL field numbering. */
480
case DRIZZLE_TYPE_LONG:
484
case DRIZZLE_TYPE_DOUBLE:
488
case DRIZZLE_TYPE_NULL:
492
case DRIZZLE_TYPE_TIMESTAMP:
496
case DRIZZLE_TYPE_LONGLONG:
500
case DRIZZLE_TYPE_DATETIME:
504
case DRIZZLE_TYPE_DATE:
508
case DRIZZLE_TYPE_VARCHAR:
512
case DRIZZLE_TYPE_DECIMAL:
516
case DRIZZLE_TYPE_ENUM:
520
case DRIZZLE_TYPE_BLOB:
527
/* Add one to compensate for tinyint removal from enum. */
528
pos[6]= field.type + 1;
531
int2store(pos+7,field.flags);
532
pos[9]= (char) field.decimals;
533
pos[10]= 0; // For the future
534
pos[11]= 0; // For the future
537
packet.length((uint32_t) (pos - packet.ptr()));
543
Mark the end of meta-data result set, and store session->server_status,
544
to show that there is no cursor.
545
Send no warning information, as it will be sent at statement end.
547
writeEOFPacket(session->server_status, session->total_warn_count);
551
my_message(ER_OUT_OF_RESOURCES, ER(ER_OUT_OF_RESOURCES),
556
bool ClientDrizzleProtocol::store(Field *from)
560
char buff[MAX_FIELD_WIDTH];
561
String str(buff,sizeof(buff), &my_charset_bin);
565
return netStoreData((const unsigned char *)str.ptr(), str.length());
568
bool ClientDrizzleProtocol::store(void)
572
return packet.append(buff, sizeof(buff), PACKET_BUFFER_EXTRA_ALLOC);
575
bool ClientDrizzleProtocol::store(int32_t from)
578
return netStoreData((unsigned char*) buff,
579
(size_t) (internal::int10_to_str(from, buff, -10) - buff));
582
bool ClientDrizzleProtocol::store(uint32_t from)
585
return netStoreData((unsigned char*) buff,
586
(size_t) (internal::int10_to_str(from, buff, 10) - buff));
589
bool ClientDrizzleProtocol::store(int64_t from)
592
return netStoreData((unsigned char*) buff,
593
(size_t) (internal::int64_t10_to_str(from, buff, -10) - buff));
596
bool ClientDrizzleProtocol::store(uint64_t from)
599
return netStoreData((unsigned char*) buff,
600
(size_t) (internal::int64_t10_to_str(from, buff, 10) - buff));
603
bool ClientDrizzleProtocol::store(double from, uint32_t decimals, String *buffer)
605
buffer->set_real(from, decimals, session->charset());
606
return netStoreData((unsigned char*) buffer->ptr(), buffer->length());
609
bool ClientDrizzleProtocol::store(const char *from, size_t length)
611
return netStoreData((const unsigned char *)from, length);
614
bool ClientDrizzleProtocol::wasAborted(void)
616
return net.error && net.vio != 0;
619
bool ClientDrizzleProtocol::haveMoreData(void)
621
return drizzleclient_net_more_data(&net);
624
bool ClientDrizzleProtocol::haveError(void)
626
return net.error || net.vio == 0;
629
bool ClientDrizzleProtocol::checkConnection(void)
639
if (drizzleclient_net_peer_addr(&net, ip, &peer_port, NI_MAXHOST))
641
my_error(ER_BAD_HOST_ERROR, MYF(0), session->security_ctx.ip.c_str());
645
session->security_ctx.ip.assign(ip);
647
drizzleclient_net_keepalive(&net, true);
649
uint32_t server_capabilites;
651
/* buff[] needs to big enough to hold the server_version variable */
652
char buff[SERVER_VERSION_LENGTH + SCRAMBLE_LENGTH + 64];
654
server_capabilites= CLIENT_BASIC_FLAGS;
656
if (using_mysql41_protocol)
657
server_capabilites|= CLIENT_PROTOCOL_MYSQL41;
660
server_capabilites|= CLIENT_COMPRESS;
661
#endif /* HAVE_COMPRESS */
663
end= buff + strlen(VERSION);
664
if ((end - buff) >= SERVER_VERSION_LENGTH)
665
end= buff + (SERVER_VERSION_LENGTH - 1);
666
memcpy(buff, VERSION, end - buff);
670
int4store((unsigned char*) end, global_thread_id);
673
/* We don't use scramble anymore. */
674
memset(end, 'X', SCRAMBLE_LENGTH_323);
675
end+= SCRAMBLE_LENGTH_323;
676
*end++= 0; /* an empty byte for some reason */
678
int2store(end, server_capabilites);
679
/* write server characteristics: up to 16 bytes allowed */
680
end[2]=(char) default_charset_info->number;
681
int2store(end+3, session->server_status);
682
memset(end+5, 0, 13);
685
/* Write scramble tail. */
686
memset(end, 'X', SCRAMBLE_LENGTH - SCRAMBLE_LENGTH_323);
687
end+= (SCRAMBLE_LENGTH - SCRAMBLE_LENGTH_323);
688
*end++= 0; /* an empty byte for some reason */
690
/* At this point we write connection message and read reply */
691
if (drizzleclient_net_write_command(&net
692
, (unsigned char) PROTOCOL_VERSION
693
, (unsigned char*) ""
695
, (unsigned char*) buff
696
, (size_t) (end-buff))
697
|| (pkt_len= drizzleclient_net_read(&net)) == packet_error
698
|| pkt_len < MIN_HANDSHAKE_SIZE)
700
my_error(ER_HANDSHAKE_ERROR, MYF(0), session->security_ctx.ip.c_str());
704
if (packet.alloc(buffer_length))
705
return false; /* The error is set by alloc(). */
707
client_capabilities= uint2korr(net.read_pos);
710
client_capabilities|= ((uint32_t) uint2korr(net.read_pos + 2)) << 16;
711
session->max_client_packet_length= uint4korr(net.read_pos + 4);
712
end= (char*) net.read_pos + 32;
715
Disable those bits which are not supported by the server.
716
This is a precautionary measure, if the client lies. See Bug#27944.
718
client_capabilities&= server_capabilites;
720
if (end >= (char*) net.read_pos + pkt_len + 2)
722
my_error(ER_HANDSHAKE_ERROR, MYF(0), session->security_ctx.ip.c_str());
726
net.return_status= &session->server_status;
729
char *passwd= strchr(user, '\0')+1;
730
uint32_t user_len= passwd - user - 1;
734
Old clients send null-terminated string as password; new clients send
735
the size (1 byte) + string (not null-terminated). Hence in case of empty
736
password both send '\0'.
738
This strlen() can't be easily deleted without changing client.
740
Cast *passwd to an unsigned char, so that it doesn't extend the sign for
741
*passwd > 127 and become 2**32-127+ after casting to uint.
743
uint32_t passwd_len= client_capabilities & CLIENT_SECURE_CONNECTION ?
744
(unsigned char)(*passwd++) : strlen(passwd);
745
l_db= client_capabilities & CLIENT_CONNECT_WITH_DB ? l_db + passwd_len + 1 : 0;
747
/* strlen() can't be easily deleted without changing client */
748
uint32_t db_len= l_db ? strlen(l_db) : 0;
750
if (passwd + passwd_len + db_len > (char *) net.read_pos + pkt_len)
752
my_error(ER_HANDSHAKE_ERROR, MYF(0), session->security_ctx.ip.c_str());
756
/* If username starts and ends in "'", chop them off */
757
if (user_len > 1 && user[0] == '\'' && user[user_len - 1] == '\'')
764
session->security_ctx.user.assign(user);
766
return session->checkUser(passwd, passwd_len, l_db);
769
bool ClientDrizzleProtocol::netStoreData(const unsigned char *from, size_t length)
771
size_t packet_length= packet.length();
773
The +9 comes from that strings of length longer than 16M require
774
9 bytes to be stored (see drizzleclient_net_store_length).
776
if (packet_length+9+length > packet.alloced_length() &&
777
packet.realloc(packet_length+9+length))
779
unsigned char *to= drizzleclient_net_store_length((unsigned char*) packet.ptr()+packet_length, length);
780
memcpy(to,from,length);
781
packet.length((size_t) (to+length-(unsigned char*) packet.ptr()));
786
Format EOF packet according to the current client and
787
write it to the network output buffer.
790
void ClientDrizzleProtocol::writeEOFPacket(uint32_t server_status,
791
uint32_t total_warn_count)
793
unsigned char buff[5];
795
Don't send warn count during SP execution, as the warn_list
796
is cleared between substatements, and mysqltest gets confused
798
uint32_t tmp= min(total_warn_count, (uint32_t)65535);
799
buff[0]= DRIZZLE_PROTOCOL_NO_MORE_DATA;
800
int2store(buff+1, tmp);
802
The following test should never be true, but it's better to do it
803
because if 'is_fatal_error' is set the server is not going to execute
804
other queries (see the if test in dispatch_command / COM_QUERY)
806
if (session->is_fatal_error)
807
server_status&= ~SERVER_MORE_RESULTS_EXISTS;
808
int2store(buff + 3, server_status);
809
drizzleclient_net_write(&net, buff, 5);
812
static ListenDrizzleProtocol *listen_obj= NULL;
814
static int init(plugin::Registry ®istry)
816
listen_obj= new ListenDrizzleProtocol("drizzle_protocol", false);
817
registry.add(listen_obj);
821
static int deinit(plugin::Registry ®istry)
823
registry.remove(listen_obj);
828
static DRIZZLE_SYSVAR_UINT(port, port, PLUGIN_VAR_RQCMDARG,
829
N_("Port number to use for connection or 0 for "
830
"default to, in order of "
831
"preference, drizzle.cnf, $DRIZZLE_TCP_PORT, "
832
"built-in default (4427)."),
833
NULL, NULL, 0, 0, 65535, 0);
834
static DRIZZLE_SYSVAR_UINT(connect_timeout, connect_timeout,
835
PLUGIN_VAR_RQCMDARG, N_("Connect Timeout."),
836
NULL, NULL, 10, 1, 300, 0);
837
static DRIZZLE_SYSVAR_UINT(read_timeout, read_timeout, PLUGIN_VAR_RQCMDARG,
838
N_("Read Timeout."), NULL, NULL, 30, 1, 300, 0);
839
static DRIZZLE_SYSVAR_UINT(write_timeout, write_timeout, PLUGIN_VAR_RQCMDARG,
840
N_("Write Timeout."), NULL, NULL, 60, 1, 300, 0);
841
static DRIZZLE_SYSVAR_UINT(retry_count, retry_count, PLUGIN_VAR_RQCMDARG,
842
N_("Retry Count."), NULL, NULL, 10, 1, 100, 0);
843
static DRIZZLE_SYSVAR_UINT(buffer_length, buffer_length, PLUGIN_VAR_RQCMDARG,
844
N_("Buffer length."), NULL, NULL, 16384, 1024,
846
static DRIZZLE_SYSVAR_STR(bind_address, bind_address, PLUGIN_VAR_READONLY,
847
N_("Address to bind to."), NULL, NULL, NULL);
849
static drizzle_sys_var* sys_variables[]= {
850
DRIZZLE_SYSVAR(port),
851
DRIZZLE_SYSVAR(connect_timeout),
852
DRIZZLE_SYSVAR(read_timeout),
853
DRIZZLE_SYSVAR(write_timeout),
854
DRIZZLE_SYSVAR(retry_count),
855
DRIZZLE_SYSVAR(buffer_length),
856
DRIZZLE_SYSVAR(bind_address),
860
DRIZZLE_DECLARE_PLUGIN
866
"Drizzle Protocol Module",
868
init, /* Plugin Init */
869
deinit, /* Plugin Deinit */
870
NULL, /* status variables */
871
sys_variables, /* system variables */
872
NULL /* config options */
874
DRIZZLE_DECLARE_PLUGIN_END;