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