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 * 3. All advertising materials mentioning features or use of this software
14 * must display the following acknowledgement:
15 * This product includes software developed by the University of
16 * California, Berkeley and its contributors.
17 * 4. Neither the name of the University nor the names of its contributors
18 * may be used to endorse or promote products derived from this software
19 * without specific prior written permission.
21 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
22 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
25 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
35 static const char copyright[] =
36 "@(#) Copyright (c) 1983, 1993\n\
37 The Regents of the University of California. All rights reserved.\n";
42 static char sccsid[] = "@(#)main.c 8.1 (Berkeley) 6/6/93";
46 #include <sys/cdefs.h>
47 __FBSDID("$FreeBSD$");
49 /* Many bug fixes are from Jim Guyton <guyton@rand-unix> */
52 * TFTP User Program -- Command Interface.
54 #include <sys/param.h>
55 #include <sys/types.h>
56 #include <sys/socket.h>
57 #include <sys/sysctl.h>
59 #include <sys/param.h>
62 #include <netinet/in.h>
63 #include <arpa/inet.h>
64 #include <arpa/tftp.h>
77 #include "tftp-utils.h"
79 #include "tftp-options.h"
83 #define TIMEOUT 5 /* secs between rexmt's */
85 static struct sockaddr_storage peeraddr;
89 volatile int txrx_error;
94 static char *margv[MAX_MARGV];
99 static void get(int, char **);
100 static void help(int, char **);
101 static void intr(int);
102 static void modecmd(int, char **);
103 static void put(int, char **);
104 static void quit(int, char **);
105 static void setascii(int, char **);
106 static void setbinary(int, char **);
107 static void setpeer0(char *, const char *);
108 static void setpeer(int, char **);
109 static void settimeoutpacket(int, char **);
110 static void settimeoutnetwork(int, char **);
111 static void setdebug(int, char **);
112 static void setverbose(int, char **);
113 static void showstatus(int, char **);
114 static void setblocksize(int, char **);
115 static void setblocksize2(int, char **);
116 static void setoptions(int, char **);
117 static void setrollover(int, char **);
118 static void setpacketdrop(int, char **);
120 static void command(void) __dead2;
121 static const char *command_prompt(void);
123 static void urihandling(char *URI);
124 static void getusage(char *);
125 static void makeargv(char *line);
126 static void putusage(char *);
127 static void settftpmode(const char *);
129 static char *tail(char *);
130 static struct cmd *getcmd(char *);
132 #define HELPINDENT (sizeof("connect"))
136 void (*handler)(int, char **);
140 static struct cmd cmdtab[] = {
141 { "connect", setpeer, "connect to remote tftp" },
142 { "mode", modecmd, "set file transfer mode" },
143 { "put", put, "send file" },
144 { "get", get, "receive file" },
145 { "quit", quit, "exit tftp" },
146 { "verbose", setverbose, "toggle verbose mode" },
147 { "status", showstatus, "show current status" },
148 { "binary", setbinary, "set mode to octet" },
149 { "ascii", setascii, "set mode to netascii" },
150 { "rexmt", settimeoutpacket,
151 "set per-packet retransmission timeout[-]" },
152 { "timeout", settimeoutnetwork,
153 "set total retransmission timeout" },
154 { "trace", setdebug, "enable 'debug packet'[-]" },
155 { "debug", setdebug, "enable verbose output" },
156 { "blocksize", setblocksize, "set blocksize[*]" },
157 { "blocksize2", setblocksize2, "set blocksize as a power of 2[**]" },
158 { "rollover", setrollover, "rollover after 64K packets[**]" },
159 { "options", setoptions,
160 "enable or disable RFC2347 style options" },
161 { "help", help, "print help information" },
162 { "packetdrop", setpacketdrop, "artifical packetloss feature" },
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[])
183 acting_as_client = 1;
185 strcpy(mode, "netascii");
186 signal(SIGINT, intr);
188 if (setjmp(toplevel) != 0)
191 if (strncmp(argv[1], "tftp://", 7) == 0) {
192 urihandling(argv[1]);
198 if (setjmp(toplevel) != 0)
206 * RFC3617 handling of TFTP URIs:
208 * tftpURI = "tftp://" host "/" file [ mode ]
209 * mode = ";" "mode=" ( "netascii" / "octet" )
210 * file = *( unreserved / escaped )
211 * host = <as specified by RFC 2732>
212 * unreserved = <as specified in RFC 2396>
213 * escaped = <as specified in RFC 2396>
215 * We are cheating a little bit by allowing any mode as specified in the
216 * modes table defined earlier on in this file and mapping it on the real
220 urihandling(char *URI)
226 const char *tmode = "octet";
231 strncpy(uri, URI, ARG_MAX);
234 if ((s = strchr(host, '/')) == NULL) {
236 "Invalid URI: Couldn't find / after hostname\n");
242 if ((s = strchr(path, ';')) != NULL) {
246 if (strncmp(opts, "mode=", 5) == 0) {
250 for (i = 0; modes[i].m_name != NULL; i++) {
251 if (strcmp(modes[i].m_name, tmode) == 0)
254 if (modes[i].m_name == NULL) {
255 fprintf(stderr, "Invalid mode: '%s'\n", mode);
258 settftpmode(modes[i].m_mode);
261 settftpmode("octet");
264 setpeer0(host, NULL);
266 sprintf(line, "get %s", path);
271 static char hostname[MAXHOSTNAMELEN];
274 setpeer0(char *host, const char *lport)
276 struct addrinfo hints, *res0, *res;
278 const char *cause = "unknown";
286 memset(&hints, 0, sizeof(hints));
287 hints.ai_family = PF_UNSPEC;
288 hints.ai_socktype = SOCK_DGRAM;
289 hints.ai_protocol = IPPROTO_UDP;
290 hints.ai_flags = AI_CANONNAME;
293 error = getaddrinfo(host, lport, &hints, &res0);
295 warnx("%s", gai_strerror(error));
299 for (res = res0; res; res = res->ai_next) {
300 if (res->ai_addrlen > sizeof(peeraddr))
302 peer = socket(res->ai_family, res->ai_socktype,
309 memset(&peer_sock, 0, sizeof(peer_sock));
310 peer_sock.ss_family = res->ai_family;
311 peer_sock.ss_len = res->ai_addrlen;
312 if (bind(peer, (struct sockaddr *)&peer_sock, peer_sock.ss_len) < 0) {
325 /* res->ai_addr <= sizeof(peeraddr) is guaranteed */
326 memcpy(&peer_sock, res->ai_addr, res->ai_addrlen);
327 if (res->ai_canonname) {
328 (void) strncpy(hostname, res->ai_canonname,
331 (void) strncpy(hostname, host, sizeof(hostname));
332 hostname[sizeof(hostname)-1] = 0;
340 setpeer(int argc, char *argv[])
345 strcpy(line, "Connect ");
347 fgets(&line[strlen(line)], sizeof line - strlen(line), stdin);
352 if ((argc < 2) || (argc > 3)) {
353 printf("usage: %s [host [port]]\n", argv[0]);
358 setpeer0(argv[1], argv[2]);
360 setpeer0(argv[1], NULL);
364 modecmd(int argc, char *argv[])
370 printf("Using %s mode to transfer files.\n", mode);
374 for (p = modes; p->m_name; p++)
375 if (strcmp(argv[1], p->m_name) == 0)
378 settftpmode(p->m_mode);
381 printf("%s: unknown mode\n", argv[1]);
382 /* drop through and print usage message */
385 printf("usage: %s [", argv[0]);
387 for (p = modes; p->m_name != NULL; p++) {
388 printf("%s%s", sep, p->m_name);
397 setbinary(int argc __unused, char *argv[] __unused)
400 settftpmode("octet");
404 setascii(int argc __unused, char *argv[] __unused)
407 settftpmode("netascii");
411 settftpmode(const char *newmode)
414 strcpy(mode, newmode);
416 printf("mode set to %s\n", mode);
424 put(int argc, char *argv[])
433 strcpy(line, "send ");
435 fgets(&line[strlen(line)], sizeof line - strlen(line), stdin);
444 targ = argv[argc - 1];
445 if (rindex(argv[argc - 1], ':')) {
448 for (n = 1; n < argc - 1; n++)
449 if (index(argv[n], ':')) {
453 lcp = argv[argc - 1];
454 targ = rindex(lcp, ':');
456 if (lcp[0] == '[' && lcp[strlen(lcp) - 1] == ']') {
457 lcp[strlen(lcp) - 1] = '\0';
463 printf("No target machine specified.\n");
467 cp = argc == 2 ? tail(targ) : argv[1];
468 fd = open(cp, O_RDONLY);
475 asprintf(&options[OPT_TSIZE].o_request, "%ju", sb.st_size);
478 printf("putting %s to %s:%s [%s]\n",
479 cp, hostname, targ, mode);
480 xmitfile(peer, port, fd, targ, mode);
483 /* this assumes the target is a directory */
484 /* on a remote unix system. hmmmm. */
485 cp = index(targ, '\0');
487 for (n = 1; n < argc - 1; n++) {
488 strcpy(cp, tail(argv[n]));
489 fd = open(argv[n], O_RDONLY);
496 asprintf(&options[OPT_TSIZE].o_request, "%ju", sb.st_size);
499 printf("putting %s to %s:%s [%s]\n",
500 argv[n], hostname, targ, mode);
501 xmitfile(peer, port, fd, targ, mode);
509 printf("usage: %s file [remotename]\n", s);
510 printf(" %s file host:remotename\n", s);
511 printf(" %s file1 file2 ... fileN [[host:]remote-directory]\n", s);
518 get(int argc, char *argv[])
527 strcpy(line, "get ");
529 fgets(&line[strlen(line)], sizeof line - strlen(line), stdin);
539 for (n = 1; n < argc ; n++)
540 if (rindex(argv[n], ':') == 0) {
541 printf("No remote host specified and "
542 "no host given for file '%s'\n", argv[n]);
547 for (n = 1; n < argc ; n++) {
548 src = rindex(argv[n], ':');
556 if (lcp[0] == '[' && lcp[strlen(lcp) - 1] == ']') {
557 lcp[strlen(lcp) - 1] = '\0';
565 cp = argc == 3 ? argv[2] : tail(src);
566 fd = creat(cp, 0644);
572 printf("getting from %s:%s to %s [%s]\n",
573 hostname, src, cp, mode);
574 recvfile(peer, port, fd, src, mode);
577 cp = tail(src); /* new .. jdg */
578 fd = creat(cp, 0644);
584 printf("getting from %s:%s to %s [%s]\n",
585 hostname, src, cp, mode);
586 recvfile(peer, port, fd, src, mode);
594 printf("usage: %s file [localname]\n", s);
595 printf(" %s [host:]file [localname]\n", s);
596 printf(" %s [host1:]file1 [host2:]file2 ... [hostN:]fileN\n", s);
600 settimeoutpacket(int argc, char *argv[])
606 strcpy(line, "Packet timeout ");
608 fgets(&line[strlen(line)], sizeof line - strlen(line), stdin);
614 printf("usage: %s value\n", argv[0]);
619 printf("%s: bad value\n", argv[1]);
623 settimeouts(t, timeoutnetwork, maxtimeouts);
627 settimeoutnetwork(int argc, char *argv[])
633 strcpy(line, "Network timeout ");
635 fgets(&line[strlen(line)], sizeof line - strlen(line), stdin);
641 printf("usage: %s value\n", argv[0]);
646 printf("%s: bad value\n", argv[1]);
650 settimeouts(timeoutpacket, t, maxtimeouts);
654 showstatus(int argc __unused, char *argv[] __unused)
657 printf("Remote host: %s\n",
658 connected ? hostname : "none specified yet");
659 printf("RFC2347 Options support: %s\n",
660 options_rfc_enabled ? "enabled" : "disabled");
661 printf("Non-RFC defined options support: %s\n",
662 options_extra_enabled ? "enabled" : "disabled");
663 printf("Mode: %s\n", mode);
664 printf("Verbose: %s\n", verbose ? "on" : "off");
665 printf("Debug: %s\n", debug_show(debug));
666 printf("Artificial packetloss: %d in 100 packets\n",
667 packetdroppercentage);
668 printf("Segment size: %d bytes\n", segsize);
669 printf("Network timeout: %d seconds\n", timeoutpacket);
670 printf("Maximum network timeout: %d seconds\n", timeoutnetwork);
671 printf("Maximum timeouts: %d \n", maxtimeouts);
675 intr(int dummy __unused)
678 signal(SIGALRM, SIG_IGN);
680 longjmp(toplevel, -1);
689 s = rindex(filename, '/');
715 static History *hist;
718 int len, num, vrbose;
723 el = el_init("tftp", stdin, stdout, stderr);
724 hist = history_init();
725 history(hist, &he, H_SETSIZE, 100);
726 el_set(el, EL_HIST, history, hist);
727 el_set(el, EL_EDITOR, "emacs");
728 el_set(el, EL_PROMPT, command_prompt);
729 el_set(el, EL_SIGNAL, 1);
734 if ((bp = el_gets(el, &num)) == NULL || num == 0)
736 len = (num > MAXLINE) ? MAXLINE : num;
737 memcpy(line, bp, len);
739 history(hist, &he, H_ENTER, bp);
742 if (fgets(line, sizeof line , stdin) == 0) {
750 if ((cp = strchr(line, '\n')))
757 c = getcmd(margv[0]);
758 if (c == (struct cmd *)-1) {
759 printf("?Ambiguous command\n");
763 printf("?Invalid command\n");
766 (*c->handler)(margc, margv);
774 struct cmd *c, *found;
775 int nmatches, longest;
780 for (c = cmdtab; (p = c->name) != NULL; c++) {
781 for (q = name; *q == *p++; q++)
782 if (*q == 0) /* exact match? */
784 if (!*q) { /* the name was a prefix */
785 if (q - name > longest) {
789 } else if (q - name == longest)
794 return ((struct cmd *)-1);
799 * Slice a string up into argc/argv.
808 if ((cp = strchr(line, '\n')) != NULL)
810 for (cp = line; margc < MAX_MARGV - 1 && *cp != '\0';) {
817 while (*cp != '\0' && !isspace(*cp))
827 quit(int argc __unused, char *argv[] __unused)
837 help(int argc, char *argv[])
842 printf("Commands may be abbreviated. Commands are:\n\n");
843 for (c = cmdtab; c->name; c++)
844 printf("%-*s\t%s\n", (int)HELPINDENT, c->name, c->help);
846 printf("\n[-] : You shouldn't use these ones anymore.\n");
847 printf("[*] : RFC2834 options support required.\n");
848 printf("[**] : Non-standard RFC2834 option.\n");
855 if (c == (struct cmd *)-1)
856 printf("?Ambiguous help command: %s\n", arg);
857 else if (c == (struct cmd *)0)
858 printf("?Invalid help command: %s\n", arg);
860 printf("%s\n", c->help);
865 setverbose(int argc __unused, char *argv[] __unused)
869 printf("Verbose mode %s.\n", verbose ? "on" : "off");
873 setoptions(int argc, char *argv[])
877 if (strcasecmp(argv[1], "enable") == 0 ||
878 strcasecmp(argv[1], "on") == 0) {
879 options_extra_enabled = 1;
880 options_rfc_enabled = 1;
882 if (strcasecmp(argv[1], "disable") == 0 ||
883 strcasecmp(argv[1], "off") == 0) {
884 options_extra_enabled = 0;
885 options_rfc_enabled = 0;
887 if (strcasecmp(argv[1], "extra") == 0)
888 options_extra_enabled = !options_extra_enabled;
890 printf("Support for RFC2347 style options are now %s.\n",
891 options_rfc_enabled ? "enabled" : "disabled");
892 printf("Support for non-RFC defined options are now %s.\n",
893 options_extra_enabled ? "enabled" : "disabled");
895 printf("\nThe following options are available:\n"
896 "\toptions on : enable support for RFC2347 style options\n"
897 "\toptions off : disable support for RFC2347 style options\n"
898 "\toptions extra : toggle support for non-RFC defined options\n"
903 setrollover(int argc, char *argv[])
907 if (strcasecmp(argv[1], "never") == 0 ||
908 strcasecmp(argv[1], "none") == 0) {
909 free(options[OPT_ROLLOVER].o_request);
910 options[OPT_ROLLOVER].o_request = NULL;
912 if (strcasecmp(argv[1], "1") == 0) {
913 free(options[OPT_ROLLOVER].o_request);
914 options[OPT_ROLLOVER].o_request = strdup("1");
916 if (strcasecmp(argv[1], "0") == 0) {
917 free(options[OPT_ROLLOVER].o_request);
918 options[OPT_ROLLOVER].o_request = strdup("0");
921 printf("Support for the rollover options is %s.\n",
922 options[OPT_ROLLOVER].o_request != NULL ? "enabled" : "disabled");
923 if (options[OPT_ROLLOVER].o_request != NULL)
924 printf("Block rollover will be to block %s.\n",
925 options[OPT_ROLLOVER].o_request);
928 printf("\nThe following rollover options are available:\n"
929 "\trollover 0 : rollover to block zero (default)\n"
930 "\trollover 1 : rollover to block one\n"
931 "\trollover never : do not support the rollover option\n"
932 "\trollover none : do not support the rollover option\n"
937 setdebug(int argc, char *argv[])
944 debug ^= debug_find(argv[i++]);
946 printf("The following debugging is enabled: %s\n", debug_show(debug));
948 printf("\nThe following debugs are available:\n");
950 while (debugs[i].name != NULL) {
951 printf("\t%s\t%s\n", debugs[i].name, debugs[i].desc);
957 setblocksize(int argc, char *argv[])
960 if (!options_rfc_enabled)
961 printf("RFC2347 style options are not enabled "
962 "(but proceding anyway)\n");
965 int size = atoi(argv[1]);
969 max = sizeof(maxdgram);
970 if (sysctlbyname("net.inet.udp.maxdgram",
971 &maxdgram, &max, NULL, 0) < 0) {
972 perror("sysctl: net.inet.udp.maxdgram");
976 if (size < BLKSIZE_MIN || size > BLKSIZE_MAX) {
977 printf("Blocksize should be between %d and %d bytes.\n",
978 BLKSIZE_MIN, BLKSIZE_MAX);
980 } else if (size > (int)maxdgram - 4) {
981 printf("Blocksize can't be bigger than %ld bytes due "
982 "to the net.inet.udp.maxdgram sysctl limitation.\n",
984 asprintf(&options[OPT_BLKSIZE].o_request,
985 "%ld", maxdgram - 4);
987 asprintf(&options[OPT_BLKSIZE].o_request, "%d", size);
990 printf("Blocksize is now %s bytes.\n", options[OPT_BLKSIZE].o_request);
994 setblocksize2(int argc, char *argv[])
997 if (!options_rfc_enabled || !options_extra_enabled)
999 "RFC2347 style or non-RFC defined options are not enabled "
1000 "(but proceding anyway)\n");
1003 int size = atoi(argv[1]);
1009 8, 16, 32, 64, 128, 256, 512, 1024,
1010 2048, 4096, 8192, 16384, 32768, 0
1013 max = sizeof(maxdgram);
1014 if (sysctlbyname("net.inet.udp.maxdgram",
1015 &maxdgram, &max, NULL, 0) < 0) {
1016 perror("sysctl: net.inet.udp.maxdgram");
1020 for (i = 0; sizes[i] != 0; i++) {
1021 if (sizes[i] == size) break;
1023 if (sizes[i] == 0) {
1024 printf("Blocksize2 should be a power of two between "
1029 if (size < BLKSIZE_MIN || size > BLKSIZE_MAX) {
1030 printf("Blocksize2 should be between "
1031 "%d and %d bytes.\n", BLKSIZE_MIN, BLKSIZE_MAX);
1033 } else if (size > (int)maxdgram - 4) {
1034 printf("Blocksize2 can't be bigger than %ld bytes due "
1035 "to the net.inet.udp.maxdgram sysctl limitation.\n",
1037 for (i = 0; sizes[i+1] != 0; i++) {
1038 if ((int)maxdgram < sizes[i+1]) break;
1040 asprintf(&options[OPT_BLKSIZE2].o_request,
1043 asprintf(&options[OPT_BLKSIZE2].o_request, "%d", size);
1046 printf("Blocksize2 is now %s bytes.\n",
1047 options[OPT_BLKSIZE2].o_request);
1051 setpacketdrop(int argc, char *argv[])
1055 packetdroppercentage = atoi(argv[1]);
1057 printf("Randomly %d in 100 packets will be dropped\n",
1058 packetdroppercentage);