util.c revision 1.120 1 /* $NetBSD: util.c,v 1.120 2005/05/07 16:19:13 lukem Exp $ */
2
3 /*-
4 * Copyright (c) 1997-2005 The NetBSD Foundation, Inc.
5 * All rights reserved.
6 *
7 * This code is derived from software contributed to The NetBSD Foundation
8 * by Luke Mewburn.
9 *
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.
13 *
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.
29 *
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.
41 */
42
43 /*
44 * Copyright (c) 1985, 1989, 1993, 1994
45 * The Regents of the University of California. All rights reserved.
46 *
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.
58 *
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.
70 */
71
72 #include <sys/cdefs.h>
73 #ifndef lint
74 __RCSID("$NetBSD: util.c,v 1.120 2005/05/07 16:19:13 lukem Exp $");
75 #endif /* not lint */
76
77 /*
78 * FTP User Program -- Misc support routines
79 */
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>
86
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 <limits.h>
94 #include <netdb.h>
95 #include <stdio.h>
96 #include <stdlib.h>
97 #include <string.h>
98 #include <termios.h>
99 #include <time.h>
100 #include <tzfile.h>
101 #include <unistd.h>
102
103 #include "ftp_var.h"
104
105 /*
106 * Connect to peer server and auto-login, if possible.
107 */
108 void
109 setpeer(int argc, char *argv[])
110 {
111 char *host;
112 char *port;
113
114 if (argc == 0)
115 goto usage;
116 if (connected) {
117 fprintf(ttyout, "Already connected to %s, use close first.\n",
118 hostname);
119 code = -1;
120 return;
121 }
122 if (argc < 2)
123 (void)another(&argc, &argv, "to");
124 if (argc < 2 || argc > 3) {
125 usage:
126 fprintf(ttyout, "usage: %s host-name [port]\n", argv[0]);
127 code = -1;
128 return;
129 }
130 if (gatemode)
131 port = gateport;
132 else
133 port = ftpport;
134 if (argc > 2)
135 port = argv[2];
136
137 if (gatemode) {
138 if (gateserver == NULL || *gateserver == '\0')
139 errx(1, "gateserver not defined (shouldn't happen)");
140 host = hookup(gateserver, port);
141 } else
142 host = hookup(argv[1], port);
143
144 if (host) {
145 if (gatemode && verbose) {
146 fprintf(ttyout,
147 "Connecting via pass-through server %s\n",
148 gateserver);
149 }
150
151 connected = 1;
152 /*
153 * Set up defaults for FTP.
154 */
155 (void)strlcpy(typename, "ascii", sizeof(typename));
156 type = TYPE_A;
157 curtype = TYPE_A;
158 (void)strlcpy(formname, "non-print", sizeof(formname));
159 form = FORM_N;
160 (void)strlcpy(modename, "stream", sizeof(modename));
161 mode = MODE_S;
162 (void)strlcpy(structname, "file", sizeof(structname));
163 stru = STRU_F;
164 (void)strlcpy(bytename, "8", sizeof(bytename));
165 bytesize = 8;
166 if (autologin)
167 (void)ftp_login(argv[1], NULL, NULL);
168 }
169 }
170
171 static void
172 parse_feat(const char *line)
173 {
174
175 /*
176 * work-around broken ProFTPd servers that can't
177 * even obey RFC 2389.
178 */
179 while (*line && isspace((int)*line))
180 line++;
181
182 if (strcasecmp(line, "MDTM") == 0)
183 features[FEAT_MDTM] = 1;
184 else if (strncasecmp(line, "MLST", sizeof("MLST") - 1) == 0) {
185 features[FEAT_MLST] = 1;
186 } else if (strcasecmp(line, "REST STREAM") == 0)
187 features[FEAT_REST_STREAM] = 1;
188 else if (strcasecmp(line, "SIZE") == 0)
189 features[FEAT_SIZE] = 1;
190 else if (strcasecmp(line, "TVFS") == 0)
191 features[FEAT_TVFS] = 1;
192 }
193
194 /*
195 * Determine the remote system type (SYST) and features (FEAT).
196 * Call after a successful login (i.e, connected = -1)
197 */
198 void
199 getremoteinfo(void)
200 {
201 int overbose, i;
202
203 overbose = verbose;
204 if (debug == 0)
205 verbose = -1;
206
207 /* determine remote system type */
208 if (command("SYST") == COMPLETE) {
209 if (overbose) {
210 char *cp, c;
211
212 c = 0;
213 cp = strchr(reply_string + 4, ' ');
214 if (cp == NULL)
215 cp = strchr(reply_string + 4, '\r');
216 if (cp) {
217 if (cp[-1] == '.')
218 cp--;
219 c = *cp;
220 *cp = '\0';
221 }
222
223 fprintf(ttyout, "Remote system type is %s.\n",
224 reply_string + 4);
225 if (cp)
226 *cp = c;
227 }
228 if (!strncmp(reply_string, "215 UNIX Type: L8", 17)) {
229 if (proxy)
230 unix_proxy = 1;
231 else
232 unix_server = 1;
233 /*
234 * Set type to 0 (not specified by user),
235 * meaning binary by default, but don't bother
236 * telling server. We can use binary
237 * for text files unless changed by the user.
238 */
239 type = 0;
240 (void)strlcpy(typename, "binary", sizeof(typename));
241 if (overbose)
242 fprintf(ttyout,
243 "Using %s mode to transfer files.\n",
244 typename);
245 } else {
246 if (proxy)
247 unix_proxy = 0;
248 else
249 unix_server = 0;
250 if (overbose &&
251 !strncmp(reply_string, "215 TOPS20", 10))
252 fputs(
253 "Remember to set tenex mode when transferring binary files from this machine.\n",
254 ttyout);
255 }
256 }
257
258 /* determine features (if any) */
259 for (i = 0; i < FEAT_max; i++)
260 features[i] = -1;
261 reply_callback = parse_feat;
262 if (command("FEAT") == COMPLETE) {
263 for (i = 0; i < FEAT_max; i++) {
264 if (features[i] == -1)
265 features[i] = 0;
266 }
267 features[FEAT_FEAT] = 1;
268 } else
269 features[FEAT_FEAT] = 0;
270 if (debug) {
271 #define DEBUG_FEAT(x) fprintf(ttyout, "features[" #x "] = %d\n", features[(x)])
272 DEBUG_FEAT(FEAT_FEAT);
273 DEBUG_FEAT(FEAT_MDTM);
274 DEBUG_FEAT(FEAT_MLST);
275 DEBUG_FEAT(FEAT_REST_STREAM);
276 DEBUG_FEAT(FEAT_SIZE);
277 DEBUG_FEAT(FEAT_TVFS);
278 #undef DEBUG_FEAT
279 }
280 reply_callback = NULL;
281
282 verbose = overbose;
283 }
284
285 /*
286 * Reset the various variables that indicate connection state back to
287 * disconnected settings.
288 * The caller is responsible for issuing any commands to the remote server
289 * to perform a clean shutdown before this is invoked.
290 */
291 void
292 cleanuppeer(void)
293 {
294
295 if (cout)
296 (void)fclose(cout);
297 cout = NULL;
298 connected = 0;
299 unix_server = 0;
300 unix_proxy = 0;
301 /*
302 * determine if anonftp was specifically set with -a
303 * (1), or implicitly set by auto_fetch() (2). in the
304 * latter case, disable after the current xfer
305 */
306 if (anonftp == 2)
307 anonftp = 0;
308 data = -1;
309 epsv4bad = 0;
310 if (username)
311 free(username);
312 username = NULL;
313 if (!proxy)
314 macnum = 0;
315 }
316
317 /*
318 * Top-level signal handler for interrupted commands.
319 */
320 void
321 intr(int signo)
322 {
323
324 sigint_raised = 1;
325 alarmtimer(0);
326 if (fromatty)
327 write(fileno(ttyout), "\n", 1);
328 siglongjmp(toplevel, 1);
329 }
330
331 /*
332 * Signal handler for lost connections; cleanup various elements of
333 * the connection state, and call cleanuppeer() to finish it off.
334 */
335 void
336 lostpeer(int dummy)
337 {
338 int oerrno = errno;
339
340 alarmtimer(0);
341 if (connected) {
342 if (cout != NULL) {
343 (void)shutdown(fileno(cout), 1+1);
344 (void)fclose(cout);
345 cout = NULL;
346 }
347 if (data >= 0) {
348 (void)shutdown(data, 1+1);
349 (void)close(data);
350 data = -1;
351 }
352 connected = 0;
353 }
354 pswitch(1);
355 if (connected) {
356 if (cout != NULL) {
357 (void)shutdown(fileno(cout), 1+1);
358 (void)fclose(cout);
359 cout = NULL;
360 }
361 connected = 0;
362 }
363 proxflag = 0;
364 pswitch(0);
365 cleanuppeer();
366 errno = oerrno;
367 }
368
369
370 /*
371 * Login to remote host, using given username & password if supplied.
372 * Return non-zero if successful.
373 */
374 int
375 ftp_login(const char *host, const char *user, const char *pass)
376 {
377 char tmp[80];
378 const char *acct;
379 int n, aflag, rval, freeuser, freepass, freeacct;
380
381 acct = NULL;
382 aflag = rval = freeuser = freepass = freeacct = 0;
383
384 if (debug)
385 fprintf(ttyout, "ftp_login: user `%s' pass `%s' host `%s'\n",
386 user ? user : "<null>", pass ? pass : "<null>",
387 host ? host : "<null>");
388
389
390 /*
391 * Set up arguments for an anonymous FTP session, if necessary.
392 */
393 if (anonftp) {
394 user = "anonymous"; /* as per RFC 1635 */
395 pass = getoptionvalue("anonpass");
396 }
397
398 if (user == NULL)
399 freeuser = 1;
400 if (pass == NULL)
401 freepass = 1;
402 freeacct = 1;
403 if (ruserpass(host, &user, &pass, &acct) < 0) {
404 code = -1;
405 goto cleanup_ftp_login;
406 }
407
408 while (user == NULL) {
409 if (localname)
410 fprintf(ttyout, "Name (%s:%s): ", host, localname);
411 else
412 fprintf(ttyout, "Name (%s): ", host);
413 *tmp = '\0';
414 if (fgets(tmp, sizeof(tmp) - 1, stdin) == NULL) {
415 fprintf(ttyout, "\nEOF received; login aborted.\n");
416 clearerr(stdin);
417 code = -1;
418 goto cleanup_ftp_login;
419 }
420 tmp[strlen(tmp) - 1] = '\0';
421 freeuser = 0;
422 if (*tmp == '\0')
423 user = localname;
424 else
425 user = tmp;
426 }
427
428 if (gatemode) {
429 char *nuser;
430 int len;
431
432 len = strlen(user) + 1 + strlen(host) + 1;
433 nuser = xmalloc(len);
434 (void)strlcpy(nuser, user, len);
435 (void)strlcat(nuser, "@", len);
436 (void)strlcat(nuser, host, len);
437 freeuser = 1;
438 user = nuser;
439 }
440
441 n = command("USER %s", user);
442 if (n == CONTINUE) {
443 if (pass == NULL) {
444 freepass = 0;
445 pass = getpass("Password:");
446 }
447 n = command("PASS %s", pass);
448 }
449 if (n == CONTINUE) {
450 aflag++;
451 if (acct == NULL) {
452 freeacct = 0;
453 acct = getpass("Account:");
454 }
455 if (acct[0] == '\0') {
456 warnx("Login failed.");
457 goto cleanup_ftp_login;
458 }
459 n = command("ACCT %s", acct);
460 }
461 if ((n != COMPLETE) ||
462 (!aflag && acct != NULL && command("ACCT %s", acct) != COMPLETE)) {
463 warnx("Login failed.");
464 goto cleanup_ftp_login;
465 }
466 rval = 1;
467 username = xstrdup(user);
468 if (proxy)
469 goto cleanup_ftp_login;
470
471 connected = -1;
472 getremoteinfo();
473 for (n = 0; n < macnum; ++n) {
474 if (!strcmp("init", macros[n].mac_name)) {
475 (void)strlcpy(line, "$init", sizeof(line));
476 makeargv();
477 domacro(margc, margv);
478 break;
479 }
480 }
481 updatelocalcwd();
482 updateremotecwd();
483
484 cleanup_ftp_login:
485 if (user != NULL && freeuser)
486 free((char *)user);
487 if (pass != NULL && freepass)
488 free((char *)pass);
489 if (acct != NULL && freeacct)
490 free((char *)acct);
491 return (rval);
492 }
493
494 /*
495 * `another' gets another argument, and stores the new argc and argv.
496 * It reverts to the top level (via intr()) on EOF/error.
497 *
498 * Returns false if no new arguments have been added.
499 */
500 int
501 another(int *pargc, char ***pargv, const char *prompt)
502 {
503 int len = strlen(line), ret;
504
505 if (len >= sizeof(line) - 3) {
506 fputs("sorry, arguments too long.\n", ttyout);
507 intr(0);
508 }
509 fprintf(ttyout, "(%s) ", prompt);
510 line[len++] = ' ';
511 if (fgets(&line[len], sizeof(line) - len, stdin) == NULL) {
512 clearerr(stdin);
513 intr(0);
514 }
515 len += strlen(&line[len]);
516 if (len > 0 && line[len - 1] == '\n')
517 line[len - 1] = '\0';
518 makeargv();
519 ret = margc > *pargc;
520 *pargc = margc;
521 *pargv = margv;
522 return (ret);
523 }
524
525 /*
526 * glob files given in argv[] from the remote server.
527 * if errbuf isn't NULL, store error messages there instead
528 * of writing to the screen.
529 */
530 char *
531 remglob(char *argv[], int doswitch, char **errbuf)
532 {
533 char temp[MAXPATHLEN];
534 static char buf[MAXPATHLEN];
535 static FILE *ftemp = NULL;
536 static char **args;
537 int oldverbose, oldhash, oldprogress, fd, len;
538 char *cp, *mode;
539
540 if (!mflag || !connected) {
541 if (!doglob)
542 args = NULL;
543 else {
544 if (ftemp) {
545 (void)fclose(ftemp);
546 ftemp = NULL;
547 }
548 }
549 return (NULL);
550 }
551 if (!doglob) {
552 if (args == NULL)
553 args = argv;
554 if ((cp = *++args) == NULL)
555 args = NULL;
556 return (cp);
557 }
558 if (ftemp == NULL) {
559 len = strlcpy(temp, tmpdir, sizeof(temp));
560 if (temp[len - 1] != '/')
561 (void)strlcat(temp, "/", sizeof(temp));
562 (void)strlcat(temp, TMPFILE, sizeof(temp));
563 if ((fd = mkstemp(temp)) < 0) {
564 warn("unable to create temporary file %s", temp);
565 return (NULL);
566 }
567 close(fd);
568 oldverbose = verbose;
569 verbose = (errbuf != NULL) ? -1 : 0;
570 oldhash = hash;
571 oldprogress = progress;
572 hash = 0;
573 progress = 0;
574 if (doswitch)
575 pswitch(!proxy);
576 for (mode = "w"; *++argv != NULL; mode = "a")
577 recvrequest("NLST", temp, *argv, mode, 0, 0);
578 if ((code / 100) != COMPLETE) {
579 if (errbuf != NULL)
580 *errbuf = reply_string;
581 }
582 if (doswitch)
583 pswitch(!proxy);
584 verbose = oldverbose;
585 hash = oldhash;
586 progress = oldprogress;
587 ftemp = fopen(temp, "r");
588 (void)unlink(temp);
589 if (ftemp == NULL) {
590 if (errbuf == NULL)
591 fputs(
592 "can't find list of remote files, oops.\n",
593 ttyout);
594 else
595 *errbuf =
596 "can't find list of remote files, oops.";
597 return (NULL);
598 }
599 }
600 if (fgets(buf, sizeof(buf), ftemp) == NULL) {
601 (void)fclose(ftemp);
602 ftemp = NULL;
603 return (NULL);
604 }
605 if ((cp = strchr(buf, '\n')) != NULL)
606 *cp = '\0';
607 return (buf);
608 }
609
610 /*
611 * Glob a local file name specification with the expectation of a single
612 * return value. Can't control multiple values being expanded from the
613 * expression, we return only the first.
614 * Returns NULL on error, or a pointer to a buffer containing the filename
615 * that's the caller's responsiblity to free(3) when finished with.
616 */
617 char *
618 globulize(const char *pattern)
619 {
620 glob_t gl;
621 int flags;
622 char *p;
623
624 if (!doglob)
625 return (xstrdup(pattern));
626
627 flags = GLOB_BRACE|GLOB_NOCHECK|GLOB_TILDE;
628 memset(&gl, 0, sizeof(gl));
629 if (glob(pattern, flags, NULL, &gl) || gl.gl_pathc == 0) {
630 warnx("%s: not found", pattern);
631 globfree(&gl);
632 return (NULL);
633 }
634 p = xstrdup(gl.gl_pathv[0]);
635 globfree(&gl);
636 return (p);
637 }
638
639 /*
640 * determine size of remote file
641 */
642 off_t
643 remotesize(const char *file, int noisy)
644 {
645 int overbose, r;
646 off_t size;
647
648 overbose = verbose;
649 size = -1;
650 if (debug == 0)
651 verbose = -1;
652 if (! features[FEAT_SIZE]) {
653 if (noisy)
654 fprintf(ttyout,
655 "SIZE is not supported by remote server.\n");
656 goto cleanup_remotesize;
657 }
658 r = command("SIZE %s", file);
659 if (r == COMPLETE) {
660 char *cp, *ep;
661
662 cp = strchr(reply_string, ' ');
663 if (cp != NULL) {
664 cp++;
665 size = STRTOLL(cp, &ep, 10);
666 if (*ep != '\0' && !isspace((unsigned char)*ep))
667 size = -1;
668 }
669 } else {
670 if (r == ERROR && code == 500 && features[FEAT_SIZE] == -1)
671 features[FEAT_SIZE] = 0;
672 if (noisy && debug == 0) {
673 fputs(reply_string, ttyout);
674 putc('\n', ttyout);
675 }
676 }
677 cleanup_remotesize:
678 verbose = overbose;
679 return (size);
680 }
681
682 /*
683 * determine last modification time (in GMT) of remote file
684 */
685 time_t
686 remotemodtime(const char *file, int noisy)
687 {
688 int overbose, ocode, r;
689 time_t rtime;
690
691 overbose = verbose;
692 ocode = code;
693 rtime = -1;
694 if (debug == 0)
695 verbose = -1;
696 if (! features[FEAT_MDTM]) {
697 if (noisy)
698 fprintf(ttyout,
699 "MDTM is not supported by remote server.\n");
700 goto cleanup_parse_time;
701 }
702 r = command("MDTM %s", file);
703 if (r == COMPLETE) {
704 struct tm timebuf;
705 char *timestr, *frac;
706 int yy, mo, day, hour, min, sec;
707
708 /*
709 * time-val = 14DIGIT [ "." 1*DIGIT ]
710 * YYYYMMDDHHMMSS[.sss]
711 * mdtm-response = "213" SP time-val CRLF / error-response
712 */
713 timestr = reply_string + 4;
714
715 /*
716 * parse fraction.
717 * XXX: ignored for now
718 */
719 frac = strchr(timestr, '\r');
720 if (frac != NULL)
721 *frac = '\0';
722 frac = strchr(timestr, '.');
723 if (frac != NULL)
724 *frac++ = '\0';
725 if (strlen(timestr) == 15 && strncmp(timestr, "191", 3) == 0) {
726 /*
727 * XXX: Workaround for lame ftpd's that return
728 * `19100' instead of `2000'
729 */
730 fprintf(ttyout,
731 "Y2K warning! Incorrect time-val `%s' received from server.\n",
732 timestr);
733 timestr++;
734 timestr[0] = '2';
735 timestr[1] = '0';
736 fprintf(ttyout, "Converted to `%s'\n", timestr);
737 }
738 if (strlen(timestr) != 14 ||
739 sscanf(timestr, "%04d%02d%02d%02d%02d%02d",
740 &yy, &mo, &day, &hour, &min, &sec) != 6) {
741 bad_parse_time:
742 fprintf(ttyout, "Can't parse time `%s'.\n", timestr);
743 goto cleanup_parse_time;
744 }
745 memset(&timebuf, 0, sizeof(timebuf));
746 timebuf.tm_sec = sec;
747 timebuf.tm_min = min;
748 timebuf.tm_hour = hour;
749 timebuf.tm_mday = day;
750 timebuf.tm_mon = mo - 1;
751 timebuf.tm_year = yy - TM_YEAR_BASE;
752 timebuf.tm_isdst = -1;
753 rtime = timegm(&timebuf);
754 if (rtime == -1) {
755 if (noisy || debug != 0)
756 goto bad_parse_time;
757 else
758 goto cleanup_parse_time;
759 } else if (debug)
760 fprintf(ttyout, "parsed date as: %s", ctime(&rtime));
761 } else {
762 if (r == ERROR && code == 500 && features[FEAT_MDTM] == -1)
763 features[FEAT_MDTM] = 0;
764 if (noisy && debug == 0) {
765 fputs(reply_string, ttyout);
766 putc('\n', ttyout);
767 }
768 }
769 cleanup_parse_time:
770 verbose = overbose;
771 if (rtime == -1)
772 code = ocode;
773 return (rtime);
774 }
775
776 /*
777 * Update global `localcwd', which contains the state of the local cwd
778 */
779 void
780 updatelocalcwd(void)
781 {
782
783 if (getcwd(localcwd, sizeof(localcwd)) == NULL)
784 localcwd[0] = '\0';
785 if (debug)
786 fprintf(ttyout, "got localcwd as `%s'\n", localcwd);
787 }
788
789 /*
790 * Update global `remotecwd', which contains the state of the remote cwd
791 */
792 void
793 updateremotecwd(void)
794 {
795 int overbose, ocode, i;
796 char *cp;
797
798 overbose = verbose;
799 ocode = code;
800 if (debug == 0)
801 verbose = -1;
802 if (command("PWD") != COMPLETE)
803 goto badremotecwd;
804 cp = strchr(reply_string, ' ');
805 if (cp == NULL || cp[0] == '\0' || cp[1] != '"')
806 goto badremotecwd;
807 cp += 2;
808 for (i = 0; *cp && i < sizeof(remotecwd) - 1; i++, cp++) {
809 if (cp[0] == '"') {
810 if (cp[1] == '"')
811 cp++;
812 else
813 break;
814 }
815 remotecwd[i] = *cp;
816 }
817 remotecwd[i] = '\0';
818 if (debug)
819 fprintf(ttyout, "got remotecwd as `%s'\n", remotecwd);
820 goto cleanupremotecwd;
821 badremotecwd:
822 remotecwd[0]='\0';
823 cleanupremotecwd:
824 verbose = overbose;
825 code = ocode;
826 }
827
828 /*
829 * Ensure file is in or under dir.
830 * Returns 1 if so, 0 if not (or an error occurred).
831 */
832 int
833 fileindir(const char *file, const char *dir)
834 {
835 char realfile[PATH_MAX+1];
836 size_t dirlen;
837
838 if (realpath(file, realfile) == NULL) {
839 warn("Unable to determine real path of `%s'", file);
840 return 0;
841 }
842 if (realfile[0] != '/') /* relative result */
843 return 1;
844 dirlen = strlen(dir);
845 #if 0
846 printf("file %s realfile %s dir %s [%d]\n", file, realfile, dir, dirlen);
847 #endif
848 if (strncmp(realfile, dir, dirlen) == 0 && realfile[dirlen] == '/')
849 return 1;
850 return 0;
851 }
852
853 /*
854 * List words in stringlist, vertically arranged
855 */
856 void
857 list_vertical(StringList *sl)
858 {
859 int i, j, w;
860 int columns, width, lines;
861 char *p;
862
863 width = 0;
864
865 for (i = 0 ; i < sl->sl_cur ; i++) {
866 w = strlen(sl->sl_str[i]);
867 if (w > width)
868 width = w;
869 }
870 width = (width + 8) &~ 7;
871
872 columns = ttywidth / width;
873 if (columns == 0)
874 columns = 1;
875 lines = (sl->sl_cur + columns - 1) / columns;
876 for (i = 0; i < lines; i++) {
877 for (j = 0; j < columns; j++) {
878 p = sl->sl_str[j * lines + i];
879 if (p)
880 fputs(p, ttyout);
881 if (j * lines + i + lines >= sl->sl_cur) {
882 putc('\n', ttyout);
883 break;
884 }
885 w = strlen(p);
886 while (w < width) {
887 w = (w + 8) &~ 7;
888 (void)putc('\t', ttyout);
889 }
890 }
891 }
892 }
893
894 /*
895 * Update the global ttywidth value, using TIOCGWINSZ.
896 */
897 void
898 setttywidth(int a)
899 {
900 struct winsize winsize;
901 int oerrno = errno;
902
903 if (ioctl(fileno(ttyout), TIOCGWINSZ, &winsize) != -1 &&
904 winsize.ws_col != 0)
905 ttywidth = winsize.ws_col;
906 else
907 ttywidth = 80;
908 errno = oerrno;
909 }
910
911 /*
912 * Change the rate limit up (SIGUSR1) or down (SIGUSR2)
913 */
914 void
915 crankrate(int sig)
916 {
917
918 switch (sig) {
919 case SIGUSR1:
920 if (rate_get)
921 rate_get += rate_get_incr;
922 if (rate_put)
923 rate_put += rate_put_incr;
924 break;
925 case SIGUSR2:
926 if (rate_get && rate_get > rate_get_incr)
927 rate_get -= rate_get_incr;
928 if (rate_put && rate_put > rate_put_incr)
929 rate_put -= rate_put_incr;
930 break;
931 default:
932 err(1, "crankrate invoked with unknown signal: %d", sig);
933 }
934 }
935
936
937 /*
938 * Setup or cleanup EditLine structures
939 */
940 #ifndef NO_EDITCOMPLETE
941 void
942 controlediting(void)
943 {
944 if (editing && el == NULL && hist == NULL) {
945 HistEvent ev;
946 int editmode;
947
948 el = el_init(getprogname(), stdin, ttyout, stderr);
949 /* init editline */
950 hist = history_init(); /* init the builtin history */
951 history(hist, &ev, H_SETSIZE, 100);/* remember 100 events */
952 el_set(el, EL_HIST, history, hist); /* use history */
953
954 el_set(el, EL_EDITOR, "emacs"); /* default editor is emacs */
955 el_set(el, EL_PROMPT, prompt); /* set the prompt functions */
956 el_set(el, EL_RPROMPT, rprompt);
957
958 /* add local file completion, bind to TAB */
959 el_set(el, EL_ADDFN, "ftp-complete",
960 "Context sensitive argument completion",
961 complete);
962 el_set(el, EL_BIND, "^I", "ftp-complete", NULL);
963 el_source(el, NULL); /* read ~/.editrc */
964 if ((el_get(el, EL_EDITMODE, &editmode) != -1) && editmode == 0)
965 editing = 0; /* the user doesn't want editing,
966 * so disable, and let statement
967 * below cleanup */
968 else
969 el_set(el, EL_SIGNAL, 1);
970 }
971 if (!editing) {
972 if (hist) {
973 history_end(hist);
974 hist = NULL;
975 }
976 if (el) {
977 el_end(el);
978 el = NULL;
979 }
980 }
981 }
982 #endif /* !NO_EDITCOMPLETE */
983
984 /*
985 * Convert the string `arg' to an int, which may have an optional SI suffix
986 * (`b', `k', `m', `g'). Returns the number for success, -1 otherwise.
987 */
988 int
989 strsuftoi(const char *arg)
990 {
991 char *cp;
992 long val;
993
994 if (!isdigit((unsigned char)arg[0]))
995 return (-1);
996
997 val = strtol(arg, &cp, 10);
998 if (cp != NULL) {
999 if (cp[0] != '\0' && cp[1] != '\0')
1000 return (-1);
1001 switch (tolower((unsigned char)cp[0])) {
1002 case '\0':
1003 case 'b':
1004 break;
1005 case 'k':
1006 val <<= 10;
1007 break;
1008 case 'm':
1009 val <<= 20;
1010 break;
1011 case 'g':
1012 val <<= 30;
1013 break;
1014 default:
1015 return (-1);
1016 }
1017 }
1018 if (val < 0 || val > INT_MAX)
1019 return (-1);
1020
1021 return (val);
1022 }
1023
1024 /*
1025 * Set up socket buffer sizes before a connection is made.
1026 */
1027 void
1028 setupsockbufsize(int sock)
1029 {
1030
1031 if (setsockopt(sock, SOL_SOCKET, SO_SNDBUF, (void *) &sndbuf_size,
1032 sizeof(rcvbuf_size)) < 0)
1033 warn("unable to set sndbuf size %d", sndbuf_size);
1034
1035 if (setsockopt(sock, SOL_SOCKET, SO_RCVBUF, (void *) &rcvbuf_size,
1036 sizeof(rcvbuf_size)) < 0)
1037 warn("unable to set rcvbuf size %d", rcvbuf_size);
1038 }
1039
1040 /*
1041 * Copy characters from src into dst, \ quoting characters that require it
1042 */
1043 void
1044 ftpvis(char *dst, size_t dstlen, const char *src, size_t srclen)
1045 {
1046 int di, si;
1047
1048 for (di = si = 0;
1049 src[si] != '\0' && di < dstlen && si < srclen;
1050 di++, si++) {
1051 switch (src[si]) {
1052 case '\\':
1053 case ' ':
1054 case '\t':
1055 case '\r':
1056 case '\n':
1057 case '"':
1058 dst[di++] = '\\';
1059 if (di >= dstlen)
1060 break;
1061 /* FALLTHROUGH */
1062 default:
1063 dst[di] = src[si];
1064 }
1065 }
1066 dst[di] = '\0';
1067 }
1068
1069 /*
1070 * Copy src into buf (which is len bytes long), expanding % sequences.
1071 */
1072 void
1073 formatbuf(char *buf, size_t len, const char *src)
1074 {
1075 const char *p;
1076 char *p2, *q;
1077 int i, op, updirs, pdirs;
1078
1079 #define ADDBUF(x) do { \
1080 if (i >= len - 1) \
1081 goto endbuf; \
1082 buf[i++] = (x); \
1083 } while (0)
1084
1085 p = src;
1086 for (i = 0; *p; p++) {
1087 if (*p != '%') {
1088 ADDBUF(*p);
1089 continue;
1090 }
1091 p++;
1092
1093 switch (op = *p) {
1094
1095 case '/':
1096 case '.':
1097 case 'c':
1098 p2 = connected ? remotecwd : "";
1099 updirs = pdirs = 0;
1100
1101 /* option to determine fixed # of dirs from path */
1102 if (op == '.' || op == 'c') {
1103 int skip;
1104
1105 q = p2;
1106 while (*p2) /* calc # of /'s */
1107 if (*p2++ == '/')
1108 updirs++;
1109 if (p[1] == '0') { /* print <x> or ... */
1110 pdirs = 1;
1111 p++;
1112 }
1113 if (p[1] >= '1' && p[1] <= '9') {
1114 /* calc # to skip */
1115 skip = p[1] - '0';
1116 p++;
1117 } else
1118 skip = 1;
1119
1120 updirs -= skip;
1121 while (skip-- > 0) {
1122 while ((p2 > q) && (*p2 != '/'))
1123 p2--; /* back up */
1124 if (skip && p2 > q)
1125 p2--;
1126 }
1127 if (*p2 == '/' && p2 != q)
1128 p2++;
1129 }
1130
1131 if (updirs > 0 && pdirs) {
1132 if (i >= len - 5)
1133 break;
1134 if (op == '.') {
1135 ADDBUF('.');
1136 ADDBUF('.');
1137 ADDBUF('.');
1138 } else {
1139 ADDBUF('/');
1140 ADDBUF('<');
1141 if (updirs > 9) {
1142 ADDBUF('9');
1143 ADDBUF('+');
1144 } else
1145 ADDBUF('0' + updirs);
1146 ADDBUF('>');
1147 }
1148 }
1149 for (; *p2; p2++)
1150 ADDBUF(*p2);
1151 break;
1152
1153 case 'M':
1154 case 'm':
1155 for (p2 = connected && username ? username : "-";
1156 *p2 ; p2++) {
1157 if (op == 'm' && *p2 == '.')
1158 break;
1159 ADDBUF(*p2);
1160 }
1161 break;
1162
1163 case 'n':
1164 for (p2 = connected ? username : "-"; *p2 ; p2++)
1165 ADDBUF(*p2);
1166 break;
1167
1168 case '%':
1169 ADDBUF('%');
1170 break;
1171
1172 default: /* display unknown codes literally */
1173 ADDBUF('%');
1174 ADDBUF(op);
1175 break;
1176
1177 }
1178 }
1179 endbuf:
1180 buf[i] = '\0';
1181 }
1182
1183 /*
1184 * Parse `port' into a TCP port number, defaulting to `defport' if `port' is
1185 * an unknown service name. If defport != -1, print a warning upon bad parse.
1186 */
1187 int
1188 parseport(const char *port, int defport)
1189 {
1190 int rv;
1191 long nport;
1192 char *p, *ep;
1193
1194 p = xstrdup(port);
1195 nport = strtol(p, &ep, 10);
1196 if (*ep != '\0' && ep == p) {
1197 struct servent *svp;
1198
1199 svp = getservbyname(port, "tcp");
1200 if (svp == NULL) {
1201 badparseport:
1202 if (defport != -1)
1203 warnx("Unknown port `%s', using port %d",
1204 port, defport);
1205 rv = defport;
1206 } else
1207 rv = ntohs(svp->s_port);
1208 } else if (nport < 1 || nport > MAX_IN_PORT_T || *ep != '\0')
1209 goto badparseport;
1210 else
1211 rv = nport;
1212 free(p);
1213 return (rv);
1214 }
1215
1216 /*
1217 * Determine if given string is an IPv6 address or not.
1218 * Return 1 for yes, 0 for no
1219 */
1220 int
1221 isipv6addr(const char *addr)
1222 {
1223 int rv = 0;
1224 #ifdef INET6
1225 struct addrinfo hints, *res;
1226
1227 memset(&hints, 0, sizeof(hints));
1228 hints.ai_family = PF_INET6;
1229 hints.ai_socktype = SOCK_DGRAM; /*dummy*/
1230 hints.ai_flags = AI_NUMERICHOST;
1231 if (getaddrinfo(addr, "0", &hints, &res) != 0)
1232 rv = 0;
1233 else {
1234 rv = 1;
1235 freeaddrinfo(res);
1236 }
1237 if (debug)
1238 fprintf(ttyout, "isipv6addr: got %d for %s\n", rv, addr);
1239 #endif
1240 return (rv == 1) ? 1 : 0;
1241 }
1242
1243
1244 /*
1245 * Internal version of connect(2); sets socket buffer sizes first and
1246 * supports a connection timeout using a non-blocking connect(2) with
1247 * a poll(2).
1248 * Socket fcntl flags are temporarily updated to include O_NONBLOCK;
1249 * these will not be reverted on connection failure.
1250 * Returns -1 upon failure (with errno set to the problem), or 0 on success.
1251 */
1252 int
1253 xconnect(int sock, const struct sockaddr *name, int namelen)
1254 {
1255 int flags, rv, timeout, error;
1256 struct timeval endtime, now, td;
1257 struct pollfd pfd[1];
1258
1259 setupsockbufsize(sock);
1260
1261 if ((flags = fcntl(sock, F_GETFL, 0)) == -1)
1262 return -1; /* get current socket flags */
1263 if (fcntl(sock, F_SETFL, flags | O_NONBLOCK) == -1)
1264 return -1; /* set non-blocking connect */
1265
1266 /* NOTE: we now must restore socket flags on successful exit */
1267
1268 pfd[0].fd = sock;
1269 pfd[0].events = POLLIN|POLLOUT;
1270
1271 if (quit_time > 0) { /* want a non default timeout */
1272 (void)gettimeofday(&endtime, NULL);
1273 endtime.tv_sec += quit_time; /* determine end time */
1274 }
1275
1276 rv = connect(sock, name, namelen); /* inititate the connection */
1277 if (rv == -1) { /* connection error */
1278 if (errno != EINPROGRESS) /* error isn't "please wait" */
1279 return -1;
1280
1281 /* connect EINPROGRESS; wait */
1282 do {
1283 if (quit_time > 0) { /* determine timeout */
1284 (void)gettimeofday(&now, NULL);
1285 timersub(&endtime, &now, &td);
1286 timeout = td.tv_sec * 1000 + td.tv_usec/1000;
1287 if (timeout < 0)
1288 timeout = 0;
1289 } else {
1290 timeout = INFTIM;
1291 }
1292 pfd[0].revents = 0;
1293 rv = xpoll(pfd, 1, timeout);
1294 /* loop until poll ! EINTR */
1295 } while (rv == -1 && errno == EINTR);
1296
1297 if (rv == 0) { /* poll (connect) timed out */
1298 errno = ETIMEDOUT;
1299 return -1;
1300 }
1301
1302 if (rv == -1) { /* poll error */
1303 return -1;
1304 } else if (pfd[0].revents & (POLLIN|POLLOUT)) {
1305 rv = sizeof(error); /* ok, or pending error */
1306 if (getsockopt(sock, SOL_SOCKET, SO_ERROR,
1307 &error, &rv) == -1)
1308 return -1; /* Solaris pending error */
1309 if (error != 0) {
1310 errno = error; /* BSD pending error */
1311 return -1;
1312 }
1313 } else {
1314 errno = EBADF; /* this shouldn't happen ... */
1315 return -1;
1316 }
1317 }
1318
1319 if (fcntl(sock, F_SETFL, flags) == -1) /* restore socket flags */
1320 return -1;
1321 return 0;
1322 }
1323
1324 /*
1325 * Internal version of listen(2); sets socket buffer sizes first.
1326 */
1327 int
1328 xlisten(int sock, int backlog)
1329 {
1330
1331 setupsockbufsize(sock);
1332 return (listen(sock, backlog));
1333 }
1334
1335 /*
1336 * Internal version of poll(2), to allow reimplementation by select(2)
1337 * on platforms without the former.
1338 */
1339 int
1340 xpoll(struct pollfd *fds, int nfds, int timeout)
1341 {
1342 return poll(fds, nfds, timeout);
1343 }
1344
1345 /*
1346 * malloc() with inbuilt error checking
1347 */
1348 void *
1349 xmalloc(size_t size)
1350 {
1351 void *p;
1352
1353 p = malloc(size);
1354 if (p == NULL)
1355 err(1, "Unable to allocate %ld bytes of memory", (long)size);
1356 return (p);
1357 }
1358
1359 /*
1360 * sl_init() with inbuilt error checking
1361 */
1362 StringList *
1363 xsl_init(void)
1364 {
1365 StringList *p;
1366
1367 p = sl_init();
1368 if (p == NULL)
1369 err(1, "Unable to allocate memory for stringlist");
1370 return (p);
1371 }
1372
1373 /*
1374 * sl_add() with inbuilt error checking
1375 */
1376 void
1377 xsl_add(StringList *sl, char *i)
1378 {
1379
1380 if (sl_add(sl, i) == -1)
1381 err(1, "Unable to add `%s' to stringlist", i);
1382 }
1383
1384 /*
1385 * strdup() with inbuilt error checking
1386 */
1387 char *
1388 xstrdup(const char *str)
1389 {
1390 char *s;
1391
1392 if (str == NULL)
1393 errx(1, "xstrdup() called with NULL argument");
1394 s = strdup(str);
1395 if (s == NULL)
1396 err(1, "Unable to allocate memory for string copy");
1397 return (s);
1398 }
1399