fetch.c revision 1.63 1 /* $NetBSD: fetch.c,v 1.63 1999/07/12 13:20:34 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.63 1999/07/12 13:20:34 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) + 1; /* user + ":" + pass */
177 clear = (char *)xmalloc(len + 1);
178 snprintf(clear, len, "%s:%s", user, pass);
179 if (gpass == NULL)
180 memset(pass, '\0', strlen(pass));
181
182 /* scheme + " " + enc */
183 len = strlen(scheme) + 1 + (len + 2) * 4 / 3;
184 *response = (char *)xmalloc(len + 1);
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 user = pass = host = path = decodedpath = puser = ppass = NULL;
459
460 #ifdef __GNUC__ /* shut up gcc warnings */
461 (void)&closefunc;
462 (void)&fin;
463 (void)&fout;
464 (void)&buf;
465 (void)&savefile;
466 (void)&rval;
467 (void)&isproxy;
468 (void)&hcode;
469 (void)&ischunked;
470 (void)&message;
471 (void)&location;
472 (void)&auth;
473 (void)&decodedpath;
474 #endif
475
476 if (parse_url(url, "URL", &urltype, &user, &pass, &host, &port, &path)
477 == -1)
478 goto cleanup_fetch_url;
479 portnum = strtol(port, NULL, 10);
480
481 if (urltype == FILE_URL_T && ! EMPTYSTRING(host)
482 && strcasecmp(host, "localhost") != 0) {
483 warnx("No support for non local file URL `%s'", url);
484 goto cleanup_fetch_url;
485 }
486
487 if (EMPTYSTRING(path)) {
488 if (urltype == FTP_URL_T) {
489 rval = fetch_ftp(url);
490 goto cleanup_fetch_url;
491 }
492 if (urltype != HTTP_URL_T || outfile == NULL) {
493 warnx("Invalid URL (no file after host) `%s'", url);
494 goto cleanup_fetch_url;
495 }
496 }
497
498 decodedpath = xstrdup(path);
499 url_decode(decodedpath);
500
501 if (outfile)
502 savefile = xstrdup(outfile);
503 else {
504 cp = strrchr(decodedpath, '/'); /* find savefile */
505 if (cp != NULL)
506 savefile = xstrdup(cp + 1);
507 else
508 savefile = xstrdup(decodedpath);
509 }
510 if (EMPTYSTRING(savefile)) {
511 if (urltype == FTP_URL_T) {
512 rval = fetch_ftp(url);
513 goto cleanup_fetch_url;
514 }
515 warnx("Invalid URL (no file after directory) `%s'", url);
516 goto cleanup_fetch_url;
517 } else {
518 if (debug)
519 fprintf(ttyout, "got savefile as `%s'\n", savefile);
520 }
521
522 filesize = -1;
523 mtime = -1;
524 if (urltype == FILE_URL_T) { /* file:// URLs */
525 struct stat sb;
526
527 direction = "copied";
528 fin = fopen(decodedpath, "r");
529 if (fin == NULL) {
530 warn("Cannot open file `%s'", decodedpath);
531 goto cleanup_fetch_url;
532 }
533 if (fstat(fileno(fin), &sb) == 0) {
534 mtime = sb.st_mtime;
535 filesize = sb.st_size;
536 }
537 if (verbose)
538 fprintf(ttyout, "Copying %s\n", decodedpath);
539 } else { /* ftp:// or http:// URLs */
540 if (proxyenv == NULL) {
541 if (urltype == HTTP_URL_T)
542 proxyenv = httpproxy;
543 else if (urltype == FTP_URL_T)
544 proxyenv = ftpproxy;
545 }
546 direction = "retrieved";
547 if (proxyenv != NULL) { /* use proxy */
548 url_t purltype;
549 char *phost, *ppath;
550 char *pport;
551
552 isproxy = 1;
553
554 /* check URL against list of no_proxied sites */
555 if (no_proxy != NULL) {
556 char *np, *np_copy;
557 long np_port;
558 size_t hlen, plen;
559
560 np_copy = xstrdup(no_proxy);
561 hlen = strlen(host);
562 while ((cp = strsep(&np_copy, " ,")) != NULL) {
563 if (*cp == '\0')
564 continue;
565 if ((np = strrchr(cp, ':')) != NULL) {
566 *np = '\0';
567 np_port =
568 strtol(np + 1, &ep, 10);
569 if (*ep != '\0')
570 continue;
571 if (portnum !=
572 htons((in_port_t)np_port))
573 continue;
574 }
575 plen = strlen(cp);
576 if (strncasecmp(host + hlen - plen,
577 cp, plen) == 0) {
578 isproxy = 0;
579 break;
580 }
581 }
582 FREEPTR(np_copy);
583 }
584
585 if (isproxy) {
586 if (parse_url(proxyenv, "proxy URL", &purltype,
587 &puser, &ppass, &phost, &pport, &ppath)
588 == -1)
589 goto cleanup_fetch_url;
590
591 if ((purltype != HTTP_URL_T
592 && purltype != FTP_URL_T) ||
593 EMPTYSTRING(phost) ||
594 (! EMPTYSTRING(ppath)
595 && strcmp(ppath, "/") != 0)) {
596 warnx("Malformed proxy URL `%s'",
597 proxyenv);
598 FREEPTR(phost);
599 FREEPTR(pport);
600 FREEPTR(ppath);
601 goto cleanup_fetch_url;
602 }
603
604 FREEPTR(host);
605 host = phost;
606 FREEPTR(port);
607 port = pport;
608 FREEPTR(path);
609 path = xstrdup(url);
610 FREEPTR(ppath);
611 }
612 } /* proxyenv != NULL */
613
614 #if 0
615 memset(&sin, 0, sizeof(sin));
616 sin.sin_family = AF_INET;
617
618 if (isdigit((unsigned char)host[0])) {
619 if (inet_aton(host, &sin.sin_addr) == 0) {
620 warnx("Invalid IP address `%s'", host);
621 goto cleanup_fetch_url;
622 }
623 } else {
624 hp = gethostbyname(host);
625 if (hp == NULL) {
626 warnx("%s: %s", host, hstrerror(h_errno));
627 goto cleanup_fetch_url;
628 }
629 if (hp->h_addrtype != AF_INET) {
630 warnx("`%s': not an Internet address?", host);
631 goto cleanup_fetch_url;
632 }
633 memcpy(&sin.sin_addr, hp->h_addr, hp->h_length);
634 }
635
636 if (port == NULL) {
637 warnx("Unknown port for URL `%s'", url);
638 goto cleanup_fetch_url;
639 }
640 sin.sin_port = portnum;
641
642 s = socket(AF_INET, SOCK_STREAM, 0);
643 if (s == -1) {
644 warn("Can't create socket");
645 goto cleanup_fetch_url;
646 }
647
648 while (xconnect(s, (struct sockaddr *)&sin,
649 sizeof(sin)) == -1) {
650 if (errno == EINTR)
651 continue;
652 if (hp && hp->h_addr_list[1]) {
653 int oerrno = errno;
654 char *ia;
655
656 ia = inet_ntoa(sin.sin_addr);
657 errno = oerrno;
658 warn("Connect to address `%s'", ia);
659 hp->h_addr_list++;
660 memcpy(&sin.sin_addr, hp->h_addr_list[0],
661 (size_t)hp->h_length);
662 if (verbose)
663 fprintf(ttyout, "Trying %s...\n",
664 inet_ntoa(sin.sin_addr));
665 (void)close(s);
666 s = socket(AF_INET, SOCK_STREAM, 0);
667 if (s < 0) {
668 warn("Can't create socket");
669 goto cleanup_fetch_url;
670 }
671 continue;
672 }
673 warn("Can't connect to `%s'", host);
674 goto cleanup_fetch_url;
675 }
676 #else
677 memset(&hints, 0, sizeof(hints));
678 hints.ai_flags = AI_CANONNAME;
679 hints.ai_family = AF_UNSPEC;
680 hints.ai_socktype = SOCK_STREAM;
681 hints.ai_protocol = 0;
682 error = getaddrinfo(host, port, &hints, &res);
683 if (error) {
684 warn(gai_strerror(error));
685 goto cleanup_fetch_url;
686 }
687 if (res->ai_canonname)
688 host = res->ai_canonname;
689
690 while (1) {
691 s = socket(res->ai_family,
692 res->ai_socktype, res->ai_protocol);
693 if (s < 0) {
694 warn("Can't create socket");
695 goto cleanup_fetch_url;
696 }
697
698 if (xconnect(s, res->ai_addr, res->ai_addrlen) < 0) {
699 char hbuf[MAXHOSTNAMELEN];
700 getnameinfo(res->ai_addr, res->ai_addrlen,
701 hbuf, sizeof(hbuf), NULL, 0,
702 NI_NUMERICHOST);
703 warn("Connect to address `%s'", hbuf);
704 close(s);
705 res = res->ai_next;
706 if (res) {
707 getnameinfo(res->ai_addr,
708 res->ai_addrlen, hbuf, sizeof(hbuf),
709 NULL, 0, NI_NUMERICHOST);
710 if (verbose)
711 fprintf(ttyout,
712 "Trying %s...\n", hbuf);
713 continue;
714 }
715 warn("Can't connect to %s", host);
716 goto cleanup_fetch_url;
717 }
718
719 break;
720 }
721 #endif
722
723
724 fin = fdopen(s, "r+");
725 /*
726 * Construct and send the request.
727 * Proxy requests don't want leading /.
728 */
729 if (isproxy) {
730 if (verbose)
731 fprintf(ttyout, "Requesting %s\n (via %s)\n",
732 url, proxyenv);
733 fprintf(fin, "GET %s HTTP/1.0\r\n", path);
734 if (flushcache)
735 fprintf(fin, "Pragma: no-cache\r\n");
736 } else {
737 struct utsname unam;
738
739 if (verbose)
740 fprintf(ttyout, "Requesting %s\n", url);
741 fprintf(fin, "GET %s HTTP/1.1\r\n", path);
742 fprintf(fin, "Host: %s:%s\r\n", host, port);
743 fprintf(fin, "Accept: */*\r\n");
744 if (uname(&unam) != -1) {
745 fprintf(fin, "User-Agent: %s-%s/ftp\r\n",
746 unam.sysname, unam.release);
747 }
748 fprintf(fin, "Connection: close\r\n");
749 if (flushcache)
750 fprintf(fin, "Cache-Control: no-cache\r\n");
751 }
752 if (wwwauth) {
753 if (verbose)
754 fprintf(ttyout, " (with authorization)\n");
755 fprintf(fin, "Authorization: %s\r\n", wwwauth);
756 }
757 if (proxyauth) {
758 if (verbose)
759 fprintf(ttyout,
760 " (with proxy authorization)\n");
761 fprintf(fin, "Proxy-Authorization: %s\r\n", proxyauth);
762 }
763 fprintf(fin, "\r\n");
764 if (fflush(fin) == EOF) {
765 warn("Writing HTTP request");
766 goto cleanup_fetch_url;
767 }
768
769 /* Read the response */
770 if ((buf = fparseln(fin, &len, NULL, "\0\0\0", 0)) == NULL) {
771 warn("Receiving HTTP reply");
772 goto cleanup_fetch_url;
773 }
774 while (len > 0 && (buf[len-1] == '\r' || buf[len-1] == '\n'))
775 buf[--len] = '\0';
776 if (debug)
777 fprintf(ttyout, "received `%s'\n", buf);
778
779 /* Determine HTTP response code */
780 cp = strchr(buf, ' ');
781 if (cp == NULL)
782 goto improper;
783 else
784 cp++;
785 hcode = strtol(cp, &ep, 10);
786 if (*ep != '\0' && !isspace((unsigned char)*ep))
787 goto improper;
788 message = xstrdup(cp);
789
790 /* Read the rest of the header. */
791 FREEPTR(buf);
792 while (1) {
793 if ((buf = fparseln(fin, &len, NULL, "\0\0\0", 0))
794 == NULL) {
795 warn("Receiving HTTP reply");
796 goto cleanup_fetch_url;
797 }
798 while (len > 0 &&
799 (buf[len-1] == '\r' || buf[len-1] == '\n'))
800 buf[--len] = '\0';
801 if (len == 0)
802 break;
803 if (debug)
804 fprintf(ttyout, "received `%s'\n", buf);
805
806 /* Look for some headers */
807 cp = buf;
808
809 #define CONTENTLEN "Content-Length: "
810 if (strncasecmp(cp, CONTENTLEN,
811 sizeof(CONTENTLEN) - 1) == 0) {
812 cp += sizeof(CONTENTLEN) - 1;
813 filesize = strtol(cp, &ep, 10);
814 if (filesize < 1 || *ep != '\0')
815 goto improper;
816 if (debug)
817 fprintf(ttyout,
818 #ifndef NO_QUAD
819 "parsed length as: %qd\n",
820 (long long)filesize);
821 #else
822 "parsed length as: %ld\n",
823 (long)filesize);
824 #endif
825
826 #define LASTMOD "Last-Modified: "
827 } else if (strncasecmp(cp, LASTMOD,
828 sizeof(LASTMOD) - 1) == 0) {
829 struct tm parsed;
830 char *t;
831
832 cp += sizeof(LASTMOD) - 1;
833 /* RFC 1123 */
834 if ((t = strptime(cp,
835 "%a, %d %b %Y %H:%M:%S GMT",
836 &parsed))
837 /* RFC 850 */
838 || (t = strptime(cp,
839 "%a, %d-%b-%y %H:%M:%S GMT",
840 &parsed))
841 /* asctime */
842 || (t = strptime(cp,
843 "%a, %b %d %H:%M:%S %Y",
844 &parsed))) {
845 parsed.tm_isdst = -1;
846 if (*t == '\0')
847 mtime = mkgmtime(&parsed);
848 if (debug && mtime != -1) {
849 fprintf(ttyout,
850 "parsed date as: %s",
851 ctime(&mtime));
852 }
853 }
854
855 #define LOCATION "Location: "
856 } else if (strncasecmp(cp, LOCATION,
857 sizeof(LOCATION) - 1) == 0) {
858 cp += sizeof(LOCATION) - 1;
859 location = xstrdup(cp);
860 if (debug)
861 fprintf(ttyout,
862 "parsed location as: %s\n", cp);
863
864 #define TRANSENC "Transfer-Encoding: "
865 } else if (strncasecmp(cp, TRANSENC,
866 sizeof(TRANSENC) - 1) == 0) {
867 cp += sizeof(TRANSENC) - 1;
868 if (strcasecmp(cp, "chunked") != 0) {
869 warnx(
870 "Unsupported transfer encoding - `%s'",
871 cp);
872 goto cleanup_fetch_url;
873 }
874 ischunked++;
875 if (debug)
876 fprintf(ttyout,
877 "using chunked encoding\n");
878
879 #define PROXYAUTH "Proxy-Authenticate: "
880 } else if (strncasecmp(cp, PROXYAUTH,
881 sizeof(PROXYAUTH) - 1) == 0) {
882 cp += sizeof(PROXYAUTH) - 1;
883 FREEPTR(auth);
884 auth = xstrdup(cp);
885 if (debug)
886 fprintf(ttyout,
887 "parsed proxy-auth as: %s\n", cp);
888
889 #define WWWAUTH "WWW-Authenticate: "
890 } else if (strncasecmp(cp, WWWAUTH,
891 sizeof(WWWAUTH) - 1) == 0) {
892 cp += sizeof(WWWAUTH) - 1;
893 FREEPTR(auth);
894 auth = xstrdup(cp);
895 if (debug)
896 fprintf(ttyout,
897 "parsed www-auth as: %s\n", cp);
898
899 }
900
901 }
902 /* finished parsing header */
903 FREEPTR(buf);
904
905 switch (hcode) {
906 case 200:
907 break;
908 case 300:
909 case 301:
910 case 302:
911 case 303:
912 case 305:
913 if (EMPTYSTRING(location)) {
914 warnx(
915 "No redirection Location provided by server");
916 goto cleanup_fetch_url;
917 }
918 if (redirect_loop++ > 5) {
919 warnx("Too many redirections requested");
920 goto cleanup_fetch_url;
921 }
922 if (hcode == 305) {
923 if (verbose)
924 fprintf(ttyout, "Redirected via %s\n",
925 location);
926 rval = fetch_url(url, location,
927 proxyauth, wwwauth);
928 } else {
929 if (verbose)
930 fprintf(ttyout, "Redirected to %s\n",
931 location);
932 rval = go_fetch(location);
933 }
934 goto cleanup_fetch_url;
935 case 401:
936 case 407:
937 {
938 char **authp;
939 char *auser, *apass;
940
941 fprintf(ttyout, "%s\n", message);
942 if (EMPTYSTRING(auth)) {
943 warnx(
944 "No authentication challenge provided by server");
945 goto cleanup_fetch_url;
946 }
947 if (hcode == 401) {
948 authp = &wwwauth;
949 auser = user;
950 apass = pass;
951 } else {
952 authp = &proxyauth;
953 auser = puser;
954 apass = ppass;
955 }
956 if (*authp != NULL) {
957 char reply[10];
958
959 fprintf(ttyout,
960 "Authorization failed. Retry (y/n)? ");
961 if (fgets(reply, sizeof(reply), stdin) != NULL
962 && tolower(reply[0]) != 'y')
963 goto cleanup_fetch_url;
964 auser = NULL;
965 apass = NULL;
966 }
967 if (auth_url(auth, authp, auser, apass) == 0) {
968 rval = fetch_url(url, proxyenv,
969 proxyauth, wwwauth);
970 memset(*authp, '\0', strlen(*authp));
971 FREEPTR(*authp);
972 }
973 goto cleanup_fetch_url;
974 }
975 default:
976 if (message)
977 warnx("Error retrieving file - `%s'", message);
978 else
979 warnx("Unknown error retrieving file");
980 goto cleanup_fetch_url;
981 }
982 } /* end of ftp:// or http:// specific setup */
983
984 oldintr = oldintp = NULL;
985
986 /* Open the output file. */
987 if (strcmp(savefile, "-") == 0) {
988 fout = stdout;
989 } else if (*savefile == '|') {
990 oldintp = signal(SIGPIPE, SIG_IGN);
991 fout = popen(savefile + 1, "w");
992 if (fout == NULL) {
993 warn("Can't run `%s'", savefile + 1);
994 goto cleanup_fetch_url;
995 }
996 closefunc = pclose;
997 } else {
998 fout = fopen(savefile, "w");
999 if (fout == NULL) {
1000 warn("Can't open `%s'", savefile);
1001 goto cleanup_fetch_url;
1002 }
1003 closefunc = fclose;
1004 }
1005
1006 /* Trap signals */
1007 if (setjmp(httpabort)) {
1008 if (oldintr)
1009 (void)signal(SIGINT, oldintr);
1010 if (oldintp)
1011 (void)signal(SIGPIPE, oldintp);
1012 goto cleanup_fetch_url;
1013 }
1014 oldintr = signal(SIGINT, aborthttp);
1015
1016 bytes = 0;
1017 hashbytes = mark;
1018 progressmeter(-1);
1019
1020 /* Finally, suck down the file. */
1021 buf = xmalloc(BUFSIZ + 1);
1022 do {
1023 ssize_t chunksize;
1024
1025 chunksize = 0;
1026 /* read chunksize */
1027 if (ischunked) {
1028 if (fgets(buf, BUFSIZ, fin) == NULL) {
1029 warnx("Unexpected EOF reading chunksize");
1030 goto cleanup_fetch_url;
1031 }
1032 chunksize = strtol(buf, &ep, 16);
1033 if (strcmp(ep, "\r\n") != 0) {
1034 warnx("Unexpected data following chunksize");
1035 goto cleanup_fetch_url;
1036 }
1037 if (debug)
1038 fprintf(ttyout,
1039 #ifndef NO_QUAD
1040 "got chunksize of %qd\n",
1041 (long long)chunksize);
1042 #else
1043 "got chunksize of %ld\n",
1044 (long)chunksize);
1045 #endif
1046 if (chunksize == 0)
1047 break;
1048 }
1049 /* transfer file or chunk */
1050 while (1) {
1051 struct timeval then, now, td;
1052 off_t bufrem;
1053
1054 (void)gettimeofday(&then, NULL);
1055 bufrem = rate_get ? rate_get : BUFSIZ;
1056 while (bufrem > 0) {
1057 len = fread(buf, sizeof(char),
1058 ischunked ? MIN(chunksize, bufrem) : BUFSIZ,
1059 fin);
1060 if (len <= 0)
1061 goto chunkdone;
1062 bytes += len;
1063 bufrem -= len;
1064 if (fwrite(buf, sizeof(char), len, fout)
1065 != len) {
1066 warn("Writing `%s'", savefile);
1067 goto cleanup_fetch_url;
1068 }
1069 }
1070 if (hash && !progress) {
1071 while (bytes >= hashbytes) {
1072 (void)putc('#', ttyout);
1073 hashbytes += mark;
1074 }
1075 (void)fflush(ttyout);
1076 }
1077 if (ischunked) {
1078 chunksize -= len;
1079 if (chunksize <= 0)
1080 goto chunkdone;
1081 }
1082 if (rate_get) {
1083 while (1) {
1084 (void)gettimeofday(&now, NULL);
1085 timersub(&now, &then, &td);
1086 if (td.tv_sec > 0)
1087 break;
1088 usleep(1000000 - td.tv_usec);
1089 }
1090 }
1091 }
1092 /* read CRLF after chunk*/
1093 chunkdone:
1094 if (ischunked) {
1095 if (fgets(buf, BUFSIZ, fin) == NULL)
1096 break;
1097 if (strcmp(buf, "\r\n") != 0) {
1098 warnx("Unexpected data following chunk");
1099 goto cleanup_fetch_url;
1100 }
1101 }
1102 } while (ischunked);
1103 if (hash && !progress && bytes > 0) {
1104 if (bytes < mark)
1105 (void)putc('#', ttyout);
1106 (void)putc('\n', ttyout);
1107 }
1108 if (ferror(fin)) {
1109 warn("Reading file");
1110 goto cleanup_fetch_url;
1111 }
1112 progressmeter(1);
1113 (void)fflush(fout);
1114 (void)signal(SIGINT, oldintr);
1115 if (oldintp)
1116 (void)signal(SIGPIPE, oldintp);
1117 if (closefunc == fclose && mtime != -1) {
1118 struct timeval tval[2];
1119
1120 (void)gettimeofday(&tval[0], NULL);
1121 tval[1].tv_sec = mtime;
1122 tval[1].tv_usec = 0;
1123 (*closefunc)(fout);
1124 fout = NULL;
1125
1126 if (utimes(savefile, tval) == -1) {
1127 fprintf(ttyout,
1128 "Can't change modification time to %s",
1129 asctime(localtime(&mtime)));
1130 }
1131 }
1132 if (bytes > 0)
1133 ptransfer(0);
1134
1135 rval = 0;
1136 goto cleanup_fetch_url;
1137
1138 improper:
1139 warnx("Improper response from `%s'", host);
1140
1141 cleanup_fetch_url:
1142 resetsockbufsize();
1143 if (fin != NULL)
1144 fclose(fin);
1145 else if (s != -1)
1146 close(s);
1147 if (closefunc != NULL && fout != NULL)
1148 (*closefunc)(fout);
1149 FREEPTR(savefile);
1150 FREEPTR(user);
1151 FREEPTR(pass);
1152 FREEPTR(host);
1153 FREEPTR(port);
1154 FREEPTR(path);
1155 FREEPTR(decodedpath);
1156 FREEPTR(puser);
1157 FREEPTR(ppass);
1158 FREEPTR(buf);
1159 FREEPTR(auth);
1160 FREEPTR(location);
1161 FREEPTR(message);
1162 return (rval);
1163 }
1164
1165 /*
1166 * Abort a HTTP retrieval
1167 */
1168 void
1169 aborthttp(notused)
1170 int notused;
1171 {
1172
1173 alarmtimer(0);
1174 fputs("\nHTTP fetch aborted.\n", ttyout);
1175 longjmp(httpabort, 1);
1176 }
1177
1178 /*
1179 * Retrieve ftp URL or classic ftp argument using FTP.
1180 * Returns 1 on failure, 0 on completed xfer, -1 if ftp connection
1181 * is still open (e.g, ftp xfer with trailing /)
1182 */
1183 static int
1184 fetch_ftp(url)
1185 const char *url;
1186 {
1187 char *cp, *xargv[5], rempath[MAXPATHLEN];
1188 char *host, *path, *dir, *file, *user, *pass;
1189 char *port;
1190 int dirhasglob, filehasglob, oautologin, rval, type, xargc;
1191 url_t urltype;
1192
1193 host = path = dir = file = user = pass = NULL;
1194 port = NULL;
1195 rval = 1;
1196 type = TYPE_I;
1197
1198 if (strncasecmp(url, FTP_URL, sizeof(FTP_URL) - 1) == 0) {
1199 if ((parse_url(url, "URL", &urltype, &user, &pass,
1200 &host, &port, &path) == -1) ||
1201 (user != NULL && *user == '\0') ||
1202 (pass != NULL && *pass == '\0') ||
1203 EMPTYSTRING(host)) {
1204 warnx("Invalid URL `%s'", url);
1205 goto cleanup_fetch_ftp;
1206 }
1207 url_decode(user);
1208 url_decode(pass);
1209 /*
1210 * Note: Don't url_decode(path) here. We need to keep the
1211 * distinction between "/" and "%2F" until later.
1212 */
1213
1214 /* check for trailing ';type=[aid]' */
1215 if (! EMPTYSTRING(path) && (cp = strrchr(path, ';')) != NULL) {
1216 if (strcasecmp(cp, ";type=a") == 0)
1217 type = TYPE_A;
1218 else if (strcasecmp(cp, ";type=i") == 0)
1219 type = TYPE_I;
1220 else if (strcasecmp(cp, ";type=d") == 0) {
1221 warnx(
1222 "Directory listing via a URL is not supported");
1223 goto cleanup_fetch_ftp;
1224 } else {
1225 warnx("Invalid suffix `%s' in URL `%s'", cp,
1226 url);
1227 goto cleanup_fetch_ftp;
1228 }
1229 *cp = 0;
1230 }
1231 } else { /* classic style `host:file' */
1232 urltype = CLASSIC_URL_T;
1233 host = xstrdup(url);
1234 cp = strchr(host, ':');
1235 if (cp != NULL) {
1236 *cp = '\0';
1237 path = xstrdup(cp + 1);
1238 }
1239 }
1240 if (EMPTYSTRING(host))
1241 goto cleanup_fetch_ftp;
1242
1243 /* Extract the file and (if present) directory name. */
1244 dir = path;
1245 if (! EMPTYSTRING(dir)) {
1246 /*
1247 * If we are dealing with classic `host:path' syntax,
1248 * then a path of the form `/file' (resulting from
1249 * input of the form `host:/file') means that we should
1250 * do "CWD /" before retrieving the file. So we set
1251 * dir="/" and file="file".
1252 *
1253 * But if we are dealing with URLs like
1254 * `ftp://host/path' then a path of the form `/file'
1255 * (resulting from a URL of the form `ftp://host//file')
1256 * means that we should do `CWD ' (with an empty
1257 * argument) before retrieving the file. So we set
1258 * dir="" and file="file".
1259 *
1260 * If the path does not contain / at all, we set
1261 * dir=NULL. (We get a path without any slashes if
1262 * we are dealing with classic `host:file' or URL
1263 * `ftp://host/file'.)
1264 *
1265 * In all other cases, we set dir to a string that does
1266 * not include the final '/' that separates the dir part
1267 * from the file part of the path. (This will be the
1268 * empty string if and only if we are dealing with a
1269 * path of the form `/file' resulting from an URL of the
1270 * form `ftp://host//file'.)
1271 */
1272 cp = strrchr(dir, '/');
1273 if (cp == dir && urltype == CLASSIC_URL_T) {
1274 file = cp + 1;
1275 dir = "/";
1276 } else if (cp != NULL) {
1277 *cp++ = '\0';
1278 file = cp;
1279 } else {
1280 file = dir;
1281 dir = NULL;
1282 }
1283 } else
1284 dir = NULL;
1285 if (urltype == FTP_URL_T && file != NULL) {
1286 url_decode(file);
1287 /* but still don't url_decode(dir) */
1288 }
1289 if (debug)
1290 fprintf(ttyout,
1291 "fetch_ftp: user `%s' pass `%s' host %s:%s path `%s' dir `%s' file `%s'\n",
1292 user ? user : "<null>", pass ? pass : "<null>",
1293 host ? host : "<null>", port ? port : "<null>",
1294 path ? path : "<null>",
1295 dir ? dir : "<null>", file ? file : "<null>");
1296
1297 dirhasglob = filehasglob = 0;
1298 if (doglob && urltype == CLASSIC_URL_T) {
1299 if (! EMPTYSTRING(dir) && strpbrk(dir, "*?[]{}") != NULL)
1300 dirhasglob = 1;
1301 if (! EMPTYSTRING(file) && strpbrk(file, "*?[]{}") != NULL)
1302 filehasglob = 1;
1303 }
1304
1305 /* Set up the connection */
1306 if (connected)
1307 disconnect(0, NULL);
1308 xargv[0] = __progname;
1309 xargv[1] = host;
1310 xargv[2] = NULL;
1311 xargc = 2;
1312 if (port) {
1313 xargv[2] = port;
1314 xargv[3] = NULL;
1315 xargc = 3;
1316 }
1317 oautologin = autologin;
1318 if (user != NULL)
1319 autologin = 0;
1320 setpeer(xargc, xargv);
1321 autologin = oautologin;
1322 if ((connected == 0) || ((connected == 1)
1323 && !ftp_login(host, user, pass))) {
1324 warnx("Can't connect or login to host `%s'", host);
1325 goto cleanup_fetch_ftp;
1326 }
1327
1328 switch (type) {
1329 case TYPE_A:
1330 setascii(0, NULL);
1331 break;
1332 case TYPE_I:
1333 setbinary(0, NULL);
1334 break;
1335 default:
1336 errx(1, "fetch_ftp: unknown transfer type %d\n", type);
1337 }
1338
1339 /*
1340 * Change directories, if necessary.
1341 *
1342 * Note: don't use EMPTYSTRING(dir) below, because
1343 * dir=="" means something different from dir==NULL.
1344 */
1345 if (dir != NULL && !dirhasglob) {
1346 char *nextpart;
1347
1348 /*
1349 * If we are dealing with a classic `host:path' (urltype
1350 * is CLASSIC_URL_T) then we have a raw directory
1351 * name (not encoded in any way) and we can change
1352 * directories in one step.
1353 *
1354 * If we are dealing with an `ftp://host/path' URL
1355 * (urltype is FTP_URL_T), then RFC 1738 says we need to
1356 * send a separate CWD command for each unescaped "/"
1357 * in the path, and we have to interpret %hex escaping
1358 * *after* we find the slashes. It's possible to get
1359 * empty components here, (from multiple adjacent
1360 * slashes in the path) and RFC 1738 says that we should
1361 * still do `CWD ' (with a null argument) in such cases.
1362 *
1363 * Many ftp servers don't support `CWD ', so if there's an
1364 * error performing that command, bail out with a descriptive
1365 * message.
1366 *
1367 * Examples:
1368 *
1369 * host: dir="", urltype=CLASSIC_URL_T
1370 * logged in (to default directory)
1371 * host:file dir=NULL, urltype=CLASSIC_URL_T
1372 * "RETR file"
1373 * host:dir/ dir="dir", urltype=CLASSIC_URL_T
1374 * "CWD dir", logged in
1375 * ftp://host/ dir="", urltype=FTP_URL_T
1376 * logged in (to default directory)
1377 * ftp://host/dir/ dir="dir", urltype=FTP_URL_T
1378 * "CWD dir", logged in
1379 * ftp://host/file dir=NULL, urltype=FTP_URL_T
1380 * "RETR file"
1381 * ftp://host//file dir="", urltype=FTP_URL_T
1382 * "CWD ", "RETR file"
1383 * host:/file dir="/", urltype=CLASSIC_URL_T
1384 * "CWD /", "RETR file"
1385 * ftp://host///file dir="/", urltype=FTP_URL_T
1386 * "CWD ", "CWD ", "RETR file"
1387 * ftp://host/%2F/file dir="%2F", urltype=FTP_URL_T
1388 * "CWD /", "RETR file"
1389 * ftp://host/foo/file dir="foo", urltype=FTP_URL_T
1390 * "CWD foo", "RETR file"
1391 * ftp://host/foo/bar/file dir="foo/bar"
1392 * "CWD foo", "CWD bar", "RETR file"
1393 * ftp://host//foo/bar/file dir="/foo/bar"
1394 * "CWD ", "CWD foo", "CWD bar", "RETR file"
1395 * ftp://host/foo//bar/file dir="foo//bar"
1396 * "CWD foo", "CWD ", "CWD bar", "RETR file"
1397 * ftp://host/%2F/foo/bar/file dir="%2F/foo/bar"
1398 * "CWD /", "CWD foo", "CWD bar", "RETR file"
1399 * ftp://host/%2Ffoo/bar/file dir="%2Ffoo/bar"
1400 * "CWD /foo", "CWD bar", "RETR file"
1401 * ftp://host/%2Ffoo%2Fbar/file dir="%2Ffoo%2Fbar"
1402 * "CWD /foo/bar", "RETR file"
1403 * ftp://host/%2Ffoo%2Fbar%2Ffile dir=NULL
1404 * "RETR /foo/bar/file"
1405 *
1406 * Note that we don't need `dir' after this point.
1407 */
1408 do {
1409 if (urltype == FTP_URL_T) {
1410 nextpart = strchr(dir, '/');
1411 if (nextpart) {
1412 *nextpart = '\0';
1413 nextpart++;
1414 }
1415 url_decode(dir);
1416 } else
1417 nextpart = NULL;
1418 if (debug)
1419 fprintf(ttyout, "dir `%s', nextpart `%s'\n",
1420 dir ? dir : "<null>",
1421 nextpart ? nextpart : "<null>");
1422 if (urltype == FTP_URL_T || *dir != '\0') {
1423 xargv[0] = "cd";
1424 xargv[1] = dir;
1425 xargv[2] = NULL;
1426 dirchange = 0;
1427 cd(2, xargv);
1428 if (! dirchange) {
1429 if (*dir == '\0' && code == 500)
1430 fprintf(stderr,
1431 "\n"
1432 "ftp: The `CWD ' command (without a directory), which is required by\n"
1433 " RFC 1738 to support the empty directory in the URL pathname (`//'),\n"
1434 " conflicts with the server's conformance to RFC 959.\n"
1435 " Try the same URL without the `//' in the URL pathname.\n"
1436 "\n");
1437 goto cleanup_fetch_ftp;
1438 }
1439 }
1440 dir = nextpart;
1441 } while (dir != NULL);
1442 }
1443
1444 if (EMPTYSTRING(file)) {
1445 rval = -1;
1446 goto cleanup_fetch_ftp;
1447 }
1448
1449 if (dirhasglob) {
1450 snprintf(rempath, sizeof(rempath), "%s/%s", dir, file);
1451 file = rempath;
1452 }
1453
1454 /* Fetch the file(s). */
1455 xargc = 2;
1456 xargv[0] = "get";
1457 xargv[1] = file;
1458 xargv[2] = NULL;
1459 if (dirhasglob || filehasglob) {
1460 int ointeractive;
1461
1462 ointeractive = interactive;
1463 interactive = 0;
1464 xargv[0] = "mget";
1465 mget(xargc, xargv);
1466 interactive = ointeractive;
1467 } else {
1468 if (outfile == NULL) {
1469 cp = strrchr(file, '/'); /* find savefile */
1470 if (cp != NULL)
1471 outfile = cp + 1;
1472 else
1473 outfile = file;
1474 }
1475 xargv[2] = (char *)outfile;
1476 xargv[3] = NULL;
1477 xargc++;
1478 if (restartautofetch)
1479 reget(xargc, xargv);
1480 else
1481 get(xargc, xargv);
1482 }
1483
1484 if ((code / 100) == COMPLETE)
1485 rval = 0;
1486
1487 cleanup_fetch_ftp:
1488 FREEPTR(host);
1489 FREEPTR(path);
1490 FREEPTR(user);
1491 FREEPTR(pass);
1492 return (rval);
1493 }
1494
1495 /*
1496 * Retrieve the given file to outfile.
1497 * Supports arguments of the form:
1498 * "host:path", "ftp://host/path" if $ftpproxy, call fetch_url() else
1499 * call fetch_ftp()
1500 * "http://host/path" call fetch_url() to use HTTP
1501 * "file:///path" call fetch_url() to copy
1502 * "about:..." print a message
1503 *
1504 * Returns 1 on failure, 0 on completed xfer, -1 if ftp connection
1505 * is still open (e.g, ftp xfer with trailing /)
1506 */
1507 static int
1508 go_fetch(url)
1509 const char *url;
1510 {
1511
1512 #ifndef NO_ABOUT
1513 /*
1514 * Check for about:*
1515 */
1516 if (strncasecmp(url, ABOUT_URL, sizeof(ABOUT_URL) - 1) == 0) {
1517 url += sizeof(ABOUT_URL) -1;
1518 if (strcasecmp(url, "ftp") == 0) {
1519 fprintf(ttyout, "%s\n%s\n",
1520 "This version of ftp has been enhanced by Luke Mewburn <lukem (at) netbsd.org>.",
1521 "Execute `man ftp' for more details");
1522 } else if (strcasecmp(url, "netbsd") == 0) {
1523 fprintf(ttyout, "%s\n%s\n",
1524 "NetBSD is a freely available and redistributable UNIX-like operating system.",
1525 "For more information, see http://www.netbsd.org/index.html");
1526 } else {
1527 fprintf(ttyout, "`%s' is an interesting topic.\n", url);
1528 }
1529 return (0);
1530 }
1531 #endif /* NO_ABOUT */
1532
1533 /*
1534 * Check for file:// and http:// URLs.
1535 */
1536 if (strncasecmp(url, HTTP_URL, sizeof(HTTP_URL) - 1) == 0 ||
1537 strncasecmp(url, FILE_URL, sizeof(FILE_URL) - 1) == 0)
1538 return (fetch_url(url, NULL, NULL, NULL));
1539
1540 /*
1541 * Try FTP URL-style and host:file arguments next.
1542 * If ftpproxy is set with an FTP URL, use fetch_url()
1543 * Othewise, use fetch_ftp().
1544 */
1545 if (ftpproxy && strncasecmp(url, FTP_URL, sizeof(FTP_URL) - 1) == 0)
1546 return (fetch_url(url, NULL, NULL, NULL));
1547
1548 return (fetch_ftp(url));
1549 }
1550
1551 /*
1552 * Retrieve multiple files from the command line,
1553 * calling go_fetch() for each file.
1554 *
1555 * If an ftp path has a trailing "/", the path will be cd-ed into and
1556 * the connection remains open, and the function will return -1
1557 * (to indicate the connection is alive).
1558 * If an error occurs the return value will be the offset+1 in
1559 * argv[] of the file that caused a problem (i.e, argv[x]
1560 * returns x+1)
1561 * Otherwise, 0 is returned if all files retrieved successfully.
1562 */
1563 int
1564 auto_fetch(argc, argv)
1565 int argc;
1566 char *argv[];
1567 {
1568 volatile int argpos;
1569 int rval;
1570
1571 argpos = 0;
1572
1573 if (setjmp(toplevel)) {
1574 if (connected)
1575 disconnect(0, NULL);
1576 return (argpos + 1);
1577 }
1578 (void)signal(SIGINT, (sig_t)intr);
1579 (void)signal(SIGPIPE, (sig_t)lostpeer);
1580
1581 /*
1582 * Loop through as long as there's files to fetch.
1583 */
1584 for (rval = 0; (rval == 0) && (argpos < argc); argpos++) {
1585 if (strchr(argv[argpos], ':') == NULL)
1586 break;
1587 redirect_loop = 0;
1588 anonftp = 1; /* Handle "automatic" transfers. */
1589 rval = go_fetch(argv[argpos]);
1590 if (outfile != NULL && strcmp(outfile, "-") != 0
1591 && outfile[0] != '|')
1592 outfile = NULL;
1593 if (rval > 0)
1594 rval = argpos + 1;
1595 }
1596
1597 if (connected && rval != -1)
1598 disconnect(0, NULL);
1599 return (rval);
1600 }
1601