/usr/share/perl5/Net/TFTPd.pm is in libnet-tftpd-perl 0.10-1.
This file is owned by root:root, with mode 0o644.
The actual contents of the file can be viewed below.
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 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 | package Net::TFTPd;
use 5.006;
use Carp;
use strict;
use warnings;
# modified by M.Vincent for IPv6 support
use Socket qw(AF_INET SO_ERROR);
my $AF_INET6 = eval { Socket::AF_INET6() };
my $HAVE_IO_Socket_IP = 0;
eval "use IO::Socket::IP -register";
if (!$@)
{
$HAVE_IO_Socket_IP = 1;
}
else
{
eval "use IO::Socket::INET";
}
require Exporter;
# modified for supporting small block sizes, O.Z. 15.08.2007
use constant TFTP_MIN_BLKSIZE => 8;
use constant TFTP_DEFAULT_BLKSIZE => 512;
use constant TFTP_MAX_BLKSIZE => 65464;
use constant TFTP_MIN_TIMEOUT => 1;
use constant TFTP_MAX_TIMEOUT => 60;
use constant TFTP_DEFAULT_PORT => 69;
use constant TFTP_OPCODE_RRQ => 1;
use constant TFTP_OPCODE_WRQ => 2;
use constant TFTP_OPCODE_DATA => 3;
use constant TFTP_OPCODE_ACK => 4;
use constant TFTP_OPCODE_ERROR => 5;
use constant TFTP_OPCODE_OACK => 6;
# Type Op # Format without header
#
# 2 bytes string 1 byte string 1 byte
# -------------------------------------------------
# RRQ/ | 01/02 | Filename | 0 | Mode | 0 |
# WRQ -------------------------------------------------
# 2 bytes 2 bytes n bytes
# -----------------------------------
# DATA | 03 | Block # | Data |
# -----------------------------------
# 2 bytes 2 bytes
# ----------------------
# ACK | 04 | Block # |
# ----------------------
# 2 bytes 2 bytes string 1 byte
# ------------------------------------------
# ERROR | 05 | ErrorCode | ErrMsg | 0 |
# ------------------------------------------
our %OPCODES = (
1 => 'RRQ',
2 => 'WRQ',
3 => 'DATA',
4 => 'ACK',
5 => 'ERROR',
6 => 'OACK',
'RRQ' => TFTP_OPCODE_RRQ,
'WRQ' => TFTP_OPCODE_WRQ,
'DATA' => TFTP_OPCODE_DATA,
'ACK' => TFTP_OPCODE_ACK,
'ERROR' => TFTP_OPCODE_ERROR,
'OACK' => TFTP_OPCODE_OACK
);
my %ERRORS = (
0 => 'Not defined, see error message (if any)',
1 => 'File not found',
2 => 'Access violation',
3 => 'Disk full or allocation exceeded',
4 => 'Illegal TFTP operation',
5 => 'Unknown transfer ID',
6 => 'File already exists',
7 => 'No such user',
8 => 'Option negotiation'
);
our @ISA = qw(Exporter);
# Items to export into callers namespace by default. Note: do not export
# names by default without a very good reason. Use EXPORT_OK instead.
# Do not simply export all your public functions/methods/constants.
# This allows declaration use Net::TFTPd ':all';
# If you do not need this, moving things directly into @EXPORT or @EXPORT_OK
# will save memory.
our %EXPORT_TAGS = (
'all' => [ qw( %OPCODES ) ]
);
our @EXPORT_OK = ( @{ $EXPORT_TAGS{'all'} } );
our @EXPORT = qw( );
our $VERSION = '0.10';
our $LASTERROR;
my $debug;
#
# Usage: $tftpdOBJ = Net::TFTPd->new( ['RootDir' => 'path/to/files' | 'FileName' => 'path/to/file'] );
# return the tftpdOBJ object if success or undef if error
#
sub new
{
# create the future TFTPd object
my $self = shift;
my $class = ref($self) || $self;
# read parameters
my %cfg = @_;
# setting defaults
$cfg{'FileName'} or $cfg{'RootDir'} or croak "Usage: \$tftpdOBJ = Net::TFTPd->new(['RootDir' => 'path/to/files' | 'FileName' => 'path/to/file'] [, [ LocalPort => portnum ] [, ...]] );";
if ($cfg{'RootDir'} and not -d($cfg{'RootDir'}) )
{
$LASTERROR = sprintf 'RootDir \'%s\' not found or is not a valid directory name\n', $cfg{'RootDir'};
return (undef);
}
if ($cfg{'FileName'} and not -e($cfg{'FileName'}) )
{
$LASTERROR = sprintf 'FileName \'%s\' not found or is not a valid filename\n', $cfg{'FileName'};
return (undef);
}
my %params = (
'Proto' => 'udp',
'LocalPort' => $cfg{'LocalPort'} || TFTP_DEFAULT_PORT
);
# modified by M.Vincent for IPv6 support
if (defined($cfg{'Family'}))
{
if ($cfg{'Family'} =~ /^(?:(?:(:?ip)?v?(?:4|6))|${\AF_INET}|$AF_INET6)$/)
{
if ($cfg{'Family'} =~ /^(?:(?:(:?ip)?v?4)|${\AF_INET})$/)
{
$params{'Family'} = AF_INET;
}
else
{
if (!$HAVE_IO_Socket_IP)
{
$LASTERROR = "IO::Socket::IP required for IPv6";
return (undef);
}
$params{'Family'} = $AF_INET6;
if ($^O ne 'MSWin32') {
$params{'V6Only'} = 1;
}
}
}
else
{
$LASTERROR = "Invalid family - $cfg{'Family'}";
return (undef);
}
}
else
{
$params{'Family'} = AF_INET;
}
if (defined($cfg{'V6Only'}))
{
if (!$HAVE_IO_Socket_IP)
{
$LASTERROR = "IO::Socket::IP required for V6Only";
return (undef);
}
$params{'V6Only'} = $cfg{'V6Only'};
}
# bind only to specified address
if ($cfg{'LocalAddr'})
{
$params{'LocalAddr'} = $cfg{'LocalAddr'};
}
if ($HAVE_IO_Socket_IP)
{
if (my $udpserver = IO::Socket::IP->new(%params))
{
return bless {
'LocalPort' => TFTP_DEFAULT_PORT,
'Timeout' => 10,
'ACKtimeout' => 4,
'ACKretries' => 4,
'Readable' => 1,
'Writable' => 0,
'CallBack' => undef,
'BlkSize' => TFTP_DEFAULT_BLKSIZE,
'Debug' => 0,
%cfg, # merge user parameters
'_UDPSERVER_' => $udpserver
}, $class;
}
else
{
$LASTERROR = "Error opening socket for listener: $@\n";
return (undef);
}
}
else
{
if (my $udpserver = IO::Socket::INET->new(%params))
{
return bless {
'LocalPort' => TFTP_DEFAULT_PORT,
'Timeout' => 10,
'ACKtimeout' => 4,
'ACKretries' => 4,
'Readable' => 1,
'Writable' => 0,
'CallBack' => undef,
'BlkSize' => TFTP_DEFAULT_BLKSIZE,
'Debug' => 0,
%cfg, # merge user parameters
'_UDPSERVER_' => $udpserver
}, $class;
}
else
{
$LASTERROR = "Error opening socket for listener: $@\n";
return (undef);
}
}
}
#
# Usage: $tftpdOBJ->waitRQ($timeout);
# return requestOBJ if success, 0 if $timeout elapsed, undef if error
#
sub waitRQ
{
# the tftpd object
# my $tftpd = shift;
my $self = shift;
my $class = ref($self) || $self;
# return bless {}, $class;
# clone the object
my $request;
foreach my $key (keys(%{$self}))
{
# everything but '_xxx_'
$key =~ /^\_.+\_$/ and next;
$request->{$key} = $self->{$key};
}
# use $timeout or default from $tftpdOBJ
my $Timeout = shift || $request->{'Timeout'};
my $udpserver = $self->{'_UDPSERVER_'};
my ($datagram, $opcode, $datain);
# vars for IO select
my ($rin, $rout, $ein, $eout) = ('', '', '', '');
vec($rin, fileno($udpserver), 1) = 1;
# check if a message is waiting
if (select($rout=$rin, undef, $eout=$ein, $Timeout))
{
# read the message
if ($udpserver->recv($datagram, TFTP_MAX_BLKSIZE + 4))
{
# decode the message
($opcode, $datain) = unpack("na*", $datagram);
$request->{'_REQUEST_'}{'OPCODE'} = $opcode;
# get peer port and address
$request->{'_REQUEST_'}{'PeerPort'} = $udpserver->peerport;
$request->{'_REQUEST_'}{'PeerAddr'} = $udpserver->peerhost;
# get filename and transfer mode
my @datain = split("\0", $datain);
$request->{'_REQUEST_'}{'FileName'} = shift(@datain);
$request->{'_REQUEST_'}{'Mode'} = uc(shift(@datain));
$request->{'_REQUEST_'}{'BlkSize'} = TFTP_DEFAULT_BLKSIZE;
$request->{'_REQUEST_'}{'LASTACK'} = 0;
$request->{'_REQUEST_'}{'PREVACK'} = -1;
# counter for transferred bytes
$request->{'_REQUEST_'}{'TotalBytes'} = 0;
if (scalar(@datain) >= 2)
{
$request->{'_REQUEST_'}{'RFC2347'} = { @datain };
}
return bless $request, $class;
}
else
{
$! = $udpserver->sockopt(SO_ERROR);
$LASTERROR = sprintf "Socket RECV error: %s\n", $!;
return (undef);
}
}
else
{
$LASTERROR = "Timed out waiting for RRQ/WRQ";
return (0);
}
}
#
# Usage: $requestOBJ->processRQ();
# return 1 if success, undef if error
#
sub processRQ
{
# the request object
my $self = shift;
if (defined($self->newSOCK()))
{
# modified for supporting NETASCII transfers on 25/05/2009
if (($self->{'_REQUEST_'}{'Mode'} ne 'OCTET') && ($self->{'_REQUEST_'}{'Mode'} ne 'NETASCII'))
{
#request is not OCTET
$LASTERROR = sprintf "%s transfer mode is not supported\n", $self->{'_REQUEST_'}{'Mode'};
$self->sendERR(0, $LASTERROR);
return (undef);
}
# new socket opened successfully
if ($self->{'_REQUEST_'}{'OPCODE'} eq TFTP_OPCODE_RRQ)
{
#################
# opcode is RRQ #
#################
if ($self->{'Readable'})
{
# read is permitted
if ($self->{'_REQUEST_'}{'FileName'} =~ /\.\.[\\\/]/)
{
# requested file contains '..\' or '../'
$LASTERROR = sprintf 'Access to \'%s\' is not permitted to %s', $self->{'_REQUEST_'}{'FileName'}, $self->{'_REQUEST_'}{'PeerAddr'};
$self->sendERR(2);
return (undef);
}
if (defined($self->checkFILE()))
{
# file is present
if (defined($self->negotiateOPTS()))
{
# RFC 2347 options negotiated
if (defined($self->openFILE()))
{
# file opened for read, start the transfer
if (defined($self->sendFILE()))
{
# file sent successfully
return (1);
}
else
{
# error sending file
return (undef);
}
}
else
{
# error opening file
return (undef);
}
}
else
{
# error negotiating options
$LASTERROR = "TFTP error 8: Option negotiation\n";
$self->sendERR(8);
return (undef);
}
}
else
{
# file not found
$LASTERROR = sprintf 'File \'%s\' not found', $self->{'_REQUEST_'}{'FileName'};
$self->sendERR(1);
return (undef);
}
}
else
{
# if server is not readable
$LASTERROR = "TFTP Error: Access violation";
$self->sendERR(2);
return (undef);
}
}
elsif ($self->{'_REQUEST_'}{'OPCODE'} eq TFTP_OPCODE_WRQ)
{
#################
# opcode is WRQ #
#################
if ($self->{'Writable'})
{
# write is permitted
if ($self->{'_REQUEST_'}{'FileName'} =~ /\.\.[\\\/]/)
{
# requested file contains '..\' or '../'
$LASTERROR = sprintf 'Access to \'%s\' is not permitted to %s', $self->{'_REQUEST_'}{'FileName'}, $self->{'_REQUEST_'}{'PeerAddr'};
$self->sendERR(2);
return (undef);
}
if (!defined($self->checkFILE()))
{
# RFC 2347 options negotiated
if (defined($self->openFILE()))
{
# file is not present
if (defined($self->negotiateOPTS()))
{
# file opened for write, start the transfer
if (defined($self->recvFILE()))
{
# file received successfully
return (1);
}
else
{
# error receiving file
return (undef);
}
}
else
{
# error negotiating options
$LASTERROR = "TFTP error 8: Option negotiation\n";
$self->sendERR(8);
return (undef);
}
}
else
{
# error opening file
$self->sendERR(3);
return (undef);
}
}
else
{
# file not found
$LASTERROR = sprintf 'File \'%s\' already exists', $self->{'_REQUEST_'}{'FileName'};
$self->sendERR(6);
return (undef);
}
}
else
{
# if server is not writable
$LASTERROR = "TFTP Error: Access violation";
$self->sendERR(2);
return (undef);
}
}
else
{
#################
# other opcodes #
#################
$LASTERROR = sprintf "Opcode %d not supported as request", $self->{'_REQUEST_'}{'OPCODE'};
$self->sendERR(4);
return (undef);
}
}
else
{
return (undef);
}
}
#
# Usage: $requestOBJ->getTotalBytes();
# returns the number of bytes transferred by the request
#
sub getTotalBytes
{
# the request object
my $self = shift;
return $self->{'_REQUEST_'}{'TotalBytes'};
}
#
# Usage: $requestOBJ->getFileName();
# returns the requested file name
#
sub getFileName
{
# the request object
my $self = shift;
return $self->{'_REQUEST_'}{'FileName'};
}
#
# Usage: $requestOBJ->getMode();
# returns the transfer mode for the request
#
sub getMode
{
# the request object
my $self = shift;
return $self->{'_REQUEST_'}{'Mode'};
}
#
# Usage: $requestOBJ->getPeerAddr();
# returns the address of the requesting client
#
sub getPeerAddr
{
# the request object
my $self = shift;
return $self->{'_REQUEST_'}{'PeerAddr'};
}
#
# Usage: $requestOBJ->getPeerPort();
# returns the port of the requesting client
#
sub getPeerPort
{
# the request object
my $self = shift;
return $self->{'_REQUEST_'}{'PeerPort'};
}
#
# Usage: $requestOBJ->getBlkSize();
# returns the block size used for the transfer
#
sub getBlkSize
{
# the request object
my $self = shift;
return $self->{'_REQUEST_'}{'BlkSize'};
}
#
# Usage: $requestOBJ->newSOCK();
# return 1 if success or undef if error
#
sub newSOCK
{
# the request object
my $self = shift;
# set parameters for the new socket
my %params = (
'Proto' => 'udp',
'PeerPort' => $self->{'_REQUEST_'}{'PeerPort'},
'PeerAddr' => $self->{'_REQUEST_'}{'PeerAddr'}
);
# bind only to specified address
if ($self->{'Address'})
{
$params{'LocalAddr'} = $self->{'Address'};
}
# open socket
if ($HAVE_IO_Socket_IP)
{
if (my $udpserver = IO::Socket::IP->new(%params))
{
$self->{'_UDPSERVER_'} = $udpserver;
return (1);
}
else
{
$LASTERROR = "Error opening socket for reply: $@\n";
return (undef);
}
}
else
{
if (my $udpserver = IO::Socket::INET->new(%params))
{
$self->{'_UDPSERVER_'} = $udpserver;
return (1);
}
else
{
$LASTERROR = "Error opening socket for reply: $@\n";
return (undef);
}
}
}
#
# Usage: $requestOBJ->negotiateOPTS();
# return 1 if success or undef if error
#
sub negotiateOPTS
{
# the request object
my $self = shift;
if ($self->{'_REQUEST_'}{'RFC2347'})
{
# parse RFC 2347 options if present
foreach my $option (keys(%{ $self->{'_REQUEST_'}{'RFC2347'} }))
{
if (uc($option) eq 'BLKSIZE')
{
# Negotiate the blocksize
if ($self->{'_REQUEST_'}{'RFC2347'}{$option} > TFTP_MAX_BLKSIZE or $self->{'_REQUEST_'}{'RFC2347'}{$option} < TFTP_MIN_BLKSIZE)
{
$self->{'_REQUEST_'}{'RFC2347'}{$option} = $self->{'BlkSize'};
}
else
{
$self->{'_RESPONSE_'}{'RFC2347'}{$option} = $self->{'_REQUEST_'}{'RFC2347'}{$option};
$self->{'BlkSize'} = $self->{'_RESPONSE_'}{'RFC2347'}{$option};
}
}
elsif (uc($option) eq 'TSIZE')
{
# Negotiate the transfer size
if ($self->{'_REQUEST_'}{'OPCODE'} eq TFTP_OPCODE_RRQ)
{
$self->{'_RESPONSE_'}{'RFC2347'}{$option} = $self->{'FileSize'};
}
else
{
$self->{'FileSize'} = $self->{'_REQUEST_'}{'RFC2347'}{$option};
}
}
elsif (uc($option) eq 'TIMEOUT')
{
# Negotiate the transfer timeout
if ($self->{'_REQUEST_'}{'RFC2347'}{$option} > TFTP_MAX_TIMEOUT or $self->{'_REQUEST_'}{'RFC2347'}{$option} < TFTP_MIN_TIMEOUT)
{
$self->{'_RESPONSE_'}{'RFC2347'}{$option} = $self->{'ACKtimeout'};
}
else
{
$self->{'_RESPONSE_'}{'RFC2347'}{$option} = $self->{'_REQUEST_'}{'RFC2347'}{$option};
$self->{'ACKtimeout'} = $self->{'_REQUEST_'}{'RFC2347'}{$option};
}
}
else
{
# Negotiate other options...
}
}
# post processing
if ($self->{'_REQUEST_'}{'OPCODE'} eq TFTP_OPCODE_WRQ)
{
if ($self->{'FileSize'} and $self->{'BlkSize'})
{
$self->{'_REQUEST_'}{'LASTACK'} = int($self->{'FileSize'} / $self->{'BlkSize'}) + 1;
}
}
# send OACK for RFC 2347 options
return ($self->sendOACK());
}
else
{
if ($self->{'_REQUEST_'}{'OPCODE'} eq TFTP_OPCODE_WRQ)
{
# opcode is WRQ: send ACK for datablock 0
if ($self->{'_UDPSERVER_'}->send(pack("nn", TFTP_OPCODE_ACK, 0)))
{
return (1);
}
else
{
$! = $self->{'_UDPSERVER_'}->sockopt(SO_ERROR);
$LASTERROR = sprintf "Socket SEND error: %s\n", $!;
return (undef);
}
}
else
{
return (1);
}
}
}
#
# Usage: $requestOBJ->readFILE(\$data);
# return number of bytes read from file if success or undef if error
#
sub readFILE
{
my $self = shift;
my $datablk = shift;
if ($self->{'_REQUEST_'}{'PREVACK'} < $self->{'_REQUEST_'}{'LASTACK'})
{
# if requested block is next block, read next block and return bytes read
my $fh = $self->{'_REQUEST_'}{'_FH_'};
# modified for supporting NETASCII transfers on 25/05/2009
# my $bytes = read ($fh, $$datablk, $self->{'BlkSize'});
my $bytes = sysread($fh, $$datablk, $self->{'BlkSize'});
if (defined($bytes))
{
return ($bytes);
}
else
{
$LASTERROR = sprintf "Error $! reading file '%s'", $self->{'_REQUEST_'}{'FileName'};
return (undef);
}
}
else
{
# if requested block is last block, return length of last block
return (length($$datablk));
}
}
#
# Usage: $requestOBJ->writeFILE(\$data);
# return number of bytes written to file if success or undef if error
#
sub writeFILE
{
my $self = shift;
my $datablk = shift;
if ($self->{'_REQUEST_'}{'PREVBLK'} > $self->{'_REQUEST_'}{'LASTBLK'})
{
# if last block is < than previous block, return length of last block
return (length($$datablk));
}
elsif ($self->{'_REQUEST_'}{'LASTBLK'} eq ($self->{'_REQUEST_'}{'PREVBLK'} + 1))
{
# if block is next block, write next block and return bytes written
my $fh = $self->{'_REQUEST_'}{'_FH_'};
my $bytes = syswrite($fh, $$datablk);
return ($bytes);
}
else
{
$LASTERROR = sprintf "TFTP Error DATA block %d is out of sequence, expected block was %d", $self->{'_REQUEST_'}{'LASTBLK'}, $self->{'_REQUEST_'}{'PREVBLK'} + 1;
$self->sendERR(5);
return (undef);
}
}
#
# Usage: $requestOBJ->sendFILE();
# return 1 if success or undef if error
#
sub sendFILE
{
my $self = shift;
while (1)
{
if ($self->{'_REQUEST_'}{'LASTACK'} < $self->{'_REQUEST_'}{'LASTBLK'})
{
my $datablk = 0;
if (defined($self->readFILE(\$datablk)))
{
# read from file successful
# increment the transferred bytes counter
$self->{'_REQUEST_'}{'TotalBytes'} += length($datablk);
if ($self->sendDATA(\$datablk))
{
# send to socket successful
if ($self->{'CallBack'})
{
&{$self->{'CallBack'}}($self);
}
}
else
{
# error sending to socket
return (undef);
}
}
else
{
# error reading from file
return (undef);
}
}
else
{
# transfer completed
return (1);
}
}
}
#
# Usage: $requestOBJ->recvFILE();
# return 1 if success or undef if error
#
sub recvFILE
{
my $self = shift;
$self->{'_REQUEST_'}{'LASTBLK'} = 0;
$self->{'_REQUEST_'}{'PREVBLK'} = 0;
while (1)
{
my $datablk = 0;
if ($self->recvDATA(\$datablk))
{
# DATA received
if (defined($self->writeFILE(\$datablk)))
{
# DATA written to file
my $udpserver = $self->{'_UDPSERVER_'};
if (defined($udpserver->send(pack("nn", TFTP_OPCODE_ACK, $self->{'_REQUEST_'}{'LASTBLK'}))))
{
# sent ACK
# increment the transferred bytes counter
$self->{'_REQUEST_'}{'TotalBytes'} += length($datablk);
if (length($datablk) < $self->{'BlkSize'})
{
return (1);
}
else
{
next;
}
}
else
{
$! = $udpserver->sockopt(SO_ERROR);
$LASTERROR = sprintf "Socket SEND error: %s\n", $!;
return (undef);
}
}
else
{
# error writing data
return (undef);
}
}
else
{
# timeout waiting for data
return (undef);
}
}
}
#
# Usage: $requestOBJ->recvDATA(\$data);
# return 1 if success or undef if error
#
sub recvDATA
{
my $self = shift;
my $datablk = shift;
my ($datagram, $opcode, $datain);
my $udpserver = $self->{'_UDPSERVER_'};
# vars for IO select
my ($rin, $rout, $ein, $eout) = ('', '', '', '');
vec($rin, fileno($udpserver), 1) = 1;
# wait for data
if (select($rout=$rin, undef, $eout=$ein, $self->{'ACKtimeout'}))
{
# read the message
if ($udpserver->recv($datagram, $self->{'BlkSize'} + 4))
{
# decode the message
($opcode, $datain) = unpack("na*", $datagram);
if ($opcode eq TFTP_OPCODE_DATA)
{
# message is DATA
$self->{'_REQUEST_'}{'PREVBLK'} = $self->{'_REQUEST_'}{'LASTBLK'};
($self->{'_REQUEST_'}{'LASTBLK'}, $$datablk) = unpack("na*", $datain);
if($self->{'CallBack'})
{
&{$self->{'CallBack'}}($self);
}
return (1);
}
elsif ($opcode eq TFTP_OPCODE_ERROR)
{
# message is ERR
$LASTERROR = sprintf "TFTP error message: %s", $datain;
return (undef);
}
else
{
# other messages...
$LASTERROR = sprintf "Opcode %d not supported waiting for DATA\n", $opcode;
return (undef);
}
}
else
{
$! = $udpserver->sockopt(SO_ERROR);
$LASTERROR = sprintf "Socket RECV error: %s\n", $!;
return (undef);
}
}
else
{
$LASTERROR = sprintf "Timeout occurred on DATA packet %d\n", $self->{'_REQUEST_'}{'LASTBLK'} + 1;
return (undef);
}
}
#
# Usage: $requestOBJ->sendDATA(\$data);
# return 1 if success or undef if error
#
sub sendDATA
{
my $self = shift;
my $datablk = shift;
my $udpserver = $self->{'_UDPSERVER_'};
my $retry = 0;
my ($datagram, $opcode, $datain);
while ($retry < $self->{'ACKretries'})
{
if ($udpserver->send(pack("nna*", TFTP_OPCODE_DATA, $self->{'_REQUEST_'}{'LASTACK'} + 1, $$datablk)))
{
# vars for IO select
my ($rin, $rout, $ein, $eout) = ('', '', '', '');
vec($rin, fileno($udpserver), 1) = 1;
# wait for acknowledge
if (select($rout=$rin, undef, $eout=$ein, $self->{'ACKtimeout'}))
{
# read the message
if ($udpserver->recv($datagram, TFTP_MAX_BLKSIZE + 4))
{
# decode the message
($opcode, $datain) = unpack("na*", $datagram);
if ($opcode eq TFTP_OPCODE_ACK)
{
# message is ACK
# modified for supporting more blocks count than 65535, O.Z. 15.08.2007
$self->{'_REQUEST_'}{'PREVACK'} = $self->{'_REQUEST_'}{'LASTACK'};
if (int(($self->{'_REQUEST_'}{'LASTACK'}+1) % 65536) == unpack("n", $datain)){
$self->{'_REQUEST_'}{'LASTACK'}++;
};
return (1);
}
elsif ($opcode eq TFTP_OPCODE_ERROR)
{
# message is ERR
$LASTERROR = sprintf "TFTP error message: %s", $datain;
return (undef);
}
else
{
# other messages...
$LASTERROR = sprintf "Opcode %d not supported as a reply to DATA\n", $opcode;
return (undef);
}
}
else
{
$! = $udpserver->sockopt(SO_ERROR);
$LASTERROR = sprintf "Socket RECV error: %s\n", $!;
return (undef);
}
}
else
{
$LASTERROR = sprintf "Retry %d - timeout occurred on ACK packet %d\n", $retry, $self->{'_REQUEST_'}{'LASTACK'} + 1;
$debug and carp($LASTERROR);
$retry++;
}
}
else
{
$! = $udpserver->sockopt(SO_ERROR);
$LASTERROR = sprintf "Socket SEND error: %s\n", $!;
return (undef);
}
}
}
#
# Usage: $requestOBJ->openFILE()
# returns 1 if file is opened, undef if error
#
sub openFILE
{
# the request object
my $self = shift;
if ($self->{'_REQUEST_'}{'OPCODE'} eq TFTP_OPCODE_RRQ)
{
########################################
# opcode is RRQ, open file for reading #
########################################
if (open(RFH, "<".$self->{'_REQUEST_'}{'FileName'}))
{
# if OCTET mode, set FileHandle to binary mode...
if ($self->{'_REQUEST_'}{'Mode'} eq 'OCTET')
{
binmode(RFH);
}
my $size = -s($self->{'_REQUEST_'}{'FileName'});
$self->{'_REQUEST_'}{'LASTBLK'} = 1 + int($size / $self->{'BlkSize'});
# save the filehandle reference...
$self->{'_REQUEST_'}{'_FH_'} = *RFH;
return (1);
}
else
{
$LASTERROR = sprintf "Error opening file \'%s\' for reading\n", $self->{'_REQUEST_'}{'FileName'};
return (undef);
}
}
elsif ($self->{'_REQUEST_'}{'OPCODE'} eq TFTP_OPCODE_WRQ)
{
########################################
# opcode is WRQ, open file for writing #
########################################
if (open(WFH, ">".$self->{'_REQUEST_'}{'FileName'}))
{
# if OCTET mode, set FileHandle to binary mode...
if ($self->{'_REQUEST_'}{'Mode'} eq 'OCTET')
{
binmode(WFH);
}
# save the filehandle reference...
$self->{'_REQUEST_'}{'_FH_'} = *WFH;
return (1);
}
else
{
$LASTERROR = sprintf "Error opening file \'%s\' for writing\n", $self->{'_REQUEST_'}{'FileName'};
return (undef);
}
}
else
{
############################
# other opcodes are errors #
############################
$LASTERROR = sprintf "OPCODE %d is not supported\n", $self->{'_REQUEST_'}{'OPCODE'};
return (undef);
}
}
#
# Usage: $requestOBJ->closeFILE()
# returns 1 if file is success, undef if error
#
sub closeFILE
{
my $self = shift;
if ($self->{'_REQUEST_'}{'_FH_'})
{
if (close($self->{'_REQUEST_'}{'_FH_'}))
{
return (1);
}
else
{
$LASTERROR = "Error closing filehandle\n";
return (undef);
}
}
else
{
return (1);
}
}
#
# Usage: $requestOBJ->checkFILE()
# returns 1 if file is found, undef if file is not found
#
sub checkFILE
{
# the request object
my $self = shift;
# requested file
my $reqfile = $self->{'_REQUEST_'}{'FileName'};
if ($self->{'FileName'})
{
# filename is fixed
$self->{'_REQUEST_'}{'FileName'} = $self->{'FileName'};
if (($self->{'FileName'} =~ /$reqfile/) and -e($self->{'FileName'}))
{
# fixed name contains requested file and file exists
$self->{'FileSize'} = -s($self->{'FileName'});
return (1);
}
}
elsif ($self->{'RootDir'})
{
# rootdir is fixed
$reqfile = $self->{'RootDir'}.'/'.$reqfile;
$self->{'_REQUEST_'}{'FileName'} = $reqfile;
if (-e($reqfile))
{
# file exists in rootdir
$self->{'FileSize'} = -s($reqfile);
return (1);
}
}
return (undef);
}
#
# Usage: $requestOBJ->sendOACK();
# return 1 for success and undef for error (see $Net::TFTPd::LASTERROR for cause)
#
sub sendOACK
{
# the request object
my $self = shift;
my $udpserver = $self->{'_UDPSERVER_'};
my $retry = 0;
my ($datagram, $opcode, $datain);
while ($retry < $self->{'ACKretries'})
{
# send oack
my $data = join("\0", %{ $self->{'_RESPONSE_'}{'RFC2347'} })."\0";
if ($udpserver->send(pack("na*", TFTP_OPCODE_OACK, $data)))
{
# opcode is RRQ
if ($self->{'_REQUEST_'}{'OPCODE'} eq TFTP_OPCODE_RRQ)
{
# vars for IO select
my ($rin, $rout, $ein, $eout) = ('', '', '', '');
vec($rin, fileno($udpserver), 1) = 1;
# wait for acknowledge
if (select($rout=$rin, undef, $eout=$ein, $self->{'ACKtimeout'}))
{
# read the message
if ($udpserver->recv($datagram, TFTP_MAX_BLKSIZE + 4))
{
# decode the message
($opcode, $datain) = unpack("na*", $datagram);
if ($opcode == TFTP_OPCODE_ACK)
{
# message is ACK
my $lastack = unpack("n", $datain);
if ($lastack)
{
# ack is not for block 0... ERROR
$LASTERROR = sprintf "Received ACK for block %d instead of 0", $lastack;
return (undef);
}
return 1;
}
elsif ($opcode == TFTP_OPCODE_ERROR)
{
# message is ERR
$LASTERROR = sprintf "TFTP error message: %s", $datain;
return (undef);
}
else
{
# other messages...
$LASTERROR = sprintf "Opcode %d not supported as a reply to OACK\n", $opcode;
return (undef);
}
}
else
{
$! = $udpserver->sockopt(SO_ERROR);
$LASTERROR = sprintf "Socket RECV error: %s\n", $!;
return (undef);
}
}
else
{
$LASTERROR = sprintf "Retry %d - timeout occurred waiting reply for OACK packet\n", $retry;
$debug and carp($LASTERROR);
$retry++;
}
}
elsif ($self->{'_REQUEST_'}{'OPCODE'} eq TFTP_OPCODE_WRQ)
{
# opcode is WRQ
return (1);
}
}
else
{
$! = $udpserver->sockopt(SO_ERROR);
$LASTERROR = sprintf "Socket SEND error: %s\n", $!;
return (undef);
}
}
}
#
# Usage: $requestOBJ->sendERR($code, $message);
# returns 1 if success, undef if error
#
sub sendERR
{
my $self = shift;
my ($errcode, $errmsg) = @_;
# modified for supporting NETASCII transfers on 25/05/2009
#$errmsg or $errmsg = '';
$errmsg or $errmsg = $ERRORS{$errcode};
my $udpserver = $self->{'_UDPSERVER_'};
if ($udpserver->send(pack("nnZ*", 5, $errcode, $errmsg)))
{
return (1);
}
else
{
$! = $udpserver->sockopt(SO_ERROR);
$LASTERROR = sprintf "Socket SEND error: %s\n", $!;
return (undef);
}
}
sub server
{
my $self = shift;
return $self->{'_UDPSERVER_'};
}
sub error
{
return ($LASTERROR);
}
# Preloaded methods go here.
1;
__END__
# Below is stub documentation for your module. You better edit it!
=head1 NAME
Net::TFTPd - Perl extension for Trivial File Transfer Protocol Server
=head1 SYNOPSIS
use strict;
use Net::TFTPd;
my $tftpdOBJ = Net::TFTPd->new('RootDir' => 'path/to/files')
or die "Error creating TFTPd listener: %s", Net::TFTPd->error;
my $tftpRQ = $tftpdOBJ->waitRQ(10)
or die "Error waiting for TFTP request: %s", Net::TFTPd->error;
$tftpRQ->processRQ()
or die "Error processing TFTP request: %s", Net::TFTPd->error;
printf "%u bytes has been transferred", $tftpRQ->getTotalBytes() || 0;
=head1 DESCRIPTION
C<Net::TFTPd> is a class implementing a simple I<Trivial File Transfer Protocol> server in Perl as described in RFC1350.
C<Net::TFTPd> also supports the TFTP Option Extension (as described in RFC2347), with the following options:
RFC2348 TFTP Blocksize Option
RFC2349 TFTP Timeout Interval and Transfer Size Options
=head1 EXPORT
None by default.
=head2 %OPCODES
The %OPCODES tag exports the I<%OPCODES> hash:
%OPCODES = (
1 => 'RRQ',
2 => 'WRQ',
3 => 'DATA',
4 => 'ACK',
5 => 'ERROR',
6 => 'OACK',
'RRQ' => 1,
'WRQ' => 2,
'DATA' => 3,
'ACK' => 4,
'ERROR' => 5,
'OACK' => 6
);
=head1 Listener constructor
=head2 new()
$listener = new Net::TFTPd( ['RootDir' => 'path/to/files' | 'FileName' => 'path/to/file'] [, OPTIONS ] );
or
$listener = Net::TFTPd->new( ['RootDir' => 'path/to/files' | 'FileName' => 'path/to/file'] [, OPTIONS ] );
Create a new Net::TFTPd object where 'path/to/files' is the default path to file repository
or 'path/to/file' is the single file allowed for download, and OPTIONS are the default server
options.
Valid options are:
Option Description Default
------ ----------- -------
LocalAddr Interface to bind to (for multi-homed server) any
LocalPort Port to bind server to 69
Timeout Timeout in seconds to wait for a request 10
ACKtimeout Timeout in seconds to wait for an ACK packet 4
ACKretries Maximum number of retries waiting for ACK 4
Readable Clients are allowed to read files 1
Writable Clients are allowed to write files 0
BlkSize Minimum blocksize to negotiate for transfers 512
CallBack Reference to code executed for each transferred block -
Debug Activates debug mode (verbose) 0
Family Address family IPv4/IPv6 IPv4
Valid values for IPv4:
4, v4, ip4, ipv4, AF_INET (constant)
Valid values for IPv6:
6, v6, ip6, ipv6, AF_INET6 (constant)
V6Only Enable / disable v6only (see IO::Socket::IP) 1
B<NOTE>: IPv6 requires B<IO::Socket::IP>. Failback is B<IO::Socket::INET>
and only IPv4 support.
=head2 CallBack
The CallBack code is called by processRQ method for each tranferred block.
The code receives (into @_ array) a reference to internal I<$request> object.
Example:
sub callback
{
my $req = shift;
printf "block: %u\/%u\n", $req->{'_REQUEST_'}{'LASTACK'}, $req->{'_REQUEST_'}{'LASTBLK'};
}
my $tftpdOBJ = Net::TFTPd->new('RootDir' => 'c:/temp', 'Timeout' => 60, 'CallBack' => \&callback) or die Net::TFTPd->error;
=head1 Listener methods
=head2 waitRQ()
$request = $listener->waitRQ([Timeout]);
Waits for a client request (RRQ or WRQ) and returns a I<$request> object or I<undef> if timed out.
If I<Timeout> is missing, the timeout defined for I<$listener> object is used instead.
When the method returns, the program should fork() and process the request invoking processRQ() while the parent process should re-start waiting for another request.
=head1 Request methods
=head2 processRQ()
$ret = $request->processRQ();
Processes a request and returns 1 if success, undef if error.
=head2 getFileName()
$ret = $request->getFileName();
Returns the requested file name.
=head2 getMode()
$ret = $request->getMode();
Returns the transfer mode for the request.
=head2 getBlkSize()
$ret = $request->getBlkSize();
Returns the block size used for the transfer.
=head2 server()
$ret = $request->server();
Return B<IO::Socket::*> object for the created server.
All B<IO::Socket::*> accessors can then be called.
=head2 getPeerAddr()
$ret = $request->getPeerAddr();
Returns the address of the requesting client.
=head2 getPeerPort()
$ret = $request->getPeerMode();
Returns the port of the requesting client.
=head2 getTotalBytes()
$ret = $request->getTotalBytes();
Returns the number of bytes transferred for the request.
=head1 CREDITS
Thanks to Michael Vincent (E<lt>VINSWORLDE<gt>) for the NETASCII support, transferred bytes and IPv6 patches.
=head1 AUTHOR
Luigino Masarati, E<lt>lmasarati@hotmail.comE<gt>
=head1 SEE ALSO
L<Net::TFTP>.
=cut
|