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