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