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