HAMMER 31B/many: Fix busy block dev on HAMMER umount
[dragonfly.git] / contrib / tnftp / util.c
blob2ab75b09e33f043e23c35fd6656a411c3ed3fb00
1 /* $NetBSD: util.c,v 1.144 2007/12/05 03:46:34 lukem Exp $ */
3 /*-
4 * Copyright (c) 1997-2007 The NetBSD Foundation, Inc.
5 * All rights reserved.
7 * This code is derived from software contributed to The NetBSD Foundation
8 * by Luke Mewburn.
10 * This code is derived from software contributed to The NetBSD Foundation
11 * by Jason R. Thorpe of the Numerical Aerospace Simulation Facility,
12 * NASA Ames Research Center.
14 * Redistribution and use in source and binary forms, with or without
15 * modification, are permitted provided that the following conditions
16 * are met:
17 * 1. Redistributions of source code must retain the above copyright
18 * notice, this list of conditions and the following disclaimer.
19 * 2. Redistributions in binary form must reproduce the above copyright
20 * notice, this list of conditions and the following disclaimer in the
21 * documentation and/or other materials provided with the distribution.
22 * 3. All advertising materials mentioning features or use of this software
23 * must display the following acknowledgement:
24 * This product includes software developed by the NetBSD
25 * Foundation, Inc. and its contributors.
26 * 4. Neither the name of The NetBSD Foundation nor the names of its
27 * contributors may be used to endorse or promote products derived
28 * from this software without specific prior written permission.
30 * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
31 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
32 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
33 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
34 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
35 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
36 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
37 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
38 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
39 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
40 * POSSIBILITY OF SUCH DAMAGE.
44 * Copyright (c) 1985, 1989, 1993, 1994
45 * The Regents of the University of California. All rights reserved.
47 * Redistribution and use in source and binary forms, with or without
48 * modification, are permitted provided that the following conditions
49 * are met:
50 * 1. Redistributions of source code must retain the above copyright
51 * notice, this list of conditions and the following disclaimer.
52 * 2. Redistributions in binary form must reproduce the above copyright
53 * notice, this list of conditions and the following disclaimer in the
54 * documentation and/or other materials provided with the distribution.
55 * 3. Neither the name of the University nor the names of its contributors
56 * may be used to endorse or promote products derived from this software
57 * without specific prior written permission.
59 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
60 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
61 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
62 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
63 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
64 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
65 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
66 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
67 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
68 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
69 * SUCH DAMAGE.
72 #include <sys/cdefs.h>
73 #ifndef lint
74 __RCSID("$NetBSD: util.c,v 1.144 2007/12/05 03:46:34 lukem Exp $");
75 #endif /* not lint */
78 * FTP User Program -- Misc support routines
80 #include <sys/param.h>
81 #include <sys/socket.h>
82 #include <sys/ioctl.h>
83 #include <sys/time.h>
84 #include <netinet/in.h>
85 #include <arpa/ftp.h>
87 #include <ctype.h>
88 #include <err.h>
89 #include <errno.h>
90 #include <fcntl.h>
91 #include <glob.h>
92 #include <signal.h>
93 #include <libgen.h>
94 #include <limits.h>
95 #include <netdb.h>
96 #include <stdio.h>
97 #include <stdlib.h>
98 #include <string.h>
99 #include <termios.h>
100 #include <time.h>
101 #include <tzfile.h>
102 #include <unistd.h>
104 #include "ftp_var.h"
107 * Connect to peer server and auto-login, if possible.
109 void
110 setpeer(int argc, char *argv[])
112 char *host;
113 char *port;
115 if (argc == 0)
116 goto usage;
117 if (connected) {
118 fprintf(ttyout, "Already connected to %s, use close first.\n",
119 hostname);
120 code = -1;
121 return;
123 if (argc < 2)
124 (void)another(&argc, &argv, "to");
125 if (argc < 2 || argc > 3) {
126 usage:
127 UPRINTF("usage: %s host-name [port]\n", argv[0]);
128 code = -1;
129 return;
131 if (gatemode)
132 port = gateport;
133 else
134 port = ftpport;
135 if (argc > 2)
136 port = argv[2];
138 if (gatemode) {
139 if (gateserver == NULL || *gateserver == '\0')
140 errx(1, "main: gateserver not defined");
141 host = hookup(gateserver, port);
142 } else
143 host = hookup(argv[1], port);
145 if (host) {
146 if (gatemode && verbose) {
147 fprintf(ttyout,
148 "Connecting via pass-through server %s\n",
149 gateserver);
152 connected = 1;
154 * Set up defaults for FTP.
156 (void)strlcpy(typename, "ascii", sizeof(typename));
157 type = TYPE_A;
158 curtype = TYPE_A;
159 (void)strlcpy(formname, "non-print", sizeof(formname));
160 form = FORM_N;
161 (void)strlcpy(modename, "stream", sizeof(modename));
162 mode = MODE_S;
163 (void)strlcpy(structname, "file", sizeof(structname));
164 stru = STRU_F;
165 (void)strlcpy(bytename, "8", sizeof(bytename));
166 bytesize = 8;
167 if (autologin)
168 (void)ftp_login(argv[1], NULL, NULL);
172 static void
173 parse_feat(const char *line)
177 * work-around broken ProFTPd servers that can't
178 * even obey RFC2389.
180 while (*line && isspace((int)*line))
181 line++;
183 if (strcasecmp(line, "MDTM") == 0)
184 features[FEAT_MDTM] = 1;
185 else if (strncasecmp(line, "MLST", sizeof("MLST") - 1) == 0) {
186 features[FEAT_MLST] = 1;
187 } else if (strcasecmp(line, "REST STREAM") == 0)
188 features[FEAT_REST_STREAM] = 1;
189 else if (strcasecmp(line, "SIZE") == 0)
190 features[FEAT_SIZE] = 1;
191 else if (strcasecmp(line, "TVFS") == 0)
192 features[FEAT_TVFS] = 1;
196 * Determine the remote system type (SYST) and features (FEAT).
197 * Call after a successful login (i.e, connected = -1)
199 void
200 getremoteinfo(void)
202 int overbose, i;
204 overbose = verbose;
205 if (ftp_debug == 0)
206 verbose = -1;
208 /* determine remote system type */
209 if (command("SYST") == COMPLETE) {
210 if (overbose) {
211 char *cp, c;
213 c = 0;
214 cp = strchr(reply_string + 4, ' ');
215 if (cp == NULL)
216 cp = strchr(reply_string + 4, '\r');
217 if (cp) {
218 if (cp[-1] == '.')
219 cp--;
220 c = *cp;
221 *cp = '\0';
224 fprintf(ttyout, "Remote system type is %s.\n",
225 reply_string + 4);
226 if (cp)
227 *cp = c;
229 if (!strncmp(reply_string, "215 UNIX Type: L8", 17)) {
230 if (proxy)
231 unix_proxy = 1;
232 else
233 unix_server = 1;
235 * Set type to 0 (not specified by user),
236 * meaning binary by default, but don't bother
237 * telling server. We can use binary
238 * for text files unless changed by the user.
240 type = 0;
241 (void)strlcpy(typename, "binary", sizeof(typename));
242 if (overbose)
243 fprintf(ttyout,
244 "Using %s mode to transfer files.\n",
245 typename);
246 } else {
247 if (proxy)
248 unix_proxy = 0;
249 else
250 unix_server = 0;
251 if (overbose &&
252 !strncmp(reply_string, "215 TOPS20", 10))
253 fputs(
254 "Remember to set tenex mode when transferring binary files from this machine.\n",
255 ttyout);
259 /* determine features (if any) */
260 for (i = 0; i < FEAT_max; i++)
261 features[i] = -1;
262 reply_callback = parse_feat;
263 if (command("FEAT") == COMPLETE) {
264 for (i = 0; i < FEAT_max; i++) {
265 if (features[i] == -1)
266 features[i] = 0;
268 features[FEAT_FEAT] = 1;
269 } else
270 features[FEAT_FEAT] = 0;
271 #ifndef NO_DEBUG
272 if (ftp_debug) {
273 #define DEBUG_FEAT(x) fprintf(ttyout, "features[" #x "] = %d\n", features[(x)])
274 DEBUG_FEAT(FEAT_FEAT);
275 DEBUG_FEAT(FEAT_MDTM);
276 DEBUG_FEAT(FEAT_MLST);
277 DEBUG_FEAT(FEAT_REST_STREAM);
278 DEBUG_FEAT(FEAT_SIZE);
279 DEBUG_FEAT(FEAT_TVFS);
280 #undef DEBUG_FEAT
282 #endif
283 reply_callback = NULL;
285 verbose = overbose;
289 * Reset the various variables that indicate connection state back to
290 * disconnected settings.
291 * The caller is responsible for issuing any commands to the remote server
292 * to perform a clean shutdown before this is invoked.
294 void
295 cleanuppeer(void)
298 if (cout)
299 (void)fclose(cout);
300 cout = NULL;
301 connected = 0;
302 unix_server = 0;
303 unix_proxy = 0;
305 * determine if anonftp was specifically set with -a
306 * (1), or implicitly set by auto_fetch() (2). in the
307 * latter case, disable after the current xfer
309 if (anonftp == 2)
310 anonftp = 0;
311 data = -1;
312 epsv4bad = 0;
313 if (username)
314 free(username);
315 username = NULL;
316 if (!proxy)
317 macnum = 0;
321 * Top-level signal handler for interrupted commands.
323 void
324 intr(int signo)
327 sigint_raised = 1;
328 alarmtimer(0);
329 if (fromatty)
330 write(fileno(ttyout), "\n", 1);
331 siglongjmp(toplevel, 1);
335 * Signal handler for lost connections; cleanup various elements of
336 * the connection state, and call cleanuppeer() to finish it off.
338 void
339 lostpeer(int dummy)
341 int oerrno = errno;
343 alarmtimer(0);
344 if (connected) {
345 if (cout != NULL) {
346 (void)shutdown(fileno(cout), 1+1);
347 (void)fclose(cout);
348 cout = NULL;
350 if (data >= 0) {
351 (void)shutdown(data, 1+1);
352 (void)close(data);
353 data = -1;
355 connected = 0;
357 pswitch(1);
358 if (connected) {
359 if (cout != NULL) {
360 (void)shutdown(fileno(cout), 1+1);
361 (void)fclose(cout);
362 cout = NULL;
364 connected = 0;
366 proxflag = 0;
367 pswitch(0);
368 cleanuppeer();
369 errno = oerrno;
374 * Login to remote host, using given username & password if supplied.
375 * Return non-zero if successful.
378 ftp_login(const char *host, const char *luser, const char *lpass)
380 char tmp[80];
381 char *user, *pass, *acct, *p;
382 char emptypass[] = "";
383 const char *errormsg;
384 int n, aflag, rval, nlen;
386 aflag = rval = 0;
387 user = pass = acct = NULL;
388 if (luser)
389 user = ftp_strdup(luser);
390 if (lpass)
391 pass = ftp_strdup(lpass);
393 DPRINTF("ftp_login: user `%s' pass `%s' host `%s'\n",
394 STRorNULL(user), STRorNULL(pass), STRorNULL(host));
397 * Set up arguments for an anonymous FTP session, if necessary.
399 if (anonftp) {
400 FREEPTR(user);
401 user = ftp_strdup("anonymous"); /* as per RFC1635 */
402 FREEPTR(pass);
403 pass = ftp_strdup(getoptionvalue("anonpass"));
406 if (ruserpass(host, &user, &pass, &acct) < 0) {
407 code = -1;
408 goto cleanup_ftp_login;
411 while (user == NULL) {
412 if (localname)
413 fprintf(ttyout, "Name (%s:%s): ", host, localname);
414 else
415 fprintf(ttyout, "Name (%s): ", host);
416 errormsg = NULL;
417 nlen = getline(stdin, tmp, sizeof(tmp), &errormsg);
418 if (nlen < 0) {
419 fprintf(ttyout, "%s; %s aborted.\n", errormsg, "login");
420 code = -1;
421 goto cleanup_ftp_login;
422 } else if (nlen == 0) {
423 user = ftp_strdup(localname);
424 } else {
425 user = ftp_strdup(tmp);
429 if (gatemode) {
430 char *nuser;
431 size_t len;
433 len = strlen(user) + 1 + strlen(host) + 1;
434 nuser = ftp_malloc(len);
435 (void)strlcpy(nuser, user, len);
436 (void)strlcat(nuser, "@", len);
437 (void)strlcat(nuser, host, len);
438 FREEPTR(user);
439 user = nuser;
442 n = command("USER %s", user);
443 if (n == CONTINUE) {
444 if (pass == NULL) {
445 p = getpass("Password: ");
446 if (p == NULL)
447 p = emptypass;
448 pass = ftp_strdup(p);
449 memset(p, 0, strlen(p));
451 n = command("PASS %s", pass);
452 memset(pass, 0, strlen(pass));
454 if (n == CONTINUE) {
455 aflag++;
456 if (acct == NULL) {
457 p = getpass("Account: ");
458 if (p == NULL)
459 p = emptypass;
460 acct = ftp_strdup(p);
461 memset(p, 0, strlen(p));
463 if (acct[0] == '\0') {
464 warnx("Login failed");
465 goto cleanup_ftp_login;
467 n = command("ACCT %s", acct);
468 memset(acct, 0, strlen(acct));
470 if ((n != COMPLETE) ||
471 (!aflag && acct != NULL && command("ACCT %s", acct) != COMPLETE)) {
472 warnx("Login failed");
473 goto cleanup_ftp_login;
475 rval = 1;
476 username = ftp_strdup(user);
477 if (proxy)
478 goto cleanup_ftp_login;
480 connected = -1;
481 getremoteinfo();
482 for (n = 0; n < macnum; ++n) {
483 if (!strcmp("init", macros[n].mac_name)) {
484 (void)strlcpy(line, "$init", sizeof(line));
485 makeargv();
486 domacro(margc, margv);
487 break;
490 updatelocalcwd();
491 updateremotecwd();
493 cleanup_ftp_login:
494 FREEPTR(user);
495 if (pass != NULL)
496 memset(pass, 0, strlen(pass));
497 FREEPTR(pass);
498 if (acct != NULL)
499 memset(acct, 0, strlen(acct));
500 FREEPTR(acct);
501 return (rval);
505 * `another' gets another argument, and stores the new argc and argv.
506 * It reverts to the top level (via intr()) on EOF/error.
508 * Returns false if no new arguments have been added.
511 another(int *pargc, char ***pargv, const char *prompt)
513 const char *errormsg;
514 int ret, nlen;
515 size_t len;
517 len = strlen(line);
518 if (len >= sizeof(line) - 3) {
519 fputs("Sorry, arguments too long.\n", ttyout);
520 intr(0);
522 fprintf(ttyout, "(%s) ", prompt);
523 line[len++] = ' ';
524 errormsg = NULL;
525 nlen = getline(stdin, line + len, sizeof(line)-len, &errormsg);
526 if (nlen < 0) {
527 fprintf(ttyout, "%s; %s aborted.\n", errormsg, "operation");
528 intr(0);
530 len += nlen;
531 makeargv();
532 ret = margc > *pargc;
533 *pargc = margc;
534 *pargv = margv;
535 return (ret);
539 * glob files given in argv[] from the remote server.
540 * if errbuf isn't NULL, store error messages there instead
541 * of writing to the screen.
543 char *
544 remglob(char *argv[], int doswitch, const char **errbuf)
546 static char buf[MAXPATHLEN];
547 static FILE *ftemp = NULL;
548 static char **args;
549 char temp[MAXPATHLEN];
550 int oldverbose, oldhash, oldprogress, fd;
551 char *cp;
552 const char *mode;
553 size_t len;
555 if (!mflag || !connected) {
556 if (!doglob)
557 args = NULL;
558 else {
559 if (ftemp) {
560 (void)fclose(ftemp);
561 ftemp = NULL;
564 return (NULL);
566 if (!doglob) {
567 if (args == NULL)
568 args = argv;
569 if ((cp = *++args) == NULL)
570 args = NULL;
571 return (cp);
573 if (ftemp == NULL) {
574 len = strlcpy(temp, tmpdir, sizeof(temp));
575 if (temp[len - 1] != '/')
576 (void)strlcat(temp, "/", sizeof(temp));
577 (void)strlcat(temp, TMPFILE, sizeof(temp));
578 if ((fd = mkstemp(temp)) < 0) {
579 warn("Unable to create temporary file `%s'", temp);
580 return (NULL);
582 close(fd);
583 oldverbose = verbose;
584 verbose = (errbuf != NULL) ? -1 : 0;
585 oldhash = hash;
586 oldprogress = progress;
587 hash = 0;
588 progress = 0;
589 if (doswitch)
590 pswitch(!proxy);
591 for (mode = "w"; *++argv != NULL; mode = "a")
592 recvrequest("NLST", temp, *argv, mode, 0, 0);
593 if ((code / 100) != COMPLETE) {
594 if (errbuf != NULL)
595 *errbuf = reply_string;
597 if (doswitch)
598 pswitch(!proxy);
599 verbose = oldverbose;
600 hash = oldhash;
601 progress = oldprogress;
602 ftemp = fopen(temp, "r");
603 (void)unlink(temp);
604 if (ftemp == NULL) {
605 if (errbuf == NULL)
606 warnx("Can't find list of remote files");
607 else
608 *errbuf =
609 "Can't find list of remote files";
610 return (NULL);
613 if (fgets(buf, sizeof(buf), ftemp) == NULL) {
614 (void)fclose(ftemp);
615 ftemp = NULL;
616 return (NULL);
618 if ((cp = strchr(buf, '\n')) != NULL)
619 *cp = '\0';
620 return (buf);
624 * Glob a local file name specification with the expectation of a single
625 * return value. Can't control multiple values being expanded from the
626 * expression, we return only the first.
627 * Returns NULL on error, or a pointer to a buffer containing the filename
628 * that's the caller's responsiblity to free(3) when finished with.
630 char *
631 globulize(const char *pattern)
633 glob_t gl;
634 int flags;
635 char *p;
637 if (!doglob)
638 return (ftp_strdup(pattern));
640 flags = GLOB_BRACE|GLOB_NOCHECK|GLOB_TILDE;
641 memset(&gl, 0, sizeof(gl));
642 if (glob(pattern, flags, NULL, &gl) || gl.gl_pathc == 0) {
643 warnx("Glob pattern `%s' not found", pattern);
644 globfree(&gl);
645 return (NULL);
647 p = ftp_strdup(gl.gl_pathv[0]);
648 globfree(&gl);
649 return (p);
653 * determine size of remote file
655 off_t
656 remotesize(const char *file, int noisy)
658 int overbose, r;
659 off_t size;
661 overbose = verbose;
662 size = -1;
663 if (ftp_debug == 0)
664 verbose = -1;
665 if (! features[FEAT_SIZE]) {
666 if (noisy)
667 fprintf(ttyout,
668 "SIZE is not supported by remote server.\n");
669 goto cleanup_remotesize;
671 r = command("SIZE %s", file);
672 if (r == COMPLETE) {
673 char *cp, *ep;
675 cp = strchr(reply_string, ' ');
676 if (cp != NULL) {
677 cp++;
678 size = STRTOLL(cp, &ep, 10);
679 if (*ep != '\0' && !isspace((unsigned char)*ep))
680 size = -1;
682 } else {
683 if (r == ERROR && code == 500 && features[FEAT_SIZE] == -1)
684 features[FEAT_SIZE] = 0;
685 if (noisy && ftp_debug == 0) {
686 fputs(reply_string, ttyout);
687 putc('\n', ttyout);
690 cleanup_remotesize:
691 verbose = overbose;
692 return (size);
696 * determine last modification time (in GMT) of remote file
698 time_t
699 remotemodtime(const char *file, int noisy)
701 int overbose, ocode, r;
702 time_t rtime;
704 overbose = verbose;
705 ocode = code;
706 rtime = -1;
707 if (ftp_debug == 0)
708 verbose = -1;
709 if (! features[FEAT_MDTM]) {
710 if (noisy)
711 fprintf(ttyout,
712 "MDTM is not supported by remote server.\n");
713 goto cleanup_parse_time;
715 r = command("MDTM %s", file);
716 if (r == COMPLETE) {
717 struct tm timebuf;
718 char *timestr, *frac;
721 * time-val = 14DIGIT [ "." 1*DIGIT ]
722 * YYYYMMDDHHMMSS[.sss]
723 * mdtm-response = "213" SP time-val CRLF / error-response
725 timestr = reply_string + 4;
728 * parse fraction.
729 * XXX: ignored for now
731 frac = strchr(timestr, '\r');
732 if (frac != NULL)
733 *frac = '\0';
734 frac = strchr(timestr, '.');
735 if (frac != NULL)
736 *frac++ = '\0';
737 if (strlen(timestr) == 15 && strncmp(timestr, "191", 3) == 0) {
739 * XXX: Workaround for lame ftpd's that return
740 * `19100' instead of `2000'
742 fprintf(ttyout,
743 "Y2K warning! Incorrect time-val `%s' received from server.\n",
744 timestr);
745 timestr++;
746 timestr[0] = '2';
747 timestr[1] = '0';
748 fprintf(ttyout, "Converted to `%s'\n", timestr);
750 memset(&timebuf, 0, sizeof(timebuf));
751 if (strlen(timestr) != 14 ||
752 (strptime(timestr, "%Y%m%d%H%M%S", &timebuf) == NULL)) {
753 bad_parse_time:
754 fprintf(ttyout, "Can't parse time `%s'.\n", timestr);
755 goto cleanup_parse_time;
757 timebuf.tm_isdst = -1;
758 rtime = timegm(&timebuf);
759 if (rtime == -1) {
760 if (noisy || ftp_debug != 0)
761 goto bad_parse_time;
762 else
763 goto cleanup_parse_time;
764 } else
765 DPRINTF("remotemodtime: parsed date `%s' as " LLF
766 ", %s",
767 timestr, (LLT)rtime,
768 rfc2822time(localtime(&rtime)));
769 } else {
770 if (r == ERROR && code == 500 && features[FEAT_MDTM] == -1)
771 features[FEAT_MDTM] = 0;
772 if (noisy && ftp_debug == 0) {
773 fputs(reply_string, ttyout);
774 putc('\n', ttyout);
777 cleanup_parse_time:
778 verbose = overbose;
779 if (rtime == -1)
780 code = ocode;
781 return (rtime);
785 * Format tm in an RFC2822 compatible manner, with a trailing \n.
786 * Returns a pointer to a static string containing the result.
788 const char *
789 rfc2822time(const struct tm *tm)
791 static char result[50];
793 if (strftime(result, sizeof(result),
794 "%a, %d %b %Y %H:%M:%S %z\n", tm) == 0)
795 errx(1, "Can't convert RFC2822 time: buffer too small");
796 return result;
800 * Update global `localcwd', which contains the state of the local cwd
802 void
803 updatelocalcwd(void)
806 if (getcwd(localcwd, sizeof(localcwd)) == NULL)
807 localcwd[0] = '\0';
808 DPRINTF("updatelocalcwd: got `%s'\n", localcwd);
812 * Update global `remotecwd', which contains the state of the remote cwd
814 void
815 updateremotecwd(void)
817 int overbose, ocode, i;
818 char *cp;
820 overbose = verbose;
821 ocode = code;
822 if (ftp_debug == 0)
823 verbose = -1;
824 if (command("PWD") != COMPLETE)
825 goto badremotecwd;
826 cp = strchr(reply_string, ' ');
827 if (cp == NULL || cp[0] == '\0' || cp[1] != '"')
828 goto badremotecwd;
829 cp += 2;
830 for (i = 0; *cp && i < sizeof(remotecwd) - 1; i++, cp++) {
831 if (cp[0] == '"') {
832 if (cp[1] == '"')
833 cp++;
834 else
835 break;
837 remotecwd[i] = *cp;
839 remotecwd[i] = '\0';
840 DPRINTF("updateremotecwd: got `%s'\n", remotecwd);
841 goto cleanupremotecwd;
842 badremotecwd:
843 remotecwd[0]='\0';
844 cleanupremotecwd:
845 verbose = overbose;
846 code = ocode;
850 * Ensure file is in or under dir.
851 * Returns 1 if so, 0 if not (or an error occurred).
854 fileindir(const char *file, const char *dir)
856 char parentdirbuf[PATH_MAX+1], *parentdir;
857 char realdir[PATH_MAX+1];
858 size_t dirlen;
860 /* determine parent directory of file */
861 (void)strlcpy(parentdirbuf, file, sizeof(parentdirbuf));
862 parentdir = dirname(parentdirbuf);
863 if (strcmp(parentdir, ".") == 0)
864 return 1; /* current directory is ok */
866 /* find the directory */
867 if (realpath(parentdir, realdir) == NULL) {
868 warn("Unable to determine real path of `%s'", parentdir);
869 return 0;
871 if (realdir[0] != '/') /* relative result is ok */
872 return 1;
873 dirlen = strlen(dir);
874 #if 0
875 printf("file %s parent %s realdir %s dir %s [%d]\n",
876 file, parentdir, realdir, dir, dirlen);
877 #endif
878 if (strncmp(realdir, dir, dirlen) == 0 &&
879 (realdir[dirlen] == '/' || realdir[dirlen] == '\0'))
880 return 1;
881 return 0;
885 * List words in stringlist, vertically arranged
887 void
888 list_vertical(StringList *sl)
890 int i, j;
891 int columns, lines;
892 char *p;
893 size_t w, width;
895 width = 0;
897 for (i = 0 ; i < sl->sl_cur ; i++) {
898 w = strlen(sl->sl_str[i]);
899 if (w > width)
900 width = w;
902 width = (width + 8) &~ 7;
904 columns = ttywidth / width;
905 if (columns == 0)
906 columns = 1;
907 lines = (sl->sl_cur + columns - 1) / columns;
908 for (i = 0; i < lines; i++) {
909 for (j = 0; j < columns; j++) {
910 p = sl->sl_str[j * lines + i];
911 if (p)
912 fputs(p, ttyout);
913 if (j * lines + i + lines >= sl->sl_cur) {
914 putc('\n', ttyout);
915 break;
917 if (p) {
918 w = strlen(p);
919 while (w < width) {
920 w = (w + 8) &~ 7;
921 (void)putc('\t', ttyout);
929 * Update the global ttywidth value, using TIOCGWINSZ.
931 void
932 setttywidth(int a)
934 struct winsize winsize;
935 int oerrno = errno;
937 if (ioctl(fileno(ttyout), TIOCGWINSZ, &winsize) != -1 &&
938 winsize.ws_col != 0)
939 ttywidth = winsize.ws_col;
940 else
941 ttywidth = 80;
942 errno = oerrno;
946 * Change the rate limit up (SIGUSR1) or down (SIGUSR2)
948 void
949 crankrate(int sig)
952 switch (sig) {
953 case SIGUSR1:
954 if (rate_get)
955 rate_get += rate_get_incr;
956 if (rate_put)
957 rate_put += rate_put_incr;
958 break;
959 case SIGUSR2:
960 if (rate_get && rate_get > rate_get_incr)
961 rate_get -= rate_get_incr;
962 if (rate_put && rate_put > rate_put_incr)
963 rate_put -= rate_put_incr;
964 break;
965 default:
966 err(1, "crankrate invoked with unknown signal: %d", sig);
972 * Setup or cleanup EditLine structures
974 #ifndef NO_EDITCOMPLETE
975 void
976 controlediting(void)
978 if (editing && el == NULL && hist == NULL) {
979 HistEvent ev;
980 int editmode;
982 el = el_init(getprogname(), stdin, ttyout, stderr);
983 /* init editline */
984 hist = history_init(); /* init the builtin history */
985 history(hist, &ev, H_SETSIZE, 100);/* remember 100 events */
986 el_set(el, EL_HIST, history, hist); /* use history */
988 el_set(el, EL_EDITOR, "emacs"); /* default editor is emacs */
989 el_set(el, EL_PROMPT, prompt); /* set the prompt functions */
990 el_set(el, EL_RPROMPT, rprompt);
992 /* add local file completion, bind to TAB */
993 el_set(el, EL_ADDFN, "ftp-complete",
994 "Context sensitive argument completion",
995 complete);
996 el_set(el, EL_BIND, "^I", "ftp-complete", NULL);
997 el_source(el, NULL); /* read ~/.editrc */
998 if ((el_get(el, EL_EDITMODE, &editmode) != -1) && editmode == 0)
999 editing = 0; /* the user doesn't want editing,
1000 * so disable, and let statement
1001 * below cleanup */
1002 else
1003 el_set(el, EL_SIGNAL, 1);
1005 if (!editing) {
1006 if (hist) {
1007 history_end(hist);
1008 hist = NULL;
1010 if (el) {
1011 el_end(el);
1012 el = NULL;
1016 #endif /* !NO_EDITCOMPLETE */
1019 * Convert the string `arg' to an int, which may have an optional SI suffix
1020 * (`b', `k', `m', `g'). Returns the number for success, -1 otherwise.
1023 strsuftoi(const char *arg)
1025 char *cp;
1026 long val;
1028 if (!isdigit((unsigned char)arg[0]))
1029 return (-1);
1031 val = strtol(arg, &cp, 10);
1032 if (cp != NULL) {
1033 if (cp[0] != '\0' && cp[1] != '\0')
1034 return (-1);
1035 switch (tolower((unsigned char)cp[0])) {
1036 case '\0':
1037 case 'b':
1038 break;
1039 case 'k':
1040 val <<= 10;
1041 break;
1042 case 'm':
1043 val <<= 20;
1044 break;
1045 case 'g':
1046 val <<= 30;
1047 break;
1048 default:
1049 return (-1);
1052 if (val < 0 || val > INT_MAX)
1053 return (-1);
1055 return (val);
1059 * Set up socket buffer sizes before a connection is made.
1061 void
1062 setupsockbufsize(int sock)
1065 if (setsockopt(sock, SOL_SOCKET, SO_SNDBUF,
1066 (void *)&sndbuf_size, sizeof(sndbuf_size)) == -1)
1067 warn("Unable to set sndbuf size %d", sndbuf_size);
1069 if (setsockopt(sock, SOL_SOCKET, SO_RCVBUF,
1070 (void *)&rcvbuf_size, sizeof(rcvbuf_size)) == -1)
1071 warn("Unable to set rcvbuf size %d", rcvbuf_size);
1075 * Copy characters from src into dst, \ quoting characters that require it
1077 void
1078 ftpvis(char *dst, size_t dstlen, const char *src, size_t srclen)
1080 int di, si;
1082 for (di = si = 0;
1083 src[si] != '\0' && di < dstlen && si < srclen;
1084 di++, si++) {
1085 switch (src[si]) {
1086 case '\\':
1087 case ' ':
1088 case '\t':
1089 case '\r':
1090 case '\n':
1091 case '"':
1092 dst[di++] = '\\';
1093 if (di >= dstlen)
1094 break;
1095 /* FALLTHROUGH */
1096 default:
1097 dst[di] = src[si];
1100 dst[di] = '\0';
1104 * Copy src into buf (which is len bytes long), expanding % sequences.
1106 void
1107 formatbuf(char *buf, size_t len, const char *src)
1109 const char *p, *p2, *q;
1110 int i, op, updirs, pdirs;
1112 #define ADDBUF(x) do { \
1113 if (i >= len - 1) \
1114 goto endbuf; \
1115 buf[i++] = (x); \
1116 } while (0)
1118 p = src;
1119 for (i = 0; *p; p++) {
1120 if (*p != '%') {
1121 ADDBUF(*p);
1122 continue;
1124 p++;
1126 switch (op = *p) {
1128 case '/':
1129 case '.':
1130 case 'c':
1131 p2 = connected ? remotecwd : "";
1132 updirs = pdirs = 0;
1134 /* option to determine fixed # of dirs from path */
1135 if (op == '.' || op == 'c') {
1136 int skip;
1138 q = p2;
1139 while (*p2) /* calc # of /'s */
1140 if (*p2++ == '/')
1141 updirs++;
1142 if (p[1] == '0') { /* print <x> or ... */
1143 pdirs = 1;
1144 p++;
1146 if (p[1] >= '1' && p[1] <= '9') {
1147 /* calc # to skip */
1148 skip = p[1] - '0';
1149 p++;
1150 } else
1151 skip = 1;
1153 updirs -= skip;
1154 while (skip-- > 0) {
1155 while ((p2 > q) && (*p2 != '/'))
1156 p2--; /* back up */
1157 if (skip && p2 > q)
1158 p2--;
1160 if (*p2 == '/' && p2 != q)
1161 p2++;
1164 if (updirs > 0 && pdirs) {
1165 if (i >= len - 5)
1166 break;
1167 if (op == '.') {
1168 ADDBUF('.');
1169 ADDBUF('.');
1170 ADDBUF('.');
1171 } else {
1172 ADDBUF('/');
1173 ADDBUF('<');
1174 if (updirs > 9) {
1175 ADDBUF('9');
1176 ADDBUF('+');
1177 } else
1178 ADDBUF('0' + updirs);
1179 ADDBUF('>');
1182 for (; *p2; p2++)
1183 ADDBUF(*p2);
1184 break;
1186 case 'M':
1187 case 'm':
1188 for (p2 = connected && hostname ? hostname : "-";
1189 *p2 ; p2++) {
1190 if (op == 'm' && *p2 == '.')
1191 break;
1192 ADDBUF(*p2);
1194 break;
1196 case 'n':
1197 for (p2 = connected ? username : "-"; *p2 ; p2++)
1198 ADDBUF(*p2);
1199 break;
1201 case '%':
1202 ADDBUF('%');
1203 break;
1205 default: /* display unknown codes literally */
1206 ADDBUF('%');
1207 ADDBUF(op);
1208 break;
1212 endbuf:
1213 buf[i] = '\0';
1217 * Parse `port' into a TCP port number, defaulting to `defport' if `port' is
1218 * an unknown service name. If defport != -1, print a warning upon bad parse.
1221 parseport(const char *port, int defport)
1223 int rv;
1224 long nport;
1225 char *p, *ep;
1227 p = ftp_strdup(port);
1228 nport = strtol(p, &ep, 10);
1229 if (*ep != '\0' && ep == p) {
1230 struct servent *svp;
1232 svp = getservbyname(port, "tcp");
1233 if (svp == NULL) {
1234 badparseport:
1235 if (defport != -1)
1236 warnx("Unknown port `%s', using port %d",
1237 port, defport);
1238 rv = defport;
1239 } else
1240 rv = ntohs(svp->s_port);
1241 } else if (nport < 1 || nport > MAX_IN_PORT_T || *ep != '\0')
1242 goto badparseport;
1243 else
1244 rv = nport;
1245 free(p);
1246 return (rv);
1250 * Determine if given string is an IPv6 address or not.
1251 * Return 1 for yes, 0 for no
1254 isipv6addr(const char *addr)
1256 int rv = 0;
1257 #ifdef INET6
1258 struct addrinfo hints, *res;
1260 memset(&hints, 0, sizeof(hints));
1261 hints.ai_family = PF_INET6;
1262 hints.ai_socktype = SOCK_DGRAM; /*dummy*/
1263 hints.ai_flags = AI_NUMERICHOST;
1264 if (getaddrinfo(addr, "0", &hints, &res) != 0)
1265 rv = 0;
1266 else {
1267 rv = 1;
1268 freeaddrinfo(res);
1270 DPRINTF("isipv6addr: got %d for %s\n", rv, addr);
1271 #endif
1272 return (rv == 1) ? 1 : 0;
1276 * Read a line from the FILE stream into buf/buflen using fgets(), so up
1277 * to buflen-1 chars will be read and the result will be NUL terminated.
1278 * If the line has a trailing newline it will be removed.
1279 * If the line is too long, excess characters will be read until
1280 * newline/EOF/error.
1281 * If EOF/error occurs or a too-long line is encountered and errormsg
1282 * isn't NULL, it will be changed to a description of the problem.
1283 * (The EOF message has a leading \n for cosmetic purposes).
1284 * Returns:
1285 * >=0 length of line (excluding trailing newline) if all ok
1286 * -1 error occurred
1287 * -2 EOF encountered
1288 * -3 line was too long
1291 getline(FILE *stream, char *buf, size_t buflen, const char **errormsg)
1293 int rv, ch;
1294 size_t len;
1296 if (fgets(buf, buflen, stream) == NULL) {
1297 if (feof(stream)) { /* EOF */
1298 rv = -2;
1299 if (errormsg)
1300 *errormsg = "\nEOF received";
1301 } else { /* error */
1302 rv = -1;
1303 if (errormsg)
1304 *errormsg = "Error encountered";
1306 clearerr(stream);
1307 return rv;
1309 len = strlen(buf);
1310 if (buf[len-1] == '\n') { /* clear any trailing newline */
1311 buf[--len] = '\0';
1312 } else if (len == buflen-1) { /* line too long */
1313 while ((ch = getchar()) != '\n' && ch != EOF)
1314 continue;
1315 if (errormsg)
1316 *errormsg = "Input line is too long";
1317 clearerr(stream);
1318 return -3;
1320 if (errormsg)
1321 *errormsg = NULL;
1322 return len;
1326 * Internal version of connect(2); sets socket buffer sizes,
1327 * binds to a specific local address (if set), and
1328 * supports a connection timeout using a non-blocking connect(2) with
1329 * a poll(2).
1330 * Socket fcntl flags are temporarily updated to include O_NONBLOCK;
1331 * these will not be reverted on connection failure.
1332 * Returns 0 on success, or -1 upon failure (with an appropriate
1333 * error message displayed.)
1336 ftp_connect(int sock, const struct sockaddr *name, socklen_t namelen)
1338 int flags, rv, timeout, error;
1339 socklen_t slen;
1340 struct timeval endtime, now, td;
1341 struct pollfd pfd[1];
1342 char hname[NI_MAXHOST];
1344 setupsockbufsize(sock);
1345 if (getnameinfo(name, namelen,
1346 hname, sizeof(hname), NULL, 0, NI_NUMERICHOST) != 0)
1347 strlcpy(hname, "?", sizeof(hname));
1349 if (bindai != NULL) { /* bind to specific addr */
1350 struct addrinfo *ai;
1352 for (ai = bindai; ai != NULL; ai = ai->ai_next) {
1353 if (ai->ai_family == name->sa_family)
1354 break;
1356 if (ai == NULL)
1357 ai = bindai;
1358 if (bind(sock, ai->ai_addr, ai->ai_addrlen) == -1) {
1359 char bname[NI_MAXHOST];
1360 int saveerr;
1362 saveerr = errno;
1363 if (getnameinfo(ai->ai_addr, ai->ai_addrlen,
1364 bname, sizeof(bname), NULL, 0, NI_NUMERICHOST) != 0)
1365 strlcpy(bname, "?", sizeof(bname));
1366 errno = saveerr;
1367 warn("Can't bind to `%s'", bname);
1368 return -1;
1372 /* save current socket flags */
1373 if ((flags = fcntl(sock, F_GETFL, 0)) == -1) {
1374 warn("Can't %s socket flags for connect to `%s'",
1375 "save", hname);
1376 return -1;
1378 /* set non-blocking connect */
1379 if (fcntl(sock, F_SETFL, flags | O_NONBLOCK) == -1) {
1380 warn("Can't set socket non-blocking for connect to `%s'",
1381 hname);
1382 return -1;
1385 /* NOTE: we now must restore socket flags on successful exit */
1387 pfd[0].fd = sock;
1388 pfd[0].events = POLLIN|POLLOUT;
1390 if (quit_time > 0) { /* want a non default timeout */
1391 (void)gettimeofday(&endtime, NULL);
1392 endtime.tv_sec += quit_time; /* determine end time */
1395 rv = connect(sock, name, namelen); /* inititate the connection */
1396 if (rv == -1) { /* connection error */
1397 if (errno != EINPROGRESS) { /* error isn't "please wait" */
1398 connecterror:
1399 warn("Can't connect to `%s'", hname);
1400 return -1;
1403 /* connect EINPROGRESS; wait */
1404 do {
1405 if (quit_time > 0) { /* determine timeout */
1406 (void)gettimeofday(&now, NULL);
1407 timersub(&endtime, &now, &td);
1408 timeout = td.tv_sec * 1000 + td.tv_usec/1000;
1409 if (timeout < 0)
1410 timeout = 0;
1411 } else {
1412 timeout = INFTIM;
1414 pfd[0].revents = 0;
1415 rv = ftp_poll(pfd, 1, timeout);
1416 /* loop until poll ! EINTR */
1417 } while (rv == -1 && errno == EINTR);
1419 if (rv == 0) { /* poll (connect) timed out */
1420 errno = ETIMEDOUT;
1421 goto connecterror;
1424 if (rv == -1) { /* poll error */
1425 goto connecterror;
1426 } else if (pfd[0].revents & (POLLIN|POLLOUT)) {
1427 slen = sizeof(error); /* OK, or pending error */
1428 if (getsockopt(sock, SOL_SOCKET, SO_ERROR,
1429 &error, &slen) == -1) {
1430 /* Solaris pending error */
1431 goto connecterror;
1432 } else if (error != 0) {
1433 errno = error; /* BSD pending error */
1434 goto connecterror;
1436 } else {
1437 errno = EBADF; /* this shouldn't happen ... */
1438 goto connecterror;
1442 if (fcntl(sock, F_SETFL, flags) == -1) {
1443 /* restore socket flags */
1444 warn("Can't %s socket flags for connect to `%s'",
1445 "restore", hname);
1446 return -1;
1448 return 0;
1452 * Internal version of listen(2); sets socket buffer sizes first.
1455 ftp_listen(int sock, int backlog)
1458 setupsockbufsize(sock);
1459 return (listen(sock, backlog));
1463 * Internal version of poll(2), to allow reimplementation by select(2)
1464 * on platforms without the former.
1467 ftp_poll(struct pollfd *fds, int nfds, int timeout)
1469 return poll(fds, nfds, timeout);
1473 * malloc() with inbuilt error checking
1475 void *
1476 ftp_malloc(size_t size)
1478 void *p;
1480 p = malloc(size);
1481 if (p == NULL)
1482 err(1, "Unable to allocate %ld bytes of memory", (long)size);
1483 return (p);
1487 * sl_init() with inbuilt error checking
1489 StringList *
1490 ftp_sl_init(void)
1492 StringList *p;
1494 p = sl_init();
1495 if (p == NULL)
1496 err(1, "Unable to allocate memory for stringlist");
1497 return (p);
1501 * sl_add() with inbuilt error checking
1503 void
1504 ftp_sl_add(StringList *sl, char *i)
1507 if (sl_add(sl, i) == -1)
1508 err(1, "Unable to add `%s' to stringlist", i);
1512 * strdup() with inbuilt error checking
1514 char *
1515 ftp_strdup(const char *str)
1517 char *s;
1519 if (str == NULL)
1520 errx(1, "ftp_strdup: called with NULL argument");
1521 s = strdup(str);
1522 if (s == NULL)
1523 err(1, "Unable to allocate memory for string copy");
1524 return (s);