1#!/usr/bin/perl
2
3# Copyright (C) Internet Systems Consortium, Inc. ("ISC")
4#
5# SPDX-License-Identifier: MPL-2.0
6#
7# This Source Code Form is subject to the terms of the Mozilla Public
8# License, v. 2.0.  If a copy of the MPL was not distributed with this
9# file, you can obtain one at https://mozilla.org/MPL/2.0/.
10#
11# See the COPYRIGHT file distributed with this work for additional
12# information regarding copyright ownership.
13
14use IO::Socket;
15use IO::File;
16use strict;
17
18# Ignore SIGPIPE so we won't fail if peer closes a TCP socket early
19local $SIG{PIPE} = 'IGNORE';
20
21# Flush logged output after every line
22local $| = 1;
23
24my $server_addr = "10.53.0.4";
25if (@ARGV > 0) {
26	$server_addr = @ARGV[0];
27}
28
29my $localport = int($ENV{'PORT'});
30if (!$localport) { $localport = 5300; }
31
32my $udpsock = IO::Socket::INET->new(LocalAddr => "$server_addr",
33   LocalPort => $localport, Proto => "udp", Reuse => 1) or die "$!";
34my $tcpsock = IO::Socket::INET->new(LocalAddr => "$server_addr",
35   LocalPort => $localport, Proto => "tcp", Listen => 5, Reuse => 1) or die "$!";
36
37print "listening on $server_addr:$localport.\n";
38
39my $pidf = new IO::File "ans.pid", "w" or die "cannot open pid file: $!";
40print $pidf "$$\n" or die "cannot write pid file: $!";
41$pidf->close or die "cannot close pid file: $!";;
42sub rmpid { unlink "ans.pid"; exit 1; };
43
44$SIG{INT} = \&rmpid;
45$SIG{TERM} = \&rmpid;
46
47# Main
48for (;;) {
49	my $rin;
50	my $rout;
51
52	$rin = '';
53	vec($rin, fileno($udpsock), 1) = 1;
54	vec($rin, fileno($tcpsock), 1) = 1;
55
56	select($rout = $rin, undef, undef, undef);
57
58	if (vec($rout, fileno($udpsock), 1)) {
59		printf "UDP request\n";
60		my $buf;
61		$udpsock->recv($buf, 512);
62	} elsif (vec($rout, fileno($tcpsock), 1)) {
63		printf "TCP request\n";
64	}
65}
66