create log files, reattach existing session
[pxelator] / bin / tftpd.pl
1 #!/usr/bin/perl
2 use strict;
3 use lib 'lib';
4 use Net::TFTPd 0.03 qw(%OPCODES);
5
6 die "need to run $0 as root like this\nsudo $0\n" unless $< == 0;
7
8 our $tftp_dir;
9 sub tftp_dir {
10         require 'config.pl';
11         warn "# config: ", readlink 'config.pl', " tftp_dir: $tftp_dir\n";
12         return $tftp_dir;
13 }
14
15 tftp_dir;
16
17 die "no $tftp_dir\n" unless -e $tftp_dir;
18
19 # callback sub used to print transfer status
20 sub callback
21 {
22         my $req = shift;
23         if($req->{'_REQUEST_'}{'OPCODE'} eq $OPCODES{'RRQ'})
24         {
25                 # RRQ
26                 printf "block: %u\/%u\n", $req->{'_REQUEST_'}{'LASTACK'}, $req->{'_REQUEST_'}{'LASTBLK'};
27         }
28         elsif($req->{'_REQUEST_'}{'OPCODE'} eq $OPCODES{'WRQ'})
29         {
30                 # WRQ
31                 printf "block: %u\/%u\n", $req->{'_REQUEST_'}{'LASTBLK'}, $req->{'_REQUEST_'}{'LASTACK'};
32         } else {
33                 warn "IGNORED: ", dump( $req );
34         }
35 }
36
37 # create the listener
38 my $listener = Net::TFTPd->new(
39         'RootDir' => $tftp_dir,
40         'Writable' => 0,
41         'Timeout' => 3600, 
42         'CallBack' => \&callback,
43 #       LocalAddr => '10.0.0.100',
44 #       BlkSize => 8192,
45 #       BlkSize => 512,
46         BlkSize => 1456,        # IBM GE seems to be picky
47         Debug => 99,
48 ) or die Net::TFTPd->error;
49 printf "TFTP on %s:%d timeout: %d dir: $tftp_dir\n", $listener->{'LocalAddr'} ? $listener->{'LocalAddr'} : "'any address'",  $listener->{'LocalPort'}, $listener->{'Timeout'};
50
51 while(1) {
52
53         # wait for any request (RRQ or WRQ)
54         if(my $request = $listener->waitRQ()) {
55
56                 $tftp_dir = tftp_dir;
57
58                 if ( $request->{RootDir} ne $tftp_dir ) {
59                         $request->{RootDir} = $tftp_dir;
60                         warn "new root: $tftp_dir\n";
61                 }
62
63                 # received request
64                 printf "Received a %s for file '%s'\n", $OPCODES{$request->{'_REQUEST_'}{'OPCODE'}}, $request->{'_REQUEST_'}{'FileName'};
65
66                 # process the request
67                 if($request->processRQ()) {
68                         print "OK, transfer completed successfully\n";
69                 } else {
70                         warn Net::TFTPd->error;
71                         $request->processRQ();
72                 }
73         } else {
74                 # request not received (timed out waiting for request etc.)
75                 warn Net::TFTPd->error;
76         }
77
78 }