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