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"
77 #define MAXLINE (2 * MAXPATHLEN)
78 #define TIMEOUT 5 /* secs between rexmt's */
80 typedef struct sockaddr_storage peeraddr;
83 static jmp_buf toplevel;
84 volatile int txrx_error;
89 static char *margv[MAX_MARGV];
92 static char *port = NULL;
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 strlcpy(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) strlcpy(hostname, res->ai_canonname,
326 (void) strlcpy(hostname, host, sizeof(hostname));
334 setpeer(int argc, char *argv[])
339 strcpy(line, "Connect ");
341 fgets(&line[strlen(line)], sizeof line - strlen(line), stdin);
346 if ((argc < 2) || (argc > 3)) {
347 printf("usage: %s [host [port]]\n", argv[0]);
352 setpeer0(argv[1], argv[2]);
354 setpeer0(argv[1], NULL);
358 modecmd(int argc, char *argv[])
364 printf("Using %s mode to transfer files.\n", mode);
368 for (p = modes; p->m_name; p++)
369 if (strcmp(argv[1], p->m_name) == 0)
372 settftpmode(p->m_mode);
375 printf("%s: unknown mode\n", argv[1]);
376 /* drop through and print usage message */
379 printf("usage: %s [", argv[0]);
381 for (p = modes; p->m_name != NULL; p++) {
382 printf("%s%s", sep, p->m_name);
391 setbinary(int argc __unused, char *argv[] __unused)
394 settftpmode("octet");
398 setascii(int argc __unused, char *argv[] __unused)
401 settftpmode("netascii");
405 settftpmode(const char *newmode)
408 strlcpy(mode, newmode, sizeof(mode));
410 printf("mode set to %s\n", mode);
418 put(int argc, char *argv[])
427 strcpy(line, "send ");
429 fgets(&line[strlen(line)], sizeof line - strlen(line), stdin);
438 targ = argv[argc - 1];
439 if (strrchr(argv[argc - 1], ':')) {
442 for (n = 1; n < argc - 1; n++)
443 if (strchr(argv[n], ':')) {
447 lcp = argv[argc - 1];
448 targ = strrchr(lcp, ':');
450 if (lcp[0] == '[' && lcp[strlen(lcp) - 1] == ']') {
451 lcp[strlen(lcp) - 1] = '\0';
457 printf("No target machine specified.\n");
461 cp = argc == 2 ? tail(targ) : argv[1];
462 fd = open(cp, O_RDONLY);
468 if (fstat(fd, &sb) < 0) {
472 asprintf(&options[OPT_TSIZE].o_request, "%ju", sb.st_size);
475 printf("putting %s to %s:%s [%s]\n",
476 cp, hostname, targ, mode);
477 xmitfile(peer, port, fd, targ, mode);
481 /* this assumes the target is a directory */
482 /* on a remote unix system. hmmmm. */
483 cp = strchr(targ, '\0');
485 for (n = 1; n < argc - 1; n++) {
486 strcpy(cp, tail(argv[n]));
487 fd = open(argv[n], O_RDONLY);
493 if (fstat(fd, &sb) < 0) {
497 asprintf(&options[OPT_TSIZE].o_request, "%ju", sb.st_size);
500 printf("putting %s to %s:%s [%s]\n",
501 argv[n], hostname, targ, mode);
502 xmitfile(peer, port, fd, targ, mode);
510 printf("usage: %s file [remotename]\n", s);
511 printf(" %s file host:remotename\n", s);
512 printf(" %s file1 file2 ... fileN [[host:]remote-directory]\n", s);
519 get(int argc, char *argv[])
528 strcpy(line, "get ");
530 fgets(&line[strlen(line)], sizeof line - strlen(line), stdin);
540 for (n = 1; n < argc ; n++)
541 if (strrchr(argv[n], ':') == 0) {
542 printf("No remote host specified and "
543 "no host given for file '%s'\n", argv[n]);
548 for (n = 1; n < argc ; n++) {
549 src = strrchr(argv[n], ':');
557 if (lcp[0] == '[' && lcp[strlen(lcp) - 1] == ']') {
558 lcp[strlen(lcp) - 1] = '\0';
566 cp = argc == 3 ? argv[2] : tail(src);
567 fd = creat(cp, 0644);
573 printf("getting from %s:%s to %s [%s]\n",
574 hostname, src, cp, mode);
575 recvfile(peer, port, fd, src, mode);
578 cp = tail(src); /* new .. jdg */
579 fd = creat(cp, 0644);
585 printf("getting from %s:%s to %s [%s]\n",
586 hostname, src, cp, mode);
587 recvfile(peer, port, fd, src, mode);
595 printf("usage: %s file [localname]\n", s);
596 printf(" %s [host:]file [localname]\n", s);
597 printf(" %s [host1:]file1 [host2:]file2 ... [hostN:]fileN\n", s);
601 settimeoutpacket(int argc, char *argv[])
607 strcpy(line, "Packet timeout ");
609 fgets(&line[strlen(line)], sizeof line - strlen(line), stdin);
615 printf("usage: %s value\n", argv[0]);
620 printf("%s: bad value\n", argv[1]);
624 settimeouts(t, timeoutnetwork, maxtimeouts);
628 settimeoutnetwork(int argc, char *argv[])
634 strcpy(line, "Network timeout ");
636 fgets(&line[strlen(line)], sizeof line - strlen(line), stdin);
642 printf("usage: %s value\n", argv[0]);
647 printf("%s: bad value\n", argv[1]);
651 settimeouts(timeoutpacket, t, maxtimeouts);
655 showstatus(int argc __unused, char *argv[] __unused)
658 printf("Remote host: %s\n",
659 connected ? hostname : "none specified yet");
660 printf("RFC2347 Options support: %s\n",
661 options_rfc_enabled ? "enabled" : "disabled");
662 printf("Non-RFC defined options support: %s\n",
663 options_extra_enabled ? "enabled" : "disabled");
664 printf("Mode: %s\n", mode);
665 printf("Verbose: %s\n", verbose ? "on" : "off");
666 printf("Debug: %s\n", debug_show(debug));
667 printf("Artificial packetloss: %d in 100 packets\n",
668 packetdroppercentage);
669 printf("Segment size: %d bytes\n", segsize);
670 printf("Network timeout: %d seconds\n", timeoutpacket);
671 printf("Maximum network timeout: %d seconds\n", timeoutnetwork);
672 printf("Maximum timeouts: %d \n", maxtimeouts);
676 intr(int dummy __unused)
679 signal(SIGALRM, SIG_IGN);
681 longjmp(toplevel, -1);
690 s = strrchr(filename, '/');
716 static History *hist;
719 int len, num, vrbose;
724 el = el_init("tftp", stdin, stdout, stderr);
725 hist = history_init();
726 history(hist, &he, H_SETSIZE, 100);
727 el_set(el, EL_HIST, history, hist);
728 el_set(el, EL_EDITOR, "emacs");
729 el_set(el, EL_PROMPT, command_prompt);
730 el_set(el, EL_SIGNAL, 1);
735 if ((bp = el_gets(el, &num)) == NULL || num == 0)
737 len = MIN(MAXLINE, num);
738 memcpy(line, bp, len);
740 history(hist, &he, H_ENTER, bp);
743 if (fgets(line, sizeof line , stdin) == NULL) {
751 if ((cp = strchr(line, '\n')))
758 c = getcmd(margv[0]);
759 if (c == (struct cmd *)-1) {
760 printf("?Ambiguous command\n");
764 printf("?Invalid command\n");
767 (*c->handler)(margc, margv);
775 struct cmd *c, *found;
776 int nmatches, longest;
781 for (c = cmdtab; (p = c->name) != NULL; c++) {
782 for (q = name; *q == *p++; q++)
783 if (*q == 0) /* exact match? */
785 if (!*q) { /* the name was a prefix */
786 if (q - name > longest) {
790 } else if (q - name == longest)
795 return ((struct cmd *)-1);
800 * Slice a string up into argc/argv.
809 if ((cp = strchr(line, '\n')) != NULL)
811 for (cp = line; margc < MAX_MARGV - 1 && *cp != '\0';) {
818 while (*cp != '\0' && !isspace(*cp))
828 quit(int argc __unused, char *argv[] __unused)
838 help(int argc, char *argv[])
843 printf("Commands may be abbreviated. Commands are:\n\n");
844 for (c = cmdtab; c->name; c++)
845 printf("%-*s\t%s\n", (int)HELPINDENT, c->name, c->help);
847 printf("\n[-] : You shouldn't use these ones anymore.\n");
848 printf("[*] : RFC2347 options support required.\n");
849 printf("[**] : Non-standard RFC2347 option.\n");
856 if (c == (struct cmd *)-1)
857 printf("?Ambiguous help command: %s\n", arg);
858 else if (c == (struct cmd *)0)
859 printf("?Invalid help command: %s\n", arg);
861 printf("%s\n", c->help);
866 setverbose(int argc __unused, char *argv[] __unused)
870 printf("Verbose mode %s.\n", verbose ? "on" : "off");
874 setoptions(int argc, char *argv[])
878 if (strcasecmp(argv[1], "enable") == 0 ||
879 strcasecmp(argv[1], "on") == 0) {
880 options_extra_enabled = 1;
881 options_rfc_enabled = 1;
883 if (strcasecmp(argv[1], "disable") == 0 ||
884 strcasecmp(argv[1], "off") == 0) {
885 options_extra_enabled = 0;
886 options_rfc_enabled = 0;
888 if (strcasecmp(argv[1], "extra") == 0)
889 options_extra_enabled = !options_extra_enabled;
891 printf("Support for RFC2347 style options are now %s.\n",
892 options_rfc_enabled ? "enabled" : "disabled");
893 printf("Support for non-RFC defined options are now %s.\n",
894 options_extra_enabled ? "enabled" : "disabled");
896 printf("\nThe following options are available:\n"
897 "\toptions on : enable support for RFC2347 style options\n"
898 "\toptions off : disable support for RFC2347 style options\n"
899 "\toptions extra : toggle support for non-RFC defined options\n"
904 setrollover(int argc, char *argv[])
908 if (strcasecmp(argv[1], "never") == 0 ||
909 strcasecmp(argv[1], "none") == 0) {
910 free(options[OPT_ROLLOVER].o_request);
911 options[OPT_ROLLOVER].o_request = NULL;
913 if (strcasecmp(argv[1], "1") == 0) {
914 free(options[OPT_ROLLOVER].o_request);
915 options[OPT_ROLLOVER].o_request = strdup("1");
917 if (strcasecmp(argv[1], "0") == 0) {
918 free(options[OPT_ROLLOVER].o_request);
919 options[OPT_ROLLOVER].o_request = strdup("0");
922 printf("Support for the rollover options is %s.\n",
923 options[OPT_ROLLOVER].o_request != NULL ? "enabled" : "disabled");
924 if (options[OPT_ROLLOVER].o_request != NULL)
925 printf("Block rollover will be to block %s.\n",
926 options[OPT_ROLLOVER].o_request);
929 printf("\nThe following rollover options are available:\n"
930 "\trollover 0 : rollover to block zero (default)\n"
931 "\trollover 1 : rollover to block one\n"
932 "\trollover never : do not support the rollover option\n"
933 "\trollover none : do not support the rollover option\n"
938 setdebug(int argc, char *argv[])
945 debug ^= debug_find(argv[i++]);
947 printf("The following debugging is enabled: %s\n", debug_show(debug));
949 printf("\nThe following debugs are available:\n");
951 while (debugs[i].name != NULL) {
952 printf("\t%s\t%s\n", debugs[i].name, debugs[i].desc);
958 setblocksize(int argc, char *argv[])
961 if (!options_rfc_enabled)
962 printf("RFC2347 style options are not enabled "
963 "(but proceeding anyway)\n");
966 int size = atoi(argv[1]);
970 max = sizeof(maxdgram);
971 if (sysctlbyname("net.inet.udp.maxdgram",
972 &maxdgram, &max, NULL, 0) < 0) {
973 perror("sysctl: net.inet.udp.maxdgram");
977 if (size < BLKSIZE_MIN || size > BLKSIZE_MAX) {
978 printf("Blocksize should be between %d and %d bytes.\n",
979 BLKSIZE_MIN, BLKSIZE_MAX);
981 } else if (size > (int)maxdgram - 4) {
982 printf("Blocksize can't be bigger than %ld bytes due "
983 "to the net.inet.udp.maxdgram sysctl limitation.\n",
985 asprintf(&options[OPT_BLKSIZE].o_request,
986 "%ld", maxdgram - 4);
988 asprintf(&options[OPT_BLKSIZE].o_request, "%d", size);
991 printf("Blocksize is now %s bytes.\n", options[OPT_BLKSIZE].o_request);
995 setblocksize2(int argc, char *argv[])
998 if (!options_rfc_enabled || !options_extra_enabled)
1000 "RFC2347 style or non-RFC defined options are not enabled "
1001 "(but proceeding anyway)\n");
1004 int size = atoi(argv[1]);
1010 8, 16, 32, 64, 128, 256, 512, 1024,
1011 2048, 4096, 8192, 16384, 32768, 0
1014 max = sizeof(maxdgram);
1015 if (sysctlbyname("net.inet.udp.maxdgram",
1016 &maxdgram, &max, NULL, 0) < 0) {
1017 perror("sysctl: net.inet.udp.maxdgram");
1021 for (i = 0; sizes[i] != 0; i++) {
1022 if (sizes[i] == size) break;
1024 if (sizes[i] == 0) {
1025 printf("Blocksize2 should be a power of two between "
1030 if (size < BLKSIZE_MIN || size > BLKSIZE_MAX) {
1031 printf("Blocksize2 should be between "
1032 "%d and %d bytes.\n", BLKSIZE_MIN, BLKSIZE_MAX);
1034 } else if (size > (int)maxdgram - 4) {
1035 printf("Blocksize2 can't be bigger than %ld bytes due "
1036 "to the net.inet.udp.maxdgram sysctl limitation.\n",
1038 for (i = 0; sizes[i+1] != 0; i++) {
1039 if ((int)maxdgram < sizes[i+1]) break;
1041 asprintf(&options[OPT_BLKSIZE2].o_request,
1044 asprintf(&options[OPT_BLKSIZE2].o_request, "%d", size);
1047 printf("Blocksize2 is now %s bytes.\n",
1048 options[OPT_BLKSIZE2].o_request);
1052 setpacketdrop(int argc, char *argv[])
1056 packetdroppercentage = atoi(argv[1]);
1058 printf("Randomly %d in 100 packets will be dropped\n",
1059 packetdroppercentage);