script/myserver.pl untested

filter: Statementstmt 0.0% 0 / 236 Branchbran 0.0% 0 / 142 Conditioncond 0.0% 0 / 35 MC/DCmcdc 0.0% 0 / 19 Subroutinesub 0.0% 0 / 12 Podpod 0.0% 0 / 6 totaltotal 0.0% 0 / 450 CC 7 SCAR 27.6
CC
7
Cov
0%
set
42.0
ok
6.0
error
2.0
CRAP 15.8
1 #!/usr/local/bin/perl
2  
3 =pod
4  
5 =head1 SYNOPSIS
6  
7 perl examples/myserver.pl --config=examples/myserver.conf --port=1234 --dsn="dbi:mysql:"
8  
9 mysql -h127.0.0.1 -P1234 -umyuser -e 'info'
10  
11 =head1 DESCRIPTION
12  
13 This is a simple server that listens for incoming connections from MySQL clients or connectors.
14  
15 Each query received is processed according to a set of configuration files, which can rewrite the query,
16 forward it to a DBI handle or construct a response or a result set on the fly from any data.
17  
18 =head1 COMMAND LINE OPTIONS
19  
20 C<--port=XXXX> - port to listen on. Default is C<23306>, which is the default MySQL port with a 2 in front.
21  
22 C<--interface=AAA.BBB.CCC.DDD> - interface to listen to. Default is C<127.0.0.1> which means that only connections from the localhost
23 will be accepted. To enable connections from the outside use C<--interface=0.0.0.0>. In this case, please make sure
24 you have some other form of access protection, e.g. like the first rule in the C<myserver.conf> example configuration file.
25  
26 C<--config=config.file> - a configuration file containing rules to be executed. The option can be specified multiple times
27 and the rules will be checked in the order specified.
28  
29 C<--dsn> - specifies a L<DBI> DSN. All queries that did not match a rule or where the rule rewrote the query or did not
30 return any response or a result set on its own will be forwarded to that database. Individual rules can forward specific
31 queries to specific DSNs. If you do not want non-matching queries to be forwarded, either create a match-all rule at
32 the bottom of your last configuration file or omit the C<--dsn> option. If you omit the option, an error message will be
33 sent to the client.
34  
35 C<--dsn_user> and C<--dsn_password> can be used to specify username and password for DBI drivers where those can not be
36 specified in the DSN string.
37  
38 =head1 RULES
39  
40 Rules to be executed are contained in configuration files. The configuration files are actually standard perl scripts and
41 are executed as perl subroutines. Therefore, they can contain any perl code -- the only requirement is that the last
42 statement in the file (that is, the return value of the file) is an array containing the rules to be executed.
43  
44 The actions from a rule will be executed for all queries that match a specific pattern. Rules are processed in order
45 and processing is terminated at the first rule that returns some data to the client. This allows you to rewrite a query
46 numerous times and have a final default rule that forwards the query to another server. If C<forward> is defined, further
47 rules are not processed.
48  
49 Each rule can have the following attributes:
50  
51 C<command> The rule will match if the MySQL command issued by the client matches C<command>. C<command> can either be
52 an integer from the list found at C<DBIx::MyServer.pm> or a reference to a C<SUB> that returns such an integer. This is
53 mainly useful for processing incoming C<COM_PING>, C<COM_INIT_DB> and C<COM_FIELD_LIST>.
54  
55 C<match> The rule will match if the test of the query matches a regular expression or is identical to a string. C<match>
56 can also be a reference to a C<SUB> in which case the sub is executed and can either return a string or a regular expression.
57  
58 If both C<command> and C<match> are specified, both must match for the rule to be executed.
59  
60 C<dbh> if specified, any matching query will be forwarded to this database handle (possibly after a C<rewrite>), rather
61 than the default handle specifeid on the command line.
62  
63 C<dsn> behaves identically, however a database handle is contructed from the C<dsn> provided and an attempt is made to
64 connect to the database. If C<dsn> is a reference to an array, the first item from the array is used as a DSN, the second
65 one is used as username and the third one is used as password.
66  
67 C<before> this can be a reference to a subroutine that will be called after a matching query has been encountered but before
68 any further processing has taken place. The subroutine will be called with the text of the query as the first argument,
69 followed by extra arguments containing the strings matched from any parenthesis found in the C<match> regular expression.
70 You can use C<before> to execute any extra queries before the main query, such as C<EXPLAIN>. The return value from the
71 C<before> subroutine is discarded and is not used.
72  
73 C<rewrite> is a string that will replace the original query that matches the rule, or a reference to a subroutine that
74 will produce such a string. If C<rewrite> is not defined, and C<match> was a string, the query is passed along unchanged.
75 If C<match> was a regular expression, the string matched by the first set of parenthesis is used. This way, if the rule
76 does not specify any C<data>, C<columns>, C<error> or C<ok> clauses, but a valid DBI handle is defined, the query
77 will be forwarded to that handle automatically.
78  
79 C<error> can be either an array reference containing three arguments for C<DBIx::MyServer::sendError()> or a reference to
80 a subroutine returning such an array (or array reference). If this is the case, the error message will be sent to the client.
81 If C<error> is not defined or the subroutine returns C<undef>, no error message will be sent. In this case, you need to
82 send at some point either an C<ok> or a result set, otherwise the client will hang forever waiting for a response.
83  
84 C<ok> behaves identically to C<error> -- if it is defined or points to a subroutine which, when called, returns a true value,
85 an OK response will be sent to the client. C<ok> can also be a reference to an array, or the subroutine can return such an
86 array -- in this case the first item is the message to be sent to the client, the second one is the number of affected rows,
87 the third is the insert_id and the last one is the warning count.
88  
89 C<columns> must contain either an array reference or a reference to a subroutine which returns and array or array reference.
90 The column names from the array will be sent to the client. By default, all columns are defined as C<MYSQL_TYPE_STRING>.
91  
92 C<data> must contain either a reference to the data to be returned to the client or a reference to subroutine that will
93 produce the data. "Data" can be a reference to a C<HASH>, in which case the hash will be sent with the key names in the
94 first column and the key values in the second. It can be a flat array, in which case the array items will be sent as
95 a single column, or it can be a reference to a nested array, with each sub-array being a single row from the response.
96  
97 C<after> is called after all other parts of the rule have been processed.
98  
99 C<forward> if defined, the query will be immediately forwarded to the server and no further rules will be processed.
100  
101 All subroutine references that are called will have the text of the query passed as the first argument and the subsequent
102 arguments will be any strings matched by parenthesis in the C<match> regular expression.
103  
104 =head1 VARIABLES
105  
106 Your code in the configuration file can save and retrieve state by using C<get($variable)> and C<set($variable, $value)>.
107 State is retained as long as the connection is open. Each new connection starts with a clean state. The following
108 variables are maintained by the system:
109  
110 C<myserver> contains a reference to the L<DBIx::MyServer> object being used to service the connection. You can use this to
111 inject data and packets directly into the network stream.
112  
113 C<username> contains the username provided by the client at connection establishment.
114  
115 C<database> contains the database requested by the client at connection establishment. By default, C<myserver.pl> will
116 not automatically handle any database changes requested by the client. You are responsible for handling those either by
117 responding with a simple OK or by updating the variables.
118  
119 C<remote_host> contains the IP of the client.
120  
121 C<dbh> and C<dsn> will contain a reference to the default DBI handle and the DSN string it was produced from, as taken
122 from the command line. Even if a specific rule has its own C<dsn>, the value of those variables will always refer to
123 the default C<dbh> and C<dsn>. If you change the <dsn> variable, the system will attempt to connect to the new dsn string
124 and will produce a new C<dbh> handle from it. If you set C<dsn> to an array reference, the first item will be used as
125 a DSN, the second one as a username and the third one as a password. C<dsn_user> and C<dsn_password> can be used for the
126 same purpose.
127  
128 C<args> contains a reference to the C<@ARGV> array, that is, the command line options that evoked myserver.pl
129  
130 C<remote_dsn>, C<remote_dsn_user> and C<remote_dsn_password> are convenience variables that can also be specified on the
131 command line. It is not used by C<myserver.pl> however you can use it in your rules, the way C<remotequery.conf> does.
132  
133 =head1 SECURITY
134  
135 IMPORTANT NOTICE: THIS SCRIPT IS MEANT FOR DEMONSTRATION PURPOSES ONLY AND SHOULD NOT BE ASSUMED TO BE SECURE BY ANY MEANS!
136  
137 By default the script will only accept incoming connections from the local host. If you relax that via the C<--interface>
138 command-line option, all connections will be accepted. However, once the connection has been established, you can implement
139 access control as demonstrated in the first rule of the C<myserver.conf> file -- it returns "Access denied" for every query
140 unless the username is "myuser". Future versions of the script will allow connections to be rejected during handshake.
141  
142 The script expects that the password is equal to the username. This is currently hard-coded.
143  
144 =head1 SAMPLE RULES
145  
146 The following rule sets are provided in the C<examples/> directory.
147  
148 =head2 Simple examples - myserver.conf
149  
150 This configuration provides some simple query rewriting examples as suggested by Giuseppe Maxia and Jan Kneschke, e.g.
151 commands like C<ls>, C<cd> as well as fixing spelling mistakes. In addition, some very simple access control is demonstrated
152 at the top of the file.
153  
154 =head2 Remote queries - remotequery.conf
155  
156 This rule set implements a C<SELECT REMOTE select_query ON 'dsn'> operator which will execute the query on <dsn> specified,
157 bring the results back into a temporary table on the default server and substitute the C<REMOTE_SELECT> part in the orignal
158 query with a reference to the temoporary table. The following scenarios are possible:
159  
160 # Standalone usage
161 mysql> SELECT REMOTE * FROM mysql.user ON 'dbi:mysql:host=remote:user=foo:password=bar'
162  
163 # CREATE ... SELECT usage
164 mysql> CREATE TABLE local_table SELECT REMOTE * FROM remote_table ON 'dbi:mysql:host=remote'
165  
166 # Non-correlated subquery
167 mysql> SELECT *
168 mysql> FROM (SELECT REMOTE * FROM mysql_user ON 'dbi:mysql:host=remote:user=foo:password=bar')
169 mysql> WHERE user = 'mojo'
170  
171 # Specify remote dsn on the command line
172 shell> ./myserver.pl --config=remotequery.conf --dsn=dbi:mysql: --remote_dsn=dbi:mysql:host=host2
173 mysql> select remote 1;
174  
175 # Specify remote dsn as variable
176  
177 mysql> set @@@remote_dsn=dbi:mysql:host=host2
178 mysql> select remote NOW();
179  
180 mysql> set @@@devel_dsn=dbi:mysql:host=dev3
181 mysql> select remote NOW() ON @@@devel_dsn;
182  
183 This is different from using the Federated storage handler because the entire C<REMOTE_SELECT> query is executed on the
184 remote server and only the result is sent back to the default server for further processing. This is useful if a lot of
185 processing is to be done on the remote server -- the Federated engine will bring most of the data to the connecting server
186 and will process it there, which can potentially be very time consuming.
187  
188 Please note that since a temporary table is created and it must reside somewhere, you need to be in a working database
189 on the default server. Updateable C<VIEW>a are not supported.
190  
191 =head2 Development support - devel.conf
192  
193 This configuration provides the following operators:
194  
195 C<shell> - can be used to execute shell commands, e.g. C<shell ls -la>.
196 C<env> - returns the operating environment of C<myserver.pl>.
197 C<stats> - executes C<SHOW STATUS> before and after each query and returns the difference. First you execute
198 C<stats select a from b> and then C<show stats>.
199 C<devel> - can be used to send specfic queries to a different server. You can execute a single query as
200 C<devel select a from b> or use a standalone C<devel> to redirect all future queries until you issue C<restore>.
201  
202 You specify the server to send "development" queries to via C<set('devel_dsn')> at the top of C<devel.conf>
203  
204 =head2 ODBC compatibility - odbc.conf
205  
206 The C<odbc.conf> contains an example on how to unintelligently answer generic queries sent by the MySQL ODBC driver and
207 the applications that use it, up to the point where real data can be sent over the connection and imported into the client
208 application.
209  
210 =cut
211  
212 use strict;
213 use Socket;
214 use DBI;
215 use DBIx::MyServer;
216 use DBIx::MyServer::DBI;
217 use Getopt::Long qw(:config pass_through);
218  
219  
220 $SIG{CHLD} = 'IGNORE';
221  
222 my $start_dsn;
223 my $start_dsn_user;
224 my $start_dsn_password;
225  
226 my $remote_dsn;
227 my $remote_dsn_user;
228 my $remote_dsn_password;
229  
230 my $port = '23306';
231 my $interface = '127.0.0.1';
232 my $debug;
233 my @config_names;
234 my @rules;
235 my %storage;
236  
237 my @args = @ARGV;
238  
239 my $result = GetOptions(
240 "dsn=s" => \$start_dsn,
241 "dsn_user=s" => \$start_dsn_user,
242 "dsn_password=s" => \$start_dsn_password,
243 "remote_dsn=s" => \$remote_dsn,
244 "remote_dsn_user=s" => \$remote_dsn_user,
245 "remote_dsn_password=s" => \$remote_dsn_password,
246 "port=i" => \$port,
247 "config=s" => \@config_names,
248 "if|interface|ip=s" => \$interface,
249 "debug" => \$debug
250 ) or die;
251  
252 @ARGV = @args;
253  
254 my $start_dbh;
255 if (defined $start_dsn) {
256 print localtime()." [$$] Connecting to DSN $start_dsn.\n" if $debug;
257 $start_dbh = DBI->connect($start_dsn, $start_dsn_user, $start_dsn_password);
258 }
259  
260 $storage{dbh} = $start_dbh;
261 $storage{dsn} = $start_dsn;
262 $storage{dsn_user} = $start_dsn_user;
263 $storage{dsn_password} = $start_dsn_password;
264  
265 $storage{remote_dsn} = $remote_dsn;
266 $storage{remote_dsn_user} = $remote_dsn_user;
267 $storage{remote_dsn_password} = $remote_dsn_password;
268  
269 foreach my $config_name (@config_names) {
270 my $config_sub;
271 open (CONFIG_FILE, $config_name) or die "unable to open $config_name: $!";
272 read (CONFIG_FILE, my $config_text, -s $config_name);
273 close (CONFIG_FILE);
274 eval ('$config_sub = sub { '.$config_text.'}') or die $@;
275 my @config_rules = &$config_sub();
276 push @rules, @config_rules;
277 print localtime()." [$$] Loaded ".($#config_rules + 1)." rules from $config_name.\n" if $debug;
278 }
279  
280 socket(SERVER_SOCK, PF_INET, SOCK_STREAM, getprotobyname('tcp'));
281 setsockopt(SERVER_SOCK, SOL_SOCKET, SO_REUSEADDR, pack("l", 1));
282 bind(SERVER_SOCK, sockaddr_in($port, inet_aton($interface))) || die "bind: $!";
283 listen(SERVER_SOCK,1);
284  
285 print localtime()." [$$] Note: port $port is now open on interface $interface.\n";
286 while (1) {
287 my $remote_paddr = accept(my $remote_socket, SERVER_SOCK);
288  
289 if (!defined(my $pid = fork)) {
290 die "cannot fork: $!";
291 } elsif ($pid) {
292 next;
293 }
294  
295 $storage{dbh} = $start_dbh->clone() if defined $start_dbh;
296 $storage{dsn} = $start_dsn;
297 $storage{args}= \@ARGV;
298
299 my $dbh = get('dbh');
300 my $myserver = DBIx::MyServer::DBI->new(
301 socket => $remote_socket,
302 dbh => $dbh,
303 banner => $0.' '.join(' ', @ARGV)
304 );
305 set('myserver', $myserver);
306  
307 $myserver->sendServerHello();
308 my ($username, $database) = $myserver->readClientHello();
309 set('username', $username); set('database', $database);
310  
311 if (!$myserver->passwordMatches($username)) {
312 $myserver->sendError("Authorization failed. Password must equal username '$username'.",1044, 28000);
313 exit();
314 }
315  
316 eval {
317 my $hersockaddr = getpeername($myserver->getSocket());
318 my ($port, $iaddr) = sockaddr_in($hersockaddr);
319 my $remote_host = inet_ntoa($iaddr);
320 set('remote_host', $remote_host);
321 };
322
323 $myserver->sendOK();
324  
325 while (1) {
326 my ($command, $query) = $myserver->readCommand();
327 print localtime()." [$$] command: $command; data = $query\n" if $debug;
328 last if (not defined $command) || ($command == DBIx::MyServer::COM_QUIT);
329  
330 my $outgoing_query = $query;
331  
332 foreach my $i (0..$#rules) {
333  
334 my $rule = $rules[$i];
335 my $rule_matches = 0;
336  
337 my @placeholders;
338  
339 if (defined $rule->{command}) {
340 if ($command == $rule->{command}) {
341 $rule_matches = 1;
342 } else {
343 next;
344 }
345 }
346  
347 my $match_type = ref($rule->{match});
348 if (defined $rule->{match}) {
349 $rule->{match_string} = $match_type eq 'CODE' ? $rule->{match}($query) : $rule->{match};
350 if (ref($rule->{match_string}) eq 'Regexp') {
351 $rule_matches = 1 if @placeholders = $query =~ $rule->{match};
352 } else {
353 $rule_matches = 1 if $query eq $rule->{match_string};
354 }
355 print localtime()." [$$] Executing 'match' from rule $i: $rule->{match_string}, result is $rule_matches.\n" if $debug;
356 } else {
357 $rule_matches = 1;
358 }
359 $rule->{placeholders} = \@placeholders;
360  
361 next if $rule_matches == 0;
362  
363 my ($definitions, $data);
364  
365 undef $storage{data_sent};
366  
367 if (defined $rule->{before}) {
368 print localtime()." [$$] Executing 'before' from rule $i\n" if $debug;
369 eval{
370 $rule->{before}($query, @{$rule->{placeholders}});
371 };
372 error($@) if defined $@ && $@ ne '';
373 }
374  
375 if (defined $rule->{rewrite}) {
376 if (ref($rule->{rewrite}) eq 'CODE') {
377 $outgoing_query = $rule->{rewrite}($query, @{$rule->{placeholders}});
378 } else {
379 $outgoing_query = $rule->{rewrite};
380 }
381 print localtime()." [$$] Executing 'rewrite' from rule $i, result is '$outgoing_query'\n" if $debug;
382 } elsif (defined $rule->{match}) {
383 $outgoing_query = $rule->{match_string} eq 'Regexp' ? $rule->{placeholders}->[0] : $outgoing_query;
384 }
385  
386 if (defined $rule->{error}) {
387 my @error = ref ($rule->{error}) eq 'CODE' ? $rule->{error}($query, @{$rule->{placeholders}}) : $rule->{error};
388 my @mid_error = ref($error[0]) eq 'ARRAY' ? @{$error[0]} : @error;
389 if (defined $mid_error[0]) {
390 print localtime()." [$$] Sending error: ".join(', ', @mid_error).".\n" if $debug;
391 error(@mid_error);
392 }
393 }
394  
395 if (defined $rule->{ok}) {
396 my @ok = ref ($rule->{ok}) eq 'CODE' ? $rule->{ok}($query, @{$rule->{placeholders}}) : $rule->{ok};
397 my @mid_ok = ref($ok[0]) eq 'ARRAY' ? @{$ok[0]} : @ok;
398 if (defined $mid_ok[0]) {
399 print localtime()." [$$] Sending OK: ".join(', ', @mid_ok).").\n" if $debug;
400 ok(@mid_ok);
401 }
402 }
403  
404 if (defined $rule->{columns}) {
405 my @column_names = ref($rule->{columns}) eq 'CODE' ? $rule->{columns}($query, @{$rule->{placeholders}}) : $rule->{columns};
406 my $column_names;
407 if (defined $column_names[1]) {
408 $column_names = \@column_names;
409 } elsif (ref($column_names[0]) eq 'ARRAY') {
410 $column_names = $column_names[0];
411 } elsif (defined $column_names[0]) {
412 $column_names = [ $column_names[0] ];
413 }
414 print localtime()." [$$] Converting column_names into definitions.\n" if $debug;
415 $definitions = [ map { $myserver->newDefinition( name => $_ ) } @$column_names ];
416 }
417  
418 if (defined $rule->{data}) {
419 my @start_data = ref($rule->{data}) eq 'CODE' ? $rule->{data}($query, @{$rule->{placeholders}}) : $rule->{data};
420 my $mid_data = defined $start_data[1] ? \@start_data : $start_data[0];
421  
422 if (ref($mid_data) eq 'HASH') {
423 print localtime()." [$$] Converting data from hash.\n" if $debug;
424 $data = [ map { [ $_, $mid_data->{$_} ] } sort keys %$mid_data ];
425 } elsif ((ref($mid_data) eq 'ARRAY') && (ref($mid_data->[0]) ne 'ARRAY')) {
426 print localtime()." [$$] Converting data from a flat array.\n" if $debug;
427 $data = [ map { [ $_ ] } @$mid_data ];
428 } elsif (ref($mid_data) eq '') {
429 $data = [ [ $mid_data ] ];
430 } else {
431 $data = $mid_data;
432 }
433 }
434  
435 if (
436 (not defined $storage{data_sent}) && (not defined $definitions) && (not defined $data) &&
437 ( ($i == $#rules) || (defined $rule->{dbh}) || (defined $rule->{forward}) )
438 ) {
439 if (defined $rule->{dbh}) {
440 $myserver->setDbh($rule->{dbh});
441 } elsif (defined $rule->{dsn}) {
442 if (ref($rule->{dsn}) eq 'ARRAY') {
443 print localtime()." [$$] Connecting to DSN $rule->{dsn}->[0].\n" if $debug;
444 $myserver->setDbh(DBI->connect(@{$rule->{dsn}}));
445 } else {
446 print localtime()." [$$] Connecting to DSN $rule->{dsn}.\n" if $debug;
447 $myserver->setDbh(DBI->connect($rule->{dsn}, get('dsn_user'), get('dsn_password')));
448 }
449 }
450 if (not defined get('dbh')) {
451 error("No --dbh specified. Can not forward query.",1235, 42000);
452 } elsif ($command == DBIx::MyServer::COM_QUERY) {
453 (my $foo, $definitions, $data) = $myserver->comQuery($outgoing_query);
454 } elsif ($command == DBIx::MyServer::COM_INIT_DB) {
455 (my $foo, $definitions, $data) = $myserver->comInitDb($outgoing_query);
456 } else {
457 error("Don't know how to handle command $command.",1235, 42000);
458 }
459 $storage{data_sent} = 1;
460 }
461  
462 if (defined $definitions) {
463 print localtime()." [$$] Sending definitions.\n" if $debug;
464 $myserver->sendDefinitions($definitions);
465 $storage{data_sent} = 1;
466 }
467
468 if (defined $data) {
469 print localtime()." [$$] Sending data.\n" if $debug;
470 $myserver->sendRows($data);
471 $storage{data_sent} = 1;
472 }
473
474 if (defined $rule->{after}) {
475 print localtime()." [$$] Executing 'after' for rule $i\n";
476 $rule->{after}($query, @{$rule->{placeholders}})
477 }
478  
479 last if defined $storage{data_sent};
480 }
481  
482 }
483  
484 print localtime()." [$$] Exit.\n";
485 exit;
486 }
487  
488 sub set {
489 my ($name, $value) = @_;
490 $storage{$name} = $value;
491 if ($name eq 'dsn') {
492 if (defined $value) {
493 my $dbh;
494 if (ref($value) eq 'ARRAY') {
495 print localtime()." [$$] Connecting to DSN $value->[0].\n" if $debug;
496 $dbh = DBI->connect(@{$value});
497 } else {
498 print localtime()." [$$] Connecting to DSN $value.\n" if $debug;
499 $dbh = DBI->connect($value, get('dsn_user'), get('dsn_password'));
500 }
501 $storage{myserver}->setDbh($dbh);
502 $storage{dbh} = $dbh;
503 } else {
504 $storage{myserver}->setDbh(undef);
505 $storage{dbh} = undef;
506 }
507 }
508 return 1;
509 }
510  
511 sub error {
512 my $myserver = get('myserver');
513 $myserver->sendError(@_);
514 $storage{data_sent} = 1;
515 }
516  
517 sub error_dbi {
518 my $myserver = get ('myserver');
519 my $dbh = $_[0] || get ('dbh');
520 $myserver->sendErrorFromDBI($dbh);
521 $storage{data_sent} = 1;
522 }
523  
524 sub ok {
525 my $myserver = get('myserver');
526 if ($_[0] == 1) {
527 $myserver->sendOK();
528 } else {
529 $myserver->sendOK(@_);
530 }
531 $storage{data_sent} = 1;
532 }
533  
534 sub disconnect { exit; }
535  
536 sub get {
537 return $storage{$_[0]};
538 }
539