--- deliantra/server/ext/tcp.ext 2006/12/15 19:29:18 1.1 +++ deliantra/server/ext/tcp.ext 2012/10/30 17:32:47 1.22 @@ -1,31 +1,61 @@ -#! perl +#! perl # mandatory # this listens for new tcp connections and hands them over to the server core -# wether this being an extension introduces or reduces stability problems +# whether this being an extension introduces or reduces stability problems # is unknown as of today. use Socket; -use IO::Socket::INET; +use AnyEvent::Socket; -our $LISTEN = new IO::Socket::INET - LocalPort => cf::settings->csport, - Listen => 1, - ReuseAddr => 1; - -if (!$LISTEN) { - # extension yes, completely stupid, not yet - warn "unable to establish listen sockect, exiting.\n"; - exit (2); -} +CONF BIND_ADDRESSES = [[undef, 13327]]; + +our $MAX_DETECT = 16; # how many bytes to raed to identify the protocol + +our @LISTENERS; + +for (@$BIND_ADDRESSES) { + my ($host, $port) = @$_; + cf::info "listening on ", (format_hostport $host, $port), "\n"; + + push @LISTENERS, tcp_server $host, $port, sub { + my ($fh, $host, $port) = @_ + or return; + + my $lhost = AnyEvent::Socket::format_address + +(AnyEvent::Socket::unpack_sockaddr getsockname $fh)[1]; + + my $id = format_hostport $host, $port; -Event->io (fd => $LISTEN, poll => 'r', data => cf::WF_AUTOCANCEL, cb => sub { - my ($fh, $peername) = $LISTEN->accept - or return; + cf::info "$id: new connection\n" + if $lhost ne $host; # do not log connections from the host, e.g. for watchdogs - my $fd = fileno $fh; - my $host = inet_ntoa +(sockaddr_in $peername)[1]; + my $buf; + my $w; $w = AE::io $fh, 0, sub { + my $len = sysread $fh, $buf, 512, length $buf; - warn "new connection from $host\n"; + if ($len) { + if ($buf =~ /^..version /s) { # deliantra protocol + undef $w; + + my $ns = cf::client::create fileno $fh, $host; + $ns->inbuf_append ($buf); + + } elsif ($buf =~ /^GET / && defined &ext::http::server) { # http or websocket + undef $w; + + &ext::http::server ($id, $fh, $buf); + + } elsif (length $buf >= $MAX_DETECT) { # unable to detect protocol + undef $w; + + cf::info "$id: protocol detection error\n"; + } + } else { + undef $w; + + cf::info "$id: read error during protocol detection\n"; + } + }; + }; +} - cf::add_client_socket $fd, $host; -});