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