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