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>
53 #include <sys/types.h>
54 #include <sys/socket.h>
55 #include <sys/sysctl.h>
59 #include <netinet/in.h>
60 #include <arpa/inet.h>
61 #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 volatile 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 **);
118 static void command(bool, EditLine *, History *, HistEvent *) __dead2;
119 static const char *command_prompt(void);
121 static void urihandling(char *URI);
122 static void getusage(char *);
123 static void makeargv(char *line);
124 static void putusage(char *);
125 static void settftpmode(const char *);
127 static char *tail(char *);
128 static struct cmd *getcmd(char *);
130 #define HELPINDENT (sizeof("connect"))
134 void (*handler)(int, char **);
138 static struct cmd cmdtab[] = {
139 { "connect", setpeer, "connect to remote tftp" },
140 { "mode", modecmd, "set file transfer mode" },
141 { "put", put, "send file" },
142 { "get", get, "receive file" },
143 { "quit", quit, "exit tftp" },
144 { "verbose", setverbose, "toggle verbose mode" },
145 { "status", showstatus, "show current status" },
146 { "binary", setbinary, "set mode to octet" },
147 { "ascii", setascii, "set mode to netascii" },
148 { "rexmt", settimeoutpacket,
149 "set per-packet retransmission timeout[-]" },
150 { "timeout", settimeoutnetwork,
151 "set total retransmission timeout" },
152 { "trace", setdebug, "enable 'debug packet'[-]" },
153 { "debug", setdebug, "enable verbose output" },
154 { "blocksize", setblocksize, "set blocksize[*]" },
155 { "blocksize2", setblocksize2, "set blocksize as a power of 2[**]" },
156 { "rollover", setrollover, "rollover after 64K packets[**]" },
157 { "options", setoptions,
158 "enable or disable RFC2347 style options" },
159 { "help", help, "print help information" },
160 { "packetdrop", setpacketdrop, "artificial packetloss feature" },
161 { "?", help, "print help information" },
165 static struct modes {
169 { "ascii", "netascii" },
170 { "netascii", "netascii" },
171 { "binary", "octet" },
172 { "image", "octet" },
173 { "octet", "octet" },
178 main(int argc, char *argv[])
182 static History *hist;
185 acting_as_client = 1;
187 strcpy(mode, "octet");
188 signal(SIGINT, intr);
190 interactive = isatty(STDIN_FILENO);
192 el = el_init("tftp", stdin, stdout, stderr);
193 hist = history_init();
194 history(hist, &he, H_SETSIZE, 100);
195 el_set(el, EL_HIST, history, hist);
196 el_set(el, EL_EDITOR, "emacs");
197 el_set(el, EL_PROMPT, command_prompt);
198 el_set(el, EL_SIGNAL, 1);
203 if (setjmp(toplevel) != 0)
206 if (strncmp(argv[1], "tftp://", 7) == 0) {
207 urihandling(argv[1]);
214 if (setjmp(toplevel) != 0) {
221 command(interactive, el, hist, &he);
225 * RFC3617 handling of TFTP URIs:
227 * tftpURI = "tftp://" host "/" file [ mode ]
228 * mode = ";" "mode=" ( "netascii" / "octet" )
229 * file = *( unreserved / escaped )
230 * host = <as specified by RFC 2732>
231 * unreserved = <as specified in RFC 2396>
232 * escaped = <as specified in RFC 2396>
234 * We are cheating a little bit by allowing any mode as specified in the
235 * modes table defined earlier on in this file and mapping it on the real
239 urihandling(char *URI)
245 const char *tmode = "octet";
250 strlcpy(uri, URI, ARG_MAX);
253 if ((s = strchr(host, '/')) == NULL) {
255 "Invalid URI: Couldn't find / after hostname\n");
261 if ((s = strchr(path, ';')) != NULL) {
265 if (strncmp(opts, "mode=", 5) == 0) {
269 for (i = 0; modes[i].m_name != NULL; i++) {
270 if (strcmp(modes[i].m_name, tmode) == 0)
273 if (modes[i].m_name == NULL) {
274 fprintf(stderr, "Invalid mode: '%s'\n", mode);
277 settftpmode(modes[i].m_mode);
280 settftpmode("octet");
283 setpeer0(host, NULL);
285 sprintf(line, "get %s", path);
290 static char hostname[MAXHOSTNAMELEN];
293 setpeer0(char *host, const char *lport)
295 struct addrinfo hints, *res0, *res;
297 const char *cause = "unknown";
305 memset(&hints, 0, sizeof(hints));
306 hints.ai_family = PF_UNSPEC;
307 hints.ai_socktype = SOCK_DGRAM;
308 hints.ai_protocol = IPPROTO_UDP;
309 hints.ai_flags = AI_CANONNAME;
312 error = getaddrinfo(host, lport, &hints, &res0);
314 warnx("%s", gai_strerror(error));
318 for (res = res0; res; res = res->ai_next) {
319 if (res->ai_addrlen > sizeof(peeraddr))
321 peer = socket(res->ai_family, res->ai_socktype,
328 memset(&peer_sock, 0, sizeof(peer_sock));
329 peer_sock.ss_family = res->ai_family;
330 peer_sock.ss_len = res->ai_addrlen;
331 if (bind(peer, (struct sockaddr *)&peer_sock, peer_sock.ss_len) < 0) {
344 /* res->ai_addr <= sizeof(peeraddr) is guaranteed */
345 memcpy(&peer_sock, res->ai_addr, res->ai_addrlen);
346 if (res->ai_canonname) {
347 (void) strlcpy(hostname, res->ai_canonname,
350 (void) strlcpy(hostname, host, sizeof(hostname));
358 setpeer(int argc, char *argv[])
363 strcpy(line, "Connect ");
365 fgets(&line[strlen(line)], sizeof line - strlen(line), stdin);
370 if ((argc < 2) || (argc > 3)) {
371 printf("usage: %s [host [port]]\n", argv[0]);
376 setpeer0(argv[1], argv[2]);
378 setpeer0(argv[1], NULL);
382 modecmd(int argc, char *argv[])
388 printf("Using %s mode to transfer files.\n", mode);
392 for (p = modes; p->m_name; p++)
393 if (strcmp(argv[1], p->m_name) == 0)
396 settftpmode(p->m_mode);
399 printf("%s: unknown mode\n", argv[1]);
400 /* drop through and print usage message */
403 printf("usage: %s [", argv[0]);
405 for (p = modes; p->m_name != NULL; p++) {
406 printf("%s%s", sep, p->m_name);
415 setbinary(int argc __unused, char *argv[] __unused)
418 settftpmode("octet");
422 setascii(int argc __unused, char *argv[] __unused)
425 settftpmode("netascii");
429 settftpmode(const char *newmode)
432 strlcpy(mode, newmode, sizeof(mode));
434 printf("mode set to %s\n", mode);
442 put(int argc, char *argv[])
451 strcpy(line, "send ");
453 fgets(&line[strlen(line)], sizeof line - strlen(line), stdin);
462 targ = argv[argc - 1];
463 if (strrchr(argv[argc - 1], ':')) {
466 for (n = 1; n < argc - 1; n++)
467 if (strchr(argv[n], ':')) {
471 lcp = argv[argc - 1];
472 targ = strrchr(lcp, ':');
474 if (lcp[0] == '[' && lcp[strlen(lcp) - 1] == ']') {
475 lcp[strlen(lcp) - 1] = '\0';
481 printf("No target machine specified.\n");
485 cp = argc == 2 ? tail(targ) : argv[1];
486 fd = open(cp, O_RDONLY);
492 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 cp, hostname, targ, mode);
502 xmitfile(peer, port, fd, targ, mode);
506 /* this assumes the target is a directory */
507 /* on a remote unix system. hmmmm. */
508 cp = strchr(targ, '\0');
510 for (n = 1; n < argc - 1; n++) {
511 strcpy(cp, tail(argv[n]));
512 fd = open(argv[n], O_RDONLY);
518 if (fstat(fd, &sb) < 0) {
522 asprintf(&options[OPT_TSIZE].o_request, "%ju", sb.st_size);
525 printf("putting %s to %s:%s [%s]\n",
526 argv[n], hostname, targ, mode);
527 xmitfile(peer, port, fd, targ, mode);
535 printf("usage: %s file [remotename]\n", s);
536 printf(" %s file host:remotename\n", s);
537 printf(" %s file1 file2 ... fileN [[host:]remote-directory]\n", s);
544 get(int argc, char *argv[])
553 strcpy(line, "get ");
555 fgets(&line[strlen(line)], sizeof line - strlen(line), stdin);
565 for (n = 1; n < argc ; n++)
566 if (strrchr(argv[n], ':') == 0) {
567 printf("No remote host specified and "
568 "no host given for file '%s'\n", argv[n]);
573 for (n = 1; n < argc ; n++) {
574 src = strrchr(argv[n], ':');
582 if (lcp[0] == '[' && lcp[strlen(lcp) - 1] == ']') {
583 lcp[strlen(lcp) - 1] = '\0';
591 cp = argc == 3 ? argv[2] : tail(src);
592 fd = creat(cp, 0644);
598 printf("getting from %s:%s to %s [%s]\n",
599 hostname, src, cp, mode);
600 recvfile(peer, port, fd, src, mode);
603 cp = tail(src); /* new .. jdg */
604 fd = creat(cp, 0644);
610 printf("getting from %s:%s to %s [%s]\n",
611 hostname, src, cp, mode);
612 recvfile(peer, port, fd, src, mode);
620 printf("usage: %s file [localname]\n", s);
621 printf(" %s [host:]file [localname]\n", s);
622 printf(" %s [host1:]file1 [host2:]file2 ... [hostN:]fileN\n", s);
626 settimeoutpacket(int argc, char *argv[])
632 strcpy(line, "Packet timeout ");
634 fgets(&line[strlen(line)], sizeof line - strlen(line), stdin);
640 printf("usage: %s value\n", argv[0]);
645 printf("%s: bad value\n", argv[1]);
649 settimeouts(t, timeoutnetwork, maxtimeouts);
653 settimeoutnetwork(int argc, char *argv[])
659 strcpy(line, "Network timeout ");
661 fgets(&line[strlen(line)], sizeof line - strlen(line), stdin);
667 printf("usage: %s value\n", argv[0]);
672 printf("%s: bad value\n", argv[1]);
676 settimeouts(timeoutpacket, t, maxtimeouts);
680 showstatus(int argc __unused, char *argv[] __unused)
683 printf("Remote host: %s\n",
684 connected ? hostname : "none specified yet");
685 printf("RFC2347 Options support: %s\n",
686 options_rfc_enabled ? "enabled" : "disabled");
687 printf("Non-RFC defined options support: %s\n",
688 options_extra_enabled ? "enabled" : "disabled");
689 printf("Mode: %s\n", mode);
690 printf("Verbose: %s\n", verbose ? "on" : "off");
691 printf("Debug: %s\n", debug_show(debug));
692 printf("Artificial packetloss: %d in 100 packets\n",
693 packetdroppercentage);
694 printf("Segment size: %d bytes\n", segsize);
695 printf("Network timeout: %d seconds\n", timeoutpacket);
696 printf("Maximum network timeout: %d seconds\n", timeoutnetwork);
697 printf("Maximum timeouts: %d \n", maxtimeouts);
701 intr(int dummy __unused)
704 signal(SIGALRM, SIG_IGN);
706 longjmp(toplevel, -1);
715 s = strrchr(filename, '/');
736 command(bool interactive, EditLine *el, History *hist, HistEvent *hep)
746 if ((bp = el_gets(el, &num)) == NULL || num == 0)
748 len = MIN(MAXLINE, num);
749 memcpy(line, bp, len);
750 line[len - 1] = '\0';
751 history(hist, hep, H_ENTER, bp);
754 if (fgets(line, sizeof line , stdin) == NULL) {
762 if ((cp = strchr(line, '\n')))
769 c = getcmd(margv[0]);
770 if (c == (struct cmd *)-1) {
771 printf("?Ambiguous command\n");
775 printf("?Invalid command\n");
778 (*c->handler)(margc, margv);
786 struct cmd *c, *found;
787 int nmatches, longest;
792 for (c = cmdtab; (p = c->name) != NULL; c++) {
793 for (q = name; *q == *p++; q++)
794 if (*q == 0) /* exact match? */
796 if (!*q) { /* the name was a prefix */
797 if (q - name > longest) {
801 } else if (q - name == longest)
806 return ((struct cmd *)-1);
811 * Slice a string up into argc/argv.
820 if ((cp = strchr(line, '\n')) != NULL)
822 for (cp = line; margc < MAX_MARGV - 1 && *cp != '\0';) {
829 while (*cp != '\0' && !isspace(*cp))
839 quit(int argc __unused, char *argv[] __unused)
849 help(int argc, char *argv[])
854 printf("Commands may be abbreviated. Commands are:\n\n");
855 for (c = cmdtab; c->name; c++)
856 printf("%-*s\t%s\n", (int)HELPINDENT, c->name, c->help);
858 printf("\n[-] : You shouldn't use these ones anymore.\n");
859 printf("[*] : RFC2347 options support required.\n");
860 printf("[**] : Non-standard RFC2347 option.\n");
867 if (c == (struct cmd *)-1)
868 printf("?Ambiguous help command: %s\n", arg);
869 else if (c == (struct cmd *)0)
870 printf("?Invalid help command: %s\n", arg);
872 printf("%s\n", c->help);
877 setverbose(int argc __unused, char *argv[] __unused)
881 printf("Verbose mode %s.\n", verbose ? "on" : "off");
885 setoptions(int argc, char *argv[])
889 if (strcasecmp(argv[1], "enable") == 0 ||
890 strcasecmp(argv[1], "on") == 0) {
891 options_extra_enabled = 1;
892 options_rfc_enabled = 1;
894 if (strcasecmp(argv[1], "disable") == 0 ||
895 strcasecmp(argv[1], "off") == 0) {
896 options_extra_enabled = 0;
897 options_rfc_enabled = 0;
899 if (strcasecmp(argv[1], "extra") == 0)
900 options_extra_enabled = !options_extra_enabled;
902 printf("Support for RFC2347 style options are now %s.\n",
903 options_rfc_enabled ? "enabled" : "disabled");
904 printf("Support for non-RFC defined options are now %s.\n",
905 options_extra_enabled ? "enabled" : "disabled");
907 printf("\nThe following options are available:\n"
908 "\toptions on : enable support for RFC2347 style options\n"
909 "\toptions off : disable support for RFC2347 style options\n"
910 "\toptions extra : toggle support for non-RFC defined options\n"
915 setrollover(int argc, char *argv[])
919 if (strcasecmp(argv[1], "never") == 0 ||
920 strcasecmp(argv[1], "none") == 0) {
921 free(options[OPT_ROLLOVER].o_request);
922 options[OPT_ROLLOVER].o_request = NULL;
924 if (strcasecmp(argv[1], "1") == 0) {
925 free(options[OPT_ROLLOVER].o_request);
926 options[OPT_ROLLOVER].o_request = strdup("1");
928 if (strcasecmp(argv[1], "0") == 0) {
929 free(options[OPT_ROLLOVER].o_request);
930 options[OPT_ROLLOVER].o_request = strdup("0");
933 printf("Support for the rollover options is %s.\n",
934 options[OPT_ROLLOVER].o_request != NULL ? "enabled" : "disabled");
935 if (options[OPT_ROLLOVER].o_request != NULL)
936 printf("Block rollover will be to block %s.\n",
937 options[OPT_ROLLOVER].o_request);
940 printf("\nThe following rollover options are available:\n"
941 "\trollover 0 : rollover to block zero (default)\n"
942 "\trollover 1 : rollover to block one\n"
943 "\trollover never : do not support the rollover option\n"
944 "\trollover none : do not support the rollover option\n"
949 setdebug(int argc, char *argv[])
956 debug ^= debug_find(argv[i++]);
958 printf("The following debugging is enabled: %s\n", debug_show(debug));
960 printf("\nThe following debugs are available:\n");
962 while (debugs[i].name != NULL) {
963 printf("\t%s\t%s\n", debugs[i].name, debugs[i].desc);
969 setblocksize(int argc, char *argv[])
972 if (!options_rfc_enabled)
973 printf("RFC2347 style options are not enabled "
974 "(but proceeding anyway)\n");
977 int size = atoi(argv[1]);
981 max = sizeof(maxdgram);
982 if (sysctlbyname("net.inet.udp.maxdgram",
983 &maxdgram, &max, NULL, 0) < 0) {
984 perror("sysctl: net.inet.udp.maxdgram");
988 if (size < BLKSIZE_MIN || size > BLKSIZE_MAX) {
989 printf("Blocksize should be between %d and %d bytes.\n",
990 BLKSIZE_MIN, BLKSIZE_MAX);
992 } else if (size > (int)maxdgram - 4) {
993 printf("Blocksize can't be bigger than %ld bytes due "
994 "to the net.inet.udp.maxdgram sysctl limitation.\n",
996 asprintf(&options[OPT_BLKSIZE].o_request,
997 "%ld", maxdgram - 4);
999 asprintf(&options[OPT_BLKSIZE].o_request, "%d", size);
1002 printf("Blocksize is now %s bytes.\n", options[OPT_BLKSIZE].o_request);
1006 setblocksize2(int argc, char *argv[])
1009 if (!options_rfc_enabled || !options_extra_enabled)
1011 "RFC2347 style or non-RFC defined options are not enabled "
1012 "(but proceeding anyway)\n");
1015 int size = atoi(argv[1]);
1021 8, 16, 32, 64, 128, 256, 512, 1024,
1022 2048, 4096, 8192, 16384, 32768, 0
1025 max = sizeof(maxdgram);
1026 if (sysctlbyname("net.inet.udp.maxdgram",
1027 &maxdgram, &max, NULL, 0) < 0) {
1028 perror("sysctl: net.inet.udp.maxdgram");
1032 for (i = 0; sizes[i] != 0; i++) {
1033 if (sizes[i] == size) break;
1035 if (sizes[i] == 0) {
1036 printf("Blocksize2 should be a power of two between "
1041 if (size < BLKSIZE_MIN || size > BLKSIZE_MAX) {
1042 printf("Blocksize2 should be between "
1043 "%d and %d bytes.\n", BLKSIZE_MIN, BLKSIZE_MAX);
1045 } else if (size > (int)maxdgram - 4) {
1046 printf("Blocksize2 can't be bigger than %ld bytes due "
1047 "to the net.inet.udp.maxdgram sysctl limitation.\n",
1049 for (i = 0; sizes[i+1] != 0; i++) {
1050 if ((int)maxdgram < sizes[i+1]) break;
1052 asprintf(&options[OPT_BLKSIZE2].o_request,
1055 asprintf(&options[OPT_BLKSIZE2].o_request, "%d", size);
1058 printf("Blocksize2 is now %s bytes.\n",
1059 options[OPT_BLKSIZE2].o_request);
1063 setpacketdrop(int argc, char *argv[])
1067 packetdroppercentage = atoi(argv[1]);
1069 printf("Randomly %d in 100 packets will be dropped\n",
1070 packetdroppercentage);