Debian Codegraph @

lib/Games/FrozenBubble/Net.pm

raw
1 package Games::FrozenBubble::Net;
2
3 use strict;
4 use IO::Socket;
5 use Fcntl;
6 use Errno qw(:POSIX);
7 use POSIX qw(uname);
8
9 use Time::HiRes qw(gettimeofday sleep);
10 use Games::FrozenBubble::Stuff;
11
12 our $proto_major = '1'; #- this is our protocol level
13 our $proto_minor = '2'; #-
14
15 my $udp_server_port = 1511; #- a.k.a 0xF 0xB thx misc
16 $SIG{PIPE} = 'IGNORE'; #- stupid send/write low-level API sending SIGPIPE when server closes connection, and stupid Perl
17 #- not allowing flags in syswrite
18
19 #- UDP discover LAN servers with broadcast
20
21 sub discover_lan_servers {
22 my $socket = IO::Socket::INET->new(Proto => 'udp');
23 if (!$socket) {
24 print STDERR "Cannot create socket: $!\n";
25 return { failure => 'Cannot send broadcast.' };
26 }
27
28 if (!$socket->setsockopt(SOL_SOCKET, SO_BROADCAST, 1)) {
29 print STDERR "Cannot setsockopt: $!\n";
30 return { failure => 'Cannot send broadcast.' };
31 }
32
33 my $destpaddr = sockaddr_in($udp_server_port, INADDR_BROADCAST());
34 if (!$socket->send("FB/$proto_major\.$proto_minor SERVER PROBE", 0, $destpaddr)) {
35 print STDERR "Cannot send broadcast: $!\n";
36 return { failure => 'Network is down/no network?' };
37 }
38
39 my $inmask = '';
40 vec($inmask, fileno($socket), 1) = 1;
41 my @servers;
42 while (select(my $outmask = $inmask, undef, undef, 2)) {
43 my ($srcpaddr, $rcvmsg);
44 if (!defined($srcpaddr = $socket->recv($rcvmsg, 128, 0))) {
45 print STDERR "Cannot receive from socket: $!\n";
46 return { failure => 'Cannot read answer from broadcast.' };
47 }
48 my ($port, $ipaddr) = sockaddr_in($srcpaddr);
49 $ipaddr = inet_ntoa($ipaddr);
50 if ($rcvmsg =~ m|^FB/$proto_major\.\d SERVER HERE AT PORT (\d+)|) {
51 push @servers, { host => $ipaddr, port => $1 };
52 } else {
53 print STDERR "\nReceive weird/incompatible answer to UDP broadcast looking for LAN servers from $ipaddr:$port:\n\t$rcvmsg\n";
54 }
55 }
56
57 return { servers => \@servers };
58 }
59
60
61
62 #- before game operations
63
64 our $sock;
65 our $ping = 200;
66
67 our $masterserver; #- for forcing the masterserver on commandline
68
69 sub send_($) {
70 my ($msg) = @_;
71 if (defined($sock)) {
72 my $bytes = syswrite($sock, "FB/$proto_major.$proto_minor $msg\n");
73 !$bytes and disconnect();
74 }
75 }
76
77 sub disconnect() {
78 if (defined($sock)) {
79 close $sock;
80 $sock = undef;
81 }
82 }
83
84 sub isconnected() {
85 return defined($sock);
86 }
87
88 my $buffered_line;
89 sub readline_() {
90 if (!defined($sock)) {
91 return undef;
92 }
93
94 my $results = $buffered_line;
95 $buffered_line = undef;
96 eval {
97 local $SIG{ALRM} = sub { die "alarm\n" };
98 alarm 5; #- in seconds
99 while ($results !~ /\n/) {
100 my $buf;
101
102 if($^O eq 'MSWin32' && !defined IO::Select->new($sock)->can_read(0.00001)) {
103 sleep($ping/1000/3);
104 next;
105 }
106
107 my $bytes = sysread($sock, $buf, 1);
108 if (!defined($bytes)) {
109 if (0 + $! == EAGAIN) {
110 sleep($ping/1000/3);
111 } elsif ($! == ECONNRESET) {
112 disconnect();
113 return $results;
114 } else {
115 printf STDERR "Oops, system error: " .(0+$!). " at line %d, %s\n", __LINE__, $^E;
116 return undef;
117 }
118 } elsif ($bytes == 0) {
119 disconnect();
120 return $results;
121 } else {
122 $results .= $buf;
123 }
124 }
125 alarm 0;
126 ($results, $buffered_line) = $results =~ /([^\n]+\n)(.*)?/s;
127 };
128 if ($@) {
129 print STDERR "Sorry, your computer or the network is too slow, giving up.\n";
130 disconnect();
131 die 'quit';
132 } else {
133 return $results;
134 }
135 }
136
137 sub readline_ifdata() {
138 $buffered_line and return readline_();
139
140 if (!defined($sock)) {
141 return undef;
142 }
143
144 return undef if $^O eq 'MSWin32' && !defined IO::Select->new($sock)->can_read(0.00001);
145
146 my $buf;
147 my $bytes = sysread($sock, $buf, 1);
148 if (!defined($bytes)) {
149 if (0 + $! == EAGAIN) { # nothing there to read
150 return undef;
151 } elsif (0 + $! == ECONNRESET) {
152 disconnect();
153 return undef;
154 } else {
155 printf STDERR "Oops, system error: " .(0+$!). " at line %d, %s\n", __LINE__, $^E;
156 return undef;
157 }
158 } elsif ($bytes == 0) {
159 disconnect();
160 return;
161 } else {
162 if ($buf eq "\n") {
163 return $buf;
164 } else {
165 return $buf . readline_();
166 }
167 }
168 }
169
170
171 sub decode_msg($) {
172 my ($msg) = @_;
173 my ($command, $message) = $msg =~ m|^FB/\d+\.\d+ (\w+): (.*)|;
174 return ($command, $message);
175 }
176
177 sub send_and_receive($;$) {
178 my ($command, $rest) = @_;
179 send_("$command $rest");
180 my $answer = undef;
181 my $to_buffer;
182 while (!defined($answer)) {
183 my $msg = readline_();
184 !defined($msg) and $answer = '';
185 my ($rcv_command, $rcv_message) = Games::FrozenBubble::Net::decode_msg($msg);
186 if ($rcv_command eq $command) {
187 $answer = $rcv_message;
188 } else {
189 #- this is not the answer we're waiting. keep that.
190 $to_buffer .= $msg;
191 }
192 }
193 $buffered_line .= $to_buffer;
194 return $answer;
195 }
196
197 sub list() {
198 my $msg = send_and_receive('LIST');
199 if ($msg =~ /(\S*) (\S*) free:(\d+) games:(\d+) playing:(\d+) at:(\S*)/) {
200 my $freenicks = $1;
201 my $freegames = $2;
202 my $free = $3;
203 my $games = $4;
204 my $playing = $5;
205 my $playing_geolocs = $6;
206 my @games;
207 while ($freegames =~ /\[([^\]]+)\]/g) {
208 push @games, [ split /,/, $1 ];
209 }
210 return ($free, $games, $freenicks, $playing, $playing_geolocs, @games);
211 } else {
212 return;
213 }
214 }
215
216 sub create($) {
217 my ($nick) = @_;
218 send_("CREATE $nick");
219 my $msg = readline_();
220 if ($msg =~ /CREATE: OK/) {
221 return 1;
222 } else {
223 $msg and print STDERR "Could not create game. Server said:\n\t$msg\n";
224 return 0;
225 }
226 }
227
228 sub join($$) {
229 my ($leader, $nick) = @_;
230 send_("JOIN $leader $nick");
231 my $msg = readline_();
232 if ($msg =~ /JOIN: OK/) {
233 return 1;
234 } else {
235 $msg and print STDERR "Could not join game. Server said:\n\t$msg\n";
236 return 0;
237 }
238 }
239
240 my $buffered_buf; #- the in game buffer. not to be read before game.
241 my @messages; #- the in game messages. same.
242
243 my ($current_name, $current_host, $current_port);
244 sub connect {
245 my ($host, $port) = @_;
246
247 my $perform_ping = 1;
248 my $tried_name;
249 if (!defined $host) {
250 #- reconnect
251 $host = $current_host;
252 $port = $current_port;
253 $tried_name = $current_name;
254 $perform_ping = 0;
255 } elsif (!defined $port) {
256 #- first param was a hash
257 my $params = $host;
258 $host = $params->{host};
259 $port = $params->{port};
260 $ping = $params->{ping};
261 $perform_ping = 0;
262 $tried_name = $params->{name};
263 }
264
265 $current_host = $current_port = undef;
266
267 $sock = IO::Socket::INET->new(PeerAddr => $host, PeerPort => $port, Proto => 'tcp', Timeout => 5);
268 if (!$sock) {
269 #print STDERR "Couldn't connect to $host:$port: $@\n";
270 return { failure => 'Server is down' };
271 }
272 $sock->autoflush;
273
274 $buffered_line = undef;
275 $buffered_buf = undef;
276 @messages = ();
277 my $msg;
278 eval { $msg = readline_(); };
279 $@ and return { failure => 'Server or computer too slow' };
280 my ($remote_major, $remote_minor, $isready) = $msg =~ m|^FB/(\d+).(\d+) (.*)|;
281 my ($servername, $serverlanguage);
282 if ($isready =~ /^PUSH: SERVER_READY (.*) (.*)/) {
283 $servername = $1;
284 $serverlanguage = $2;
285 } else {
286 disconnect();
287 if ($isready eq 'PUSH: SERVER_IS_FULL') {
288 print STDERR "Dropping $host:$port: server is full\n";
289 return { failure => 'Server is full' };
290 } elsif ($isready eq 'PUSH: SERVER_IS_OVERLOADED') {
291 print STDERR "Dropping $host:$port: server is overloaded\n";
292 return { failure => 'Server overloaded' };
293 } elsif ($remote_minor < $proto_minor) {
294 print STDERR "Dropping $host:$port: deprecated protocol $remote_major.$remote_minor\n";
295 return { failure => 'Server deprecated' };
296 } else {
297 print STDERR "Dropping $host:$port: not a Frozen-Bubble server\n";
298 return { failure => 'Not an FB server' };
299 }
300 }
301
302 if ($perform_ping) {
303 $ping = 200;
304
305 my @pings;
306 foreach (1..4) {
307 reping:
308 my $t0 = gettimeofday;
309 send_('PING');
310 eval { $msg = readline_(); };
311 $@ and return { failure => 'Server or computer too slow' };
312 my $t1 = gettimeofday;
313 if ($msg =~ /INCOMPATIBLE_PROTOCOL/) {
314 disconnect();
315 print STDERR "Dropping $host:$port: imcompatible Frozen-Bubble server\n";
316 return { failure => 'Incompatible server' };
317 } elsif ($msg =~ /PUSH/) {
318 #- drop PUSHes, server might be sending TALK messages which we don't care at that point
319 goto reping;
320 } elsif ($msg !~ /PONG/) {
321 print STDERR "$host:$port answer to PING was not recognized. Server said:\n\t$msg\n";
322 disconnect();
323 return { failure => 'Incompatible server' };
324 }
325 push @pings, ($t1-$t0) * 1000;
326 if ($_ == 2 && $pings[0] > 250 && $pings[1] > 250) {
327 #- don't wait too much on slower servers
328 last;
329 }
330 }
331
332 if (@pings > 2) { #- keep 2 worst
333 @pings = difference2(\@pings, [ min(@pings) ]) while @pings > 2;
334 }
335 $ping = sprintf("%.1f", sum(@pings)/@pings);
336 }
337
338 #BEWARE non-blocking sockets work on Win32 only with IO-1.24 or higher
339 # http://www.codeguru.com/forum/showthread.php?t=468281
340 # http://perldoc.perl.org/IO/Select.html
341 $sock->blocking(0);
342 return { failure => 'Cannot set unblocking '.(0+$!) } if 0+$!;
343
344 $current_host = $host;
345 $current_port = $port;
346 $current_name = $tried_name;
347 return { ping => $ping, name => $servername, language => $serverlanguage };
348 }
349
350 sub current_server_name {
351 return $current_name;
352 }
353 sub current_server_hostport {
354 return "$current_host:$current_port";
355 }
356
357 sub reconnect() {
358 if (defined($current_host) && defined($current_port)) {
359 disconnect();
360 my $ret = Games::FrozenBubble::Net::connect();
361 return exists $ret->{ping};
362 }
363 }
364
365 sub http_download($) {
366 my ($url) = @_;
367
368 my ($host, $port, $path) = $url =~ m,^http://([^/:]+)(?::(\d+))?(/\S*)?$,;
369 $port ||= 80;
370
371 my $sock = IO::Socket::INET->new(PeerAddr => $host, PeerPort => $port, Proto => 'tcp', Timeout => 5);
372 if (!$sock) {
373 print STDERR "Couldn't connect to $host:$port:\n\t$@\n";
374 return;
375 }
376 $sock->autoflush;
377
378 my ($sysname, undef, undef, undef, $machine) = uname();
379 my $bytes = syswrite($sock, join("\r\n",
380 "GET $path HTTP/1.0",
381 "Host: $host:$port",
382 "User-Agent: Frozen-Bubble client version $Games::FrozenBubble::RELEASE_VERSION (protocol version $proto_major.$proto_minor) on $sysname/$machine",
383 "", ""));
384 if (!$bytes) {
385 close $sock;
386 return;
387 }
388
389 #- skip until empty line
390 my ($now, $last, $buf, $tmp) = 0;
391 my $read = sub {
392 my $got = sysread($sock, $buf, 1);
393 if ($got == 0) {
394 die 'eof';
395 } elsif (!defined($got)) {
396 die "sys error: $!";
397 } else {
398 $tmp .= $buf;
399 };
400 };
401 eval {
402 do {
403 $last = $now;
404 &$read; &$read if $buf =~ /\015/;
405 $now = $buf =~ /\012/;
406 } until $now && $last;
407
408 if ($tmp =~ m|^HTTP/\d\.\d (.*\b(\d+)\b.*)| && $2 == 200) {
409 $tmp = '';
410 while (1) { &$read }
411 } else {
412 die "HTTP error fetching http://$host:$port$path: $1\n";
413 }
414 };
415
416 if ($@ =~ /^eof/) {
417 close $sock;
418 return $tmp;
419 } elsif ($@ =~ /^alarm/) {
420 die;
421 } else {
422 print STDERR "http_download: $@\n";
423 close $sock;
424 return;
425 }
426 }
427
428 sub get_server_list() {
429 my @masters = qw(http://www.frozen-bubble.org/servers/serverlist
430 http://frozen-bubble.sourceforge.net/serverlist
431 http://webother.linuxfr.org/serverlist
432 http://fb.mandrivalinux.org/serverlist);
433 foreach ($masterserver || map { "$_-$proto_major" } @masters) {
434 my $serverlist = http_download($_);
435 defined $serverlist and return $serverlist;
436 }
437 return;
438 }
439
440 our $myid;
441 sub setmyid($) {
442 $myid = $_[0];
443 }
444
445 sub sleep_reasonably {
446 sleep($ping/1000/3);
447 }
448
449
450 #- in game operations
451
452 #- data is command:parameters
453 #- supported commands:
454 #- ! (synchro) [this one is special, server propagates also to emitter]
455 #- a (angle)
456 #- A (attack)
457 #- b (bubble)
458 #- f (fire)
459 #- F (finished)
460 #- g (generatemalus)
461 #- l (leave)
462 #- m (malus)
463 #- M (malusstick)
464 #- n (newgame)
465 #- N (nextbubble)
466 #- r (rotate)
467 #- p (ping) [this one is special, server doesn't propagate back]
468 #- s (stick)
469 #- t (talk)
470 #- T (tobelaunchedbubble)
471 sub gsend($) {
472 my ($msg) = @_;
473 if (defined($sock)) {
474 my $bytes = syswrite($sock, $myid . "$msg\n");
475 !$bytes and disconnect();
476 }
477 }
478
479 sub grecv() {
480 my @msg = @messages;
481 @messages = ();
482
483 if (!defined($sock)) {
484 return @msg;
485 }
486
487 return @msg if $^O eq 'MSWin32' && !defined IO::Select->new($sock)->can_read(0.00001);
488
489 my $buf;
490 my $bytes = sysread($sock, $buf, 1024);
491 if (!defined($bytes)) {
492 if ($! == EAGAIN) {
493 return @msg;
494 } elsif ($! == ECONNRESET) {
495 disconnect();
496 return;
497 } else {
498 printf STDERR "Oops, system error: " .(0+$!). " at line %d, %s\n", __LINE__, $^E;
499 return undef;
500 }
501 } elsif ($bytes == 0) {
502 disconnect();
503 return;
504 }
505 # print "received $bytes bytes, adding to buffered ", length($buffered_buf), "\n";
506 $buf = $buffered_buf . $buf;
507 $buffered_buf = undef;
508 # my @ascii = unpack("C*", $buf);
509 # print "bytes in buf: @ascii\n";
510
511 while ($buf) {
512 #- first byte of a "frame" is the id of the sender
513 my $id = substr($buf, 0, 1);
514 $buf = substr($buf, 1);
515 #- match data of a frame (NUL terminated)
516 if (my ($msg, $rest) = $buf =~ /([^\n]+)\n(.*)?/s) { #-?
517 $buf = $rest;
518 push @msg, { id => $id, msg => $msg };
519 # print "\trecv-msg:", ord($id), ":$msg\n";
520 } else {
521 #- no match means that we received a partial packet
522 # print "*** partial receive! for <$buf>, buffering (theoretically harmless)\n";
523 $buffered_buf = $id . $buf;
524 $buf = undef;
525 }
526 }
527
528 return @msg;
529 }
530
531 sub gdelay_messages(@) {
532 push @messages, @_;
533 }
534
535 sub grecv_get1msg_ifdata() {
536 my ($msg, @rest) = grecv();
537 push @messages, @rest;
538 return $msg;
539 }
540
541 sub grecv_get1msg {
542 eval {
543 local $SIG{ALRM} = sub { die "alarm\n" };
544 alarm 10;
545 while (!@messages) {
546 sleep($ping/1000/3);
547 @messages = grecv();
548 }
549 alarm 0;
550 };
551 if ($@) {
552 print STDERR "Sorry, we are not receiving the expected message. If the other ends are legal Frozen-Bubble\n" .
553 "clients, it means your computer or the network is too slow. Giving up.\n";
554 disconnect();
555 die 'quit';
556 } else {
557 return shift @messages;
558 }
559 }
560
561 1;
562
563 __END__
564
565 =encoding UTF-8
566
567 =head1 Frozen-Bubble
568
569 Copyright © 2004 Guillaume Cottenceau
570
571 This program is free software; you can redistribute it and/or modify
572 it under the terms of the GNU General Public License version 2, as
573 published by the Free Software Foundation.
574
575 This program is distributed in the hope that it will be useful,
576 but WITHOUT ANY WARRANTY; without even the implied warranty of
577 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
578 GNU General Public License for more details.
579
580 You should have received a copy of the GNU General Public License
581 along with this program; if not, write to the Free Software
582 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.