| 1 | # TFTP.pm | ||
| 2 | # | ||
| 3 | # Copyright (c) 1998 G. S. Marzot <gmarzot@baynetworks.com>. | ||
| 4 | # All rights reserved. | ||
| 5 | # This program is free software; you can redistribute it and/or | ||
| 6 | # modify it under the same terms as Perl itself. | ||
| 7 | # | ||
| 8 | |||
| 9 | package TFTP; | ||
| 10 | |||
| 11 | require 5.001; | ||
| 12 | |||
| 13 | use strict; | ||
| 14 | use vars qw(@ISA $VERSION); | ||
| 15 | |||
| 16 | use Socket 1.3; | ||
| 17 | use Time::localtime; | ||
| 18 | |||
| 19 | $VERSION = 1.00; | ||
| 20 | |||
| 21 | my $TftpPort = 69; | ||
| 22 | |||
| 23 | my $RRQ = 1; | ||
| 24 | my $WRQ = 2; | ||
| 25 | my $DATA = 3; | ||
| 26 | my $ACK = 4; | ||
| 27 | my $ERR = 5; | ||
| 28 | my @OPS = ('NA','RRQ','WRQ','DATA','ACK','ERR'); | ||
| 29 | |||
| 30 | my $ErrUndef = 0; | ||
| 31 | my $ErrFileNotFound = 1; | ||
| 32 | my $ErrAccessViolation = 2; | ||
| 33 | my $ErrDiskFull = 3; | ||
| 34 | my $ErrIllegalOperation = 4; | ||
| 35 | my $ErrUnknownPort = 5; | ||
| 36 | my $ErrFileExists = 6; | ||
| 37 | my $ErrNoSuchUser = 7; | ||
| 38 | |||
| 39 | my $ModeNetAscii = 'NETASCII'; | ||
| 40 | my $ModeOctet = 'OCTET'; | ||
| 41 | my $ModeMail = 'MAIL'; | ||
| 42 | my %decode = ("\012" => "\012", "\0" => "\015"); | ||
| 43 | my %encode = ("\012" => "\012", "\015" => "\0"); | ||
| 44 | |||
| 45 | my $TftpDataSize = 512; | ||
| 46 | my $TftpBufSize = $TftpDataSize + 4; | ||
| 47 | |||
| 48 | my $Timeout = 2; | ||
| 49 | my $MaxTimeout = 8; | ||
| 50 | my $Retries = 3; | ||
| 51 | |||
| 52 | sub new | ||
| 53 | { | ||
| 54 | my $pkg = shift; | ||
| 55 | my $peer = shift; | ||
| 56 | my %arg = @_; | ||
| 57 | my $tftp = {}; | ||
| 58 | |||
| 59 | socket(SOCKET, PF_INET, SOCK_DGRAM, getprotobyname('udp')) or | ||
| 60 | $tftp->{errstr} = "Could not create socket:$!\n", return undef; | ||
| 61 | $tftp->{'sock'} = \*SOCKET; | ||
| 62 | |||
| 63 | $tftp->{'host'} = $peer || 'localhost'; # Remote hostname | ||
| 64 | $tftp->{'port'} = $arg{Port} || $TftpPort; # Remote port | ||
| 65 | $tftp->{'mode'} = $arg{Mode} || $ModeNetAscii; | ||
| 66 | $tftp->{'timeout'} = $arg{Timeout} || $Timeout; | ||
| 67 | $tftp->{'max_timeout'} = $arg{MaxTimeout} || $MaxTimeout; | ||
| 68 | $tftp->{'retries'} = $arg{Retries} || $Retries; | ||
| 69 | $tftp->{'errstr'} = ''; | ||
| 70 | $tftp->{'debug'}= $arg{Debug}; | ||
| 71 | bless($tftp,$pkg); | ||
| 72 | } | ||
| 73 | |||
| 74 | sub DESTROY { shift->quit } | ||
| 75 | |||
| 76 | sub timeout | ||
| 77 | { | ||
| 78 | my $self = shift; | ||
| 79 | my $retry = shift; | ||
| 80 | my $timeout = $self->{'timeout'}; | ||
| 81 | |||
| 82 | $timeout *= ($retry+1); | ||
| 83 | return ($timeout > $MaxTimeout ? $MaxTimeout : $timeout); | ||
| 84 | } | ||
| 85 | |||
| 86 | ## | ||
| 87 | ## User interface methods | ||
| 88 | ## | ||
| 89 | |||
| 90 | sub netascii { shift->mode($ModeNetAscii); } | ||
| 91 | sub ascii { shift->mode($ModeNetAscii); } | ||
| 92 | sub octet { shift->mode($ModeOctet); } | ||
| 93 | sub binary { shift->mode($ModeOctet); } | ||
| 94 | |||
| 95 | sub mode | ||
| 96 | { | ||
| 97 | my $tftp = shift; | ||
| 98 | my $mode = shift; | ||
| 99 | my $oldval = $tftp->{'mode'}; | ||
| 100 | |||
| 101 | $tftp->{'mode'} = $mode if defined $mode; | ||
| 102 | |||
| 103 | $oldval; | ||
| 104 | } | ||
| 105 | |||
| 106 | sub get | ||
| 107 | { | ||
| 108 | my($tftp,$remote,$local) = @_; | ||
| 109 | my($loc,$inlen,$inbuf,$outlen,$outbuf,$data,$lastcr); | ||
| 110 | my($rin,$rout,$eout,$remote_iaddr,$remote_paddr,$last_paddr,$port,$host); | ||
| 111 | my($count, $op, $block, $expected_block, $retry, $err); | ||
| 112 | local *FD; | ||
| 113 | # setup and open local file if needed | ||
| 114 | if (ref($local)) { | ||
| 115 | $loc = $local; | ||
| 116 | } else { | ||
| 117 | ($local = $remote) =~ s!.*/!! unless defined $local; | ||
| 118 | unless (open(FD,">$local")) { | ||
| 119 | $tftp->{'errstr'} = "Cannot open local file:$local:$!\n"; | ||
| 120 | return undef; | ||
| 121 | } | ||
| 122 | $loc = \*FD; | ||
| 123 | } | ||
| 124 | # set binary mode if needed | ||
| 125 | my $mode = $tftp->mode; | ||
| 126 | if ($mode eq $ModeOctet and !binmode($loc)) { | ||
| 127 | $tftp->{'errstr'} = "Cannot binmode Local file $local:$!"; | ||
| 128 | goto GET_ERR; | ||
| 129 | } | ||
| 130 | # fetch socket check that socket is defined | ||
| 131 | my $sock = $tftp->{'sock'}; | ||
| 132 | unless (defined $sock) { | ||
| 133 | $tftp->{'errstr'}="Socket closed: cannot initiate transfer"; | ||
| 134 | goto GET_ERR; | ||
| 135 | } | ||
| 136 | # make request packet | ||
| 137 | my $flen = length($remote) + 1; | ||
| 138 | my $mlen = length($mode) + 1; | ||
| 139 | $outbuf = pack("na${flen}a${mlen}", $RRQ, $remote, $mode); | ||
| 140 | # set up destination addr | ||
| 141 | $remote_iaddr = inet_aton($tftp->{'host'}); | ||
| 142 | unless ($remote_iaddr) { $tftp->{'errstr'} = "Unknown host"; goto GET_ERR } | ||
| 143 | $remote_paddr = sockaddr_in($tftp->{'port'}, $remote_iaddr); | ||
| 144 | # send request packet | ||
| 145 | $outlen = send($sock, $outbuf, 0, $remote_paddr); | ||
| 146 | print STDERR "sent:$OPS[$RRQ]:$remote:$mode:$outlen\n" if $tftp->{'debug'}; | ||
| 147 | # prepare to wait for DATA | ||
| 148 | print STDERR "fileno($sock) = ", fileno($sock),"\n" if $tftp->{'debug'}; | ||
| 149 | vec($rin='', fileno($sock),1) = 1; | ||
| 150 | $inlen = 0; $block = 0; $expected_block = 1; $retry = 0; | ||
| 151 | while (1) { | ||
| 152 | # wait for packet, or exception, or timeout | ||
| 153 | $count = select($rout=$rin, undef, $eout=$rin, $tftp->timeout($retry)); | ||
| 154 | # abort after too many retries | ||
| 155 | $tftp->{'errstr'} = "Transfer timeout", last | ||
| 156 | if $retry >= $tftp->{'retries'}; | ||
| 157 | # retry if timeout or exception | ||
| 158 | $retry++, goto DO_GET_SEND | ||
| 159 | unless vec($rout,fileno($sock),1) and !vec($eout,fileno($sock),1); | ||
| 160 | # recieve incoming packet | ||
| 161 | print STDERR "trying recv:select returned $count:$!\n" if $tftp->{'debug'}; | ||
| 162 | $remote_paddr = recv($sock, $inbuf, $TftpBufSize,0); | ||
| 163 | # check source, ignore if not from original source address | ||
| 164 | ($port, $remote_iaddr) = sockaddr_in($remote_paddr); | ||
| 165 | next if $last_paddr and $last_paddr ne $remote_paddr; | ||
| 166 | $last_paddr ||= $remote_paddr; | ||
| 167 | ($op,$block,$data) = unpack("nna*",$inbuf); | ||
| 168 | $inlen = length($data); | ||
| 169 | if ($tftp->{'debug'}) { | ||
| 170 | $host = gethostbyaddr($remote_iaddr, AF_INET); | ||
| 171 | print STDERR "recvd:$host:$port:$OPS[$op]:$block:$inlen:$!\n"; | ||
| 172 | } | ||
| 173 | # check packet type | ||
| 174 | if ($op == $ERR) { $tftp->{'errstr'} = $data; last } # abort on ERR | ||
| 175 | next unless $op == $DATA; # ignore other non DATA packets | ||
| 176 | # check block number of responses | ||
| 177 | if ($block == $expected_block or $block == $expected_block-1) { | ||
| 178 | if ($mode eq $ModeNetAscii) { | ||
| 179 | # prepend cr from previous packet if there was one | ||
| 180 | substr($data,0,0) = $lastcr if $lastcr; | ||
| 181 | # decode cr lf => lf, cr nul => cr, and strip trailing cr | ||
| 182 | $data =~ s/\015([\012\0])(\015\Z(?!\n))?/$decode{$1}/sge; | ||
| 183 | # $data =~ s/\015([\012\0])(\015\Z(?!\n))?/($1?$1:\015)/sge; | ||
| 184 | # save trailing cr if there was one | ||
| 185 | $lastcr = $2; | ||
| 186 | } | ||
| 187 | # write data to output file | ||
| 188 | syswrite($loc,$data,length($data)) | ||
| 189 | if length($data) and $block == $expected_block; | ||
| 190 | # prepare to ACK | ||
| 191 | $outbuf = pack("nn",$ACK,$block); # ACK current block | ||
| 192 | $expected_block = $block + 1; # expect the next one | ||
| 193 | $retry = 0; # we are back on track sending good new ACKs | ||
| 194 | DO_GET_SEND: | ||
| 195 | # (re)send pending ACK (or RRQ) | ||
| 196 | $outlen = send($sock, $outbuf, 0, $remote_paddr); | ||
| 197 | print STDERR "sent:",$OPS[unpack("n",$outbuf)],":$block:$outlen:$!\n" if $tftp->{'debug'}; | ||
| 198 | } else { | ||
| 199 | $tftp->{'errstr'} = "Bad block:$block:expected:$expected_block"; | ||
| 200 | last; | ||
| 201 | } | ||
| 202 | # done if not-first packet and packet size less than expected | ||
| 203 | last if $inlen < $TftpDataSize and $block; | ||
| 204 | } # while | ||
| 205 | GET_ERR: | ||
| 206 | close($loc) unless ref($local); # close file unless filhandle passed in | ||
| 207 | unlink($local) if $tftp->{'errstr'} and !ref($local); # delete file if err | ||
| 208 | return ($tftp->{'errstr'} ? undef : $local); | ||
| 209 | } | ||
| 210 | |||
| 211 | sub put | ||
| 212 | { | ||
| 213 | my($tftp,$local,$remote) = @_; | ||
| 214 | my($loc,$inlen,$inbuf,$outlen,$outbuf,$localfd,$data,$c,$nextc); | ||
| 215 | my($rin,$rout,$eout,$remote_iaddr,$remote_paddr,$last_paddr,$port,$host); | ||
| 216 | my($op,$block,$expected_block,$retry,$count,$err); | ||
| 217 | local *FD; | ||
| 218 | |||
| 219 | # setup and open local file if needed | ||
| 220 | if (ref($local)) { | ||
| 221 | $loc = $local; | ||
| 222 | } else { | ||
| 223 | ($remote = $local) =~ s!.*/!! unless defined $remote; | ||
| 224 | unless (open(FD,"<$local")) { | ||
| 225 | $tftp->{'errstr'} = "Cannot open local file:$local:$!\n"; | ||
| 226 | return undef; | ||
| 227 | } | ||
| 228 | $loc = \*FD; | ||
| 229 | } | ||
| 230 | # set binary mode if needed | ||
| 231 | my $mode = $tftp->mode; | ||
| 232 | if ($mode eq $ModeOctet and !binmode($loc)) { | ||
| 233 | $tftp->{'errstr'} = "Cannot binmode Local file $local:$!"; | ||
| 234 | goto PUT_ERR; | ||
| 235 | } | ||
| 236 | # fetch socket check that socket is defined | ||
| 237 | my $sock = $tftp->{'sock'}; | ||
| 238 | unless (defined $sock) { | ||
| 239 | $tftp->{'errstr'}="Socket closed: cannot initiate transfer"; | ||
| 240 | goto PUT_ERR; | ||
| 241 | } | ||
| 242 | # make request packet | ||
| 243 | my $flen = length($remote) + 1; | ||
| 244 | my $mlen = length($mode) + 1; | ||
| 245 | $outbuf = pack("na${flen}a${mlen}", $WRQ, $remote, $mode); | ||
| 246 | # set up destination addr | ||
| 247 | $remote_iaddr = inet_aton($tftp->{'host'}); | ||
| 248 | unless ($remote_iaddr) { $tftp->{'errstr'} = "Unknown host";goto PUT_ERR; } | ||
| 249 | $remote_paddr = sockaddr_in($tftp->{'port'}, $remote_iaddr); | ||
| 250 | # send request packet | ||
| 251 | $outlen = send($sock, $outbuf, 0, $remote_paddr); | ||
| 252 | print STDERR "sent:$OPS[$WRQ]:$remote:$mode:$outlen:$!\n" if $tftp->{'debug'}; | ||
| 253 | # prepare to wait for ACK | ||
| 254 | vec($rin='', fileno($sock), 1) = 1; | ||
| 255 | $inlen = 0; $block = 0; $expected_block = 0; $retry = 0; | ||
| 256 | while (1) { | ||
| 257 | # wait for packet, or exception, or timeout | ||
| 258 | $count = select($rout=$rin, undef, $eout=$rin, $tftp->timeout($retry)); | ||
| 259 | # abort after too many retries | ||
| 260 | $tftp->{'errstr'} = "Transfer timeout", last | ||
| 261 | if $retry >= $tftp->{'retries'}; | ||
| 262 | # retry if timeout or exception | ||
| 263 | $retry++, goto DO_PUT_SEND | ||
| 264 | unless vec($rout,fileno($sock),1) and !vec($eout,fileno($sock),1); | ||
| 265 | # recieve incoming packet | ||
| 266 | print STDERR "trying recv:select returned $count:$!\n" if $tftp->{'debug'}; | ||
| 267 | $remote_paddr = recv($sock, $inbuf, $TftpBufSize,0); | ||
| 268 | # check source, ignore if not from original source address | ||
| 269 | ($port, $remote_iaddr) = sockaddr_in($remote_paddr); | ||
| 270 | next if $last_paddr and $last_paddr ne $remote_paddr; | ||
| 271 | $last_paddr ||= $remote_paddr; | ||
| 272 | ($op,$block,$data) = unpack("nna*",$inbuf); | ||
| 273 | $inlen = length($data); | ||
| 274 | if ($tftp->{'debug'}) { | ||
| 275 | $host = gethostbyaddr($remote_iaddr, AF_INET); | ||
| 276 | print STDERR "recvd:$host:$port:$OPS[$op]:$block:$inlen:$!\n"; | ||
| 277 | } | ||
| 278 | if ($op == $ERR) { $tftp->{'errstr'} = $data; last } # abort on ERR | ||
| 279 | next unless $op == $ACK; # ignore other non ACK packets | ||
| 280 | if ($block == $expected_block) { | ||
| 281 | # done if not-first packet and packet size less than expected | ||
| 282 | last if $outlen < $TftpBufSize and $block; | ||
| 283 | # prepare to send DATA | ||
| 284 | if ($mode eq $ModeNetAscii) { | ||
| 285 | for ($outlen = 0; $outlen < $TftpDataSize; $outlen++) { | ||
| 286 | $data .= $nextc, undef($nextc), next if defined $nextc; | ||
| 287 | last unless $c = getc($loc); | ||
| 288 | $c = "\015" if defined($nextc = $encode{$c}); | ||
| 289 | $data .= $c; | ||
| 290 | } | ||
| 291 | } else { | ||
| 292 | $outlen = sysread($loc,$data,$TftpDataSize); | ||
| 293 | } | ||
| 294 | $expected_block = $block + 1; | ||
| 295 | $outbuf = pack("nna${outlen}",$DATA,$expected_block,$data); | ||
| 296 | $retry = 0; # we are back on track sending good new DATA | ||
| 297 | DO_PUT_SEND: | ||
| 298 | # (re)send pending DATA (or WRQ) | ||
| 299 | $outlen = send($sock, $outbuf, 0, $remote_paddr); | ||
| 300 | print STDERR "sent:",$OPS[unpack("n",$outbuf)],":$expected_block:$outlen\n" if $tftp->{'debug'}; | ||
| 301 | } elsif ($block == $expected_block - 1) { | ||
| 302 | print STDERR "duplicate ACK:$block\n" if $tftp->{'debug'}; | ||
| 303 | next; # ignore duplicate ACK to avoid "sorcerer's apprentice" | ||
| 304 | } else { | ||
| 305 | print STDERR "bad block:expected block:$expected_block\n" if $tftp->{'debug'}; | ||
| 306 | $tftp->{'errstr'} = "Bad block:$block:expected:$expected_block"; | ||
| 307 | last; | ||
| 308 | } | ||
| 309 | } # while | ||
| 310 | PUT_ERR: | ||
| 311 | close($loc) unless ref($local); # close file if ours | ||
| 312 | return ($tftp->{'errstr'} ? undef : $local); | ||
| 313 | } | ||
| 314 | |||
| 315 | sub quit | ||
| 316 | { | ||
| 317 | my $tftp = shift; | ||
| 318 | |||
| 319 | close($tftp->{'sock'}); | ||
| 320 | delete $tftp->{'sock'}; | ||
| 321 | } | ||
| 322 | |||
| 323 | 1; | ||
| 324 | |||
| 325 | __END__ |