Merge branch 'vendor/EE'
[dragonfly.git] / contrib / tnftp / fetch.c
1 /*      $NetBSD: fetch.c,v 1.202 2013/02/23 13:47:36 christos Exp $     */
2
3 /*-
4  * Copyright (c) 1997-2009 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 Scott Aaron Bamford.
12  *
13  * Redistribution and use in source and binary forms, with or without
14  * modification, are permitted provided that the following conditions
15  * are met:
16  * 1. Redistributions of source code must retain the above copyright
17  *    notice, this list of conditions and the following disclaimer.
18  * 2. Redistributions in binary form must reproduce the above copyright
19  *    notice, this list of conditions and the following disclaimer in the
20  *    documentation and/or other materials provided with the distribution.
21  *
22  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
23  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
24  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
25  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
26  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
27  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
28  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
29  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
30  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
31  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
32  * POSSIBILITY OF SUCH DAMAGE.
33  */
34
35 #include <sys/cdefs.h>
36 #ifndef lint
37 __RCSID("$NetBSD: fetch.c,v 1.202 2013/02/23 13:47:36 christos Exp $");
38 #endif /* not lint */
39
40 /*
41  * FTP User Program -- Command line file retrieval
42  */
43
44 #include <sys/types.h>
45 #include <sys/param.h>
46 #include <sys/socket.h>
47 #include <sys/stat.h>
48 #include <sys/time.h>
49
50 #include <netinet/in.h>
51
52 #include <arpa/ftp.h>
53 #include <arpa/inet.h>
54
55 #include <assert.h>
56 #include <ctype.h>
57 #include <err.h>
58 #include <errno.h>
59 #include <netdb.h>
60 #include <fcntl.h>
61 #include <stdio.h>
62 #include <libutil.h>
63 #include <stdlib.h>
64 #include <string.h>
65 #include <unistd.h>
66 #include <time.h>
67
68 #include "ssl.h"
69 #include "ftp_var.h"
70 #include "version.h"
71
72 typedef enum {
73         UNKNOWN_URL_T=-1,
74         HTTP_URL_T,
75 #ifdef WITH_SSL
76         HTTPS_URL_T,
77 #endif
78         FTP_URL_T,
79         FILE_URL_T,
80         CLASSIC_URL_T
81 } url_t;
82
83 __dead static void      aborthttp(int);
84 #ifndef NO_AUTH
85 static int      auth_url(const char *, char **, const char *, const char *);
86 static void     base64_encode(const unsigned char *, size_t, unsigned char *);
87 #endif
88 static int      go_fetch(const char *);
89 static int      fetch_ftp(const char *);
90 static int      fetch_url(const char *, const char *, char *, char *);
91 static const char *match_token(const char **, const char *);
92 static int      parse_url(const char *, const char *, url_t *, char **,
93                             char **, char **, char **, in_port_t *, char **);
94 static void     url_decode(char *);
95
96 static int      redirect_loop;
97
98
99 #define STRNEQUAL(a,b)  (strncasecmp((a), (b), sizeof((b))-1) == 0)
100 #define ISLWS(x)        ((x)=='\r' || (x)=='\n' || (x)==' ' || (x)=='\t')
101 #define SKIPLWS(x)      do { while (ISLWS((*x))) x++; } while (0)
102
103
104 #define ABOUT_URL       "about:"        /* propaganda */
105 #define FILE_URL        "file://"       /* file URL prefix */
106 #define FTP_URL         "ftp://"        /* ftp URL prefix */
107 #define HTTP_URL        "http://"       /* http URL prefix */
108 #ifdef WITH_SSL
109 #define HTTPS_URL       "https://"      /* https URL prefix */
110
111 #define IS_HTTP_TYPE(urltype) \
112         (((urltype) == HTTP_URL_T) || ((urltype) == HTTPS_URL_T))
113 #else
114 #define IS_HTTP_TYPE(urltype) \
115         ((urltype) == HTTP_URL_T)
116 #endif
117
118 /*
119  * Determine if token is the next word in buf (case insensitive).
120  * If so, advance buf past the token and any trailing LWS, and
121  * return a pointer to the token (in buf).  Otherwise, return NULL.
122  * token may be preceded by LWS.
123  * token must be followed by LWS or NUL.  (I.e, don't partial match).
124  */
125 static const char *
126 match_token(const char **buf, const char *token)
127 {
128         const char      *p, *orig;
129         size_t          tlen;
130
131         tlen = strlen(token);
132         p = *buf;
133         SKIPLWS(p);
134         orig = p;
135         if (strncasecmp(p, token, tlen) != 0)
136                 return NULL;
137         p += tlen;
138         if (*p != '\0' && !ISLWS(*p))
139                 return NULL;
140         SKIPLWS(p);
141         orig = *buf;
142         *buf = p;
143         return orig;
144 }
145
146 #ifndef NO_AUTH
147 /*
148  * Generate authorization response based on given authentication challenge.
149  * Returns -1 if an error occurred, otherwise 0.
150  * Sets response to a malloc(3)ed string; caller should free.
151  */
152 static int
153 auth_url(const char *challenge, char **response, const char *guser,
154         const char *gpass)
155 {
156         const char      *cp, *scheme, *errormsg;
157         char            *ep, *clear, *realm;
158         char             uuser[BUFSIZ], *gotpass;
159         const char      *upass;
160         int              rval;
161         size_t           len, clen, rlen;
162
163         *response = NULL;
164         clear = realm = NULL;
165         rval = -1;
166         cp = challenge;
167         scheme = "Basic";       /* only support Basic authentication */
168         gotpass = NULL;
169
170         DPRINTF("auth_url: challenge `%s'\n", challenge);
171
172         if (! match_token(&cp, scheme)) {
173                 warnx("Unsupported authentication challenge `%s'",
174                     challenge);
175                 goto cleanup_auth_url;
176         }
177
178 #define REALM "realm=\""
179         if (STRNEQUAL(cp, REALM))
180                 cp += sizeof(REALM) - 1;
181         else {
182                 warnx("Unsupported authentication challenge `%s'",
183                     challenge);
184                 goto cleanup_auth_url;
185         }
186 /* XXX: need to improve quoted-string parsing to support \ quoting, etc. */
187         if ((ep = strchr(cp, '\"')) != NULL) {
188                 len = ep - cp;
189                 realm = (char *)ftp_malloc(len + 1);
190                 (void)strlcpy(realm, cp, len + 1);
191         } else {
192                 warnx("Unsupported authentication challenge `%s'",
193                     challenge);
194                 goto cleanup_auth_url;
195         }
196
197         fprintf(ttyout, "Username for `%s': ", realm);
198         if (guser != NULL) {
199                 (void)strlcpy(uuser, guser, sizeof(uuser));
200                 fprintf(ttyout, "%s\n", uuser);
201         } else {
202                 (void)fflush(ttyout);
203                 if (get_line(stdin, uuser, sizeof(uuser), &errormsg) < 0) {
204                         warnx("%s; can't authenticate", errormsg);
205                         goto cleanup_auth_url;
206                 }
207         }
208         if (gpass != NULL)
209                 upass = gpass;
210         else {
211                 gotpass = getpass("Password: ");
212                 if (gotpass == NULL) {
213                         warnx("Can't read password");
214                         goto cleanup_auth_url;
215                 }
216                 upass = gotpass;
217         }
218
219         clen = strlen(uuser) + strlen(upass) + 2;       /* user + ":" + pass + "\0" */
220         clear = (char *)ftp_malloc(clen);
221         (void)strlcpy(clear, uuser, clen);
222         (void)strlcat(clear, ":", clen);
223         (void)strlcat(clear, upass, clen);
224         if (gotpass)
225                 memset(gotpass, 0, strlen(gotpass));
226
227                                                 /* scheme + " " + enc + "\0" */
228         rlen = strlen(scheme) + 1 + (clen + 2) * 4 / 3 + 1;
229         *response = (char *)ftp_malloc(rlen);
230         (void)strlcpy(*response, scheme, rlen);
231         len = strlcat(*response, " ", rlen);
232                         /* use  `clen - 1'  to not encode the trailing NUL */
233         base64_encode((unsigned char *)clear, clen - 1,
234             (unsigned char *)*response + len);
235         memset(clear, 0, clen);
236         rval = 0;
237
238  cleanup_auth_url:
239         FREEPTR(clear);
240         FREEPTR(realm);
241         return (rval);
242 }
243
244 /*
245  * Encode len bytes starting at clear using base64 encoding into encoded,
246  * which should be at least ((len + 2) * 4 / 3 + 1) in size.
247  */
248 static void
249 base64_encode(const unsigned char *clear, size_t len, unsigned char *encoded)
250 {
251         static const unsigned char enc[] =
252             "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
253         unsigned char   *cp;
254         size_t   i;
255
256         cp = encoded;
257         for (i = 0; i < len; i += 3) {
258                 *(cp++) = enc[((clear[i + 0] >> 2))];
259                 *(cp++) = enc[((clear[i + 0] << 4) & 0x30)
260                             | ((clear[i + 1] >> 4) & 0x0f)];
261                 *(cp++) = enc[((clear[i + 1] << 2) & 0x3c)
262                             | ((clear[i + 2] >> 6) & 0x03)];
263                 *(cp++) = enc[((clear[i + 2]     ) & 0x3f)];
264         }
265         *cp = '\0';
266         while (i-- > len)
267                 *(--cp) = '=';
268 }
269 #endif
270
271 /*
272  * Decode %xx escapes in given string, `in-place'.
273  */
274 static void
275 url_decode(char *url)
276 {
277         unsigned char *p, *q;
278
279         if (EMPTYSTRING(url))
280                 return;
281         p = q = (unsigned char *)url;
282
283 #define HEXTOINT(x) (x - (isdigit(x) ? '0' : (islower(x) ? 'a' : 'A') - 10))
284         while (*p) {
285                 if (p[0] == '%'
286                     && p[1] && isxdigit((unsigned char)p[1])
287                     && p[2] && isxdigit((unsigned char)p[2])) {
288                         *q++ = HEXTOINT(p[1]) * 16 + HEXTOINT(p[2]);
289                         p+=3;
290                 } else
291                         *q++ = *p++;
292         }
293         *q = '\0';
294 }
295
296
297 /*
298  * Parse URL of form (per RFC 3986):
299  *      <type>://[<user>[:<password>]@]<host>[:<port>][/<path>]
300  * Returns -1 if a parse error occurred, otherwise 0.
301  * It's the caller's responsibility to url_decode() the returned
302  * user, pass and path.
303  *
304  * Sets type to url_t, each of the given char ** pointers to a
305  * malloc(3)ed strings of the relevant section, and port to
306  * the number given, or ftpport if ftp://, or httpport if http://.
307  *
308  * XXX: this is not totally RFC 3986 compliant; <path> will have the
309  * leading `/' unless it's an ftp:// URL, as this makes things easier
310  * for file:// and http:// URLs.  ftp:// URLs have the `/' between the
311  * host and the URL-path removed, but any additional leading slashes
312  * in the URL-path are retained (because they imply that we should
313  * later do "CWD" with a null argument).
314  *
315  * Examples:
316  *       input URL                       output path
317  *       ---------                       -----------
318  *      "http://host"                   "/"
319  *      "http://host/"                  "/"
320  *      "http://host/path"              "/path"
321  *      "file://host/dir/file"          "dir/file"
322  *      "ftp://host"                    ""
323  *      "ftp://host/"                   ""
324  *      "ftp://host//"                  "/"
325  *      "ftp://host/dir/file"           "dir/file"
326  *      "ftp://host//dir/file"          "/dir/file"
327  */
328 static int
329 parse_url(const char *url, const char *desc, url_t *utype,
330                 char **uuser, char **pass, char **host, char **port,
331                 in_port_t *portnum, char **path)
332 {
333         const char      *origurl, *tport;
334         char            *cp, *ep, *thost;
335         size_t           len;
336
337         if (url == NULL || desc == NULL || utype == NULL || uuser == NULL
338             || pass == NULL || host == NULL || port == NULL || portnum == NULL
339             || path == NULL)
340                 errx(1, "parse_url: invoked with NULL argument!");
341         DPRINTF("parse_url: %s `%s'\n", desc, url);
342
343         origurl = url;
344         *utype = UNKNOWN_URL_T;
345         *uuser = *pass = *host = *port = *path = NULL;
346         *portnum = 0;
347         tport = NULL;
348
349         if (STRNEQUAL(url, HTTP_URL)) {
350                 url += sizeof(HTTP_URL) - 1;
351                 *utype = HTTP_URL_T;
352                 *portnum = HTTP_PORT;
353                 tport = httpport;
354         } else if (STRNEQUAL(url, FTP_URL)) {
355                 url += sizeof(FTP_URL) - 1;
356                 *utype = FTP_URL_T;
357                 *portnum = FTP_PORT;
358                 tport = ftpport;
359         } else if (STRNEQUAL(url, FILE_URL)) {
360                 url += sizeof(FILE_URL) - 1;
361                 *utype = FILE_URL_T;
362 #ifdef WITH_SSL
363         } else if (STRNEQUAL(url, HTTPS_URL)) {
364                 url += sizeof(HTTPS_URL) - 1;
365                 *utype = HTTPS_URL_T;
366                 *portnum = HTTPS_PORT;
367                 tport = httpsport;
368 #endif
369         } else {
370                 warnx("Invalid %s `%s'", desc, url);
371  cleanup_parse_url:
372                 FREEPTR(*uuser);
373                 if (*pass != NULL)
374                         memset(*pass, 0, strlen(*pass));
375                 FREEPTR(*pass);
376                 FREEPTR(*host);
377                 FREEPTR(*port);
378                 FREEPTR(*path);
379                 return (-1);
380         }
381
382         if (*url == '\0')
383                 return (0);
384
385                         /* find [user[:pass]@]host[:port] */
386         ep = strchr(url, '/');
387         if (ep == NULL)
388                 thost = ftp_strdup(url);
389         else {
390                 len = ep - url;
391                 thost = (char *)ftp_malloc(len + 1);
392                 (void)strlcpy(thost, url, len + 1);
393                 if (*utype == FTP_URL_T)        /* skip first / for ftp URLs */
394                         ep++;
395                 *path = ftp_strdup(ep);
396         }
397
398         cp = strchr(thost, '@');        /* look for user[:pass]@ in URLs */
399         if (cp != NULL) {
400                 if (*utype == FTP_URL_T)
401                         anonftp = 0;    /* disable anonftp */
402                 *uuser = thost;
403                 *cp = '\0';
404                 thost = ftp_strdup(cp + 1);
405                 cp = strchr(*uuser, ':');
406                 if (cp != NULL) {
407                         *cp = '\0';
408                         *pass = ftp_strdup(cp + 1);
409                 }
410                 url_decode(*uuser);
411                 if (*pass)
412                         url_decode(*pass);
413         }
414
415 #ifdef INET6
416                         /*
417                          * Check if thost is an encoded IPv6 address, as per
418                          * RFC 3986:
419                          *      `[' ipv6-address ']'
420                          */
421         if (*thost == '[') {
422                 cp = thost + 1;
423                 if ((ep = strchr(cp, ']')) == NULL ||
424                     (ep[1] != '\0' && ep[1] != ':')) {
425                         warnx("Invalid address `%s' in %s `%s'",
426                             thost, desc, origurl);
427                         goto cleanup_parse_url;
428                 }
429                 len = ep - cp;          /* change `[xyz]' -> `xyz' */
430                 memmove(thost, thost + 1, len);
431                 thost[len] = '\0';
432                 if (! isipv6addr(thost)) {
433                         warnx("Invalid IPv6 address `%s' in %s `%s'",
434                             thost, desc, origurl);
435                         goto cleanup_parse_url;
436                 }
437                 cp = ep + 1;
438                 if (*cp == ':')
439                         cp++;
440                 else
441                         cp = NULL;
442         } else
443 #endif /* INET6 */
444                 if ((cp = strchr(thost, ':')) != NULL)
445                         *cp++ = '\0';
446         *host = thost;
447
448                         /* look for [:port] */
449         if (cp != NULL) {
450                 unsigned long   nport;
451
452                 nport = strtoul(cp, &ep, 10);
453                 if (*cp == '\0' || *ep != '\0' ||
454                     nport < 1 || nport > MAX_IN_PORT_T) {
455                         warnx("Unknown port `%s' in %s `%s'",
456                             cp, desc, origurl);
457                         goto cleanup_parse_url;
458                 }
459                 *portnum = nport;
460                 tport = cp;
461         }
462
463         if (tport != NULL)
464                 *port = ftp_strdup(tport);
465         if (*path == NULL) {
466                 const char *emptypath = "/";
467                 if (*utype == FTP_URL_T)        /* skip first / for ftp URLs */
468                         emptypath++;
469                 *path = ftp_strdup(emptypath);
470         }
471
472         DPRINTF("parse_url: user `%s' pass `%s' host %s port %s(%d) "
473             "path `%s'\n",
474             STRorNULL(*uuser), STRorNULL(*pass),
475             STRorNULL(*host), STRorNULL(*port),
476             *portnum ? *portnum : -1, STRorNULL(*path));
477
478         return (0);
479 }
480
481 sigjmp_buf      httpabort;
482
483 /*
484  * Retrieve URL, via a proxy if necessary, using HTTP.
485  * If proxyenv is set, use that for the proxy, otherwise try ftp_proxy or
486  * http_proxy/https_proxy as appropriate.
487  * Supports HTTP redirects.
488  * Returns 1 on failure, 0 on completed xfer, -1 if ftp connection
489  * is still open (e.g, ftp xfer with trailing /)
490  */
491 static int
492 fetch_url(const char *url, const char *proxyenv, char *proxyauth, char *wwwauth)
493 {
494         struct addrinfo         hints, *res, *res0 = NULL;
495         int                     error;
496         sigfunc volatile        oldintr;
497         sigfunc volatile        oldintp;
498         int volatile            s;
499         struct stat             sb;
500         int volatile            ischunked;
501         int volatile            isproxy;
502         int volatile            rval;
503         int volatile            hcode;
504         int                     len;
505         size_t                  flen;
506         static size_t           bufsize;
507         static char             *xferbuf;
508         const char              *cp, *token;
509         char                    *ep;
510         char                    buf[FTPBUFLEN];
511         const char              *errormsg;
512         char                    *volatile savefile;
513         char                    *volatile auth;
514         char                    *volatile location;
515         char                    *volatile message;
516         char                    *uuser, *pass, *host, *port, *path;
517         char                    *volatile decodedpath;
518         char                    *puser, *ppass, *useragent;
519         off_t                   hashbytes, rangestart, rangeend, entitylen;
520         int                     (*volatile closefunc)(FILE *);
521         FETCH                   *volatile fin;
522         FILE                    *volatile fout;
523         time_t                  mtime;
524         url_t                   urltype;
525         in_port_t               portnum;
526 #ifdef WITH_SSL
527         void                    *ssl;
528 #endif
529
530         DPRINTF("fetch_url: `%s' proxyenv `%s'\n", url, STRorNULL(proxyenv));
531
532         oldintr = oldintp = NULL;
533         closefunc = NULL;
534         fin = NULL;
535         fout = NULL;
536         s = -1;
537         savefile = NULL;
538         auth = location = message = NULL;
539         ischunked = isproxy = hcode = 0;
540         rval = 1;
541         uuser = pass = host = path = decodedpath = puser = ppass = NULL;
542
543         if (parse_url(url, "URL", &urltype, &uuser, &pass, &host, &port,
544             &portnum, &path) == -1)
545                 goto cleanup_fetch_url;
546
547         if (urltype == FILE_URL_T && ! EMPTYSTRING(host)
548             && strcasecmp(host, "localhost") != 0) {
549                 warnx("No support for non local file URL `%s'", url);
550                 goto cleanup_fetch_url;
551         }
552
553         if (EMPTYSTRING(path)) {
554                 if (urltype == FTP_URL_T) {
555                         rval = fetch_ftp(url);
556                         goto cleanup_fetch_url;
557                 }
558                 if (!IS_HTTP_TYPE(urltype) || outfile == NULL)  {
559                         warnx("Invalid URL (no file after host) `%s'", url);
560                         goto cleanup_fetch_url;
561                 }
562         }
563
564         decodedpath = ftp_strdup(path);
565         url_decode(decodedpath);
566
567         if (outfile)
568                 savefile = ftp_strdup(outfile);
569         else {
570                 cp = strrchr(decodedpath, '/');         /* find savefile */
571                 if (cp != NULL)
572                         savefile = ftp_strdup(cp + 1);
573                 else
574                         savefile = ftp_strdup(decodedpath);
575         }
576         DPRINTF("fetch_url: savefile `%s'\n", savefile);
577         if (EMPTYSTRING(savefile)) {
578                 if (urltype == FTP_URL_T) {
579                         rval = fetch_ftp(url);
580                         goto cleanup_fetch_url;
581                 }
582                 warnx("No file after directory (you must specify an "
583                     "output file) `%s'", url);
584                 goto cleanup_fetch_url;
585         }
586
587         restart_point = 0;
588         filesize = -1;
589         rangestart = rangeend = entitylen = -1;
590         mtime = -1;
591         if (restartautofetch) {
592                 if (strcmp(savefile, "-") != 0 && *savefile != '|' &&
593                     stat(savefile, &sb) == 0)
594                         restart_point = sb.st_size;
595         }
596         if (urltype == FILE_URL_T) {            /* file:// URLs */
597                 direction = "copied";
598                 fin = fetch_open(decodedpath, "r");
599                 if (fin == NULL) {
600                         warn("Can't open `%s'", decodedpath);
601                         goto cleanup_fetch_url;
602                 }
603                 if (fstat(fetch_fileno(fin), &sb) == 0) {
604                         mtime = sb.st_mtime;
605                         filesize = sb.st_size;
606                 }
607                 if (restart_point) {
608                         if (lseek(fetch_fileno(fin), restart_point, SEEK_SET) < 0) {
609                                 warn("Can't seek to restart `%s'",
610                                     decodedpath);
611                                 goto cleanup_fetch_url;
612                         }
613                 }
614                 if (verbose) {
615                         fprintf(ttyout, "Copying %s", decodedpath);
616                         if (restart_point)
617                                 fprintf(ttyout, " (restarting at " LLF ")",
618                                     (LLT)restart_point);
619                         fputs("\n", ttyout);
620                 }
621                 if (0 == rcvbuf_size) {
622                         rcvbuf_size = 8 * 1024; /* XXX */
623                 }
624         } else {                                /* ftp:// or http:// URLs */
625                 const char *leading;
626                 int hasleading;
627
628                 if (proxyenv == NULL) {
629 #ifdef WITH_SSL
630                         if (urltype == HTTPS_URL_T)
631                                 proxyenv = getoptionvalue("https_proxy");
632 #endif
633                         if (proxyenv == NULL && IS_HTTP_TYPE(urltype))
634                                 proxyenv = getoptionvalue("http_proxy");
635                         else if (urltype == FTP_URL_T)
636                                 proxyenv = getoptionvalue("ftp_proxy");
637                 }
638                 direction = "retrieved";
639                 if (! EMPTYSTRING(proxyenv)) {                  /* use proxy */
640                         url_t purltype;
641                         char *phost, *ppath;
642                         char *pport, *no_proxy;
643                         in_port_t pportnum;
644
645                         isproxy = 1;
646
647                                 /* check URL against list of no_proxied sites */
648                         no_proxy = getoptionvalue("no_proxy");
649                         if (! EMPTYSTRING(no_proxy)) {
650                                 char *np, *np_copy, *np_iter;
651                                 unsigned long np_port;
652                                 size_t hlen, plen;
653
654                                 np_iter = np_copy = ftp_strdup(no_proxy);
655                                 hlen = strlen(host);
656                                 while ((cp = strsep(&np_iter, " ,")) != NULL) {
657                                         if (*cp == '\0')
658                                                 continue;
659                                         if ((np = strrchr(cp, ':')) != NULL) {
660                                                 *np++ =  '\0';
661                                                 np_port = strtoul(np, &ep, 10);
662                                                 if (*np == '\0' || *ep != '\0')
663                                                         continue;
664                                                 if (np_port != portnum)
665                                                         continue;
666                                         }
667                                         plen = strlen(cp);
668                                         if (hlen < plen)
669                                                 continue;
670                                         if (strncasecmp(host + hlen - plen,
671                                             cp, plen) == 0) {
672                                                 isproxy = 0;
673                                                 break;
674                                         }
675                                 }
676                                 FREEPTR(np_copy);
677                                 if (isproxy == 0 && urltype == FTP_URL_T) {
678                                         rval = fetch_ftp(url);
679                                         goto cleanup_fetch_url;
680                                 }
681                         }
682
683                         if (isproxy) {
684                                 if (restart_point) {
685                                         warnx("Can't restart via proxy URL `%s'",
686                                             proxyenv);
687                                         goto cleanup_fetch_url;
688                                 }
689                                 if (parse_url(proxyenv, "proxy URL", &purltype,
690                                     &puser, &ppass, &phost, &pport, &pportnum,
691                                     &ppath) == -1)
692                                         goto cleanup_fetch_url;
693
694                                 if ((!IS_HTTP_TYPE(purltype)
695                                      && purltype != FTP_URL_T) ||
696                                     EMPTYSTRING(phost) ||
697                                     (! EMPTYSTRING(ppath)
698                                      && strcmp(ppath, "/") != 0)) {
699                                         warnx("Malformed proxy URL `%s'",
700                                             proxyenv);
701                                         FREEPTR(phost);
702                                         FREEPTR(pport);
703                                         FREEPTR(ppath);
704                                         goto cleanup_fetch_url;
705                                 }
706                                 if (isipv6addr(host) &&
707                                     strchr(host, '%') != NULL) {
708                                         warnx(
709 "Scoped address notation `%s' disallowed via web proxy",
710                                             host);
711                                         FREEPTR(phost);
712                                         FREEPTR(pport);
713                                         FREEPTR(ppath);
714                                         goto cleanup_fetch_url;
715                                 }
716
717                                 FREEPTR(host);
718                                 host = phost;
719                                 FREEPTR(port);
720                                 port = pport;
721                                 FREEPTR(path);
722                                 path = ftp_strdup(url);
723                                 FREEPTR(ppath);
724                                 urltype = purltype;
725                         }
726                 } /* ! EMPTYSTRING(proxyenv) */
727
728                 memset(&hints, 0, sizeof(hints));
729                 hints.ai_flags = 0;
730                 hints.ai_family = family;
731                 hints.ai_socktype = SOCK_STREAM;
732                 hints.ai_protocol = 0;
733                 error = getaddrinfo(host, port, &hints, &res0);
734                 if (error) {
735                         warnx("Can't LOOKUP `%s:%s': %s", host, port,
736                             (error == EAI_SYSTEM) ? strerror(errno)
737                                                   : gai_strerror(error));
738                         goto cleanup_fetch_url;
739                 }
740                 if (res0->ai_canonname)
741                         host = res0->ai_canonname;
742
743                 s = -1;
744 #ifdef WITH_SSL
745                 ssl = NULL;
746 #endif
747                 for (res = res0; res; res = res->ai_next) {
748                         char    hname[NI_MAXHOST], sname[NI_MAXSERV];
749
750                         ai_unmapped(res);
751                         if (getnameinfo(res->ai_addr, res->ai_addrlen,
752                             hname, sizeof(hname), sname, sizeof(sname),
753                             NI_NUMERICHOST | NI_NUMERICSERV) != 0) {
754                                 strlcpy(hname, "?", sizeof(hname));
755                                 strlcpy(sname, "?", sizeof(sname));
756                         }
757
758                         if (verbose && res0->ai_next) {
759                                 fprintf(ttyout, "Trying %s:%s ...\n",
760                                     hname, sname);
761                         }
762
763                         s = socket(res->ai_family, SOCK_STREAM,
764                             res->ai_protocol);
765                         if (s < 0) {
766                                 warn(
767                                     "Can't create socket for connection to "
768                                     "`%s:%s'", hname, sname);
769                                 continue;
770                         }
771
772                         if (ftp_connect(s, res->ai_addr, res->ai_addrlen,
773                             verbose || !res->ai_next) < 0) {
774                                 close(s);
775                                 s = -1;
776                                 continue;
777                         }
778
779 #ifdef WITH_SSL
780                         if (urltype == HTTPS_URL_T) {
781                                 if ((ssl = fetch_start_ssl(s)) == NULL) {
782                                         close(s);
783                                         s = -1;
784                                         continue;
785                                 }
786                         }
787 #endif
788
789                         /* success */
790                         break;
791                 }
792
793                 if (s < 0) {
794                         warnx("Can't connect to `%s:%s'", host, port);
795                         goto cleanup_fetch_url;
796                 }
797
798                 fin = fetch_fdopen(s, "r+");
799                 fetch_set_ssl(fin, ssl);
800
801                 /*
802                  * Construct and send the request.
803                  */
804                 if (verbose)
805                         fprintf(ttyout, "Requesting %s\n", url);
806                 leading = "  (";
807                 hasleading = 0;
808                 if (isproxy) {
809                         if (verbose) {
810                                 fprintf(ttyout, "%svia %s:%s", leading,
811                                     host, port);
812                                 leading = ", ";
813                                 hasleading++;
814                         }
815                         fetch_printf(fin, "GET %s HTTP/1.0\r\n", path);
816                         if (flushcache)
817                                 fetch_printf(fin, "Pragma: no-cache\r\n");
818                 } else {
819                         fetch_printf(fin, "GET %s HTTP/1.1\r\n", path);
820                         if (strchr(host, ':')) {
821                                 char *h, *p;
822
823                                 /*
824                                  * strip off IPv6 scope identifier, since it is
825                                  * local to the node
826                                  */
827                                 h = ftp_strdup(host);
828                                 if (isipv6addr(h) &&
829                                     (p = strchr(h, '%')) != NULL) {
830                                         *p = '\0';
831                                 }
832                                 fetch_printf(fin, "Host: [%s]", h);
833                                 free(h);
834                         } else
835                                 fetch_printf(fin, "Host: %s", host);
836 #ifdef WITH_SSL
837                         if ((urltype == HTTP_URL_T && portnum != HTTP_PORT) ||
838                             (urltype == HTTPS_URL_T && portnum != HTTPS_PORT))
839 #else
840                         if (portnum != HTTP_PORT)
841 #endif
842                                 fetch_printf(fin, ":%u", portnum);
843                         fetch_printf(fin, "\r\n");
844                         fetch_printf(fin, "Accept: */*\r\n");
845                         fetch_printf(fin, "Connection: close\r\n");
846                         if (restart_point) {
847                                 fputs(leading, ttyout);
848                                 fetch_printf(fin, "Range: bytes=" LLF "-\r\n",
849                                     (LLT)restart_point);
850                                 fprintf(ttyout, "restarting at " LLF,
851                                     (LLT)restart_point);
852                                 leading = ", ";
853                                 hasleading++;
854                         }
855                         if (flushcache)
856                                 fetch_printf(fin, "Cache-Control: no-cache\r\n");
857                 }
858                 if ((useragent=getenv("FTPUSERAGENT")) != NULL) {
859                         fetch_printf(fin, "User-Agent: %s\r\n", useragent);
860                 } else {
861                         fetch_printf(fin, "User-Agent: %s/%s\r\n",
862                             FTP_PRODUCT, FTP_VERSION);
863                 }
864                 if (wwwauth) {
865                         if (verbose) {
866                                 fprintf(ttyout, "%swith authorization",
867                                     leading);
868                                 leading = ", ";
869                                 hasleading++;
870                         }
871                         fetch_printf(fin, "Authorization: %s\r\n", wwwauth);
872                 }
873                 if (proxyauth) {
874                         if (verbose) {
875                                 fprintf(ttyout,
876                                     "%swith proxy authorization", leading);
877                                 leading = ", ";
878                                 hasleading++;
879                         }
880                         fetch_printf(fin, "Proxy-Authorization: %s\r\n", proxyauth);
881                 }
882                 if (verbose && hasleading)
883                         fputs(")\n", ttyout);
884                 fetch_printf(fin, "\r\n");
885                 if (fetch_flush(fin) == EOF) {
886                         warn("Writing HTTP request");
887                         goto cleanup_fetch_url;
888                 }
889
890                                 /* Read the response */
891                 len = fetch_getline(fin, buf, sizeof(buf), &errormsg);
892                 if (len < 0) {
893                         if (*errormsg == '\n')
894                                 errormsg++;
895                         warnx("Receiving HTTP reply: %s", errormsg);
896                         goto cleanup_fetch_url;
897                 }
898                 while (len > 0 && (ISLWS(buf[len-1])))
899                         buf[--len] = '\0';
900                 DPRINTF("fetch_url: received `%s'\n", buf);
901
902                                 /* Determine HTTP response code */
903                 cp = strchr(buf, ' ');
904                 if (cp == NULL)
905                         goto improper;
906                 else
907                         cp++;
908                 hcode = strtol(cp, &ep, 10);
909                 if (*ep != '\0' && !isspace((unsigned char)*ep))
910                         goto improper;
911                 message = ftp_strdup(cp);
912
913                                 /* Read the rest of the header. */
914                 while (1) {
915                         len = fetch_getline(fin, buf, sizeof(buf), &errormsg);
916                         if (len < 0) {
917                                 if (*errormsg == '\n')
918                                         errormsg++;
919                                 warnx("Receiving HTTP reply: %s", errormsg);
920                                 goto cleanup_fetch_url;
921                         }
922                         while (len > 0 && (ISLWS(buf[len-1])))
923                                 buf[--len] = '\0';
924                         if (len == 0)
925                                 break;
926                         DPRINTF("fetch_url: received `%s'\n", buf);
927
928                 /*
929                  * Look for some headers
930                  */
931
932                         cp = buf;
933
934                         if (match_token(&cp, "Content-Length:")) {
935                                 filesize = STRTOLL(cp, &ep, 10);
936                                 if (filesize < 0 || *ep != '\0')
937                                         goto improper;
938                                 DPRINTF("fetch_url: parsed len as: " LLF "\n",
939                                     (LLT)filesize);
940
941                         } else if (match_token(&cp, "Content-Range:")) {
942                                 if (! match_token(&cp, "bytes"))
943                                         goto improper;
944
945                                 if (*cp == '*')
946                                         cp++;
947                                 else {
948                                         rangestart = STRTOLL(cp, &ep, 10);
949                                         if (rangestart < 0 || *ep != '-')
950                                                 goto improper;
951                                         cp = ep + 1;
952                                         rangeend = STRTOLL(cp, &ep, 10);
953                                         if (rangeend < 0 || rangeend < rangestart)
954                                                 goto improper;
955                                         cp = ep;
956                                 }
957                                 if (*cp != '/')
958                                         goto improper;
959                                 cp++;
960                                 if (*cp == '*')
961                                         cp++;
962                                 else {
963                                         entitylen = STRTOLL(cp, &ep, 10);
964                                         if (entitylen < 0)
965                                                 goto improper;
966                                         cp = ep;
967                                 }
968                                 if (*cp != '\0')
969                                         goto improper;
970
971 #ifndef NO_DEBUG
972                                 if (ftp_debug) {
973                                         fprintf(ttyout, "parsed range as: ");
974                                         if (rangestart == -1)
975                                                 fprintf(ttyout, "*");
976                                         else
977                                                 fprintf(ttyout, LLF "-" LLF,
978                                                     (LLT)rangestart,
979                                                     (LLT)rangeend);
980                                         fprintf(ttyout, "/" LLF "\n", (LLT)entitylen);
981                                 }
982 #endif
983                                 if (! restart_point) {
984                                         warnx(
985                                     "Received unexpected Content-Range header");
986                                         goto cleanup_fetch_url;
987                                 }
988
989                         } else if (match_token(&cp, "Last-Modified:")) {
990                                 struct tm parsed;
991                                 const char *t;
992
993                                 memset(&parsed, 0, sizeof(parsed));
994                                 t = parse_rfc2616time(&parsed, cp);
995                                 if (t != NULL) {
996                                         parsed.tm_isdst = -1;
997                                         if (*t == '\0')
998                                                 mtime = timegm(&parsed);
999 #ifndef NO_DEBUG
1000                                         if (ftp_debug && mtime != -1) {
1001                                                 fprintf(ttyout,
1002                                                     "parsed time as: %s",
1003                                                 rfc2822time(localtime(&mtime)));
1004                                         }
1005 #endif
1006                                 }
1007
1008                         } else if (match_token(&cp, "Location:")) {
1009                                 location = ftp_strdup(cp);
1010                                 DPRINTF("fetch_url: parsed location as `%s'\n",
1011                                     cp);
1012
1013                         } else if (match_token(&cp, "Transfer-Encoding:")) {
1014                                 if (match_token(&cp, "binary")) {
1015                                         warnx(
1016                         "Bogus transfer encoding `binary' (fetching anyway)");
1017                                         continue;
1018                                 }
1019                                 if (! (token = match_token(&cp, "chunked"))) {
1020                                         warnx(
1021                                     "Unsupported transfer encoding `%s'",
1022                                             token);
1023                                         goto cleanup_fetch_url;
1024                                 }
1025                                 ischunked++;
1026                                 DPRINTF("fetch_url: using chunked encoding\n");
1027
1028                         } else if (match_token(&cp, "Proxy-Authenticate:")
1029                                 || match_token(&cp, "WWW-Authenticate:")) {
1030                                 if (! (token = match_token(&cp, "Basic"))) {
1031                                         DPRINTF(
1032                         "fetch_url: skipping unknown auth scheme `%s'\n",
1033                                                     token);
1034                                         continue;
1035                                 }
1036                                 FREEPTR(auth);
1037                                 auth = ftp_strdup(token);
1038                                 DPRINTF("fetch_url: parsed auth as `%s'\n", cp);
1039                         }
1040
1041                 }
1042                                 /* finished parsing header */
1043
1044                 switch (hcode) {
1045                 case 200:
1046                         break;
1047                 case 206:
1048                         if (! restart_point) {
1049                                 warnx("Not expecting partial content header");
1050                                 goto cleanup_fetch_url;
1051                         }
1052                         break;
1053                 case 300:
1054                 case 301:
1055                 case 302:
1056                 case 303:
1057                 case 305:
1058                 case 307:
1059                         if (EMPTYSTRING(location)) {
1060                                 warnx(
1061                                 "No redirection Location provided by server");
1062                                 goto cleanup_fetch_url;
1063                         }
1064                         if (redirect_loop++ > 5) {
1065                                 warnx("Too many redirections requested");
1066                                 goto cleanup_fetch_url;
1067                         }
1068                         if (hcode == 305) {
1069                                 if (verbose)
1070                                         fprintf(ttyout, "Redirected via %s\n",
1071                                             location);
1072                                 rval = fetch_url(url, location,
1073                                     proxyauth, wwwauth);
1074                         } else {
1075                                 if (verbose)
1076                                         fprintf(ttyout, "Redirected to %s\n",
1077                                             location);
1078                                 rval = go_fetch(location);
1079                         }
1080                         goto cleanup_fetch_url;
1081 #ifndef NO_AUTH
1082                 case 401:
1083                 case 407:
1084                     {
1085                         char **authp;
1086                         char *auser, *apass;
1087
1088                         if (hcode == 401) {
1089                                 authp = &wwwauth;
1090                                 auser = uuser;
1091                                 apass = pass;
1092                         } else {
1093                                 authp = &proxyauth;
1094                                 auser = puser;
1095                                 apass = ppass;
1096                         }
1097                         if (verbose || *authp == NULL ||
1098                             auser == NULL || apass == NULL)
1099                                 fprintf(ttyout, "%s\n", message);
1100                         if (EMPTYSTRING(auth)) {
1101                                 warnx(
1102                             "No authentication challenge provided by server");
1103                                 goto cleanup_fetch_url;
1104                         }
1105                         if (*authp != NULL) {
1106                                 char reply[10];
1107
1108                                 fprintf(ttyout,
1109                                     "Authorization failed. Retry (y/n)? ");
1110                                 if (get_line(stdin, reply, sizeof(reply), NULL)
1111                                     < 0) {
1112                                         goto cleanup_fetch_url;
1113                                 }
1114                                 if (tolower((unsigned char)reply[0]) != 'y')
1115                                         goto cleanup_fetch_url;
1116                                 auser = NULL;
1117                                 apass = NULL;
1118                         }
1119                         if (auth_url(auth, authp, auser, apass) == 0) {
1120                                 rval = fetch_url(url, proxyenv,
1121                                     proxyauth, wwwauth);
1122                                 memset(*authp, 0, strlen(*authp));
1123                                 FREEPTR(*authp);
1124                         }
1125                         goto cleanup_fetch_url;
1126                     }
1127 #endif
1128                 default:
1129                         if (message)
1130                                 warnx("Error retrieving file `%s'", message);
1131                         else
1132                                 warnx("Unknown error retrieving file");
1133                         goto cleanup_fetch_url;
1134                 }
1135         }               /* end of ftp:// or http:// specific setup */
1136
1137                         /* Open the output file. */
1138         if (strcmp(savefile, "-") == 0) {
1139                 fout = stdout;
1140         } else if (*savefile == '|') {
1141                 oldintp = xsignal(SIGPIPE, SIG_IGN);
1142                 fout = popen(savefile + 1, "w");
1143                 if (fout == NULL) {
1144                         warn("Can't execute `%s'", savefile + 1);
1145                         goto cleanup_fetch_url;
1146                 }
1147                 closefunc = pclose;
1148         } else {
1149                 if ((rangeend != -1 && rangeend <= restart_point) ||
1150                     (rangestart == -1 && filesize != -1 && filesize <= restart_point)) {
1151                         /* already done */
1152                         if (verbose)
1153                                 fprintf(ttyout, "already done\n");
1154                         rval = 0;
1155                         goto cleanup_fetch_url;
1156                 }
1157                 if (restart_point && rangestart != -1) {
1158                         if (entitylen != -1)
1159                                 filesize = entitylen;
1160                         if (rangestart != restart_point) {
1161                                 warnx(
1162                                     "Size of `%s' differs from save file `%s'",
1163                                     url, savefile);
1164                                 goto cleanup_fetch_url;
1165                         }
1166                         fout = fopen(savefile, "a");
1167                 } else
1168                         fout = fopen(savefile, "w");
1169                 if (fout == NULL) {
1170                         warn("Can't open `%s'", savefile);
1171                         goto cleanup_fetch_url;
1172                 }
1173                 closefunc = fclose;
1174         }
1175
1176                         /* Trap signals */
1177         if (sigsetjmp(httpabort, 1))
1178                 goto cleanup_fetch_url;
1179         (void)xsignal(SIGQUIT, psummary);
1180         oldintr = xsignal(SIGINT, aborthttp);
1181
1182         assert(rcvbuf_size > 0);
1183         if ((size_t)rcvbuf_size > bufsize) {
1184                 if (xferbuf)
1185                         (void)free(xferbuf);
1186                 bufsize = rcvbuf_size;
1187                 xferbuf = ftp_malloc(bufsize);
1188         }
1189
1190         bytes = 0;
1191         hashbytes = mark;
1192         progressmeter(-1);
1193
1194                         /* Finally, suck down the file. */
1195         do {
1196                 long chunksize;
1197                 short lastchunk;
1198
1199                 chunksize = 0;
1200                 lastchunk = 0;
1201                                         /* read chunk-size */
1202                 if (ischunked) {
1203                         if (fetch_getln(xferbuf, bufsize, fin) == NULL) {
1204                                 warnx("Unexpected EOF reading chunk-size");
1205                                 goto cleanup_fetch_url;
1206                         }
1207                         errno = 0;
1208                         chunksize = strtol(xferbuf, &ep, 16);
1209                         if (ep == xferbuf) {
1210                                 warnx("Invalid chunk-size");
1211                                 goto cleanup_fetch_url;
1212                         }
1213                         if (errno == ERANGE || chunksize < 0) {
1214                                 errno = ERANGE;
1215                                 warn("Chunk-size `%.*s'",
1216                                     (int)(ep-xferbuf), xferbuf);
1217                                 goto cleanup_fetch_url;
1218                         }
1219
1220                                 /*
1221                                  * XXX: Work around bug in Apache 1.3.9 and
1222                                  *      1.3.11, which incorrectly put trailing
1223                                  *      space after the chunk-size.
1224                                  */
1225                         while (*ep == ' ')
1226                                 ep++;
1227
1228                                         /* skip [ chunk-ext ] */
1229                         if (*ep == ';') {
1230                                 while (*ep && *ep != '\r')
1231                                         ep++;
1232                         }
1233
1234                         if (strcmp(ep, "\r\n") != 0) {
1235                                 warnx("Unexpected data following chunk-size");
1236                                 goto cleanup_fetch_url;
1237                         }
1238                         DPRINTF("fetch_url: got chunk-size of " LLF "\n",
1239                             (LLT)chunksize);
1240                         if (chunksize == 0) {
1241                                 lastchunk = 1;
1242                                 goto chunkdone;
1243                         }
1244                 }
1245                                         /* transfer file or chunk */
1246                 while (1) {
1247                         struct timeval then, now, td;
1248                         off_t bufrem;
1249
1250                         if (rate_get)
1251                                 (void)gettimeofday(&then, NULL);
1252                         bufrem = rate_get ? rate_get : (off_t)bufsize;
1253                         if (ischunked)
1254                                 bufrem = MIN(chunksize, bufrem);
1255                         while (bufrem > 0) {
1256                                 flen = fetch_read(xferbuf, sizeof(char),
1257                                     MIN((off_t)bufsize, bufrem), fin);
1258                                 if (flen <= 0)
1259                                         goto chunkdone;
1260                                 bytes += flen;
1261                                 bufrem -= flen;
1262                                 if (fwrite(xferbuf, sizeof(char), flen, fout)
1263                                     != flen) {
1264                                         warn("Writing `%s'", savefile);
1265                                         goto cleanup_fetch_url;
1266                                 }
1267                                 if (hash && !progress) {
1268                                         while (bytes >= hashbytes) {
1269                                                 (void)putc('#', ttyout);
1270                                                 hashbytes += mark;
1271                                         }
1272                                         (void)fflush(ttyout);
1273                                 }
1274                                 if (ischunked) {
1275                                         chunksize -= flen;
1276                                         if (chunksize <= 0)
1277                                                 break;
1278                                 }
1279                         }
1280                         if (rate_get) {
1281                                 while (1) {
1282                                         (void)gettimeofday(&now, NULL);
1283                                         timersub(&now, &then, &td);
1284                                         if (td.tv_sec > 0)
1285                                                 break;
1286                                         usleep(1000000 - td.tv_usec);
1287                                 }
1288                         }
1289                         if (ischunked && chunksize <= 0)
1290                                 break;
1291                 }
1292                                         /* read CRLF after chunk*/
1293  chunkdone:
1294                 if (ischunked) {
1295                         if (fetch_getln(xferbuf, bufsize, fin) == NULL) {
1296                                 warnx("Unexpected EOF reading chunk CRLF");
1297                                 goto cleanup_fetch_url;
1298                         }
1299                         if (strcmp(xferbuf, "\r\n") != 0) {
1300                                 warnx("Unexpected data following chunk");
1301                                 goto cleanup_fetch_url;
1302                         }
1303                         if (lastchunk)
1304                                 break;
1305                 }
1306         } while (ischunked);
1307
1308 /* XXX: deal with optional trailer & CRLF here? */
1309
1310         if (hash && !progress && bytes > 0) {
1311                 if (bytes < mark)
1312                         (void)putc('#', ttyout);
1313                 (void)putc('\n', ttyout);
1314         }
1315         if (fetch_error(fin)) {
1316                 warn("Reading file");
1317                 goto cleanup_fetch_url;
1318         }
1319         progressmeter(1);
1320         (void)fflush(fout);
1321         if (closefunc == fclose && mtime != -1) {
1322                 struct timeval tval[2];
1323
1324                 (void)gettimeofday(&tval[0], NULL);
1325                 tval[1].tv_sec = mtime;
1326                 tval[1].tv_usec = 0;
1327                 (*closefunc)(fout);
1328                 fout = NULL;
1329
1330                 if (utimes(savefile, tval) == -1) {
1331                         fprintf(ttyout,
1332                             "Can't change modification time to %s",
1333                             rfc2822time(localtime(&mtime)));
1334                 }
1335         }
1336         if (bytes > 0)
1337                 ptransfer(0);
1338         bytes = 0;
1339
1340         rval = 0;
1341         goto cleanup_fetch_url;
1342
1343  improper:
1344         warnx("Improper response from `%s:%s'", host, port);
1345
1346  cleanup_fetch_url:
1347         if (oldintr)
1348                 (void)xsignal(SIGINT, oldintr);
1349         if (oldintp)
1350                 (void)xsignal(SIGPIPE, oldintp);
1351         if (fin != NULL)
1352                 fetch_close(fin);
1353         else if (s != -1)
1354                 close(s);
1355         if (closefunc != NULL && fout != NULL)
1356                 (*closefunc)(fout);
1357         if (res0)
1358                 freeaddrinfo(res0);
1359         FREEPTR(savefile);
1360         FREEPTR(uuser);
1361         if (pass != NULL)
1362                 memset(pass, 0, strlen(pass));
1363         FREEPTR(pass);
1364         FREEPTR(host);
1365         FREEPTR(port);
1366         FREEPTR(path);
1367         FREEPTR(decodedpath);
1368         FREEPTR(puser);
1369         if (ppass != NULL)
1370                 memset(ppass, 0, strlen(ppass));
1371         FREEPTR(ppass);
1372         FREEPTR(auth);
1373         FREEPTR(location);
1374         FREEPTR(message);
1375         return (rval);
1376 }
1377
1378 /*
1379  * Abort a HTTP retrieval
1380  */
1381 static void
1382 aborthttp(int notused)
1383 {
1384         char msgbuf[100];
1385         size_t len;
1386
1387         sigint_raised = 1;
1388         alarmtimer(0);
1389         len = strlcpy(msgbuf, "\nHTTP fetch aborted.\n", sizeof(msgbuf));
1390         write(fileno(ttyout), msgbuf, len);
1391         siglongjmp(httpabort, 1);
1392 }
1393
1394 /*
1395  * Retrieve ftp URL or classic ftp argument using FTP.
1396  * Returns 1 on failure, 0 on completed xfer, -1 if ftp connection
1397  * is still open (e.g, ftp xfer with trailing /)
1398  */
1399 static int
1400 fetch_ftp(const char *url)
1401 {
1402         char            *cp, *xargv[5], rempath[MAXPATHLEN];
1403         char            *host, *path, *dir, *file, *uuser, *pass;
1404         char            *port;
1405         char             cmdbuf[MAXPATHLEN];
1406         char             dirbuf[4];
1407         int              dirhasglob, filehasglob, rval, transtype, xargc;
1408         int              oanonftp, oautologin;
1409         in_port_t        portnum;
1410         url_t            urltype;
1411
1412         DPRINTF("fetch_ftp: `%s'\n", url);
1413         host = path = dir = file = uuser = pass = NULL;
1414         port = NULL;
1415         rval = 1;
1416         transtype = TYPE_I;
1417
1418         if (STRNEQUAL(url, FTP_URL)) {
1419                 if ((parse_url(url, "URL", &urltype, &uuser, &pass,
1420                     &host, &port, &portnum, &path) == -1) ||
1421                     (uuser != NULL && *uuser == '\0') ||
1422                     EMPTYSTRING(host)) {
1423                         warnx("Invalid URL `%s'", url);
1424                         goto cleanup_fetch_ftp;
1425                 }
1426                 /*
1427                  * Note: Don't url_decode(path) here.  We need to keep the
1428                  * distinction between "/" and "%2F" until later.
1429                  */
1430
1431                                         /* check for trailing ';type=[aid]' */
1432                 if (! EMPTYSTRING(path) && (cp = strrchr(path, ';')) != NULL) {
1433                         if (strcasecmp(cp, ";type=a") == 0)
1434                                 transtype = TYPE_A;
1435                         else if (strcasecmp(cp, ";type=i") == 0)
1436                                 transtype = TYPE_I;
1437                         else if (strcasecmp(cp, ";type=d") == 0) {
1438                                 warnx(
1439                             "Directory listing via a URL is not supported");
1440                                 goto cleanup_fetch_ftp;
1441                         } else {
1442                                 warnx("Invalid suffix `%s' in URL `%s'", cp,
1443                                     url);
1444                                 goto cleanup_fetch_ftp;
1445                         }
1446                         *cp = 0;
1447                 }
1448         } else {                        /* classic style `[user@]host:[file]' */
1449                 urltype = CLASSIC_URL_T;
1450                 host = ftp_strdup(url);
1451                 cp = strchr(host, '@');
1452                 if (cp != NULL) {
1453                         *cp = '\0';
1454                         uuser = host;
1455                         anonftp = 0;    /* disable anonftp */
1456                         host = ftp_strdup(cp + 1);
1457                 }
1458                 cp = strchr(host, ':');
1459                 if (cp != NULL) {
1460                         *cp = '\0';
1461                         path = ftp_strdup(cp + 1);
1462                 }
1463         }
1464         if (EMPTYSTRING(host))
1465                 goto cleanup_fetch_ftp;
1466
1467                         /* Extract the file and (if present) directory name. */
1468         dir = path;
1469         if (! EMPTYSTRING(dir)) {
1470                 /*
1471                  * If we are dealing with classic `[user@]host:[path]' syntax,
1472                  * then a path of the form `/file' (resulting from input of the
1473                  * form `host:/file') means that we should do "CWD /" before
1474                  * retrieving the file.  So we set dir="/" and file="file".
1475                  *
1476                  * But if we are dealing with URLs like `ftp://host/path' then
1477                  * a path of the form `/file' (resulting from a URL of the form
1478                  * `ftp://host//file') means that we should do `CWD ' (with an
1479                  * empty argument) before retrieving the file.  So we set
1480                  * dir="" and file="file".
1481                  *
1482                  * If the path does not contain / at all, we set dir=NULL.
1483                  * (We get a path without any slashes if we are dealing with
1484                  * classic `[user@]host:[file]' or URL `ftp://host/file'.)
1485                  *
1486                  * In all other cases, we set dir to a string that does not
1487                  * include the final '/' that separates the dir part from the
1488                  * file part of the path.  (This will be the empty string if
1489                  * and only if we are dealing with a path of the form `/file'
1490                  * resulting from an URL of the form `ftp://host//file'.)
1491                  */
1492                 cp = strrchr(dir, '/');
1493                 if (cp == dir && urltype == CLASSIC_URL_T) {
1494                         file = cp + 1;
1495                         (void)strlcpy(dirbuf, "/", sizeof(dirbuf));
1496                         dir = dirbuf;
1497                 } else if (cp != NULL) {
1498                         *cp++ = '\0';
1499                         file = cp;
1500                 } else {
1501                         file = dir;
1502                         dir = NULL;
1503                 }
1504         } else
1505                 dir = NULL;
1506         if (urltype == FTP_URL_T && file != NULL) {
1507                 url_decode(file);
1508                 /* but still don't url_decode(dir) */
1509         }
1510         DPRINTF("fetch_ftp: user `%s' pass `%s' host %s port %s "
1511             "path `%s' dir `%s' file `%s'\n",
1512             STRorNULL(uuser), STRorNULL(pass),
1513             STRorNULL(host), STRorNULL(port),
1514             STRorNULL(path), STRorNULL(dir), STRorNULL(file));
1515
1516         dirhasglob = filehasglob = 0;
1517         if (doglob && urltype == CLASSIC_URL_T) {
1518                 if (! EMPTYSTRING(dir) && strpbrk(dir, "*?[]{}") != NULL)
1519                         dirhasglob = 1;
1520                 if (! EMPTYSTRING(file) && strpbrk(file, "*?[]{}") != NULL)
1521                         filehasglob = 1;
1522         }
1523
1524                         /* Set up the connection */
1525         oanonftp = anonftp;
1526         if (connected)
1527                 disconnect(0, NULL);
1528         anonftp = oanonftp;
1529         (void)strlcpy(cmdbuf, getprogname(), sizeof(cmdbuf));
1530         xargv[0] = cmdbuf;
1531         xargv[1] = host;
1532         xargv[2] = NULL;
1533         xargc = 2;
1534         if (port) {
1535                 xargv[2] = port;
1536                 xargv[3] = NULL;
1537                 xargc = 3;
1538         }
1539         oautologin = autologin;
1540                 /* don't autologin in setpeer(), use ftp_login() below */
1541         autologin = 0;
1542         setpeer(xargc, xargv);
1543         autologin = oautologin;
1544         if ((connected == 0) ||
1545             (connected == 1 && !ftp_login(host, uuser, pass))) {
1546                 warnx("Can't connect or login to host `%s:%s'",
1547                         host, port ? port : "?");
1548                 goto cleanup_fetch_ftp;
1549         }
1550
1551         switch (transtype) {
1552         case TYPE_A:
1553                 setascii(1, xargv);
1554                 break;
1555         case TYPE_I:
1556                 setbinary(1, xargv);
1557                 break;
1558         default:
1559                 errx(1, "fetch_ftp: unknown transfer type %d", transtype);
1560         }
1561
1562                 /*
1563                  * Change directories, if necessary.
1564                  *
1565                  * Note: don't use EMPTYSTRING(dir) below, because
1566                  * dir=="" means something different from dir==NULL.
1567                  */
1568         if (dir != NULL && !dirhasglob) {
1569                 char *nextpart;
1570
1571                 /*
1572                  * If we are dealing with a classic `[user@]host:[path]'
1573                  * (urltype is CLASSIC_URL_T) then we have a raw directory
1574                  * name (not encoded in any way) and we can change
1575                  * directories in one step.
1576                  *
1577                  * If we are dealing with an `ftp://host/path' URL
1578                  * (urltype is FTP_URL_T), then RFC 3986 says we need to
1579                  * send a separate CWD command for each unescaped "/"
1580                  * in the path, and we have to interpret %hex escaping
1581                  * *after* we find the slashes.  It's possible to get
1582                  * empty components here, (from multiple adjacent
1583                  * slashes in the path) and RFC 3986 says that we should
1584                  * still do `CWD ' (with a null argument) in such cases.
1585                  *
1586                  * Many ftp servers don't support `CWD ', so if there's an
1587                  * error performing that command, bail out with a descriptive
1588                  * message.
1589                  *
1590                  * Examples:
1591                  *
1592                  * host:                        dir="", urltype=CLASSIC_URL_T
1593                  *              logged in (to default directory)
1594                  * host:file                    dir=NULL, urltype=CLASSIC_URL_T
1595                  *              "RETR file"
1596                  * host:dir/                    dir="dir", urltype=CLASSIC_URL_T
1597                  *              "CWD dir", logged in
1598                  * ftp://host/                  dir="", urltype=FTP_URL_T
1599                  *              logged in (to default directory)
1600                  * ftp://host/dir/              dir="dir", urltype=FTP_URL_T
1601                  *              "CWD dir", logged in
1602                  * ftp://host/file              dir=NULL, urltype=FTP_URL_T
1603                  *              "RETR file"
1604                  * ftp://host//file             dir="", urltype=FTP_URL_T
1605                  *              "CWD ", "RETR file"
1606                  * host:/file                   dir="/", urltype=CLASSIC_URL_T
1607                  *              "CWD /", "RETR file"
1608                  * ftp://host///file            dir="/", urltype=FTP_URL_T
1609                  *              "CWD ", "CWD ", "RETR file"
1610                  * ftp://host/%2F/file          dir="%2F", urltype=FTP_URL_T
1611                  *              "CWD /", "RETR file"
1612                  * ftp://host/foo/file          dir="foo", urltype=FTP_URL_T
1613                  *              "CWD foo", "RETR file"
1614                  * ftp://host/foo/bar/file      dir="foo/bar"
1615                  *              "CWD foo", "CWD bar", "RETR file"
1616                  * ftp://host//foo/bar/file     dir="/foo/bar"
1617                  *              "CWD ", "CWD foo", "CWD bar", "RETR file"
1618                  * ftp://host/foo//bar/file     dir="foo//bar"
1619                  *              "CWD foo", "CWD ", "CWD bar", "RETR file"
1620                  * ftp://host/%2F/foo/bar/file  dir="%2F/foo/bar"
1621                  *              "CWD /", "CWD foo", "CWD bar", "RETR file"
1622                  * ftp://host/%2Ffoo/bar/file   dir="%2Ffoo/bar"
1623                  *              "CWD /foo", "CWD bar", "RETR file"
1624                  * ftp://host/%2Ffoo%2Fbar/file dir="%2Ffoo%2Fbar"
1625                  *              "CWD /foo/bar", "RETR file"
1626                  * ftp://host/%2Ffoo%2Fbar%2Ffile       dir=NULL
1627                  *              "RETR /foo/bar/file"
1628                  *
1629                  * Note that we don't need `dir' after this point.
1630                  */
1631                 do {
1632                         if (urltype == FTP_URL_T) {
1633                                 nextpart = strchr(dir, '/');
1634                                 if (nextpart) {
1635                                         *nextpart = '\0';
1636                                         nextpart++;
1637                                 }
1638                                 url_decode(dir);
1639                         } else
1640                                 nextpart = NULL;
1641                         DPRINTF("fetch_ftp: dir `%s', nextpart `%s'\n",
1642                             STRorNULL(dir), STRorNULL(nextpart));
1643                         if (urltype == FTP_URL_T || *dir != '\0') {
1644                                 (void)strlcpy(cmdbuf, "cd", sizeof(cmdbuf));
1645                                 xargv[0] = cmdbuf;
1646                                 xargv[1] = dir;
1647                                 xargv[2] = NULL;
1648                                 dirchange = 0;
1649                                 cd(2, xargv);
1650                                 if (! dirchange) {
1651                                         if (*dir == '\0' && code == 500)
1652                                                 fprintf(stderr,
1653 "\n"
1654 "ftp: The `CWD ' command (without a directory), which is required by\n"
1655 "     RFC 3986 to support the empty directory in the URL pathname (`//'),\n"
1656 "     conflicts with the server's conformance to RFC 959.\n"
1657 "     Try the same URL without the `//' in the URL pathname.\n"
1658 "\n");
1659                                         goto cleanup_fetch_ftp;
1660                                 }
1661                         }
1662                         dir = nextpart;
1663                 } while (dir != NULL);
1664         }
1665
1666         if (EMPTYSTRING(file)) {
1667                 rval = -1;
1668                 goto cleanup_fetch_ftp;
1669         }
1670
1671         if (dirhasglob) {
1672                 (void)strlcpy(rempath, dir,     sizeof(rempath));
1673                 (void)strlcat(rempath, "/",     sizeof(rempath));
1674                 (void)strlcat(rempath, file,    sizeof(rempath));
1675                 file = rempath;
1676         }
1677
1678                         /* Fetch the file(s). */
1679         xargc = 2;
1680         (void)strlcpy(cmdbuf, "get", sizeof(cmdbuf));
1681         xargv[0] = cmdbuf;
1682         xargv[1] = file;
1683         xargv[2] = NULL;
1684         if (dirhasglob || filehasglob) {
1685                 int ointeractive;
1686
1687                 ointeractive = interactive;
1688                 interactive = 0;
1689                 if (restartautofetch)
1690                         (void)strlcpy(cmdbuf, "mreget", sizeof(cmdbuf));
1691                 else
1692                         (void)strlcpy(cmdbuf, "mget", sizeof(cmdbuf));
1693                 xargv[0] = cmdbuf;
1694                 mget(xargc, xargv);
1695                 interactive = ointeractive;
1696         } else {
1697                 if (outfile == NULL) {
1698                         cp = strrchr(file, '/');        /* find savefile */
1699                         if (cp != NULL)
1700                                 outfile = cp + 1;
1701                         else
1702                                 outfile = file;
1703                 }
1704                 xargv[2] = (char *)outfile;
1705                 xargv[3] = NULL;
1706                 xargc++;
1707                 if (restartautofetch)
1708                         reget(xargc, xargv);
1709                 else
1710                         get(xargc, xargv);
1711         }
1712
1713         if ((code / 100) == COMPLETE)
1714                 rval = 0;
1715
1716  cleanup_fetch_ftp:
1717         FREEPTR(port);
1718         FREEPTR(host);
1719         FREEPTR(path);
1720         FREEPTR(uuser);
1721         if (pass)
1722                 memset(pass, 0, strlen(pass));
1723         FREEPTR(pass);
1724         return (rval);
1725 }
1726
1727 /*
1728  * Retrieve the given file to outfile.
1729  * Supports arguments of the form:
1730  *      "host:path", "ftp://host/path"  if $ftpproxy, call fetch_url() else
1731  *                                      call fetch_ftp()
1732  *      "http://host/path"              call fetch_url() to use HTTP
1733  *      "file:///path"                  call fetch_url() to copy
1734  *      "about:..."                     print a message
1735  *
1736  * Returns 1 on failure, 0 on completed xfer, -1 if ftp connection
1737  * is still open (e.g, ftp xfer with trailing /)
1738  */
1739 static int
1740 go_fetch(const char *url)
1741 {
1742         char *proxyenv;
1743         char *p;
1744
1745 #ifndef NO_ABOUT
1746         /*
1747          * Check for about:*
1748          */
1749         if (STRNEQUAL(url, ABOUT_URL)) {
1750                 url += sizeof(ABOUT_URL) -1;
1751                 if (strcasecmp(url, "ftp") == 0 ||
1752                     strcasecmp(url, "tnftp") == 0) {
1753                         fputs(
1754 "This version of ftp has been enhanced by Luke Mewburn <lukem@NetBSD.org>\n"
1755 "for the NetBSD project.  Execute `man ftp' for more details.\n", ttyout);
1756                 } else if (strcasecmp(url, "lukem") == 0) {
1757                         fputs(
1758 "Luke Mewburn is the author of most of the enhancements in this ftp client.\n"
1759 "Please email feedback to <lukem@NetBSD.org>.\n", ttyout);
1760                 } else if (strcasecmp(url, "netbsd") == 0) {
1761                         fputs(
1762 "NetBSD is a freely available and redistributable UNIX-like operating system.\n"
1763 "For more information, see http://www.NetBSD.org/\n", ttyout);
1764                 } else if (strcasecmp(url, "version") == 0) {
1765                         fprintf(ttyout, "Version: %s %s%s\n",
1766                             FTP_PRODUCT, FTP_VERSION,
1767 #ifdef INET6
1768                             ""
1769 #else
1770                             " (-IPv6)"
1771 #endif
1772                         );
1773                 } else {
1774                         fprintf(ttyout, "`%s' is an interesting topic.\n", url);
1775                 }
1776                 fputs("\n", ttyout);
1777                 return (0);
1778         }
1779 #endif
1780
1781         /*
1782          * Check for file:// and http:// URLs.
1783          */
1784         if (STRNEQUAL(url, HTTP_URL)
1785 #ifdef WITH_SSL
1786             || STRNEQUAL(url, HTTPS_URL)
1787 #endif
1788             || STRNEQUAL(url, FILE_URL))
1789                 return (fetch_url(url, NULL, NULL, NULL));
1790
1791         /*
1792          * If it contains "://" but does not begin with ftp://
1793          * or something that was already handled, then it's
1794          * unsupported.
1795          *
1796          * If it contains ":" but not "://" then we assume the
1797          * part before the colon is a host name, not an URL scheme,
1798          * so we don't try to match that here.
1799          */
1800         if ((p = strstr(url, "://")) != NULL && ! STRNEQUAL(url, FTP_URL))
1801                 errx(1, "Unsupported URL scheme `%.*s'", (int)(p - url), url);
1802
1803         /*
1804          * Try FTP URL-style and host:file arguments next.
1805          * If ftpproxy is set with an FTP URL, use fetch_url()
1806          * Othewise, use fetch_ftp().
1807          */
1808         proxyenv = getoptionvalue("ftp_proxy");
1809         if (!EMPTYSTRING(proxyenv) && STRNEQUAL(url, FTP_URL))
1810                 return (fetch_url(url, NULL, NULL, NULL));
1811
1812         return (fetch_ftp(url));
1813 }
1814
1815 /*
1816  * Retrieve multiple files from the command line,
1817  * calling go_fetch() for each file.
1818  *
1819  * If an ftp path has a trailing "/", the path will be cd-ed into and
1820  * the connection remains open, and the function will return -1
1821  * (to indicate the connection is alive).
1822  * If an error occurs the return value will be the offset+1 in
1823  * argv[] of the file that caused a problem (i.e, argv[x]
1824  * returns x+1)
1825  * Otherwise, 0 is returned if all files retrieved successfully.
1826  */
1827 int
1828 auto_fetch(int argc, char *argv[])
1829 {
1830         volatile int    argpos, rval;
1831
1832         argpos = rval = 0;
1833
1834         if (sigsetjmp(toplevel, 1)) {
1835                 if (connected)
1836                         disconnect(0, NULL);
1837                 if (rval > 0)
1838                         rval = argpos + 1;
1839                 return (rval);
1840         }
1841         (void)xsignal(SIGINT, intr);
1842         (void)xsignal(SIGPIPE, lostpeer);
1843
1844         /*
1845          * Loop through as long as there's files to fetch.
1846          */
1847         for (; (rval == 0) && (argpos < argc); argpos++) {
1848                 if (strchr(argv[argpos], ':') == NULL)
1849                         break;
1850                 redirect_loop = 0;
1851                 if (!anonftp)
1852                         anonftp = 2;    /* Handle "automatic" transfers. */
1853                 rval = go_fetch(argv[argpos]);
1854                 if (outfile != NULL && strcmp(outfile, "-") != 0
1855                     && outfile[0] != '|')
1856                         outfile = NULL;
1857                 if (rval > 0)
1858                         rval = argpos + 1;
1859         }
1860
1861         if (connected && rval != -1)
1862                 disconnect(0, NULL);
1863         return (rval);
1864 }
1865
1866
1867 /*
1868  * Upload multiple files from the command line.
1869  *
1870  * If an error occurs the return value will be the offset+1 in
1871  * argv[] of the file that caused a problem (i.e, argv[x]
1872  * returns x+1)
1873  * Otherwise, 0 is returned if all files uploaded successfully.
1874  */
1875 int
1876 auto_put(int argc, char **argv, const char *uploadserver)
1877 {
1878         char    *uargv[4], *path, *pathsep;
1879         int      uargc, rval, argpos;
1880         size_t   len;
1881         char     cmdbuf[MAX_C_NAME];
1882
1883         (void)strlcpy(cmdbuf, "mput", sizeof(cmdbuf));
1884         uargv[0] = cmdbuf;
1885         uargv[1] = argv[0];
1886         uargc = 2;
1887         uargv[2] = uargv[3] = NULL;
1888         pathsep = NULL;
1889         rval = 1;
1890
1891         DPRINTF("auto_put: target `%s'\n", uploadserver);
1892
1893         path = ftp_strdup(uploadserver);
1894         len = strlen(path);
1895         if (path[len - 1] != '/' && path[len - 1] != ':') {
1896                         /*
1897                          * make sure we always pass a directory to auto_fetch
1898                          */
1899                 if (argc > 1) {         /* more than one file to upload */
1900                         len = strlen(uploadserver) + 2; /* path + "/" + "\0" */
1901                         free(path);
1902                         path = (char *)ftp_malloc(len);
1903                         (void)strlcpy(path, uploadserver, len);
1904                         (void)strlcat(path, "/", len);
1905                 } else {                /* single file to upload */
1906                         (void)strlcpy(cmdbuf, "put", sizeof(cmdbuf));
1907                         uargv[0] = cmdbuf;
1908                         pathsep = strrchr(path, '/');
1909                         if (pathsep == NULL) {
1910                                 pathsep = strrchr(path, ':');
1911                                 if (pathsep == NULL) {
1912                                         warnx("Invalid URL `%s'", path);
1913                                         goto cleanup_auto_put;
1914                                 }
1915                                 pathsep++;
1916                                 uargv[2] = ftp_strdup(pathsep);
1917                                 pathsep[0] = '/';
1918                         } else
1919                                 uargv[2] = ftp_strdup(pathsep + 1);
1920                         pathsep[1] = '\0';
1921                         uargc++;
1922                 }
1923         }
1924         DPRINTF("auto_put: URL `%s' argv[2] `%s'\n",
1925             path, STRorNULL(uargv[2]));
1926
1927                         /* connect and cwd */
1928         rval = auto_fetch(1, &path);
1929         if(rval >= 0)
1930                 goto cleanup_auto_put;
1931
1932         rval = 0;
1933
1934                         /* target filename provided; upload 1 file */
1935                         /* XXX : is this the best way? */
1936         if (uargc == 3) {
1937                 uargv[1] = argv[0];
1938                 put(uargc, uargv);
1939                 if ((code / 100) != COMPLETE)
1940                         rval = 1;
1941         } else {        /* otherwise a target dir: upload all files to it */
1942                 for(argpos = 0; argv[argpos] != NULL; argpos++) {
1943                         uargv[1] = argv[argpos];
1944                         mput(uargc, uargv);
1945                         if ((code / 100) != COMPLETE) {
1946                                 rval = argpos + 1;
1947                                 break;
1948                         }
1949                 }
1950         }
1951
1952  cleanup_auto_put:
1953         free(path);
1954         FREEPTR(uargv[2]);
1955         return (rval);
1956 }