Debian Codegraph @

lib/Games/FrozenBubble/NetDiscover.pm

raw
1 package Games::FrozenBubble::NetDiscover;
2
3 use strict;
4 use warnings;
5 use IO::Socket;
6 use IO::Select;
7 use Time::HiRes qw(gettimeofday tv_interval);
8 use Carp;
9
10 use Games::FrozenBubble::Net;
11 my $proto_hdr = "FB/" . $Games::FrozenBubble::Net::proto_major . "." .$Games::FrozenBubble::Net::proto_minor;
12
13 # configuration parameters
14 my $number_of_pings = 2; # ping each server this many times
15 my $time_between_connections = 0.1; # 100ms, 10 connections per second
16 my $connection_timeout = 5;
17
18 # note: the ping-averaging code below assumes $number_of_pings >= 2.
19
20
21 sub new {
22 my ($package, @servers) = @_;
23 my $time = [gettimeofday];
24 # force the first connection immediately
25 $$time[0]--;
26 my $self = {
27 begin_time => $time, # used to sequence the connect()s
28 not_started => {}, # server entries move from here...
29 pending => {}, # ... to here ...
30 complete => {}, # ... to here.
31 revmapping => {}, # used after select(), to map handles to hashkeys
32 };
33 my $servid = 1;
34 foreach my $server (@servers) {
35 croak "server $server is not a hash reference" unless ref $server eq 'HASH';
36 croak "server has no 'host' field" unless exists $$server{host};
37 croak "server has no 'port' field" unless exists $$server{port};
38 $$server{pingtimes} = []; # we will average these results together
39 $$self{not_started}{$servid++} = $server;
40 }
41 return bless($self, $package);
42 }
43
44
45 sub found {
46 my $self = shift;
47 return values %{$$self{complete}};
48 }
49
50 sub pending {
51 my $self = shift;
52 return scalar(keys %{$$self{pending}})
53 + scalar(keys %{$$self{not_started}});
54 }
55
56 sub work {
57 my ($self, $timeout) = @_;
58 my $starttime = [gettimeofday];
59 # run through it once quickly, even if $timeout is 0.
60 do {
61 # try connect if not_started servers exist, and timestamp says its time
62 $self->try_connect()
63 if(scalar(keys %{$$self{not_started}})
64 && tv_interval($$self{begin_time}) >= $time_between_connections);
65
66 # do a select, to see who has connected, and who has sent data to us
67 my $select = IO::Select->new();
68 $select->add( map { $$_{sock} } (values %{$$self{pending}}));
69 my $thistime = $timeout - tv_interval($starttime);
70 $thistime = 0 if $thistime < 0;
71 my @ready = $select->can_read($thistime);
72 foreach my $sock (@ready) {
73 # the revmapping table maps stringified sockets to hash keys, so
74 # we don't have to do a search for it.
75 my $key = $$self{revmapping}{"$sock"};
76 $self->server_sm($key);
77 }
78 my @dead = $select->has_exception(0);
79 foreach my $sock (@dead) {
80 my $key = $$self{revmapping}{"$sock"};
81 $self->give_up_on($key, "Select exception");
82 }
83 } while(tv_interval($starttime) < $timeout);
84 # rip those which have connection timeout
85 foreach my $pending (keys %{$$self{pending}}) {
86 if (tv_interval($$self{pending}{$pending}{begin_time}) >= $connection_timeout
87 && !$$self{pending}{$pending}{name}) {
88 $self->give_up_on($pending, "Connection timeout (${connection_timeout}s)");
89 }
90 }
91 return $self->pending();
92 }
93
94 sub try_connect {
95 my $self = shift;
96 my @newkeys = sort keys %{$$self{not_started}};
97 croak "try_connect called, but everything is already connected!"
98 unless scalar @newkeys;
99 # just pull the first entry off the list
100 my $key = shift(@newkeys);
101 # move server entry from not_started hash to pending hash
102 my $ref = $$self{not_started}{$key};
103 $$self{pending}{$key} = $ref;
104 delete($$self{not_started}{$key});
105 my $sock = IO::Socket::INET->new(
106 PeerAddr => $$ref{host},
107 PeerPort => $$ref{port},
108 Proto => 'tcp',
109 Blocking => 0,
110 );
111 if(defined($sock)) {
112 $$ref{sock} = $sock;
113 $$self{revmapping}{"$sock"} = $key;
114 $$ref{begin_time} = $$self{begin_time} = [gettimeofday];
115 } else {
116 $self->give_up_on($key, "Could not create socket");
117 }
118 }
119
120 sub server_sm {
121 my ($self, $connid) = @_;
122 my $conn = $$self{pending}{$connid};
123 if(!defined($$conn{state})) {
124 # new connection!
125 $$conn{state} = 'connected';
126 $$conn{rxdata} = '';
127 return; # the first "PUSH" line might not arrive at the same moment as
128 # the connection. When it comes in, we'll will come back here.
129 } else {
130 # read some data.
131 my $newdata = '';
132 my $sock = $$conn{sock};
133 if (!defined($sock->recv($newdata, 1024, 0))) {
134 # an error occurred, give up
135 $self->give_up_on($connid, $!);
136 return;
137 }
138 $$conn{rxdata} .= $newdata;
139 }
140
141 my $index;
142 while(($index = index($$conn{rxdata}, "\n")) > -1) {
143 my $str = substr($$conn{rxdata}, 0, $index);
144 $$conn{rxdata} = substr($$conn{rxdata}, $index+1);
145
146 # strip off the protocol header.
147 if(substr($str, 0, length($proto_hdr)+1) eq "$proto_hdr ") {
148 $str = substr($str, length($proto_hdr) + 1);
149 } else {
150 # protocol mismatch, give up.
151 $self->give_up_on($connid, "Frozen-Bubble protocol mismatch");
152 }
153
154 if ($str =~ /^PUSH: SERVER_READY (.*) (.*)/) {
155 $$conn{name} = $1;
156 $$conn{language} = $2;
157 $$conn{sock}->send("$proto_hdr PING\n");
158 $$conn{ping_time} = [gettimeofday];
159 } elsif($str =~ /^PING: PONG/) {
160 # nothing to parse. take a time measurement, send another one if
161 # necessary.
162 my $reply_time = tv_interval($$conn{ping_time});
163 push(@{$$conn{pingtimes}}, tv_interval($$conn{ping_time}));
164 if(scalar @{$$conn{pingtimes}} >= $number_of_pings) {
165 $$conn{sock}->send("$proto_hdr LIST\n");
166 delete($$conn{ping_time});
167 } else {
168 $$conn{sock}->send("$proto_hdr PING\n");
169 $$conn{ping_time} = [gettimeofday];
170 }
171 } elsif($str =~ /LIST: (\S*) (\S*) free:(\d+) games:(\d+) playing:(\d+) at:(\S*)/) {
172 $$conn{freenicks} = $1;
173 $$conn{freegames} = $2;
174 $$conn{free} = $3;
175 $$conn{games} = $4;
176 $$conn{playing} = $5;
177 $$conn{geolocs} = $6;
178 # we're done, get out of here.
179 # move connection to "complete" list
180 delete($$self{pending}{$connid});
181 $$self{complete}{$connid} = $conn;
182 # clean up temporary stuff
183 delete($$conn{state});
184 delete($$conn{rxdata});
185 # disconnect from server
186 delete($$conn{sock});
187 # calculate average ping time from worst 2 pings
188 my @pingtimes = reverse sort @{$$conn{pingtimes}};
189 $pingtimes[0] += $pingtimes[1];
190 $$conn{ping} = $pingtimes[0] / 2;
191 $$conn{ping} = sprintf("%.1f", $$conn{ping} * 1000); # time in ms
192 return;
193 } else {
194 # drop the line, for now
195 }
196 }
197 }
198
199 sub give_up_on {
200 my ($self, $connid, $reason) = @_;
201 print STDERR "Problem with server $$self{pending}{$connid}{host}:$$self{pending}{$connid}{port}: $reason.\n";
202 $$self{pending}{$connid}{sock}->shutdown(2)
203 if defined $$self{pending}{$connid}{sock};
204 delete($$self{pending}{$connid});
205 }
206
207 1;
208
209 __END__
210
211 =encoding UTF-8
212
213 =head1 Frozen-Bubble
214
215 Copyright © 2010 The Frozen-Bubble Team
216
217 This program is free software; you can redistribute it and/or modify
218 it under the terms of the GNU General Public License version 2, as
219 published by the Free Software Foundation.
220
221 This program is distributed in the hope that it will be useful,
222 but WITHOUT ANY WARRANTY; without even the implied warranty of
223 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
224 GNU General Public License for more details.
225
226 You should have received a copy of the GNU General Public License
227 along with this program; if not, write to the Free Software
228 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
229
230 =head1 NAME
231
232 Games::FrozenBubble::NetDiscover - high performance server discovery plugin for frozen bubble
233
234 =head1 SYNOPSIS
235
236
237 my $discover = Games::FrozenBubble::NetDiscover->new(
238 { host => "1.2.3.4", port => 1511 },
239 { host => "5.6.7.8", port => 1512 }, ...);
240 while($discover->pending()) {
241 my @servers = $discover->found();
242 for(my $server = 0; $server < @servers; $server++) {
243 printf("%02i: ip %s ping %i\n",
244 $server, $servers[$server]{ip}, $servers[$server]{ping});
245 }
246 $discover->work(0.1); # sit in a select loop for 100ms
247
248 # update your screen, and all of that stuff, here.
249 }
250
251 =head1 DESCRIPTION
252
253 Games::FrozenBubble::NetDiscover checks a list of servers, finding their versions, ping times,
254 and number of current clients. It uses nonblocking IO and select, to
255 connect to multiple servers in parallel, thus reducing the total amount of
256 time elapsed. This, in turn, allows the user to begin playing frozen bubble
257 more quickly. :)
258
259 This module is designed to be called from a GUI loop. It has to spend sit in
260 a select loop for most of its life in order to get accurate ping times, but
261 it will return back to your loop at intervals you specify, so you can check
262 for keystrokes and refresh the screen and so forth.
263
264 In order to get consistent results on slow dialup links, this module will only
265 attempt to connect to one server per each 200ms. This means for 18 servers
266 that there are 3.4 seconds of extra guaranteed lag, but it also means packets
267 from multiple servers are less likely to bump into eachother in the queue, so
268 ping reply times will be more reliable.
269
270 In the source script, there are two configuration parameters: $number_of_pings
271 and $time_between_connections. These are set to 2 and 0.2, respectively.
272 These two parameters will determine the amount of bandwidth used, and the
273 amount of time taken before the user can select a server. Assuming the user's
274 internet connection can handle the traffic without extra latency from queueing
275 or retransmissions, the worst case latency will be, in seconds:
276
277 N*L + T*(S-1)
278
279 where
280
281 N = $number_of_pings
282 L = the roundtrip time of the slowest server in the list, in seconds
283 T = $time_between_connections
284 S = the number of servers in the list
285
286 =head1 CONSTRUCTOR
287
288 ...->new ({host => "server1", port => port}, {host => "server2", port => port}, ...)
289
290 Takes a list of servers as arguments. Each server argument should be a hash
291 reference, consisting of {host => host, port => port}. Returns a
292 Games::FrozenBubble::NetDiscover object, which can be used within a GUI loop to discover all of
293 your servers.
294
295 The host string should ideally be an IP address. A hostname string should work
296 too, but DNS lookups will introduce extra, unpredictable latency later on.
297
298 =head1 METHODS
299
300 These methods define the public API for instances of this class.
301
302 =head2 found
303
304 Returns a list of 0 or more servers found. Each return value is a hash
305 reference, containing the following keys:
306
307 host: the IP address of the server
308 port: the TCP port of the server
309 pingtimes: array reference, contains the actual result times of 4 pings
310 ping: the average roundtrip latency of the server, in ms
311 freenicks: the list of players connected
312 freegames: the list of open games (not yet started)
313 free: the number of idle clients connected to this server
314 games: the number of clients connected to this server, who are playing games
315 playing: the list of players in games
316 geolocs: the geolocations of players in games
317 name: the self-proclaimed "name" reported by the server
318 language: the preferred language reported by the server
319
320 =head2 pending
321
322 Returns non-zero if we are still waiting for a response from one or more
323 servers; returns 0 if processing is complete.
324
325 =head2 work(seconds)
326
327 Enters the main loop of this module. This method requires one argument, a
328 numeric count of seconds to work for. This is expected to be a floating point
329 decimal, for sub-second precision. Returns the number of servers pending, just
330 like the pending method does.
331
332 =head1 INTERNAL METHODS
333
334 These methods are only meant to be called from within the module. They are
335 subject to change without notice.
336
337 =head2 try_connect
338
339 Attempts to connect to a server. Moves the first "not_started" server to the
340 "pending" list, and creates a non-blocking IO::Socket::INET object for it.
341 Updates the begin_time timestamp, to determine when the next server should be
342 connected.
343
344 =head2 server_sm(connection_number)
345
346 Implements a simple state machine. Called with an index into the pending
347 array, to indicate that data is available for reading from this server.
348
349 =head2 give_up_on(connection_number, reason)
350
351 Called if select reports a socket as has_exception. Also called if the
352 server has a bogus version, times out, or we can't parse the IP address or
353 something. Removes the entry from further processing, and emits an error
354 message on stderr.
355
356 =head1 EXPORT
357
358 None.
359
360 =head1 BUGS
361
362 implement some sort of timeout, for servers which don't respond within 5 seconds.
363
364 =head1 AUTHOR
365
366 Mark Glines, <[email protected]>.
367
368 =head1 COPYRIGHT AND LICENSE
369
370 This code is donated to the frozen bubble project, www.frozen-bubble.org, so
371 they can do whatever they want with it. Copyright is therefore assigned to
372 those guys.