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