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