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