]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - usr.bin/tftp/main.c
ping: use the monotonic clock to measure durations
[FreeBSD/FreeBSD.git] / usr.bin / tftp / main.c
1 /*-
2  * SPDX-License-Identifier: BSD-3-Clause
3  *
4  * Copyright (c) 1983, 1993
5  *      The Regents of the University of California.  All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
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.
18  *
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
29  * SUCH DAMAGE.
30  */
31
32 #ifndef lint
33 static const char copyright[] =
34 "@(#) Copyright (c) 1983, 1993\n\
35         The Regents of the University of California.  All rights reserved.\n";
36 #endif
37
38 #if 0
39 #ifndef lint
40 static char sccsid[] = "@(#)main.c      8.1 (Berkeley) 6/6/93";
41 #endif
42 #endif
43
44 #include <sys/cdefs.h>
45 __FBSDID("$FreeBSD$");
46
47 /* Many bug fixes are from Jim Guyton <guyton@rand-unix> */
48
49 /*
50  * TFTP User Program -- Command Interface.
51  */
52 #include <sys/param.h>
53 #include <sys/types.h>
54 #include <sys/socket.h>
55 #include <sys/sysctl.h>
56 #include <sys/file.h>
57 #include <sys/stat.h>
58
59 #include <netinet/in.h>
60 #include <arpa/inet.h>
61 #include <arpa/tftp.h>
62
63 #include <ctype.h>
64 #include <err.h>
65 #include <histedit.h>
66 #include <netdb.h>
67 #include <setjmp.h>
68 #include <signal.h>
69 #include <stdbool.h>
70 #include <stdio.h>
71 #include <stdlib.h>
72 #include <string.h>
73 #include <unistd.h>
74
75 #include "tftp-utils.h"
76 #include "tftp-io.h"
77 #include "tftp-options.h"
78 #include "tftp.h"
79
80 #define MAXLINE         (2 * MAXPATHLEN)
81 #define TIMEOUT         5               /* secs between rexmt's */
82
83 typedef struct  sockaddr_storage peeraddr;
84 static int      connected;
85 static char     mode[32];
86 static jmp_buf  toplevel;
87 volatile int    txrx_error;
88 static int      peer;
89
90 #define MAX_MARGV       20
91 static int      margc;
92 static char     *margv[MAX_MARGV];
93
94 int             verbose;
95 static char     *port = NULL;
96
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
118 static void command(bool, EditLine *, History *, HistEvent *) __dead2;
119 static const char *command_prompt(void);
120
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 *);
126
127 static char     *tail(char *);
128 static struct   cmd *getcmd(char *);
129
130 #define HELPINDENT (sizeof("connect"))
131
132 struct cmd {
133         const char      *name;
134         void    (*handler)(int, char **);
135         const char      *help;
136 };
137
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"        },
162         { NULL,         NULL,           NULL                            }
163 };
164
165 static struct   modes {
166         const char *m_name;
167         const char *m_mode;
168 } modes[] = {
169         { "ascii",      "netascii" },
170         { "netascii",   "netascii" },
171         { "binary",     "octet" },
172         { "image",      "octet" },
173         { "octet",      "octet" },
174         { NULL,         NULL }
175 };
176
177 int
178 main(int argc, char *argv[])
179 {
180         HistEvent he;
181         static EditLine *el;
182         static History *hist;
183         bool interactive;
184
185         acting_as_client = 1;
186         peer = -1;
187         strcpy(mode, "octet");
188         signal(SIGINT, intr);
189
190         interactive = isatty(STDIN_FILENO);
191         if (interactive) {
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);
199                 el_source(el, NULL);
200         }
201
202         if (argc > 1) {
203                 if (setjmp(toplevel) != 0)
204                         exit(txrx_error);
205
206                 if (strncmp(argv[1], "tftp://", 7) == 0) {
207                         urihandling(argv[1]);
208                         exit(txrx_error);
209                 }
210
211                 setpeer(argc, argv);
212         }
213
214         if (setjmp(toplevel) != 0) {
215                 if (interactive)
216                         el_reset(el);
217                 (void)putchar('\n');
218         }
219
220         init_options();
221         command(interactive, el, hist, &he);
222 }
223
224 /*
225  * RFC3617 handling of TFTP URIs:
226  *
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>
233  *
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
236  * mode.
237  */
238 static void
239 urihandling(char *URI)
240 {
241         char    uri[ARG_MAX];
242         char    *host = NULL;
243         char    *path = NULL;
244         char    *opts = NULL;
245         const char *tmode = "octet";
246         char    *s;
247         char    line[MAXLINE];
248         int     i;
249
250         strlcpy(uri, URI, ARG_MAX);
251         host = uri + 7;
252
253         if ((s = strchr(host, '/')) == NULL) {
254                 fprintf(stderr,
255                     "Invalid URI: Couldn't find / after hostname\n");
256                 exit(1);
257         }
258         *s = '\0';
259         path = s + 1;
260
261         if ((s = strchr(path, ';')) != NULL) {
262                 *s = '\0';
263                 opts = s + 1;
264
265                 if (strncmp(opts, "mode=", 5) == 0) {
266                         tmode = opts;
267                         tmode += 5;
268
269                         for (i = 0; modes[i].m_name != NULL; i++) {
270                                 if (strcmp(modes[i].m_name, tmode) == 0)
271                                         break;
272                         }
273                         if (modes[i].m_name == NULL) {
274                                 fprintf(stderr, "Invalid mode: '%s'\n", mode);
275                                 exit(1);
276                         }
277                         settftpmode(modes[i].m_mode);
278                 }
279         } else {
280                 settftpmode("octet");
281         }
282
283         setpeer0(host, NULL);
284
285         sprintf(line, "get %s", path);
286         makeargv(line);
287         get(margc, margv);
288 }
289
290 static char    hostname[MAXHOSTNAMELEN];
291
292 static void
293 setpeer0(char *host, const char *lport)
294 {
295         struct addrinfo hints, *res0, *res;
296         int error;
297         const char *cause = "unknown";
298
299         if (connected) {
300                 close(peer);
301                 peer = -1;
302         }
303         connected = 0;
304
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;
310         if (!lport)
311                 lport = "tftp";
312         error = getaddrinfo(host, lport, &hints, &res0);
313         if (error) {
314                 warnx("%s", gai_strerror(error));
315                 return;
316         }
317
318         for (res = res0; res; res = res->ai_next) {
319                 if (res->ai_addrlen > sizeof(peeraddr))
320                         continue;
321                 peer = socket(res->ai_family, res->ai_socktype,
322                         res->ai_protocol);
323                 if (peer < 0) {
324                         cause = "socket";
325                         continue;
326                 }
327
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) {
332                         cause = "bind";
333                         close(peer);
334                         peer = -1;
335                         continue;
336                 }
337
338                 break;
339         }
340
341         if (peer < 0)
342                 warn("%s", cause);
343         else {
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,
348                                 sizeof(hostname));
349                 } else
350                         (void) strlcpy(hostname, host, sizeof(hostname));
351                 connected = 1;
352         }
353
354         freeaddrinfo(res0);
355 }
356
357 static void
358 setpeer(int argc, char *argv[])
359 {
360         char    line[MAXLINE];
361
362         if (argc < 2) {
363                 strcpy(line, "Connect ");
364                 printf("(to) ");
365                 fgets(&line[strlen(line)], sizeof line - strlen(line), stdin);
366                 makeargv(line);
367                 argc = margc;
368                 argv = margv;
369         }
370         if ((argc < 2) || (argc > 3)) {
371                 printf("usage: %s [host [port]]\n", argv[0]);
372                 return;
373         }
374         if (argc == 3) {
375                 port = argv[2];
376                 setpeer0(argv[1], argv[2]);
377         } else
378                 setpeer0(argv[1], NULL);
379 }
380
381 static void
382 modecmd(int argc, char *argv[])
383 {
384         struct modes *p;
385         const char *sep;
386
387         if (argc < 2) {
388                 printf("Using %s mode to transfer files.\n", mode);
389                 return;
390         }
391         if (argc == 2) {
392                 for (p = modes; p->m_name; p++)
393                         if (strcmp(argv[1], p->m_name) == 0)
394                                 break;
395                 if (p->m_name) {
396                         settftpmode(p->m_mode);
397                         return;
398                 }
399                 printf("%s: unknown mode\n", argv[1]);
400                 /* drop through and print usage message */
401         }
402
403         printf("usage: %s [", argv[0]);
404         sep = " ";
405         for (p = modes; p->m_name != NULL; p++) {
406                 printf("%s%s", sep, p->m_name);
407                 if (*sep == ' ')
408                         sep = " | ";
409         }
410         printf(" ]\n");
411         return;
412 }
413
414 static void
415 setbinary(int argc __unused, char *argv[] __unused)
416 {
417
418         settftpmode("octet");
419 }
420
421 static void
422 setascii(int argc __unused, char *argv[] __unused)
423 {
424
425         settftpmode("netascii");
426 }
427
428 static void
429 settftpmode(const char *newmode)
430 {
431
432         strlcpy(mode, newmode, sizeof(mode));
433         if (verbose)
434                 printf("mode set to %s\n", mode);
435 }
436
437
438 /*
439  * Send file(s).
440  */
441 static void
442 put(int argc, char *argv[])
443 {
444         int     fd;
445         int     n;
446         char    *cp, *targ;
447         char    line[MAXLINE];
448         struct stat sb;
449
450         if (argc < 2) {
451                 strcpy(line, "send ");
452                 printf("(file) ");
453                 fgets(&line[strlen(line)], sizeof line - strlen(line), stdin);
454                 makeargv(line);
455                 argc = margc;
456                 argv = margv;
457         }
458         if (argc < 2) {
459                 putusage(argv[0]);
460                 return;
461         }
462         targ = argv[argc - 1];
463         if (strrchr(argv[argc - 1], ':')) {
464                 char *lcp;
465
466                 for (n = 1; n < argc - 1; n++)
467                         if (strchr(argv[n], ':')) {
468                                 putusage(argv[0]);
469                                 return;
470                         }
471                 lcp = argv[argc - 1];
472                 targ = strrchr(lcp, ':');
473                 *targ++ = 0;
474                 if (lcp[0] == '[' && lcp[strlen(lcp) - 1] == ']') {
475                         lcp[strlen(lcp) - 1] = '\0';
476                         lcp++;
477                 }
478                 setpeer0(lcp, NULL);
479         }
480         if (!connected) {
481                 printf("No target machine specified.\n");
482                 return;
483         }
484         if (argc < 4) {
485                 cp = argc == 2 ? tail(targ) : argv[1];
486                 fd = open(cp, O_RDONLY);
487                 if (fd < 0) {
488                         warn("%s", cp);
489                         return;
490                 }
491
492                 if (fstat(fd, &sb) < 0) {
493                         warn("%s", cp);
494                         return;
495                 }
496                 asprintf(&options[OPT_TSIZE].o_request, "%ju", sb.st_size);
497
498                 if (verbose)
499                         printf("putting %s to %s:%s [%s]\n",
500                             cp, hostname, targ, mode);
501                 xmitfile(peer, port, fd, targ, mode);
502                 close(fd);
503                 return;
504         }
505                                 /* this assumes the target is a directory */
506                                 /* on a remote unix system.  hmmmm.  */
507         cp = strchr(targ, '\0');
508         *cp++ = '/';
509         for (n = 1; n < argc - 1; n++) {
510                 strcpy(cp, tail(argv[n]));
511                 fd = open(argv[n], O_RDONLY);
512                 if (fd < 0) {
513                         warn("%s", argv[n]);
514                         continue;
515                 }
516
517                 if (fstat(fd, &sb) < 0) {
518                         warn("%s", argv[n]);
519                         continue;
520                 }
521                 asprintf(&options[OPT_TSIZE].o_request, "%ju", sb.st_size);
522
523                 if (verbose)
524                         printf("putting %s to %s:%s [%s]\n",
525                             argv[n], hostname, targ, mode);
526                 xmitfile(peer, port, fd, targ, mode);
527         }
528 }
529
530 static void
531 putusage(char *s)
532 {
533
534         printf("usage: %s file [remotename]\n", s);
535         printf("       %s file host:remotename\n", s);
536         printf("       %s file1 file2 ... fileN [[host:]remote-directory]\n", s);
537 }
538
539 /*
540  * Receive file(s).
541  */
542 static void
543 get(int argc, char *argv[])
544 {
545         int fd;
546         int n;
547         char *cp;
548         char *src;
549         char    line[MAXLINE];
550
551         if (argc < 2) {
552                 strcpy(line, "get ");
553                 printf("(files) ");
554                 fgets(&line[strlen(line)], sizeof line - strlen(line), stdin);
555                 makeargv(line);
556                 argc = margc;
557                 argv = margv;
558         }
559         if (argc < 2) {
560                 getusage(argv[0]);
561                 return;
562         }
563         if (!connected) {
564                 for (n = 1; n < argc ; n++)
565                         if (strrchr(argv[n], ':') == 0) {
566                                 printf("No remote host specified and "
567                                     "no host given for file '%s'\n", argv[n]);
568                                 getusage(argv[0]);
569                                 return;
570                         }
571         }
572         for (n = 1; n < argc ; n++) {
573                 src = strrchr(argv[n], ':');
574                 if (src == NULL)
575                         src = argv[n];
576                 else {
577                         char *lcp;
578
579                         *src++ = 0;
580                         lcp = argv[n];
581                         if (lcp[0] == '[' && lcp[strlen(lcp) - 1] == ']') {
582                                 lcp[strlen(lcp) - 1] = '\0';
583                                 lcp++;
584                         }
585                         setpeer0(lcp, NULL);
586                         if (!connected)
587                                 continue;
588                 }
589                 if (argc < 4) {
590                         cp = argc == 3 ? argv[2] : tail(src);
591                         fd = creat(cp, 0644);
592                         if (fd < 0) {
593                                 warn("%s", cp);
594                                 return;
595                         }
596                         if (verbose)
597                                 printf("getting from %s:%s to %s [%s]\n",
598                                     hostname, src, cp, mode);
599                         recvfile(peer, port, fd, src, mode);
600                         break;
601                 }
602                 cp = tail(src);         /* new .. jdg */
603                 fd = creat(cp, 0644);
604                 if (fd < 0) {
605                         warn("%s", cp);
606                         continue;
607                 }
608                 if (verbose)
609                         printf("getting from %s:%s to %s [%s]\n",
610                             hostname, src, cp, mode);
611                 recvfile(peer, port, fd, src, mode);
612         }
613 }
614
615 static void
616 getusage(char *s)
617 {
618
619         printf("usage: %s file [localname]\n", s);
620         printf("       %s [host:]file [localname]\n", s);
621         printf("       %s [host1:]file1 [host2:]file2 ... [hostN:]fileN\n", s);
622 }
623
624 static void
625 settimeoutpacket(int argc, char *argv[])
626 {
627         int t;
628         char    line[MAXLINE];
629
630         if (argc < 2) {
631                 strcpy(line, "Packet timeout ");
632                 printf("(value) ");
633                 fgets(&line[strlen(line)], sizeof line - strlen(line), stdin);
634                 makeargv(line);
635                 argc = margc;
636                 argv = margv;
637         }
638         if (argc != 2) {
639                 printf("usage: %s value\n", argv[0]);
640                 return;
641         }
642         t = atoi(argv[1]);
643         if (t < 0) {
644                 printf("%s: bad value\n", argv[1]);
645                 return;
646         }
647
648         settimeouts(t, timeoutnetwork, maxtimeouts);
649 }
650
651 static void
652 settimeoutnetwork(int argc, char *argv[])
653 {
654         int t;
655         char    line[MAXLINE];
656
657         if (argc < 2) {
658                 strcpy(line, "Network timeout ");
659                 printf("(value) ");
660                 fgets(&line[strlen(line)], sizeof line - strlen(line), stdin);
661                 makeargv(line);
662                 argc = margc;
663                 argv = margv;
664         }
665         if (argc != 2) {
666                 printf("usage: %s value\n", argv[0]);
667                 return;
668         }
669         t = atoi(argv[1]);
670         if (t < 0) {
671                 printf("%s: bad value\n", argv[1]);
672                 return;
673         }
674
675         settimeouts(timeoutpacket, t, maxtimeouts);
676 }
677
678 static void
679 showstatus(int argc __unused, char *argv[] __unused)
680 {
681
682         printf("Remote host: %s\n",
683             connected ? hostname : "none specified yet");
684         printf("RFC2347 Options support: %s\n",
685             options_rfc_enabled ? "enabled" : "disabled");
686         printf("Non-RFC defined options support: %s\n",
687             options_extra_enabled ? "enabled" : "disabled");
688         printf("Mode: %s\n", mode);
689         printf("Verbose: %s\n", verbose ? "on" : "off");
690         printf("Debug: %s\n", debug_show(debug));
691         printf("Artificial packetloss: %d in 100 packets\n",
692             packetdroppercentage);
693         printf("Segment size: %d bytes\n", segsize);
694         printf("Network timeout: %d seconds\n", timeoutpacket);
695         printf("Maximum network timeout: %d seconds\n", timeoutnetwork);
696         printf("Maximum timeouts: %d \n", maxtimeouts);
697 }
698
699 static void
700 intr(int dummy __unused)
701 {
702
703         signal(SIGALRM, SIG_IGN);
704         alarm(0);
705         longjmp(toplevel, -1);
706 }
707
708 static char *
709 tail(char *filename)
710 {
711         char *s;
712
713         while (*filename) {
714                 s = strrchr(filename, '/');
715                 if (s == NULL)
716                         break;
717                 if (s[1])
718                         return (s + 1);
719                 *s = '\0';
720         }
721         return (filename);
722 }
723
724 static const char *
725 command_prompt(void)
726 {
727
728         return ("tftp> ");
729 }
730
731 /*
732  * Command parser.
733  */
734 static void
735 command(bool interactive, EditLine *el, History *hist, HistEvent *hep)
736 {
737         struct cmd *c;
738         const char *bp;
739         char *cp;
740         int len, num;
741         char    line[MAXLINE];
742
743         for (;;) {
744                 if (interactive) {
745                         if ((bp = el_gets(el, &num)) == NULL || num == 0)
746                                 exit(0);
747                         len = MIN(MAXLINE, num);
748                         memcpy(line, bp, len);
749                         line[len] = '\0';
750                         history(hist, hep, H_ENTER, bp);
751                 } else {
752                         line[0] = 0;
753                         if (fgets(line, sizeof line , stdin) == NULL) {
754                                 if (feof(stdin)) {
755                                         exit(txrx_error);
756                                 } else {
757                                         continue;
758                                 }
759                         }
760                 }
761                 if ((cp = strchr(line, '\n')))
762                         *cp = '\0';
763                 if (line[0] == 0)
764                         continue;
765                 makeargv(line);
766                 if (margc == 0)
767                         continue;
768                 c = getcmd(margv[0]);
769                 if (c == (struct cmd *)-1) {
770                         printf("?Ambiguous command\n");
771                         continue;
772                 }
773                 if (c == NULL) {
774                         printf("?Invalid command\n");
775                         continue;
776                 }
777                 (*c->handler)(margc, margv);
778         }
779 }
780
781 static struct cmd *
782 getcmd(char *name)
783 {
784         const char *p, *q;
785         struct cmd *c, *found;
786         int nmatches, longest;
787
788         longest = 0;
789         nmatches = 0;
790         found = 0;
791         for (c = cmdtab; (p = c->name) != NULL; c++) {
792                 for (q = name; *q == *p++; q++)
793                         if (*q == 0)            /* exact match? */
794                                 return (c);
795                 if (!*q) {                      /* the name was a prefix */
796                         if (q - name > longest) {
797                                 longest = q - name;
798                                 nmatches = 1;
799                                 found = c;
800                         } else if (q - name == longest)
801                                 nmatches++;
802                 }
803         }
804         if (nmatches > 1)
805                 return ((struct cmd *)-1);
806         return (found);
807 }
808
809 /*
810  * Slice a string up into argc/argv.
811  */
812 static void
813 makeargv(char *line)
814 {
815         char *cp;
816         char **argp = margv;
817
818         margc = 0;
819         if ((cp = strchr(line, '\n')) != NULL)
820                 *cp = '\0';
821         for (cp = line; margc < MAX_MARGV - 1 && *cp != '\0';) {
822                 while (isspace(*cp))
823                         cp++;
824                 if (*cp == '\0')
825                         break;
826                 *argp++ = cp;
827                 margc += 1;
828                 while (*cp != '\0' && !isspace(*cp))
829                         cp++;
830                 if (*cp == '\0')
831                         break;
832                 *cp++ = '\0';
833         }
834         *argp++ = 0;
835 }
836
837 static void
838 quit(int argc __unused, char *argv[] __unused)
839 {
840
841         exit(txrx_error);
842 }
843
844 /*
845  * Help command.
846  */
847 static void
848 help(int argc, char *argv[])
849 {
850         struct cmd *c;
851
852         if (argc == 1) {
853                 printf("Commands may be abbreviated.  Commands are:\n\n");
854                 for (c = cmdtab; c->name; c++)
855                         printf("%-*s\t%s\n", (int)HELPINDENT, c->name, c->help);
856
857                 printf("\n[-] : You shouldn't use these ones anymore.\n");
858                 printf("[*] : RFC2347 options support required.\n");
859                 printf("[**] : Non-standard RFC2347 option.\n");
860                 return;
861         }
862         while (--argc > 0) {
863                 char *arg;
864                 arg = *++argv;
865                 c = getcmd(arg);
866                 if (c == (struct cmd *)-1)
867                         printf("?Ambiguous help command: %s\n", arg);
868                 else if (c == (struct cmd *)0)
869                         printf("?Invalid help command: %s\n", arg);
870                 else
871                         printf("%s\n", c->help);
872         }
873 }
874
875 static void
876 setverbose(int argc __unused, char *argv[] __unused)
877 {
878
879         verbose = !verbose;
880         printf("Verbose mode %s.\n", verbose ? "on" : "off");
881 }
882
883 static void
884 setoptions(int argc, char *argv[])
885 {
886
887         if (argc == 2) {
888                 if (strcasecmp(argv[1], "enable") == 0 ||
889                     strcasecmp(argv[1], "on") == 0) {
890                         options_extra_enabled = 1;
891                         options_rfc_enabled = 1;
892                 }
893                 if (strcasecmp(argv[1], "disable") == 0 ||
894                     strcasecmp(argv[1], "off") == 0) {
895                         options_extra_enabled = 0;
896                         options_rfc_enabled = 0;
897                 }
898                 if (strcasecmp(argv[1], "extra") == 0)
899                         options_extra_enabled = !options_extra_enabled;
900         }
901         printf("Support for RFC2347 style options are now %s.\n",
902             options_rfc_enabled ? "enabled" : "disabled");
903         printf("Support for non-RFC defined options are now %s.\n",
904             options_extra_enabled ? "enabled" : "disabled");
905
906         printf("\nThe following options are available:\n"
907             "\toptions on       : enable support for RFC2347 style options\n"
908             "\toptions off      : disable support for RFC2347 style options\n"
909             "\toptions extra    : toggle support for non-RFC defined options\n"
910         );
911 }
912
913 static void
914 setrollover(int argc, char *argv[])
915 {
916
917         if (argc == 2) {
918                 if (strcasecmp(argv[1], "never") == 0 ||
919                     strcasecmp(argv[1], "none") == 0) {
920                         free(options[OPT_ROLLOVER].o_request);
921                         options[OPT_ROLLOVER].o_request = NULL;
922                 }
923                 if (strcasecmp(argv[1], "1") == 0) {
924                         free(options[OPT_ROLLOVER].o_request);
925                         options[OPT_ROLLOVER].o_request = strdup("1");
926                 }
927                 if (strcasecmp(argv[1], "0") == 0) {
928                         free(options[OPT_ROLLOVER].o_request);
929                         options[OPT_ROLLOVER].o_request = strdup("0");
930                 }
931         }
932         printf("Support for the rollover options is %s.\n",
933             options[OPT_ROLLOVER].o_request != NULL ? "enabled" : "disabled");
934         if (options[OPT_ROLLOVER].o_request != NULL)
935                 printf("Block rollover will be to block %s.\n",
936                     options[OPT_ROLLOVER].o_request);
937
938
939         printf("\nThe following rollover options are available:\n"
940             "\trollover 0       : rollover to block zero (default)\n"
941             "\trollover 1       : rollover to block one\n"
942             "\trollover never   : do not support the rollover option\n"
943             "\trollover none    : do not support the rollover option\n"
944         );
945 }
946
947 static void
948 setdebug(int argc, char *argv[])
949 {
950         int i;
951
952         if (argc != 1) {
953                 i = 1;
954                 while (i < argc)
955                         debug ^= debug_find(argv[i++]);
956         }
957         printf("The following debugging is enabled: %s\n", debug_show(debug));
958
959         printf("\nThe following debugs are available:\n");
960         i = 0;
961         while (debugs[i].name != NULL) {
962                 printf("\t%s\t%s\n", debugs[i].name, debugs[i].desc);
963                 i++;
964         }
965 }
966
967 static void
968 setblocksize(int argc, char *argv[])
969 {
970
971         if (!options_rfc_enabled)
972                 printf("RFC2347 style options are not enabled "
973                     "(but proceeding anyway)\n");
974
975         if (argc != 1) {
976                 int size = atoi(argv[1]);
977                 size_t max;
978                 u_long maxdgram;
979
980                 max = sizeof(maxdgram);
981                 if (sysctlbyname("net.inet.udp.maxdgram",
982                         &maxdgram, &max, NULL, 0) < 0) {
983                         perror("sysctl: net.inet.udp.maxdgram");
984                         return;
985                 }
986
987                 if (size < BLKSIZE_MIN || size > BLKSIZE_MAX) {
988                         printf("Blocksize should be between %d and %d bytes.\n",
989                                 BLKSIZE_MIN, BLKSIZE_MAX);
990                         return;
991                 } else if (size > (int)maxdgram - 4) {
992                         printf("Blocksize can't be bigger than %ld bytes due "
993                             "to the net.inet.udp.maxdgram sysctl limitation.\n",
994                             maxdgram - 4);
995                         asprintf(&options[OPT_BLKSIZE].o_request,
996                             "%ld", maxdgram - 4);
997                 } else {
998                         asprintf(&options[OPT_BLKSIZE].o_request, "%d", size);
999                 }
1000         }
1001         printf("Blocksize is now %s bytes.\n", options[OPT_BLKSIZE].o_request);
1002 }
1003
1004 static void
1005 setblocksize2(int argc, char *argv[])
1006 {
1007
1008         if (!options_rfc_enabled || !options_extra_enabled)
1009                 printf(
1010                     "RFC2347 style or non-RFC defined options are not enabled "
1011                     "(but proceeding anyway)\n");
1012
1013         if (argc != 1) {
1014                 int size = atoi(argv[1]);
1015                 int i;
1016                 size_t max;
1017                 u_long maxdgram;
1018
1019                 int sizes[] = {
1020                         8, 16, 32, 64, 128, 256, 512, 1024,
1021                         2048, 4096, 8192, 16384, 32768, 0
1022                 };
1023
1024                 max = sizeof(maxdgram);
1025                 if (sysctlbyname("net.inet.udp.maxdgram",
1026                         &maxdgram, &max, NULL, 0) < 0) {
1027                         perror("sysctl: net.inet.udp.maxdgram");
1028                         return;
1029                 }
1030
1031                 for (i = 0; sizes[i] != 0; i++) {
1032                         if (sizes[i] == size) break;
1033                 }
1034                 if (sizes[i] == 0) {
1035                         printf("Blocksize2 should be a power of two between "
1036                             "8 and 32768.\n");
1037                         return;
1038                 }
1039
1040                 if (size < BLKSIZE_MIN || size > BLKSIZE_MAX) {
1041                         printf("Blocksize2 should be between "
1042                             "%d and %d bytes.\n", BLKSIZE_MIN, BLKSIZE_MAX);
1043                         return;
1044                 } else if (size > (int)maxdgram - 4) {
1045                         printf("Blocksize2 can't be bigger than %ld bytes due "
1046                             "to the net.inet.udp.maxdgram sysctl limitation.\n",
1047                             maxdgram - 4);
1048                         for (i = 0; sizes[i+1] != 0; i++) {
1049                                 if ((int)maxdgram < sizes[i+1]) break;
1050                         }
1051                         asprintf(&options[OPT_BLKSIZE2].o_request,
1052                             "%d", sizes[i]);
1053                 } else {
1054                         asprintf(&options[OPT_BLKSIZE2].o_request, "%d", size);
1055                 }
1056         }
1057         printf("Blocksize2 is now %s bytes.\n",
1058             options[OPT_BLKSIZE2].o_request);
1059 }
1060
1061 static void
1062 setpacketdrop(int argc, char *argv[])
1063 {
1064
1065         if (argc != 1)
1066                 packetdroppercentage = atoi(argv[1]);
1067
1068         printf("Randomly %d in 100 packets will be dropped\n",
1069             packetdroppercentage);
1070 }