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