aboutsummaryrefslogtreecommitdiff
path: root/lib/MasterServer/UDP/BeaconCatcher.pm
blob: b3d2c187ca76dc5ddc05307ee68327ed3ad79562 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67

package MasterServer::UDP::BeaconCatcher;

use strict;
use warnings;
use AnyEvent::Handle::UDP;
use Socket qw(sockaddr_in inet_ntoa);
use Exporter 'import';

our @EXPORT = qw| beacon_catcher on_beacon_receive|;

##
## Receive UDP beacons according the \heartbeat\7778\gamename\ut\ format 
## where "ut" depicts the game and 7778 the query port of the game.
sub beacon_catcher {
  my $self = shift;
  
  # module startup log
  $self->log("load","Loading UDP Beacon Catcher.");
  
  # UDP server
  my $udp_server; 
     $udp_server = AnyEvent::Handle::UDP->new(
  
    # Bind to this host and use the port specified in the config file
    bind => ['0.0.0.0', $self->{beacon_port}],
  
    # when datagrams are received
    on_recv => sub {$self->on_beacon_receive(@_)},
  );
  
  # display that the server is up and listening for beacons
  $self->log("info", "Listening for UT Beacons on port $self->{beacon_port}.");
  
  # allow object to exist beyond this scope. Objects have ambitions too.
  return $udp_server;
}

## process (new) beacons
sub on_beacon_receive {
  # $self, beacon address, handle, packed client address
  my ($self, $b, $udp, $pa) = @_; 

  # unpack ip from packed client address
  my ($port, $iaddr) = sockaddr_in($pa);
  my $peer_addr      = inet_ntoa($iaddr);
  
  # if the beacon has a length longer than a certain amount, assume it is
  # a fraud or crash attempt
  if (length $b > 64) {
    # log
    $self->log("attack","length exceeded in beacon: $peer_addr:$port sent $b");
    
    # truncate and try to continue
    $b = substr $b, 0, 64;
  }
  
  # if a heartbeat format was detected...
  $self->process_udp_beacon($udp, $pa, $b, $peer_addr, $port) 
    if ($b =~ m/\\heartbeat\\/ && $b =~ m/\\gamename\\/);
  
  # or if this is a secure response, verify the response code and add mark it verified
  $self->process_udp_validate($b, $peer_addr, $port, undef) 
    if ($b =~ m/\\validate\\/);
}

1;