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