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