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