lib/DBIx/MyServer.pm untested

filter: Statementstmt 0.0% 0 / 771 Branchbran 0.0% 0 / 194 Conditioncond 0.0% 0 / 24 MC/DCmcdc 0.0% 0 / 13 Subroutinesub 0.0% 0 / 202 Podpod 0.0% 0 / 75 totaltotal 0.0% 0 / 1279 CC 98 SCAR 47.8
CC
98
Cov
0%
comQuery
812.0
processCommand
506.0
_readPacket
56.0
CRAP 119.4
1 package DBIx::MyServer;
2  
3 use warnings;
4 use strict;
5 use Socket;
6 use Carp qw(cluck carp croak);
7  
8 use Digest::SHA1;
9  
10 our $VERSION = '0.42';
11  
12 use constant MYSERVER_PACKET_COUNT => 0;
13 use constant MYSERVER_SOCKET => 1;
14 use constant MYSERVER_DATABASE => 4;
15 use constant MYSERVER_THREAD_ID => 5;
16 use constant MYSERVER_SCRAMBLE => 6;
17 use constant MYSERVER_DBH => 7;
18 use constant MYSERVER_PARSER => 8;
19 use constant MYSERVER_BANNER => 9;
20 use constant MYSERVER_SERVER_CHARSET => 10;
21 use constant MYSERVER_CLIENT_CHARSET => 11;
22 use constant MYSERVER_SALT => 12;
23  
24 use constant FIELD_CATALOG => 0;
25 use constant FIELD_DB => 1;
26 use constant FIELD_TABLE => 2;
27 use constant FIELD_ORG_TABLE => 3;
28 use constant FIELD_NAME => 4;
29 use constant FIELD_ORG_NAME => 5;
30 use constant FIELD_LENGTH => 6;
31 use constant FIELD_TYPE => 7;
32 use constant FIELD_FLAGS => 8;
33 use constant FIELD_DECIMALS => 9;
34 use constant FIELD_DEFAULT => 10;
35  
36  
37 #
38 # This comes from include/mysql_com.h of the MySQL source
39 #
40  
41 use constant CLIENT_LONG_PASSWORD => 1;
42 use constant CLIENT_FOUND_ROWS => 2;
43 use constant CLIENT_LONG_FLAG => 4;
44 use constant CLIENT_CONNECT_WITH_DB => 8;
45 use constant CLIENT_NO_SCHEMA => 16;
46 use constant CLIENT_COMPRESS => 32; # Must implement that one
47 use constant CLIENT_ODBC => 64;
48 use constant CLIENT_LOCAL_FILES => 128;
49 use constant CLIENT_IGNORE_SPACE => 256;
50 use constant CLIENT_PROTOCOL_41 => 512;
51 use constant CLIENT_INTERACTIVE => 1024;
52 use constant CLIENT_SSL => 2048; # Must implement that one
53 use constant CLIENT_IGNORE_SIGPIPE => 4096;
54 use constant CLIENT_TRANSACTIONS => 8192;
55 use constant CLIENT_RESERVED => 16384;
56 use constant CLIENT_SECURE_CONNECTION => 32768;
57 use constant CLIENT_MULTI_STATEMENTS => 1 << 16;
58 use constant CLIENT_MULTI_RESULTS => 1 << 17;
59 use constant CLIENT_SSL_VERIFY_SERVER_CERT => 1 << 30;
60 use constant CLIENT_REMEMBER_OPTIONS => 1 << 31;
61  
62 use constant SERVER_STATUS_IN_TRANS => 1;
63 use constant SERVER_STATUS_AUTOCOMMIT => 2;
64 use constant SERVER_MORE_RESULTS_EXISTS => 8;
65 use constant SERVER_QUERY_NO_GOOD_INDEX_USED => 16;
66 use constant SERVER_QUERY_NO_INDEX_USED => 32;
67 use constant SERVER_STATUS_CURSOR_EXISTS => 64;
68 use constant SERVER_STATUS_LAST_ROW_SENT => 128;
69 use constant SERVER_STATUS_DB_DROPPED => 256;
70 use constant SERVER_STATUS_NO_BACKSLASH_ESCAPES => 512;
71  
72 use constant COM_SLEEP => 0;
73 use constant COM_QUIT => 1;
74 use constant COM_INIT_DB => 2;
75 use constant COM_QUERY => 3;
76 use constant COM_FIELD_LIST => 4;
77 use constant COM_CREATE_DB => 5;
78 use constant COM_DROP_DB => 6;
79 use constant COM_REFRESH => 7;
80 use constant COM_SHUTDOWN => 8;
81 use constant COM_STATISTICS => 9;
82 use constant COM_PROCESS_INFO => 10;
83 use constant COM_CONNECT => 11;
84 use constant COM_PROCESS_KILL => 12;
85 use constant COM_DEBUG => 13;
86 use constant COM_PING => 14;
87 use constant COM_TIME => 15;
88 use constant COM_DELAYED_INSERT => 16;
89 use constant COM_CHANGE_USER => 17;
90 use constant COM_BINLOG_DUMP => 18;
91 use constant COM_TABLE_DUMP => 19;
92 use constant COM_CONNECT_OUT => 20;
93 use constant COM_REGISTER_SLAVE => 21;
94 use constant COM_STMT_PREPARE => 22;
95 use constant COM_STMT_EXECUTE => 23;
96 use constant COM_STMT_SEND_LONG_DATA => 24;
97 use constant COM_STMT_CLOSE => 25;
98 use constant COM_STMT_RESET => 26;
99 use constant COM_SET_OPTION => 27;
100 use constant COM_STMT_FETCH => 28;
101 use constant COM_END => 29;
102  
103 # This is taken from include/mysql_com.h
104  
105 use constant MYSQL_TYPE_DECIMAL => 0;
106 use constant MYSQL_TYPE_TINY => 1;
107 use constant MYSQL_TYPE_SHORT => 2;
108 use constant MYSQL_TYPE_LONG => 3;
109 use constant MYSQL_TYPE_FLOAT => 4;
110 use constant MYSQL_TYPE_DOUBLE => 5;
111 use constant MYSQL_TYPE_NULL => 6;
112 use constant MYSQL_TYPE_TIMESTAMP => 7;
113 use constant MYSQL_TYPE_LONGLONG => 8;
114 use constant MYSQL_TYPE_INT24 => 9;
115 use constant MYSQL_TYPE_DATE => 10;
116 use constant MYSQL_TYPE_TIME => 11;
117 use constant MYSQL_TYPE_DATETIME => 12;
118 use constant MYSQL_TYPE_YEAR => 13;
119 use constant MYSQL_TYPE_NEWDATE => 14;
120 use constant MYSQL_TYPE_VARCHAR => 15;
121 use constant MYSQL_TYPE_BIT => 16;
122 use constant MYSQL_TYPE_NEWDECIMAL => 246;
123 use constant MYSQL_TYPE_ENUM => 247;
124 use constant MYSQL_TYPE_SET => 248;
125 use constant MYSQL_TYPE_TINY_BLOB => 249;
126 use constant MYSQL_TYPE_MEDIUM_BLOB => 250;
127 use constant MYSQL_TYPE_LONG_BLOB => 251;
128 use constant MYSQL_TYPE_BLOB => 252;
129 use constant MYSQL_TYPE_VAR_STRING => 253;
130 use constant MYSQL_TYPE_STRING => 254;
131 use constant MYSQL_TYPE_GEOMETRY => 255;
132  
133 use constant NOT_NULL_FLAG => 1;
134 use constant PRI_KEY_FLAG => 2;
135 use constant UNIQUE_KEY_FLAG => 4;
136 use constant MULTIPLE_KEY_FLAG => 8;
137 use constant BLOB_FLAG => 16;
138 use constant UNSIGNED_FLAG => 32;
139 use constant ZEROFILL_FLAG => 64;
140 use constant BINARY_FLAG => 128;
141 use constant ENUM_FLAG => 256;
142 use constant AUTO_INCREMENT_FLAG => 512;
143 use constant TIMESTAMP_FLAG => 1024;
144 use constant SET_FLAG => 2048;
145 use constant NO_DEFAULT_VALUE_FLAG => 4096;
146 use constant NUM_FLAG => 32768;
147  
148 =head1 NAME
149  
150 DBIx::MyServer - Server-side implementation of the MySQL network protocol
151  
152 =head1 SYNOPSIS
153  
154 Please see the scripts in the C<examples> directory.
155 C<examples/dbi.pl> along with C<DBIx::MyParse::DBI> shows how to use this module by subclassing it.
156 C<examples/echo.pl> shows how to use this module directly.
157  
158 =head1 DESCRIPTION
159  
160 This module emulates the server side of the MySQL protocol. This allows you to run
161 your own faux-MySQL servers which can accept commands and queries and reply accordingly.
162  
163 Please see C<examples/myserver.pl> for a system that allows building functional mysql servers that rewrite queries
164 or return arbitary data.
165  
166 =head1 CONSTRUCTOR
167  
168 =item C<< my $myserver = DBIx::MyServer->new( socket => $socket, parser => $parser, dbh => $dbh ... ) >>
169  
170 The following parameters are accepted:
171  
172 C<socket> - the socket that will be used for communication with the client. The socket must be created in advance with
173 L<socket()> and an incoming connection must be already established using L<accept()>
174  
175 C<dbh> - a L<DBI> handle. L<DBIx::MyServer> does not use it however it can be used by modules inheriting from L<DBIx::MyServer>
176  
177 C<parser> - a L<DBIx::MyParser> handle. If you do not override the C<comQuery()> method, this handle will be used to parse the
178 SQL in order to call the appropriate C<sqlcom...> method.
179  
180 C<banner> - the server version string that is announced to the client. If not specified, the name and the version of the
181 L<DBIx::MyServer> module is sent. Some clients, e.g. L<DBD::mysql> attempt to parse that string as a version number in order
182 to determine the server capabilities. Therefore, it may be a good idea to start your C<banner> with a string in the form
183 C<5.0.37>. For example, the C<examples/dbi.pl> example takes the C<banner> from the actual MySQL server the connection is
184 forwarded to. Please note that the MySQL client may isssue a C<select @@version_comment limit 1> command and display the
185 result to the user.
186  
187 C<server_charset> - the character set (and collation) the server announces to the client. A number is expected, not
188 a character set or collation name. To onvert between numbers and names, please consult the C<sql/share/charsets/Index.xml>
189 file from your MySQL source tree. The numbers are found under the C<id> property of each XML leaf.
190  
191 Generally you do not need to override the constructor. If you do, please keep in mind that it returns
192 a blessed C<@ARRAY>, not a blessed C<%HASH>, even though new() accepts an argument hash. This is
193 done for performance reasons. The first 20 items from the array are reserved for the parent module,
194 so please put your object properties into the array members from 20 onwards.
195  
196 =head1 CONNECTION ESTABLISHMENT
197  
198 You are responsible for opening your listening socket and accepting a connection on it (and possibly forking
199 a child process). Once the connection has been accepted, you create a C<DBIx::MyServer> object and pass the socket
200 to it. From then on, you have two options:
201  
202 =head2 Procedural Connection Establishment
203  
204 If you want to handle connection establishment yourself, you will need to call those two functions consequtively.
205 Please see C<examples/echo.pl> for a script that uses procedural connection establishment.
206  
207 =item C<< $myserver->sendServerHello() >>
208  
209 The server is the one that initiates the handshake by sending his greeting to the client.
210  
211 =item C<< my ($username, $database) = $myserver->readClientHello() >>
212  
213 The client provides his username and the database it wants to connect to. If C<$username> is C<undef>, the client
214 disconnected before authenticating. To check the password, use C<$myserver->passwordMatches($correct_password)
215 which will return C<1> if the password provided by the client is correct and C<undef> otherwise.
216  
217 If you need to know the IP of the client, you need to extract it from the socket that you established yourself.
218 Please check out the implementation of C<DBIx::MyParse::handshake()> for the correct way to call C<getpeername()>.
219 The socket being serviced by the current C<DBIx::MyParse> object can be obtained by calling C<getSocket()>.
220  
221 If you want to let the client in, do a C<< $myserver->sendOK() >>. Otherwise, use C<< $myserver->sendError() >> as described below.
222  
223 =head2 Connection Establishment with Subclassing
224  
225 If you are subclassing C<DBIx::MyParse>, the way C<DBIx::MyParse::DBI> does, to establish a connection you call:
226  
227 =item C<< $myserver->handshake() >>
228  
229 which completes the handshake between the two parties. The return value will be C<undef> if some I/O error
230 occured, or the result of the client authorization routine. When the client sends its credentials, the
231 module will call:
232  
233 =item C<< $myserver->authorize($remote_host, $username, $database) >>
234  
235 whose default action is to accept only localhost connections regardless of username or password. You should
236 override this method to install your own security requirements. If your C<authorize()> returns C<undef>, the
237 connection will be rejected, if it returns anything else, the connection will be completed and the return
238 value will be passed back to the caller of C<handshake()>. You can use this return value to communicate the
239 access rights the particular user is entitled to, so that your script can know them and enforce them.
240  
241 In case you want to reject the connection, you need to send your own error message via C<sendError()>. If
242 you accept the connection, the module will send the C<OK> message back to the client for you.
243  
244 The password supplied by the client is irreversibly encrypted, therefore to verify it, you need to use:
245  
246 =item C<< $myserver->passwordMatches($expected_password) >>
247  
248 which will return C<undef> if the password does not match and C<1> otherwise.
249  
250 If the client supplied a database name on connect, C<comInitDb($database)> will be called.
251  
252 For an example of a custom C<authorize()>, please see C<DBIx::MyParse::DBI> which does some extra connection setup.
253  
254 =head1 COMMAND PROCESSING
255  
256 =head2 Procedural Command Processing
257  
258 If you want to handle each command individually on your own, you need to call
259  
260 =item C<< my ($command, $data) = $myserver->readCommand() >>
261  
262 in a loop and process each command. Sending result sets and errors and terminating the connection is entirely up to you.
263 The C<examples/odbc.pl> script uses this approach to process queries in the simples possible way without reflecting much
264 on their contents.
265  
266 =head2 Command Processing with Subclassing
267  
268 If you are subclassing C<DBIx::MyParse>, your main script needs to call:
269  
270 =item C<< $myserver->processCommand() >>
271  
272 in a loop. The default C<processCommand()> handler will obtain the next command from the client using C<readCommand()>
273 and will call the appropriate individual command handler, described below. You can override C<processCommand()> if
274 you want to process the entire packet yourself, in which case you are responsible for calling C<readCommand()> yourself.
275  
276 C<processCommand()> will return whatever the individual command handler returned. C<undef> is reserved for I/O errors,
277 which will allow you to conveniently exit your loop. Therefore it is recommended that any handlers that you
278 override return C<1> to indicate correct operation or non-fatal errors.
279  
280 =head1 INDIVIDUAL COMMAND HANDLERS
281  
282 If you do not override the generic C<< processCommand() >> method, the following individual handlers will
283 be called depending on the actual MySQL command received by the server. The default action of those handlers is
284 to send a "command unsupported" error back to the client, unless specified otherwise below.
285  
286 If you want to send an error or an OK message to the client as a response to a command or query, you need to use
287 C<sendOK()> and C<sendError()> yourself. The parent module will not send any of those for you under no circumstances.
288  
289 =item C<< $myserver->comSleep($data) >>
290  
291 The meaning of this command is not clear.
292  
293 =item C<< $myserver->comQuit() >>
294  
295 The default action is to C<return undef>, meaning that C<processCommand()> will return C<undef>, which you can use
296 to exit your command loop. Alternatively, you can override this to call C<die()> or C<exit()>, if you are forking individual
297 child processes for each client.
298  
299 =item C<< $myserver->comInitDb($database) >>
300  
301 This command is used by the client to select a default working database. The default action is to set
302 the default database for the parser object if one has been specified. This enables the parser to parse
303 some SQL statements that require a default database, such as SHOW TABLE STATUS. The command is then converted into a
304 C<USE $database> SQL statement which in turn will trigger C<comQuery("USE $database")> or C<sqlcomChangeDB()>
305  
306 =item C<< $myserver->comQuery($query_text) >>
307  
308 This handler is called for all SQL queries received by the server. The action of the default handler is to parse
309 the query using L<DBIx::MyParse> and evoke a more specific handler. If the parsing results in an error, C<sqlcomError()>
310 is called which returns the parser error message to the client.
311  
312 If you override this handler, your implementation must return an array of three items. The first item is the value that
313 will be returned to your main loop as the return value of C<processCommand()>. You can return anything you please, including
314 references to complex objects. Returning C<undef> can be used to conveniently terminate the command loop, so you are
315 generally encouraged to return some true and definied value to indicate proper operation.
316  
317 The second item you can return is a reference to an array of field definitions created with C<newDefinition()>.
318 If you provide it, your field definitions will be sent to the client using C<sendDefinitions()>. If you do not provide
319 a reference, you are responsible for calling C<sendDefinitions()> yourself before you send any data.
320  
321 The third item you can return is a reference to an array of values that is the actual data to be sent to the client in
322 response to the query. If you do not provide a reference, you are responsible for sending the data yourself by using the
323 functions described elsewhere in this document.
324  
325 =item C<< $myserver->comFieldList($table) >>
326  
327 This handler is called if the mysql client requests the field list for the specified table. The handler must create a
328 set of field definitions using C<newDefinition()> and then send them to the client using
329 C<sendDefinitions(\@definitions, 1)>. It is strongly reccomended that you provide your own working
330 implementation for C<comFieldList()> because this MySQL command is often issued by the various MySQL connectors and
331 is essential for the functioning of the C<FEDERATED> table handler.
332  
333 For an example of easily handling C<comFieldList()>, see L<DBIx::MyServer::DBI> which uses L<DBI>'s C<column_info> to
334 return the definition of an actual MySQL table from another server.
335  
336 =item C<< $myserver->comCreateDb($database_name) >>
337  
338 This handler is called when C<mysqladmin create $database_name> is used. The default is to convert the command into a
339 C<CREATE DATABASE $database_name> SQL statement, so that C<comQuery("CREATE DATABASE $database_name")> is triggered,
340 which in turn will call C<sqlcomCreateDb()>.
341  
342 =item C<< $myserver->comDropDb($database_name) >>
343  
344 This handler is called when C<mysqladmin drop $database_name> is used. The default is to convert the command into a
345 C<DROP DATABASE $database_name> SQL statement so that C<comQuery("DROP DATABASE $database_name")> is triggered, which
346 in turn will call C<sqlcomDropDb()>.
347  
348 =item C<< $myserver->comShutdown() >>
349  
350 This handler is called when C<mysqladmin shutdown> is used. The default action is to die(), in other words,
351 any authorized client can shut down its own child, or the entire server, if the server is not forking.
352  
353 =item C<< $myserver->comStatistics() >>
354  
355 The default action is to send our PID to the client. If you want to override that, you can use C<_sendPacket($string)>
356 (rather than C<sendOK()>) to deliver a single string to your client. Please note that C<mysql> and C<mysqladmin>
357 may attempt to parse this string before displaying it, so you may wish to keep it identical to the one sent by real MySQL servers:
358  
359 C<Uptime: 10659 Threads: 1 Questions: 756 Slow queries: 0 Opens: 109 Flush tables: 1 Open tables: 30 Queries per second avg: 0.071>
360  
361 =item C<< $myserver->comProcessInfo() >>
362  
363 This handler is called when C<mysqladmin processlist> is called from the command line.
364  
365 =item C<< $myserver->comProcessKill($thread_id) >>
366  
367 This handler is called as a response by the command issued by C<< mysqladmin kill >>. In C<DBIx::MyServer>,
368 the MySQL thread ID is equal to the PID of the server process. The default action will L<kill()> the PID however
369 you are only allowed to kill your own PID.
370  
371 =item C<< $myserver->comPing() >>
372  
373 This is used to check if the server is reachable and running. The default action is to do a C<sendOK()>. If you are using
374 that in a conjunction with an automated monitoring and alert system, you may wish to do a C<sendOK()> only after doing
375 extra health checks on your own, e.g. if you are reading data from an external data source, do not send an OK unless that
376 source is reachable.
377  
378 =head1 INDIVIDUAL QUERY HANDLERS
379  
380 If you do not override the generic C<< comQuery() >> method, the incoming MySQL query will be parsed to a
381 L<DBIx::MyParse::Query> object and the object will be dispatched to one of the C<sqlcom...> handlers based on the
382 type of the query.
383  
384 The default handlers all return "query unsupported". If you override any of the default handlers, your handler must
385 return one two or three items as described under C<comQuery()>.
386  
387 Each C<sqlcom...> handler receives at least two arguments. The first one is the L<DBIx::MyParse::Query> object produced
388 by L<DBIx::MyParse>. The second is the text of the query. C<sqlcom...> handlers dealing with databases will get the
389 database name in question as their third argument.
390  
391 If the parsing resulted in an error, C<sqlcomError($query, $query_string)> is called. The default action of this handler
392 is to send the parser error message as is to the client.
393  
394 =head1 RETURNING MESSAGES TO CLIENT
395  
396 =item C<< $myserver->sendOK($message, $affected_rows, $insert_id, $warning_count) >>
397  
398 Returns a simple OK response, which can contain a custom message, the number of rows affected by the query, etc.
399  
400 =item C<< $myserver->sendError($message, $errno, $sqlstate) >>
401  
402 Returns an error response. IF no C<errno> and C<sqlstate> are specified, generic values will be sent to client.
403  
404 =head1 RETURNING DATA TO CLIENT
405  
406 =item C<< my $definition = $myserver->newDefinition(name => 'field_name') >>
407  
408 Prepares a new field definition that can then be sent to the client. Apart from C<name>, the following attributes are
409 supported:
410  
411 catalog, db, table, org_table
412 name, org_name, length, type,
413 flags, decimals, default
414  
415 The default C<type> is C<MYSQL_TYPE_STRING>. The complete list of type constants is available from C<MyServer.pm>.
416  
417 =item C<< $myserver->sendDefinitions( \@definitions, $skip_envelope ) >>
418  
419 Sends the previously prepared field definitions to the client. You need to do that before sending the first data row.
420 You also need to use C<sendDefinitions()> to send a table definition in response to C<comFieldList()> command,
421 however due to an inconsistency in the MySQL protocol, C<$skip_envelope> must be true.
422  
423 =item C<sendRow($array_ref)> and C<sendRows($array_ref)>
424  
425 Those two functions are used to send the actual data to the client. C<sendRow()> expect a reference to the array
426 containing the values you wish to send. C<sendRows()> expects a reference to an array containing references to arrays.
427  
428 Please note in the MySQL protocol, all values are sent consequtively without row boundaries. The number of columns in
429 each row is determined by how many field definitions you send before you start sending the actual data.
430  
431 =item C<sendEOF()>
432  
433 Indicates the end of the data from the record set.
434  
435 =head1 PREPARED STATEMENTS
436  
437 L<DBIx::MyServer> does not currently support the prepared statement protocol. By default, the C<comStmtPrepare()> handler
438 will return ER_UNSUPPORTED_PS back to the client, which should instruct a wise client to retry the query using
439 conventional statemements.
440  
441 As of Nov 7th, 2006, the ODBC Driver version 3.51.12 does not use prepared statements at all. The FEDERATED
442 database engine does not use them. DBD::Mysql version 3.0008_1 will attempt a prepared statement and if
443 ER_UNSUPPORTED_PS is received, it will fall back to normal statements. To force the use of normal statements,
444 add C<mysql_emulated_prepare=1> to your DSN string.
445  
446 =head1 SECURITY CONSIDERATIONS
447  
448 The defaults of this module are meant to allow quick prototyping of MySQL servers by subclassing. Therefore, by default:
449  
450 =item
451  
452 Only localhost connections are allowed if you use C<handshake()>. Beyond checking that, no other access checks are
453 made and all usernames are accepted. No password checks are made. After the handshake, any access restrictions on
454 individual commands or queriesare entirely up to you.
455  
456 =item
457  
458 The default action for comQuit() and comShutdown() is to die() which allows anyone to bring down a server that is not
459 forking child processes. The default action of C<comProcessKill()> only allows you to kill your own server process via SIGTERM.
460  
461 =item
462  
463 A single cryptographic salt is used throughout the lifetime of the process, which may be a security risk.
464  
465 =cut
466  
467 sub new {
468 my $class = shift;
469 my $myserver = bless([], $class);
470  
471 my %args = (
472 socket => MYSERVER_SOCKET,
473 dbh => MYSERVER_DBH,
474 parser => MYSERVER_PARSER,
475 banner => MYSERVER_BANNER,
476 server_charset => MYSERVER_SERVER_CHARSET
477 );
478  
479 my $max_arg = (scalar(@_) / 2) - 1;
480  
481 foreach my $i (0..$max_arg) {
482 if (exists $args{$_[$i * 2]}) {
483 $myserver->[$args{$_[$i * 2]}] = $_[$i * 2 + 1];
484 } else {
485 carp "Unkown argument $_[$i * 2] to $class";
486 }
487 }
488  
489 carp "Argument 'socket' to $class must be present" if not defined $myserver->[MYSERVER_SOCKET];
490  
491 $myserver->[MYSERVER_PACKET_COUNT] = 0;
492 $myserver->[MYSERVER_THREAD_ID] = $$;
493 $myserver->[MYSERVER_SALT] = join('',map { chr(int(33 + rand(94))) } (1..20));
494  
495 return $myserver;
496 }
497  
498 sub getSocket {
499 my $myserver = shift;
500 return $myserver->[MYSERVER_SOCKET];
501 }
502  
503 sub getDbh {
504 my $myserver = shift;
505 return $myserver->[MYSERVER_DBH];
506 }
507  
508 sub setDbh {
509 $_[0]->[MYSERVER_DBH] = $_[1];
510 }
511  
512 sub getParser {
513 my $myserver = shift;
514 return $myserver->[MYSERVER_PARSER];
515 }
516  
517 sub getClientCharset {
518 my $myserver = shift;
519 return $myserver->[MYSERVER_CLIENT_CHARSET];
520 }
521  
522 sub _createPacket {
523 my ($myserver, $data) = @_;
524 my $header;
525 $header .= substr(pack('V',length($data)),0,3);
526 $header .= chr($myserver->[MYSERVER_PACKET_COUNT]++ % 256);
527 return $header.$data;
528 }
529  
530 sub _sendPacket {
531 my ($myserver, $payload) = @_;
532 return $myserver->_writeData($myserver->_createPacket($payload));
533 }
534  
535 sub _writeData {
536 my ($myserver, $data) = @_;
537 return syswrite($myserver->[MYSERVER_SOCKET], $data);
538 }
539  
540 sub sendOK {
541 ### Sending OK...
542 my ($myserver, $message, $affected_rows, $insert_id, $warning_count) = @_;
543 #### $message
544 #### $affected_rows
545 #### $insert_id
546 #### $warning_count
547  
548 my $data;
549  
550 $affected_rows = 0 if not defined $affected_rows;
551 $warning_count = 0 if not defined $warning_count;
552  
553 $data .= "\0"; # Field Count, always 0
554 $data .= $myserver->_lengthCodedBinary($affected_rows);
555 $data .= $myserver->_lengthCodedBinary($insert_id);
556 $data .= pack('v', SERVER_STATUS_AUTOCOMMIT);
557 $data .= pack('v', $warning_count);
558 $data .= $myserver->_lengthCodedString($message);
559  
560 my $send_result = $myserver->_sendPacket($data);
561  
562 $myserver->[MYSERVER_PACKET_COUNT] = 0;
563  
564 return $send_result;
565 }
566  
567 sub newDefinition {
568 my $myserver = shift;
569  
570 my %params = @_;
571  
572 my $definition = bless([], 'DBIx::MyServer::Definition');
573 $definition->[FIELD_CATALOG] = $params{catalog};
574 $definition->[FIELD_DB] = $params{db} ? $params{db} : $params{database};
575 $definition->[FIELD_TABLE] = $params{table};
576 $definition->[FIELD_ORG_TABLE] = $params{org_table};
577 $definition->[FIELD_NAME] = $params{name};
578 $definition->[FIELD_ORG_NAME] = $params{org_name};
579 $definition->[FIELD_LENGTH] = defined $params{length} ? $params{length} : 0;
580 $definition->[FIELD_TYPE] = defined $params{type} ? $params{type} : MYSQL_TYPE_STRING;
581 $definition->[FIELD_FLAGS] = defined $params{flags} ? $params{flags} : 0;
582 $definition->[FIELD_DECIMALS] = $params{decimals};
583 $definition->[FIELD_DEFAULT] = $params{default};
584 return $definition;
585 }
586  
587 sub sendDefinitions {
588 ### Sending Definitions...
589 my ($myserver, $definitions, $skip_envelope) = @_;
590  
591 if (not defined $skip_envelope) {
592 $myserver->_sendHeader(scalar(@{$definitions}));
593 }
594  
595 my $last_send_result;
596  
597 foreach my $definition (@{$definitions}) {
598 $last_send_result = $myserver->_sendDefinition($definition);
599 };
600  
601 if (not defined $skip_envelope) {
602 return $myserver->_sendDefinitionsEOF();
603 } else {
604 return $last_send_result;
605 }
606 }
607  
608 sub _sendDefinition {
609 ### Sending Definition...
610 my ($myserver, $definition) = @_;
611  
612 my (
613 $field_catalog, $field_db, $field_table,
614 $field_org_table, $field_name, $field_org_name,
615 $field_length, $field_type, $field_flags,
616 $field_decimals, $field_default
617 ) = (
618 $definition->[FIELD_CATALOG], $definition->[FIELD_DB],
619 $definition->[FIELD_TABLE], $definition->[FIELD_ORG_TABLE],
620 $definition->[FIELD_NAME], $definition->[FIELD_ORG_NAME],
621 $definition->[FIELD_LENGTH], $definition->[FIELD_TYPE],
622 $definition->[FIELD_FLAGS], $definition->[FIELD_DECIMALS],
623 $definition->[FIELD_DEFAULT]
624 );
625  
626 #### $field_catalog
627 #### $field_db
628 #### $field_table
629 #### $field_org_table
630 #### $field_name
631 #### $field_org_name
632 #### $field_length
633 #### $field_type
634  
635 my $payload = join('', map { defined $_ ? $myserver->_lengthCodedBinary(length($_)).$_ : chr(0) } (
636 $field_catalog, $field_db, $field_table,
637 $field_org_table, $field_name, $field_org_name
638 ));
639  
640 $payload .= chr(0x0c); # Filler
641 $payload .= pack('v', 11); # US ASCII
642 $payload .= pack('V', $field_length);
643 $payload .= chr($field_type);
644 $payload .= defined $field_flags ? pack('v', $field_flags) : pack('v', 0);
645 $payload .= defined $field_decimals ? chr($field_decimals) : pack('v','0');
646 $payload .= pack('v', 0); # Filler
647 $payload .= $myserver->_lengthCodedString($field_default);
648  
649 return $myserver->_sendPacket($payload);
650 }
651  
652 sub sendRow {
653 ### Sending Row...
654 my ($myserver, $row) = @_;
655
656 my $payload;
657 foreach my $cell (@{$row}) {
658 if (not defined $cell) {
659 $payload .= chr(251); # Meaning undef value
660 } else {
661 $payload .= $myserver->_lengthCodedString($cell);
662 }
663 }
664  
665 return $myserver->_sendPacket($payload);
666 }
667  
668 sub sendRows {
669 ### Sending Rows...
670 my ($myserver, $rows) = @_;
671 my $big_data;
672 return $myserver->sendEOF() if not defined $rows;
673 foreach my $row (@{$rows}) {
674 # The data stream is constructed in-line for extra performance
675 my $small_data;
676 foreach (@{$row}) {
677 if (not defined $_) {
678 $small_data .= chr(251); # Undef value
679 } else {
680 $small_data .= $myserver->_lengthCodedString($_);
681 }
682 }
683 $big_data .= substr(pack('V',length($small_data)),0,3).chr($myserver->[MYSERVER_PACKET_COUNT]++ % 256).$small_data;
684 }
685 $myserver->_writeData($big_data) if defined $big_data;
686 return $myserver->sendEOF();
687 }
688  
689 sub _sendHeader {
690 ### Sending Header...
691 my ($myserver, $field_count) = @_;
692 #### $field_count
693 return $myserver->_sendPacket($myserver->_lengthCodedBinary($field_count));
694 }
695  
696 sub _sendDefinitionsEOF {
697 ### Sending Definitions EOF...
698 return $_[0]->_sendPacket(chr(0xfe));
699 }
700  
701 sub sendEOF {
702 ### Sending EOF
703 my ($myserver, $warning_count, $server_status) = @_;
704 #### $warning_count
705 #### $server_status
706 my $payload;
707  
708 $warning_count = 0 if not defined $warning_count;
709 $server_status = SERVER_STATUS_AUTOCOMMIT if not defined $server_status;
710  
711 $payload .= chr(0xfe);
712 $payload .= pack('v', $warning_count);
713 $payload .= pack('v', $server_status);
714  
715 my $result = $myserver->_sendPacket($payload);
716 $myserver->[MYSERVER_PACKET_COUNT] = 0;
717  
718 return $result;
719 }
720  
721 sub handshake {
722 ### Handshaking...
723 my $myserver = shift;
724  
725 my $server_result = $myserver->sendServerHello();
726  
727 return undef if $server_result < 1;
728
729 my ($username, $database) = $myserver->readClientHello();
730  
731 return undef if not defined $username;
732  
733 my $remote_host;
734  
735 eval {
736 my $hersockaddr = getpeername($myserver->getSocket());
737 my ($port, $iaddr) = sockaddr_in($hersockaddr);
738 $remote_host = inet_ntoa($iaddr);
739 };
740  
741 $remote_host = '127.0.0.1' if (not defined $remote_host) || ($remote_host eq '');
742  
743 my $authorize_result = $myserver->authorize($remote_host, $username, $database);
744  
745 if (defined $authorize_result) {
746 $myserver->sendOK();
747 } else {
748 $myserver->sendError("Authorization failed.",1044, 28000);
749 }
750  
751 return $authorize_result;
752  
753 }
754  
755 sub sendServerHello {
756 ### Sending Server Hello...
757 my $myserver = shift;
758  
759 my $payload = chr(10); # Protocol version
760  
761 if (defined $myserver->[MYSERVER_BANNER]) {
762 $payload .= $myserver->[MYSERVER_BANNER]."\0"; # Server string
763 } else {
764 $payload .= ref($myserver)." ".$VERSION."\0"; # e.g. 'DBIx::Myparse 0.81'
765 }
766  
767 $payload .= pack('V', $myserver->[MYSERVER_THREAD_ID]);
768  
769 $payload .= substr($myserver->[MYSERVER_SALT],0,8)."\0";
770  
771 # Server capabilities
772 $payload .= pack('v', CLIENT_LONG_PASSWORD | CLIENT_CONNECT_WITH_DB | CLIENT_PROTOCOL_41 | CLIENT_SECURE_CONNECTION);
773
774 my $charset = defined $myserver->[MYSERVER_SERVER_CHARSET] ? chr($myserver->[MYSERVER_SERVER_CHARSET]) : chr(0x21); # latin1
775 $payload .= $charset;
776  
777 $payload .= pack('v', SERVER_STATUS_AUTOCOMMIT); # Server status
778  
779 $payload .= "\0" x 13; # Unused space
780  
781 $payload .= substr($myserver->[MYSERVER_SALT],8)."\0";
782
783 return $myserver->_sendPacket($payload);
784 }
785  
786 sub _readPacket {
787 ### Reading Packet...
788 my $myserver = shift;
789  
790 my ($header, $header_read_result);
791  
792 $header_read_result = sysread($myserver->[MYSERVER_SOCKET], $header, 4);
793  
794 if (not defined $header_read_result) {
795 return undef;
796 } elsif ($header_read_result == 0) {
797 # EOF
798 return undef;
799 } elsif ($header_read_result < 4) {
800 # Incomplete read
801 return undef;
802 }
803  
804 my $packet_length = unpack('V', substr($header, 0, 3)."\0");
805  
806 my ($all_data, $data_read_result);
807 my $total_read = 0;
808 while () {
809 my $data_read_result = sysread($myserver->[MYSERVER_SOCKET], my $packet_data, $packet_length);
810 $all_data .= $packet_data;
811 $total_read = $total_read + $data_read_result;
812 return undef if not defined $data_read_result;
813 last if $data_read_result == 0;
814 last if $total_read >= $packet_length;
815 }
816  
817 $myserver->[MYSERVER_PACKET_COUNT]++;
818 return $all_data;
819 }
820  
821 sub readClientHello {
822 ### Reading Client Hello...
823  
824 # http://dev.mysql.com/doc/internals/en/the-packet-header.html
825  
826 my $myserver = shift;
827 my $data = $myserver->_readPacket();
828 return undef if not defined $data;
829  
830 my $ptr = 0;
831  
832 my $client_flags = substr($data, $ptr, 4);
833 $ptr = $ptr + 4;
834  
835 my $max_packet_size = substr($data, $ptr, 4);
836 $ptr = $ptr + 4;
837  
838 my $charset_number = substr($data, $ptr, 1);
839 $myserver->[MYSERVER_CLIENT_CHARSET] = ord($charset_number);
840 $ptr++;
841
842 my $filler1 = substr($data, $ptr, 23);
843 $ptr = $ptr + 23;
844  
845 my $username_end = index($data, "\0", $ptr);
846 my $username = substr($data, $ptr, $username_end - $ptr);
847 $ptr = $username_end + 1;
848  
849 my $scramble_buff;
850  
851 my $scramble_length = ord(substr($data, $ptr, 1));
852 $ptr++;
853  
854 if ($scramble_length > 0) {
855 $myserver->[MYSERVER_SCRAMBLE] = substr($data, $ptr, $scramble_length);
856 $ptr = $ptr + $scramble_length;
857 }
858
859 my $database;
860  
861 my $database_end = index( $data, "\0", $ptr);
862 if ($database_end != -1 ) {
863 $database = substr($data, $ptr, $database_end - $ptr);
864 }
865  
866 return ($username, $database);
867  
868 }
869  
870 sub readCommand {
871 ### Reading Client Command...
872 my $data = $_[0]->_readPacket();
873 return undef if not defined $data;
874 return (
875 unpack('C', substr($data, 0, 1)), # Command
876 length($data) > 1 ? substr($data, 1) : undef # Extra arguments
877 );
878 }
879  
880 sub _lengthCodedString {
881 my ($myserver, $string) = @_;
882 return chr(0) if (not defined $string);
883 return chr(253).substr(pack('V',length($string)),0,3).$string;
884 }
885  
886 sub _lengthCodedBinary {
887 my ($myserver, $number) = @_;
888 if (not defined $number) {
889 return chr(251);
890 } elsif ($number < 251) {
891 return chr($number);
892 } elsif ($number < 0x10000) {
893 return chr(252).pack('v', $number);
894 } elsif ($number < 0x1000000) {
895 return chr(253).substr(pack('V', $number), 0, 3);
896 } else {
897 return chr(254).pack('V', $number >> 32).pack('V', $number & 0xffffffff);
898 }
899 }
900  
901 sub sendError() {
902 ### Sending Error ...
903 my ($myserver, $message, $errno, $sqlstate) = @_;
904 #### $errno
905 #### $sqlstate
906 #### $message
907 # http://dev.mysql.com/doc/internals/en/error-packet.html
908  
909 $message = 'Unknown MySQL error' if not defined $message;
910 $errno = 2000 if not defined $errno;
911 $sqlstate = 'HY000' if not defined $sqlstate;
912  
913 my $payload = chr(0xff); # field_count, always = 0xff
914 $payload .= pack('v', $errno);
915 $payload .= '#'; # sqlstate marker, always #
916 $payload .= $sqlstate;
917 $payload .= $message."\0";
918  
919 my $send_result = $myserver->_sendPacket($payload);
920 $myserver->[MYSERVER_PACKET_COUNT] = 0;
921 return $send_result;
922 }
923  
924 # ====================================
925  
926 sub processCommand {
927 ### Processing Command...
928 my $myserver = shift;
929  
930 my ($command, $data) = $myserver->readCommand();
931  
932 #### $command
933 #### $data
934 my ($outcome, $definitions, $rows);
935  
936 if ($command == COM_SLEEP) {
937 ($outcome, $definitions, $rows) = $myserver->comSleep($data);
938 } elsif ($command == COM_QUIT) {
939 ($outcome, $definitions, $rows) = $myserver->comQuit();
940 } elsif ($command == COM_INIT_DB) {
941 ($outcome, $definitions, $rows) = $myserver->comInitDb($data);
942 } elsif ($command == COM_QUERY) {
943 ($outcome, $definitions, $rows) = $myserver->comQuery($data);
944 } elsif ($command == COM_FIELD_LIST) {
945 my $table_name = substr($data, 0, -1); # Strip trailing \0
946 ($outcome, $definitions, $rows) = $myserver->comFieldList($table_name);
947 } elsif ($command == COM_CREATE_DB) {
948 ($outcome, $definitions, $rows) = $myserver->comCreateDb($data);
949 } elsif ($command == COM_DROP_DB) {
950 ($outcome, $definitions, $rows) = $myserver->comDropDb($data);
951 } elsif ($command == COM_SHUTDOWN) {
952 ($outcome, $definitions, $rows) = $myserver->comShutdown($data);
953 } elsif ($command == COM_STATISTICS) {
954 ($outcome, $definitions, $rows) = $myserver->comStatistics();
955 } elsif ($command == COM_PROCESS_INFO) {
956 # ($outcome, $definitions, $rows) = $myserver->comProcessInfo($data);
957 # } elsif ($command == COM_CONNECT) {
958 # ($outcome, $definitions, $rows) = $myserver->comConnect($data);
959 } elsif ($command == COM_PROCESS_KILL) {
960 ($outcome, $definitions, $rows) = $myserver->comProcessKill($data);
961 } elsif ($command == COM_DEBUG) {
962 ($outcome, $definitions, $rows) = $myserver->comDebug($data);
963 } elsif ($command == COM_PING) {
964 ($outcome, $definitions, $rows) = $myserver->comPing($data);
965 # } elsif ($command == COM_TIME) {
966 # ($outcome, $definitions, $rows) = $myserver->comTime($data);
967 # } elsif ($command == COM_DELAYED_INSERT) {
968 # ($outcome, $definitions, $rows) = $myserver->comDelayedInsert($data);
969 # } elsif ($command == COM_CHANGE_USER) {
970 # ($outcome, $definitions, $rows) = $myserver->comChangeUser($data);
971 } elsif ($command == COM_STMT_PREPARE) {
972 ($outcome, $definitions, $rows) = $myserver->comStmtPrepare($data);
973 } elsif ($command == COM_STMT_EXECUTE) {
974 ($outcome, $definitions, $rows) = $myserver->comStmtExecute($data);
975 } elsif ($command == COM_STMT_SEND_LONG_DATA) {
976 ($outcome, $definitions, $rows) = $myserver->comStmtSendLongData($data);
977 } elsif ($command == COM_STMT_CLOSE) {
978 ($outcome, $definitions, $rows) = $myserver->comStmtClose($data);
979 } elsif ($command == COM_STMT_RESET) {
980 ($outcome, $definitions, $rows) = $myserver->comStmtReset($data);
981 # } elsif ($command == COM_SET_OPTION) {
982 # ($outcome, $definitions, $rows) = $myserver->comSetOption($data);
983 } elsif ($command == COM_STMT_FETCH) {
984 ($outcome, $definitions, $rows) = $myserver->comStmtFetch($data);
985 } else {
986 ($outcome, $definitions, $rows) = $myserver->sendErrorUnsupported($command);
987 }
988  
989 $myserver->sendDefinitions($definitions) if ref($definitions) eq 'ARRAY';
990 $myserver->sendRows($rows) if ref($rows) eq 'ARRAY';
991 #### Outcome is $outcome; command is $command
992 return $outcome;
993 }
994  
995 sub comSleep {
996 my $myserver = shift;
997 return $myserver->sendErrorUnsupported("COM_SLEEP");
998 }
999  
1000 sub comQuit {
1001 return undef;
1002 # die "Unhandled COM_QUIT command; default action is to die()";
1003 }
1004  
1005 sub comInitDb {
1006 my ($myserver, $database) = @_;
1007 my $parser = $myserver->getParser();
1008 $parser->setDatabase($database) if defined $parser;
1009 return $myserver->comQuery("USE $database");
1010 }
1011  
1012 sub comQuery {
1013 ### Processing Query ...
1014 my ($myserver, $query_text) = @_;
1015 #### $query_text
1016 print "Q: $query_text\n";
1017 my $parser = $myserver->getParser();
1018 if (not defined $parser) {
1019 return $myserver->sendError('0', "Default comQuery() handler requires a DBIx::MyParse object.",0,0);
1020 }
1021  
1022 my $query = $parser->parse($query_text);
1023 my $command = $query->getCommand();
1024  
1025 if ($command eq 'SQLCOM_ERROR') {
1026 return $myserver->sqlcomError($query, $query_text);
1027 } elsif ($command eq 'SQLCOM_SELECT') {
1028 my $orig_command = $query->getOrigCommand();
1029  
1030 if (
1031 ($orig_command ne 'SQLCOM_SHOW_DATABASES') &&
1032 ($orig_command ne 'SQLCOM_SHOW_TABLES') &&
1033 ($orig_command ne 'SQLCOM_SHOW_TABLE_STATUS') &&
1034 ($orig_command ne 'SQLCOM_SHOW_FIELDS')
1035 ) {
1036 return $myserver->sqlcomSelect($query, $query_text);
1037 }
1038  
1039 my $schema_select = $query->getSchemaSelect();
1040 my $db_name = $schema_select->getDatabaseName();
1041  
1042 if ($orig_command eq 'SQLCOM_SHOW_DATABASES') {
1043 return $myserver->sqlcomShowDatabases($query, $query_text);
1044 } elsif ($orig_command eq 'SQLCOM_SHOW_TABLES') {
1045 return $myserver->sqlcomShowTables($query, $query_text, $db_name, $query->getWild());
1046 } elsif ($orig_command eq 'SQLCOM_SHOW_TABLE_STATUS') {
1047 return $myserver->sqlcomShowTableStatus($query, $query_text, $db_name, $query->getWild());
1048 } elsif ($orig_command eq 'SQLCOM_SHOW_FIELDS') {
1049 return $myserver->sqlcomShowFields($query, $query_text, $db_name, $schema_select->getTableName());
1050 }
1051 } elsif ($command eq 'SQLCOM_INSERT') {
1052 return $myserver->sqlcomInsert($query, $query_text);
1053 } elsif ($command eq 'SQLCOM_INSERT_SELECT') {
1054 return $myserver->sqlcomInsertSelect($query, $query_text);
1055 } elsif ($command eq 'SQLCOM_REPLACE') {
1056 return $myserver->sqlcomReplace($query, $query_text);
1057 } elsif ($command eq 'SQLCOM_REPLACE_SELECT') {
1058 return $myserver->sqlcomReplaceSelect($query, $query_text);
1059 } elsif ($command eq 'SQLCOM_UPDATE') {
1060 return $myserver->sqlcomUpdate($query, $query_text);
1061 } elsif ($command eq 'SQLCOM_UPDATE_MULTI') {
1062 return $myserver->sqlcomUpdateMulti($query, $query_text);
1063 } elsif ($command eq 'SQLCOM_DELETE') {
1064 return $myserver->sqlcomDelete();
1065 } elsif ($command eq 'SQLCOM_DELETE_MULTI') {
1066 return $myserver->sqlcomDeleteMulti($query, $query_text);
1067 } elsif ($command eq 'SQLCOM_BEGIN') {
1068 return $myserver->sqlcomBegin($query, $query_text);
1069 } elsif ($command eq 'SQLCOM_COMMIT') {
1070 return $myserver->sqlcomCommit($query, $query_text);
1071 } elsif ($command eq 'SQLCOM_ROLLBACK') {
1072 return $myserver->sqlcomRollback($query, $query_text);
1073 } elsif ($command eq 'SQLCOM_SAVEPOINT') {
1074 return $myserver->sqlcomSavepoint($query, $query_text);
1075 } elsif ($command eq 'SQLCOM_ROLLBACK_TO_SAVEPOINT') {
1076 return $myserver->sqlcomRollbackToSavepoint($query, $query_text);
1077 } elsif ($command eq 'SQLCOM_DROP_TABLE') {
1078 return $myserver->sqlcomDropTable($query, $query_text);
1079 } elsif ($command eq 'SQLCOM_RENAME_TABLE') {
1080 return $myserver->sqlcomRenameTable($query, $query_text);
1081 } elsif (
1082 ($command eq 'SQLCOM_CHANGE_DB') ||
1083 ($command eq 'SQLCOM_CREATE_DB') ||
1084 ($command eq 'SQLCOM_DROP_DB')
1085 ) {
1086 my $schema_select = $query->getSchemaSelect();
1087 my $db_name = $schema_select->getDatabaseName();
1088 return $myserver->sqlcomChangeDb($query, $query_text, $db_name) if $command eq 'SQLCOM_CHANGE_DB';
1089 return $myserver->sqlcomCreateDb($query, $query_text, $db_name) if $command eq 'SQLCOM_CREATE_DB';
1090 return $myserver->sqlcomDropDb($query, $query_text, $db_name) if $command eq 'SQLCOM_DROP_DB';
1091 } else {
1092 return $myserver->sendErrorUnsupported($command);
1093 }
1094 }
1095 sub sqlcomError {
1096 ### Sending SQL Error
1097 my ($myserver, $query, $query_text) = @_;
1098 my $error = $query->getError();
1099 my $errstr = $query->getErrstr();
1100 return $myserver->sendError("$error: $errstr", $query->getErrno(), $query->getSQLState());
1101 }
1102  
1103 sub sqlcomSelect {
1104 ### SQL Select
1105 return $_[0]->sendErrorUnsupported($_[1]->getCommand());
1106 }
1107  
1108 sub sqlcomShowDatabases {
1109 ### SQL Show Databases
1110 return $_[0]->sendErrorUnsupported($_[1]->getOrigCommand());
1111 }
1112  
1113 sub sqlcomShowTables {
1114 ### SQL Show Tables
1115 return $_[0]->sendErrorUnsupported($_[1]->getOrigCommand());
1116 }
1117  
1118 sub sqlcomShowTableStatus {
1119 return $_[0]->sendErrorUnsupported($_[1]->getOrigCommand());
1120 }
1121  
1122 sub sqlcomShowFields {
1123 return $_[0]->sendErrorUnsupported($_[1]->getOrigCommand());
1124 }
1125  
1126 sub sqlcomInsert {
1127 return $_[0]->sendErrorUnsupported($_[1]->getCommand());
1128 }
1129  
1130 sub sqlcomInsertSelect {
1131 return $_[0]->sendErrorUnsupported($_[1]->getCommand());
1132 }
1133  
1134 sub sqlcomReplace {
1135 return $_[0]->sendErrorUnsupported($_[1]->getCommand());
1136 }
1137  
1138 sub sqlcomReplaceSelect {
1139 return $_[0]->sendErrorUnsupported($_[1]->getCommand());
1140 }
1141  
1142 sub sqlcomUpdate {
1143 return $_[0]->sendErrorUnsupported($_[1]->getCommand());
1144 }
1145  
1146 sub sqlcomUpdateMulti {
1147 return $_[0]->sendErrorUnsupported($_[1]->getCommand());
1148 }
1149  
1150 sub sqlcomDelete {
1151 return $_[0]->sendErrorUnsupported($_[1]->getCommand());
1152 }
1153  
1154 sub sqlcomDeleteMulti {
1155 return $_[0]->sendErrorUnsupported($_[1]->getCommand());
1156 }
1157  
1158 sub sqlcomBegin {
1159 return $_[0]->sendErrorUnsupported($_[1]->getCommand());
1160 }
1161  
1162 sub sqlcomCommit {
1163 return $_[0]->sendErrorUnsupported($_[1]->getCommand());
1164 }
1165  
1166 sub sqlcomRollback {
1167 return $_[0]->sendErrorUnsupported($_[1]->getCommand());
1168 }
1169  
1170 sub sqlcomSavepoint {
1171 return $_[0]->sendErrorUnsupported($_[1]->getCommand());
1172 }
1173  
1174 sub sqlcomRollbackToSavepoint {
1175 return $_[0]->sendErrorUnsupported($_[1]->getCommand());
1176 }
1177  
1178 sub sqlcomDropDb {
1179 return $_[0]->sendErrorUnsupported($_[1]->getCommand());
1180 }
1181  
1182 sub sqlcomDropTable {
1183 return $_[0]->sendErrorUnsupported($_[1]->getCommand());
1184 }
1185  
1186 sub sqlcomRenameTable {
1187 return $_[0]->sendErrorUnsupported($_[1]->getCommand());
1188 }
1189  
1190 sub sqlcomChangeDb {
1191 return $_[0]->sendErrorUnsupported($_[1]->getCommand());
1192 }
1193  
1194 sub sqlcomCreateDb {
1195 return $_[0]->sendErrorUnsupported($_[1]->getCommand());
1196 }
1197  
1198 sub comFieldList {
1199 my $myserver = shift;
1200 return $myserver->sendErrorUnsupported("COM_FIELD_LIST");
1201 }
1202  
1203 sub comCreateDb {
1204 my ($myserver, $database) = @_;
1205 return $myserver->comQuery("CREATE DATABASE $database");
1206 }
1207  
1208 sub comDropDb {
1209 my $myserver = shift;
1210 return $myserver->sendErrorUnsupported("COM_DROP_DB");
1211 }
1212  
1213 sub comShutdown {
1214 my $myserver = shift;
1215 die "Unhandled COM_SHUTDOWN command; default action is to die()";
1216 return undef;
1217 }
1218  
1219 sub comStatistics {
1220 my $myserver = shift;
1221 return $myserver->_sendPacket("My PID is $$");
1222 }
1223  
1224 sub comProcessInfo {
1225 my $myserver = shift;
1226 return $myserver->sendErrorUnsupported("COM_PROCESS_INFO");
1227 }
1228  
1229 sub comProcessKill {
1230 my ($myserver, $data) = @_;
1231 my $pid = unpack('V', $data);
1232 if ($$ == $pid) {
1233 kill(15, $pid);
1234 return 1;
1235 } else {
1236 $myserver->sendError("ER_SPECIFIC_ACCESS_DENIED_ERROR: by default you can kill only your own PID.",1227, 42000);
1237 return 1;
1238 }
1239 }
1240  
1241 sub comDebug {
1242 my $myserver = shift;
1243 return $myserver->sendErrorUnsupported("COM_DEBUG");
1244 }
1245  
1246 sub comPing {
1247 my $myserver = shift;
1248 return $myserver->sendOK();
1249 }
1250  
1251 sub comStmtPrepare {
1252 return $_[0]->_sendErrorPrepared("COM_STMT_PREPARE");
1253 }
1254  
1255 sub comStmtExecute {
1256 return $_[0]->_sendErrorPrepared("COM_STMT_EXECUTE");
1257 }
1258  
1259 sub comStmtSendLongData {
1260 return $_[0]->_sendErrorPrepared("COM_STMT_SEND_LONG_DATA");
1261 }
1262  
1263 sub comStmtClose {
1264 return $_[0]->_sendErrorPrepared("COM_STMT_CLOSE");
1265 }
1266  
1267 sub comStmtReset {
1268 return $_[0]->_sendErrorPrepared("COM_STMT_RESET");
1269 }
1270  
1271 sub comStmtFetch {
1272 return $_[0]->_sendErrorPrepared("COM_STMT_FETCH");
1273 }
1274  
1275 sub _sendErrorPrepared {
1276 my ($myserver, $command) = @_;
1277 carp ref($myserver)." Prepared statement command $command not supported.";
1278 return $myserver->sendError(ref($myserver).": Prepared statement command $command not supported.",1295, 'HY100');
1279 }
1280  
1281 sub sendErrorUnsupported {
1282 my ($myserver, $command) = @_;
1283 carp ref($myserver)." Unhandled command: $command";
1284 return $myserver->sendError(ref($myserver).": Command $command not supported.",1235, 42000);
1285 }
1286  
1287  
1288 sub authorize {
1289 ### Authorizing...
1290 my ($myserver, $remote_host, $username, $database) = @_;
1291 #### $remote_host
1292 #### $username
1293 #### $database
1294 warn "using default authorize($remote_host, $username).";
1295  
1296 if (($remote_host eq '127.0.0.1') || ($remote_host =~ m{^192\.168})) {
1297 return 1;
1298 } else {
1299 $myserver->sendError("Default authorize() only allows localhost connections regardless of username or password. Your host is $remote_host.",1044, 28000);
1300 return undef;
1301 }
1302 }
1303  
1304 sub passwordMatches {
1305 ### Checking Password...
1306 my ($myserver, $password) = @_;
1307 #### $password
1308  
1309 my $ctx = Digest::SHA1->new;
1310 $ctx->reset;
1311 $ctx->add($password);
1312 my $stage1 = $ctx->digest;
1313  
1314 $ctx->reset;
1315 $ctx->add($stage1);
1316 my $stage2 = $ctx->digest;
1317  
1318 $ctx->reset;
1319 $ctx->add($myserver->[MYSERVER_SALT]);
1320 $ctx->add($stage2);
1321 my $result = $ctx->digest;
1322  
1323 return undef if ($password ne '') && (not defined $myserver->[MYSERVER_SCRAMBLE]);
1324  
1325 return 1 if $myserver->_xor($result, $stage1) eq $myserver->[MYSERVER_SCRAMBLE];
1326  
1327 return undef;
1328 }
1329  
1330 sub _xor {
1331 my ($myserver, $s1, $s2) = @_;
1332 my $l = length($s1) - 1;
1333 my $result = '';
1334 for my $i (0..$l) {
1335 $result .= pack 'C', (unpack('C', substr($s1, $i, 1)) ^ unpack('C', substr($s2, $i, 1)));
1336 }
1337 return $result;
1338 }
1339  
1340 1;
1341  
1342 =head1 AUTHOR
1343  
1344 Philip Stoev, E<lt>philip@stoev.org<gt>
1345  
1346 =head1 COPYRIGHT AND LICENSE
1347  
1348 Copyright (C) 2006 by Philip Stoev
1349  
1350 This library is free software; you can redistribute it and/or modify
1351 it under the terms of the GNU General Public License Agreement.
1352  
1353 Please note that that the MySQL Protocol is proprietary and is also
1354 covered by the GNU General Public License. Please see
1355  
1356 http://dev.mysql.com/doc/internals/en/licensing-notice.html
1357  
1358 If you have any licensing doubts, please contact MySQL AB directly.
1359  
1360 =head1 SEE ALSO AND THANKS
1361  
1362 The following sources of information have been very helpful in creating
1363 this module:
1364  
1365 http://dev.mysql.com/doc/internals/en/client-server-protocol.html
1366  
1367 http://www.redferni.uklinux.net/mysql/MySQL-Protocol.html
1368  
1369 =cut
1370