2 * SPDX-License-Identifier: BSD-3-Clause
4 * Copyright (c) 1983, 1993
5 * The Regents of the University of California. All rights reserved.
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
10 * 1. Redistributions of source code must retain the above copyright
11 * notice, this list of conditions and the following disclaimer.
12 * 2. Redistributions in binary form must reproduce the above copyright
13 * notice, this list of conditions and the following disclaimer in the
14 * documentation and/or other materials provided with the distribution.
15 * 3. Neither the name of the University nor the names of its contributors
16 * may be used to endorse or promote products derived from this software
17 * without specific prior written permission.
19 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
20 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
23 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
25 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
26 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
27 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
28 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
33 static const char copyright[] =
34 "@(#) Copyright (c) 1983, 1993\n\
35 The Regents of the University of California. All rights reserved.\n";
40 static char sccsid[] = "@(#)main.c 8.1 (Berkeley) 6/6/93";
44 #include <sys/cdefs.h>
45 __FBSDID("$FreeBSD$");
47 /* Many bug fixes are from Jim Guyton <guyton@rand-unix> */
50 * TFTP User Program -- Command Interface.
52 #include <sys/param.h>
54 #include <sys/socket.h>
56 #include <sys/sysctl.h>
58 #include <netinet/in.h>
59 #include <arpa/inet.h>
60 #include <arpa/tftp.h>
75 #include "tftp-utils.h"
77 #include "tftp-options.h"
80 #define MAXLINE (2 * MAXPATHLEN)
81 #define TIMEOUT 5 /* secs between rexmt's */
83 typedef struct sockaddr_storage peeraddr;
86 static jmp_buf toplevel;
87 static int txrx_error;
92 static char *margv[MAX_MARGV];
95 static char *port = NULL;
97 static void get(int, char **);
98 static void help(int, char **);
99 static void intr(int);
100 static void modecmd(int, char **);
101 static void put(int, char **);
102 static void quit(int, char **);
103 static void setascii(int, char **);
104 static void setbinary(int, char **);
105 static void setpeer0(char *, const char *);
106 static void setpeer(int, char **);
107 static void settimeoutpacket(int, char **);
108 static void settimeoutnetwork(int, char **);
109 static void setdebug(int, char **);
110 static void setverbose(int, char **);
111 static void showstatus(int, char **);
112 static void setblocksize(int, char **);
113 static void setblocksize2(int, char **);
114 static void setoptions(int, char **);
115 static void setrollover(int, char **);
116 static void setpacketdrop(int, char **);
117 static void setwindowsize(int, char **);
119 static void command(bool, EditLine *, History *, HistEvent *) __dead2;
120 static const char *command_prompt(void);
122 static void urihandling(char *URI);
123 static void getusage(char *);
124 static void makeargv(char *line);
125 static void putusage(char *);
126 static void settftpmode(const char *);
128 static char *tail(char *);
129 static const struct cmd *getcmd(const char *);
131 #define HELPINDENT (sizeof("connect"))
135 void (*handler)(int, char **);
139 static struct cmd cmdtab[] = {
140 { "connect", setpeer, "connect to remote tftp" },
141 { "mode", modecmd, "set file transfer mode" },
142 { "put", put, "send file" },
143 { "get", get, "receive file" },
144 { "quit", quit, "exit tftp" },
145 { "verbose", setverbose, "toggle verbose mode" },
146 { "status", showstatus, "show current status" },
147 { "binary", setbinary, "set mode to octet" },
148 { "ascii", setascii, "set mode to netascii" },
149 { "rexmt", settimeoutpacket,
150 "set per-packet retransmission timeout[-]" },
151 { "timeout", settimeoutnetwork,
152 "set total retransmission timeout" },
153 { "trace", setdebug, "enable 'debug packet'[-]" },
154 { "debug", setdebug, "enable verbose output" },
155 { "blocksize", setblocksize, "set blocksize[*]" },
156 { "blocksize2", setblocksize2, "set blocksize as a power of 2[**]" },
157 { "rollover", setrollover, "rollover after 64K packets[**]" },
158 { "options", setoptions,
159 "enable or disable RFC2347 style options" },
160 { "help", help, "print help information" },
161 { "packetdrop", setpacketdrop, "artificial packetloss feature" },
162 { "windowsize", setwindowsize, "set windowsize[*]" },
163 { "?", help, "print help information" },
167 static struct modes {
171 { "ascii", "netascii" },
172 { "netascii", "netascii" },
173 { "binary", "octet" },
174 { "image", "octet" },
175 { "octet", "octet" },
180 main(int argc, char *argv[])
184 static History *hist;
187 acting_as_client = 1;
189 strcpy(mode, "octet");
190 signal(SIGINT, intr);
192 interactive = isatty(STDIN_FILENO);
194 el = el_init("tftp", stdin, stdout, stderr);
195 hist = history_init();
196 history(hist, &he, H_SETSIZE, 100);
197 el_set(el, EL_HIST, history, hist);
198 el_set(el, EL_EDITOR, "emacs");
199 el_set(el, EL_PROMPT, command_prompt);
200 el_set(el, EL_SIGNAL, 1);
205 if (setjmp(toplevel) != 0)
208 if (strncmp(argv[1], "tftp://", 7) == 0) {
209 urihandling(argv[1]);
216 if (setjmp(toplevel) != 0) {
223 command(interactive, el, hist, &he);
227 * RFC3617 handling of TFTP URIs:
229 * tftpURI = "tftp://" host "/" file [ mode ]
230 * mode = ";" "mode=" ( "netascii" / "octet" )
231 * file = *( unreserved / escaped )
232 * host = <as specified by RFC 2732>
233 * unreserved = <as specified in RFC 2396>
234 * escaped = <as specified in RFC 2396>
236 * We are cheating a little bit by allowing any mode as specified in the
237 * modes table defined earlier on in this file and mapping it on the real
241 urihandling(char *URI)
247 const char *tmode = "octet";
252 strlcpy(uri, URI, ARG_MAX);
255 if ((s = strchr(host, '/')) == NULL) {
257 "Invalid URI: Couldn't find / after hostname\n");
263 if ((s = strchr(path, ';')) != NULL) {
267 if (strncmp(opts, "mode=", 5) == 0) {
271 for (i = 0; modes[i].m_name != NULL; i++) {
272 if (strcmp(modes[i].m_name, tmode) == 0)
275 if (modes[i].m_name == NULL) {
276 fprintf(stderr, "Invalid mode: '%s'\n", mode);
279 settftpmode(modes[i].m_mode);
282 settftpmode("octet");
285 setpeer0(host, NULL);
287 sprintf(line, "get %s", path);
292 static char hostname[MAXHOSTNAMELEN];
295 setpeer0(char *host, const char *lport)
297 struct addrinfo hints, *res0, *res;
299 const char *cause = "unknown";
307 memset(&hints, 0, sizeof(hints));
308 hints.ai_family = PF_UNSPEC;
309 hints.ai_socktype = SOCK_DGRAM;
310 hints.ai_protocol = IPPROTO_UDP;
311 hints.ai_flags = AI_CANONNAME;
314 error = getaddrinfo(host, lport, &hints, &res0);
316 warnx("%s", gai_strerror(error));
320 for (res = res0; res; res = res->ai_next) {
321 if (res->ai_addrlen > sizeof(peeraddr))
323 peer = socket(res->ai_family, res->ai_socktype,
330 memset(&peer_sock, 0, sizeof(peer_sock));
331 peer_sock.ss_family = res->ai_family;
332 peer_sock.ss_len = res->ai_addrlen;
333 if (bind(peer, (struct sockaddr *)&peer_sock, peer_sock.ss_len) < 0) {
346 /* res->ai_addr <= sizeof(peeraddr) is guaranteed */
347 memcpy(&peer_sock, res->ai_addr, res->ai_addrlen);
348 if (res->ai_canonname) {
349 (void) strlcpy(hostname, res->ai_canonname,
352 (void) strlcpy(hostname, host, sizeof(hostname));
360 setpeer(int argc, char *argv[])
365 strcpy(line, "Connect ");
367 fgets(&line[strlen(line)], sizeof line - strlen(line), stdin);
372 if ((argc < 2) || (argc > 3)) {
373 printf("usage: %s [host [port]]\n", argv[0]);
378 setpeer0(argv[1], argv[2]);
380 setpeer0(argv[1], NULL);
384 modecmd(int argc, char *argv[])
390 printf("Using %s mode to transfer files.\n", mode);
394 for (p = modes; p->m_name; p++)
395 if (strcmp(argv[1], p->m_name) == 0)
398 settftpmode(p->m_mode);
401 printf("%s: unknown mode\n", argv[1]);
402 /* drop through and print usage message */
405 printf("usage: %s [", argv[0]);
407 for (p = modes; p->m_name != NULL; p++) {
408 printf("%s%s", sep, p->m_name);
417 setbinary(int argc __unused, char *argv[] __unused)
420 settftpmode("octet");
424 setascii(int argc __unused, char *argv[] __unused)
427 settftpmode("netascii");
431 settftpmode(const char *newmode)
434 strlcpy(mode, newmode, sizeof(mode));
436 printf("mode set to %s\n", mode);
444 put(int argc, char *argv[])
448 char *cp, *targ, *path;
453 strcpy(line, "send ");
455 fgets(&line[strlen(line)], sizeof line - strlen(line), stdin);
464 targ = argv[argc - 1];
465 if (strrchr(argv[argc - 1], ':')) {
468 for (n = 1; n < argc - 1; n++)
469 if (strchr(argv[n], ':')) {
473 lcp = argv[argc - 1];
474 targ = strrchr(lcp, ':');
476 if (lcp[0] == '[' && lcp[strlen(lcp) - 1] == ']') {
477 lcp[strlen(lcp) - 1] = '\0';
483 printf("No target machine specified.\n");
487 cp = argc == 2 ? tail(targ) : argv[1];
488 fd = open(cp, O_RDONLY);
494 if (fstat(fd, &sb) < 0) {
499 options_set_request(OPT_TSIZE, "%ju", (uintmax_t)sb.st_size);
502 printf("putting %s to %s:%s [%s]\n",
503 cp, hostname, targ, mode);
504 if (xmitfile(peer, port, fd, targ, mode))
509 /* this assumes the target is a directory */
510 /* on a remote unix system. hmmmm. */
511 for (n = 1; n < argc - 1; n++) {
512 if (asprintf(&path, "%s/%s", targ, tail(argv[n])) < 0)
515 fd = open(argv[n], O_RDONLY);
522 if (fstat(fd, &sb) < 0) {
528 options_set_request(OPT_TSIZE, "%ju", (uintmax_t)sb.st_size);
531 printf("putting %s to %s:%s [%s]\n",
532 argv[n], hostname, path, mode);
533 if (xmitfile(peer, port, fd, path, mode) != 0)
545 printf("usage: %s file [remotename]\n", s);
546 printf(" %s file host:remotename\n", s);
547 printf(" %s file1 file2 ... fileN [[host:]remote-directory]\n", s);
554 get(int argc, char *argv[])
563 strcpy(line, "get ");
565 fgets(&line[strlen(line)], sizeof line - strlen(line), stdin);
575 for (n = 1; n < argc ; n++)
576 if (strrchr(argv[n], ':') == 0) {
577 printf("No remote host specified and "
578 "no host given for file '%s'\n", argv[n]);
583 for (n = 1; n < argc ; n++) {
584 src = strrchr(argv[n], ':');
592 if (lcp[0] == '[' && lcp[strlen(lcp) - 1] == ']') {
593 lcp[strlen(lcp) - 1] = '\0';
601 cp = argc == 3 ? argv[2] : tail(src);
602 fd = creat(cp, 0644);
608 printf("getting from %s:%s to %s [%s]\n",
609 hostname, src, cp, mode);
610 if (recvfile(peer, port, fd, src, mode) != 0)
614 cp = tail(src); /* new .. jdg */
615 fd = creat(cp, 0644);
621 printf("getting from %s:%s to %s [%s]\n",
622 hostname, src, cp, mode);
623 if (recvfile(peer, port, fd, src, mode) != 0)
632 printf("usage: %s file [localname]\n", s);
633 printf(" %s [host:]file [localname]\n", s);
634 printf(" %s [host1:]file1 [host2:]file2 ... [hostN:]fileN\n", s);
638 settimeoutpacket(int argc, char *argv[])
644 strcpy(line, "Packet timeout ");
646 fgets(&line[strlen(line)], sizeof line - strlen(line), stdin);
652 printf("usage: %s value\n", argv[0]);
657 printf("%s: bad value\n", argv[1]);
661 settimeouts(t, timeoutnetwork, maxtimeouts);
665 settimeoutnetwork(int argc, char *argv[])
671 strcpy(line, "Network timeout ");
673 fgets(&line[strlen(line)], sizeof line - strlen(line), stdin);
679 printf("usage: %s value\n", argv[0]);
684 printf("%s: bad value\n", argv[1]);
688 settimeouts(timeoutpacket, t, maxtimeouts);
692 showstatus(int argc __unused, char *argv[] __unused)
695 printf("Remote host: %s\n",
696 connected ? hostname : "none specified yet");
697 printf("RFC2347 Options support: %s\n",
698 options_rfc_enabled ? "enabled" : "disabled");
699 printf("Non-RFC defined options support: %s\n",
700 options_extra_enabled ? "enabled" : "disabled");
701 printf("Mode: %s\n", mode);
702 printf("Verbose: %s\n", verbose ? "on" : "off");
703 printf("Debug: %s\n", debug_show(debug));
704 printf("Artificial packetloss: %d in 100 packets\n",
705 packetdroppercentage);
706 printf("Segment size: %d bytes\n", segsize);
707 printf("Network timeout: %d seconds\n", timeoutpacket);
708 printf("Maximum network timeout: %d seconds\n", timeoutnetwork);
709 printf("Maximum timeouts: %d \n", maxtimeouts);
713 intr(int dummy __unused)
716 signal(SIGALRM, SIG_IGN);
718 longjmp(toplevel, -1);
727 s = strrchr(filename, '/');
748 command(bool interactive, EditLine *el, History *hist, HistEvent *hep)
758 if ((bp = el_gets(el, &num)) == NULL || num == 0)
760 len = MIN(MAXLINE, num);
761 memcpy(line, bp, len);
762 line[len - 1] = '\0';
763 history(hist, hep, H_ENTER, bp);
766 if (fgets(line, sizeof line , stdin) == NULL) {
774 if ((cp = strchr(line, '\n')))
781 c = getcmd(margv[0]);
782 if (c == (struct cmd *)-1) {
783 printf("?Ambiguous command\n");
787 printf("?Invalid command\n");
790 (*c->handler)(margc, margv);
794 static const struct cmd *
795 getcmd(const char *name)
798 const struct cmd *c, *found;
805 for (c = cmdtab; (p = c->name) != NULL; c++) {
806 for (q = name; *q == *p++; q++)
807 if (*q == '\0') /* exact match? */
809 if (*q == '\0') { /* the name was a prefix */
810 if (q - name > longest) {
814 } else if (q - name == longest)
819 return ((struct cmd *)-1);
824 * Slice a string up into argc/argv.
833 if ((cp = strchr(line, '\n')) != NULL)
835 for (cp = line; margc < MAX_MARGV - 1 && *cp != '\0';) {
842 while (*cp != '\0' && !isspace(*cp))
852 quit(int argc __unused, char *argv[] __unused)
862 help(int argc, char *argv[])
867 printf("Commands may be abbreviated. Commands are:\n\n");
868 for (c = cmdtab; c->name; c++)
869 printf("%-*s\t%s\n", (int)HELPINDENT, c->name, c->help);
871 printf("\n[-] : You shouldn't use these ones anymore.\n");
872 printf("[*] : RFC2347 options support required.\n");
873 printf("[**] : Non-standard RFC2347 option.\n");
880 if (c == (struct cmd *)-1)
881 printf("?Ambiguous help command: %s\n", arg);
882 else if (c == (struct cmd *)0)
883 printf("?Invalid help command: %s\n", arg);
885 printf("%s\n", c->help);
890 setverbose(int argc __unused, char *argv[] __unused)
894 printf("Verbose mode %s.\n", verbose ? "on" : "off");
898 setoptions(int argc, char *argv[])
902 if (strcasecmp(argv[1], "enable") == 0 ||
903 strcasecmp(argv[1], "on") == 0) {
904 options_extra_enabled = 1;
905 options_rfc_enabled = 1;
907 if (strcasecmp(argv[1], "disable") == 0 ||
908 strcasecmp(argv[1], "off") == 0) {
909 options_extra_enabled = 0;
910 options_rfc_enabled = 0;
912 if (strcasecmp(argv[1], "extra") == 0)
913 options_extra_enabled = !options_extra_enabled;
915 printf("Support for RFC2347 style options are now %s.\n",
916 options_rfc_enabled ? "enabled" : "disabled");
917 printf("Support for non-RFC defined options are now %s.\n",
918 options_extra_enabled ? "enabled" : "disabled");
920 printf("\nThe following options are available:\n"
921 "\toptions on : enable support for RFC2347 style options\n"
922 "\toptions off : disable support for RFC2347 style options\n"
923 "\toptions extra : toggle support for non-RFC defined options\n"
928 setrollover(int argc, char *argv[])
932 if (strcasecmp(argv[1], "never") == 0 ||
933 strcasecmp(argv[1], "none") == 0) {
934 options_set_request(OPT_ROLLOVER, NULL);
936 if (strcasecmp(argv[1], "1") == 0) {
937 options_set_request(OPT_ROLLOVER, "1");
939 if (strcasecmp(argv[1], "0") == 0) {
940 options_set_request(OPT_ROLLOVER, "0");
943 printf("Support for the rollover options is %s.\n",
944 options[OPT_ROLLOVER].o_request != NULL ? "enabled" : "disabled");
945 if (options[OPT_ROLLOVER].o_request != NULL)
946 printf("Block rollover will be to block %s.\n",
947 options[OPT_ROLLOVER].o_request);
950 printf("\nThe following rollover options are available:\n"
951 "\trollover 0 : rollover to block zero (default)\n"
952 "\trollover 1 : rollover to block one\n"
953 "\trollover never : do not support the rollover option\n"
954 "\trollover none : do not support the rollover option\n"
959 setdebug(int argc, char *argv[])
966 debug ^= debug_find(argv[i++]);
968 printf("The following debugging is enabled: %s\n", debug_show(debug));
970 printf("\nThe following debugs are available:\n");
972 while (debugs[i].name != NULL) {
973 printf("\t%s\t%s\n", debugs[i].name, debugs[i].desc);
979 setblocksize(int argc, char *argv[])
982 if (!options_rfc_enabled)
983 printf("RFC2347 style options are not enabled "
984 "(but proceeding anyway)\n");
987 int size = atoi(argv[1]);
991 max = sizeof(maxdgram);
992 if (sysctlbyname("net.inet.udp.maxdgram",
993 &maxdgram, &max, NULL, 0) < 0) {
994 perror("sysctl: net.inet.udp.maxdgram");
998 if (size < BLKSIZE_MIN || size > BLKSIZE_MAX) {
999 printf("Blocksize should be between %d and %d bytes.\n",
1000 BLKSIZE_MIN, BLKSIZE_MAX);
1002 } else if (size > (int)maxdgram - 4) {
1003 printf("Blocksize can't be bigger than %ld bytes due "
1004 "to the net.inet.udp.maxdgram sysctl limitation.\n",
1006 options_set_request(OPT_BLKSIZE, "%ld", maxdgram - 4);
1008 options_set_request(OPT_BLKSIZE, "%d", size);
1011 printf("Blocksize is now %s bytes.\n", options[OPT_BLKSIZE].o_request);
1015 setblocksize2(int argc, char *argv[])
1018 if (!options_rfc_enabled || !options_extra_enabled)
1020 "RFC2347 style or non-RFC defined options are not enabled "
1021 "(but proceeding anyway)\n");
1024 int size = atoi(argv[1]);
1030 8, 16, 32, 64, 128, 256, 512, 1024,
1031 2048, 4096, 8192, 16384, 32768, 0
1034 max = sizeof(maxdgram);
1035 if (sysctlbyname("net.inet.udp.maxdgram",
1036 &maxdgram, &max, NULL, 0) < 0) {
1037 perror("sysctl: net.inet.udp.maxdgram");
1041 for (i = 0; sizes[i] != 0; i++) {
1042 if (sizes[i] == size) break;
1044 if (sizes[i] == 0) {
1045 printf("Blocksize2 should be a power of two between "
1050 if (size < BLKSIZE_MIN || size > BLKSIZE_MAX) {
1051 printf("Blocksize2 should be between "
1052 "%d and %d bytes.\n", BLKSIZE_MIN, BLKSIZE_MAX);
1054 } else if (size > (int)maxdgram - 4) {
1055 printf("Blocksize2 can't be bigger than %ld bytes due "
1056 "to the net.inet.udp.maxdgram sysctl limitation.\n",
1058 for (i = 0; sizes[i+1] != 0; i++) {
1059 if ((int)maxdgram < sizes[i+1]) break;
1061 options_set_request(OPT_BLKSIZE2, "%d", sizes[i]);
1063 options_set_request(OPT_BLKSIZE2, "%d", size);
1066 printf("Blocksize2 is now %s bytes.\n",
1067 options[OPT_BLKSIZE2].o_request);
1071 setpacketdrop(int argc, char *argv[])
1075 packetdroppercentage = atoi(argv[1]);
1077 printf("Randomly %d in 100 packets will be dropped\n",
1078 packetdroppercentage);
1082 setwindowsize(int argc, char *argv[])
1085 if (!options_rfc_enabled)
1086 printf("RFC2347 style options are not enabled "
1087 "(but proceeding anyway)\n");
1090 int size = atoi(argv[1]);
1092 if (size < WINDOWSIZE_MIN || size > WINDOWSIZE_MAX) {
1093 printf("Windowsize should be between %d and %d "
1094 "blocks.\n", WINDOWSIZE_MIN, WINDOWSIZE_MAX);
1097 options_set_request(OPT_WINDOWSIZE, "%d", size);
1100 printf("Windowsize is now %s blocks.\n",
1101 options[OPT_WINDOWSIZE].o_request);