2 * Copyright (c) 1983, 1993
3 * The Regents of the University of California. All rights reserved.
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
8 * 1. Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 * 2. Redistributions in binary form must reproduce the above copyright
11 * notice, this list of conditions and the following disclaimer in the
12 * documentation and/or other materials provided with the distribution.
13 * 4. Neither the name of the University nor the names of its contributors
14 * may be used to endorse or promote products derived from this software
15 * without specific prior written permission.
17 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
18 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
21 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31 static const char copyright[] =
32 "@(#) Copyright (c) 1983, 1993\n\
33 The Regents of the University of California. All rights reserved.\n";
38 static char sccsid[] = "@(#)main.c 8.1 (Berkeley) 6/6/93";
42 #include <sys/cdefs.h>
43 __FBSDID("$FreeBSD$");
45 /* Many bug fixes are from Jim Guyton <guyton@rand-unix> */
48 * TFTP User Program -- Command Interface.
50 #include <sys/param.h>
51 #include <sys/types.h>
52 #include <sys/socket.h>
53 #include <sys/sysctl.h>
57 #include <netinet/in.h>
58 #include <arpa/inet.h>
59 #include <arpa/tftp.h>
72 #include "tftp-utils.h"
74 #include "tftp-options.h"
78 #define TIMEOUT 5 /* secs between rexmt's */
80 typedef struct sockaddr_storage peeraddr;
84 volatile int txrx_error;
89 static char *margv[MAX_MARGV];
94 static void get(int, char **);
95 static void help(int, char **);
96 static void intr(int);
97 static void modecmd(int, char **);
98 static void put(int, char **);
99 static void quit(int, char **);
100 static void setascii(int, char **);
101 static void setbinary(int, char **);
102 static void setpeer0(char *, const char *);
103 static void setpeer(int, char **);
104 static void settimeoutpacket(int, char **);
105 static void settimeoutnetwork(int, char **);
106 static void setdebug(int, char **);
107 static void setverbose(int, char **);
108 static void showstatus(int, char **);
109 static void setblocksize(int, char **);
110 static void setblocksize2(int, char **);
111 static void setoptions(int, char **);
112 static void setrollover(int, char **);
113 static void setpacketdrop(int, char **);
115 static void command(void) __dead2;
116 static const char *command_prompt(void);
118 static void urihandling(char *URI);
119 static void getusage(char *);
120 static void makeargv(char *line);
121 static void putusage(char *);
122 static void settftpmode(const char *);
124 static char *tail(char *);
125 static struct cmd *getcmd(char *);
127 #define HELPINDENT (sizeof("connect"))
131 void (*handler)(int, char **);
135 static struct cmd cmdtab[] = {
136 { "connect", setpeer, "connect to remote tftp" },
137 { "mode", modecmd, "set file transfer mode" },
138 { "put", put, "send file" },
139 { "get", get, "receive file" },
140 { "quit", quit, "exit tftp" },
141 { "verbose", setverbose, "toggle verbose mode" },
142 { "status", showstatus, "show current status" },
143 { "binary", setbinary, "set mode to octet" },
144 { "ascii", setascii, "set mode to netascii" },
145 { "rexmt", settimeoutpacket,
146 "set per-packet retransmission timeout[-]" },
147 { "timeout", settimeoutnetwork,
148 "set total retransmission timeout" },
149 { "trace", setdebug, "enable 'debug packet'[-]" },
150 { "debug", setdebug, "enable verbose output" },
151 { "blocksize", setblocksize, "set blocksize[*]" },
152 { "blocksize2", setblocksize2, "set blocksize as a power of 2[**]" },
153 { "rollover", setrollover, "rollover after 64K packets[**]" },
154 { "options", setoptions,
155 "enable or disable RFC2347 style options" },
156 { "help", help, "print help information" },
157 { "packetdrop", setpacketdrop, "artificial packetloss feature" },
158 { "?", help, "print help information" },
162 static struct modes {
166 { "ascii", "netascii" },
167 { "netascii", "netascii" },
168 { "binary", "octet" },
169 { "image", "octet" },
170 { "octet", "octet" },
175 main(int argc, char *argv[])
178 acting_as_client = 1;
180 strcpy(mode, "netascii");
181 signal(SIGINT, intr);
183 if (setjmp(toplevel) != 0)
186 if (strncmp(argv[1], "tftp://", 7) == 0) {
187 urihandling(argv[1]);
193 if (setjmp(toplevel) != 0)
201 * RFC3617 handling of TFTP URIs:
203 * tftpURI = "tftp://" host "/" file [ mode ]
204 * mode = ";" "mode=" ( "netascii" / "octet" )
205 * file = *( unreserved / escaped )
206 * host = <as specified by RFC 2732>
207 * unreserved = <as specified in RFC 2396>
208 * escaped = <as specified in RFC 2396>
210 * We are cheating a little bit by allowing any mode as specified in the
211 * modes table defined earlier on in this file and mapping it on the real
215 urihandling(char *URI)
221 const char *tmode = "octet";
226 strncpy(uri, URI, ARG_MAX);
229 if ((s = strchr(host, '/')) == NULL) {
231 "Invalid URI: Couldn't find / after hostname\n");
237 if ((s = strchr(path, ';')) != NULL) {
241 if (strncmp(opts, "mode=", 5) == 0) {
245 for (i = 0; modes[i].m_name != NULL; i++) {
246 if (strcmp(modes[i].m_name, tmode) == 0)
249 if (modes[i].m_name == NULL) {
250 fprintf(stderr, "Invalid mode: '%s'\n", mode);
253 settftpmode(modes[i].m_mode);
256 settftpmode("octet");
259 setpeer0(host, NULL);
261 sprintf(line, "get %s", path);
266 static char hostname[MAXHOSTNAMELEN];
269 setpeer0(char *host, const char *lport)
271 struct addrinfo hints, *res0, *res;
273 const char *cause = "unknown";
281 memset(&hints, 0, sizeof(hints));
282 hints.ai_family = PF_UNSPEC;
283 hints.ai_socktype = SOCK_DGRAM;
284 hints.ai_protocol = IPPROTO_UDP;
285 hints.ai_flags = AI_CANONNAME;
288 error = getaddrinfo(host, lport, &hints, &res0);
290 warnx("%s", gai_strerror(error));
294 for (res = res0; res; res = res->ai_next) {
295 if (res->ai_addrlen > sizeof(peeraddr))
297 peer = socket(res->ai_family, res->ai_socktype,
304 memset(&peer_sock, 0, sizeof(peer_sock));
305 peer_sock.ss_family = res->ai_family;
306 peer_sock.ss_len = res->ai_addrlen;
307 if (bind(peer, (struct sockaddr *)&peer_sock, peer_sock.ss_len) < 0) {
320 /* res->ai_addr <= sizeof(peeraddr) is guaranteed */
321 memcpy(&peer_sock, res->ai_addr, res->ai_addrlen);
322 if (res->ai_canonname) {
323 (void) strncpy(hostname, res->ai_canonname,
326 (void) strncpy(hostname, host, sizeof(hostname));
327 hostname[sizeof(hostname)-1] = 0;
335 setpeer(int argc, char *argv[])
340 strcpy(line, "Connect ");
342 fgets(&line[strlen(line)], sizeof line - strlen(line), stdin);
347 if ((argc < 2) || (argc > 3)) {
348 printf("usage: %s [host [port]]\n", argv[0]);
353 setpeer0(argv[1], argv[2]);
355 setpeer0(argv[1], NULL);
359 modecmd(int argc, char *argv[])
365 printf("Using %s mode to transfer files.\n", mode);
369 for (p = modes; p->m_name; p++)
370 if (strcmp(argv[1], p->m_name) == 0)
373 settftpmode(p->m_mode);
376 printf("%s: unknown mode\n", argv[1]);
377 /* drop through and print usage message */
380 printf("usage: %s [", argv[0]);
382 for (p = modes; p->m_name != NULL; p++) {
383 printf("%s%s", sep, p->m_name);
392 setbinary(int argc __unused, char *argv[] __unused)
395 settftpmode("octet");
399 setascii(int argc __unused, char *argv[] __unused)
402 settftpmode("netascii");
406 settftpmode(const char *newmode)
409 strcpy(mode, newmode);
411 printf("mode set to %s\n", mode);
419 put(int argc, char *argv[])
428 strcpy(line, "send ");
430 fgets(&line[strlen(line)], sizeof line - strlen(line), stdin);
439 targ = argv[argc - 1];
440 if (rindex(argv[argc - 1], ':')) {
443 for (n = 1; n < argc - 1; n++)
444 if (index(argv[n], ':')) {
448 lcp = argv[argc - 1];
449 targ = rindex(lcp, ':');
451 if (lcp[0] == '[' && lcp[strlen(lcp) - 1] == ']') {
452 lcp[strlen(lcp) - 1] = '\0';
458 printf("No target machine specified.\n");
462 cp = argc == 2 ? tail(targ) : argv[1];
463 fd = open(cp, O_RDONLY);
470 asprintf(&options[OPT_TSIZE].o_request, "%ju", sb.st_size);
473 printf("putting %s to %s:%s [%s]\n",
474 cp, hostname, targ, mode);
475 xmitfile(peer, port, fd, targ, mode);
478 /* this assumes the target is a directory */
479 /* on a remote unix system. hmmmm. */
480 cp = index(targ, '\0');
482 for (n = 1; n < argc - 1; n++) {
483 strcpy(cp, tail(argv[n]));
484 fd = open(argv[n], O_RDONLY);
491 asprintf(&options[OPT_TSIZE].o_request, "%ju", sb.st_size);
494 printf("putting %s to %s:%s [%s]\n",
495 argv[n], hostname, targ, mode);
496 xmitfile(peer, port, fd, targ, mode);
504 printf("usage: %s file [remotename]\n", s);
505 printf(" %s file host:remotename\n", s);
506 printf(" %s file1 file2 ... fileN [[host:]remote-directory]\n", s);
513 get(int argc, char *argv[])
522 strcpy(line, "get ");
524 fgets(&line[strlen(line)], sizeof line - strlen(line), stdin);
534 for (n = 1; n < argc ; n++)
535 if (rindex(argv[n], ':') == 0) {
536 printf("No remote host specified and "
537 "no host given for file '%s'\n", argv[n]);
542 for (n = 1; n < argc ; n++) {
543 src = rindex(argv[n], ':');
551 if (lcp[0] == '[' && lcp[strlen(lcp) - 1] == ']') {
552 lcp[strlen(lcp) - 1] = '\0';
560 cp = argc == 3 ? argv[2] : tail(src);
561 fd = creat(cp, 0644);
567 printf("getting from %s:%s to %s [%s]\n",
568 hostname, src, cp, mode);
569 recvfile(peer, port, fd, src, mode);
572 cp = tail(src); /* new .. jdg */
573 fd = creat(cp, 0644);
579 printf("getting from %s:%s to %s [%s]\n",
580 hostname, src, cp, mode);
581 recvfile(peer, port, fd, src, mode);
589 printf("usage: %s file [localname]\n", s);
590 printf(" %s [host:]file [localname]\n", s);
591 printf(" %s [host1:]file1 [host2:]file2 ... [hostN:]fileN\n", s);
595 settimeoutpacket(int argc, char *argv[])
601 strcpy(line, "Packet timeout ");
603 fgets(&line[strlen(line)], sizeof line - strlen(line), stdin);
609 printf("usage: %s value\n", argv[0]);
614 printf("%s: bad value\n", argv[1]);
618 settimeouts(t, timeoutnetwork, maxtimeouts);
622 settimeoutnetwork(int argc, char *argv[])
628 strcpy(line, "Network timeout ");
630 fgets(&line[strlen(line)], sizeof line - strlen(line), stdin);
636 printf("usage: %s value\n", argv[0]);
641 printf("%s: bad value\n", argv[1]);
645 settimeouts(timeoutpacket, t, maxtimeouts);
649 showstatus(int argc __unused, char *argv[] __unused)
652 printf("Remote host: %s\n",
653 connected ? hostname : "none specified yet");
654 printf("RFC2347 Options support: %s\n",
655 options_rfc_enabled ? "enabled" : "disabled");
656 printf("Non-RFC defined options support: %s\n",
657 options_extra_enabled ? "enabled" : "disabled");
658 printf("Mode: %s\n", mode);
659 printf("Verbose: %s\n", verbose ? "on" : "off");
660 printf("Debug: %s\n", debug_show(debug));
661 printf("Artificial packetloss: %d in 100 packets\n",
662 packetdroppercentage);
663 printf("Segment size: %d bytes\n", segsize);
664 printf("Network timeout: %d seconds\n", timeoutpacket);
665 printf("Maximum network timeout: %d seconds\n", timeoutnetwork);
666 printf("Maximum timeouts: %d \n", maxtimeouts);
670 intr(int dummy __unused)
673 signal(SIGALRM, SIG_IGN);
675 longjmp(toplevel, -1);
684 s = rindex(filename, '/');
710 static History *hist;
713 int len, num, vrbose;
718 el = el_init("tftp", stdin, stdout, stderr);
719 hist = history_init();
720 history(hist, &he, H_SETSIZE, 100);
721 el_set(el, EL_HIST, history, hist);
722 el_set(el, EL_EDITOR, "emacs");
723 el_set(el, EL_PROMPT, command_prompt);
724 el_set(el, EL_SIGNAL, 1);
729 if ((bp = el_gets(el, &num)) == NULL || num == 0)
731 len = (num > MAXLINE) ? MAXLINE : num;
732 memcpy(line, bp, len);
734 history(hist, &he, H_ENTER, bp);
737 if (fgets(line, sizeof line , stdin) == 0) {
745 if ((cp = strchr(line, '\n')))
752 c = getcmd(margv[0]);
753 if (c == (struct cmd *)-1) {
754 printf("?Ambiguous command\n");
758 printf("?Invalid command\n");
761 (*c->handler)(margc, margv);
769 struct cmd *c, *found;
770 int nmatches, longest;
775 for (c = cmdtab; (p = c->name) != NULL; c++) {
776 for (q = name; *q == *p++; q++)
777 if (*q == 0) /* exact match? */
779 if (!*q) { /* the name was a prefix */
780 if (q - name > longest) {
784 } else if (q - name == longest)
789 return ((struct cmd *)-1);
794 * Slice a string up into argc/argv.
803 if ((cp = strchr(line, '\n')) != NULL)
805 for (cp = line; margc < MAX_MARGV - 1 && *cp != '\0';) {
812 while (*cp != '\0' && !isspace(*cp))
822 quit(int argc __unused, char *argv[] __unused)
832 help(int argc, char *argv[])
837 printf("Commands may be abbreviated. Commands are:\n\n");
838 for (c = cmdtab; c->name; c++)
839 printf("%-*s\t%s\n", (int)HELPINDENT, c->name, c->help);
841 printf("\n[-] : You shouldn't use these ones anymore.\n");
842 printf("[*] : RFC2347 options support required.\n");
843 printf("[**] : Non-standard RFC2347 option.\n");
850 if (c == (struct cmd *)-1)
851 printf("?Ambiguous help command: %s\n", arg);
852 else if (c == (struct cmd *)0)
853 printf("?Invalid help command: %s\n", arg);
855 printf("%s\n", c->help);
860 setverbose(int argc __unused, char *argv[] __unused)
864 printf("Verbose mode %s.\n", verbose ? "on" : "off");
868 setoptions(int argc, char *argv[])
872 if (strcasecmp(argv[1], "enable") == 0 ||
873 strcasecmp(argv[1], "on") == 0) {
874 options_extra_enabled = 1;
875 options_rfc_enabled = 1;
877 if (strcasecmp(argv[1], "disable") == 0 ||
878 strcasecmp(argv[1], "off") == 0) {
879 options_extra_enabled = 0;
880 options_rfc_enabled = 0;
882 if (strcasecmp(argv[1], "extra") == 0)
883 options_extra_enabled = !options_extra_enabled;
885 printf("Support for RFC2347 style options are now %s.\n",
886 options_rfc_enabled ? "enabled" : "disabled");
887 printf("Support for non-RFC defined options are now %s.\n",
888 options_extra_enabled ? "enabled" : "disabled");
890 printf("\nThe following options are available:\n"
891 "\toptions on : enable support for RFC2347 style options\n"
892 "\toptions off : disable support for RFC2347 style options\n"
893 "\toptions extra : toggle support for non-RFC defined options\n"
898 setrollover(int argc, char *argv[])
902 if (strcasecmp(argv[1], "never") == 0 ||
903 strcasecmp(argv[1], "none") == 0) {
904 free(options[OPT_ROLLOVER].o_request);
905 options[OPT_ROLLOVER].o_request = NULL;
907 if (strcasecmp(argv[1], "1") == 0) {
908 free(options[OPT_ROLLOVER].o_request);
909 options[OPT_ROLLOVER].o_request = strdup("1");
911 if (strcasecmp(argv[1], "0") == 0) {
912 free(options[OPT_ROLLOVER].o_request);
913 options[OPT_ROLLOVER].o_request = strdup("0");
916 printf("Support for the rollover options is %s.\n",
917 options[OPT_ROLLOVER].o_request != NULL ? "enabled" : "disabled");
918 if (options[OPT_ROLLOVER].o_request != NULL)
919 printf("Block rollover will be to block %s.\n",
920 options[OPT_ROLLOVER].o_request);
923 printf("\nThe following rollover options are available:\n"
924 "\trollover 0 : rollover to block zero (default)\n"
925 "\trollover 1 : rollover to block one\n"
926 "\trollover never : do not support the rollover option\n"
927 "\trollover none : do not support the rollover option\n"
932 setdebug(int argc, char *argv[])
939 debug ^= debug_find(argv[i++]);
941 printf("The following debugging is enabled: %s\n", debug_show(debug));
943 printf("\nThe following debugs are available:\n");
945 while (debugs[i].name != NULL) {
946 printf("\t%s\t%s\n", debugs[i].name, debugs[i].desc);
952 setblocksize(int argc, char *argv[])
955 if (!options_rfc_enabled)
956 printf("RFC2347 style options are not enabled "
957 "(but proceeding anyway)\n");
960 int size = atoi(argv[1]);
964 max = sizeof(maxdgram);
965 if (sysctlbyname("net.inet.udp.maxdgram",
966 &maxdgram, &max, NULL, 0) < 0) {
967 perror("sysctl: net.inet.udp.maxdgram");
971 if (size < BLKSIZE_MIN || size > BLKSIZE_MAX) {
972 printf("Blocksize should be between %d and %d bytes.\n",
973 BLKSIZE_MIN, BLKSIZE_MAX);
975 } else if (size > (int)maxdgram - 4) {
976 printf("Blocksize can't be bigger than %ld bytes due "
977 "to the net.inet.udp.maxdgram sysctl limitation.\n",
979 asprintf(&options[OPT_BLKSIZE].o_request,
980 "%ld", maxdgram - 4);
982 asprintf(&options[OPT_BLKSIZE].o_request, "%d", size);
985 printf("Blocksize is now %s bytes.\n", options[OPT_BLKSIZE].o_request);
989 setblocksize2(int argc, char *argv[])
992 if (!options_rfc_enabled || !options_extra_enabled)
994 "RFC2347 style or non-RFC defined options are not enabled "
995 "(but proceeding anyway)\n");
998 int size = atoi(argv[1]);
1004 8, 16, 32, 64, 128, 256, 512, 1024,
1005 2048, 4096, 8192, 16384, 32768, 0
1008 max = sizeof(maxdgram);
1009 if (sysctlbyname("net.inet.udp.maxdgram",
1010 &maxdgram, &max, NULL, 0) < 0) {
1011 perror("sysctl: net.inet.udp.maxdgram");
1015 for (i = 0; sizes[i] != 0; i++) {
1016 if (sizes[i] == size) break;
1018 if (sizes[i] == 0) {
1019 printf("Blocksize2 should be a power of two between "
1024 if (size < BLKSIZE_MIN || size > BLKSIZE_MAX) {
1025 printf("Blocksize2 should be between "
1026 "%d and %d bytes.\n", BLKSIZE_MIN, BLKSIZE_MAX);
1028 } else if (size > (int)maxdgram - 4) {
1029 printf("Blocksize2 can't be bigger than %ld bytes due "
1030 "to the net.inet.udp.maxdgram sysctl limitation.\n",
1032 for (i = 0; sizes[i+1] != 0; i++) {
1033 if ((int)maxdgram < sizes[i+1]) break;
1035 asprintf(&options[OPT_BLKSIZE2].o_request,
1038 asprintf(&options[OPT_BLKSIZE2].o_request, "%d", size);
1041 printf("Blocksize2 is now %s bytes.\n",
1042 options[OPT_BLKSIZE2].o_request);
1046 setpacketdrop(int argc, char *argv[])
1050 packetdroppercentage = atoi(argv[1]);
1052 printf("Randomly %d in 100 packets will be dropped\n",
1053 packetdroppercentage);