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