fetch.c revision 1.98 1 /* $NetBSD: fetch.c,v 1.98 1999/12/03 06:10:01 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.98 1999/12/03 06:10:01 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
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, *res0 = NULL;
455 int error;
456 const char *reason;
457 char hbuf[NI_MAXHOST];
458 #else
459 struct sockaddr_in sin;
460 struct hostent *hp = NULL;
461 #endif
462 volatile sig_t 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 #ifndef NI_NUMERICHOST
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 reason = NULL;
742 s = -1;
743 for (res = res0; res; res = res->ai_next) {
744 if (getnameinfo(res->ai_addr, res->ai_addrlen,
745 hbuf, sizeof(hbuf), NULL, 0,
746 NI_NUMERICHOST) != 0)
747 strncpy(hbuf, "invalid", sizeof(hbuf));
748
749 if (verbose && res != res0)
750 fprintf(ttyout, "Trying %s...\n", hbuf);
751
752 s = socket(res->ai_family, res->ai_socktype,
753 res->ai_protocol);
754 if (s < 0) {
755 reason = "socket";
756 warn("Can't create socket");
757 continue;
758 }
759
760 if (xconnect(s, res->ai_addr, res->ai_addrlen) < 0) {
761 reason = "connect";
762 warn("Connect to address `%s'", hbuf);
763 close(s);
764 s = -1;
765 continue;
766 }
767
768 /* success */
769 break;
770 }
771 freeaddrinfo(res0);
772
773 if (s < 0) {
774 warn("Can't connect to %s", host);
775 goto cleanup_fetch_url;
776 }
777 #endif
778
779 fin = fdopen(s, "r+");
780 /*
781 * Construct and send the request.
782 */
783 if (verbose)
784 fprintf(ttyout, "Requesting %s\n", url);
785 leading = " (";
786 hasleading = 0;
787 if (isproxy) {
788 if (verbose) {
789 fprintf(ttyout, "%svia %s:%s", leading,
790 host, port);
791 leading = ", ";
792 hasleading++;
793 }
794 fprintf(fin, "GET %s HTTP/1.0\r\n", path);
795 if (flushcache)
796 fprintf(fin, "Pragma: no-cache\r\n");
797 } else {
798 fprintf(fin, "GET %s HTTP/1.1\r\n", path);
799 fprintf(fin, "Host: %s:%d\r\n", host, portnum);
800 fprintf(fin, "Accept: */*\r\n");
801 fprintf(fin, "Connection: close\r\n");
802 if (restart_point) {
803 fputs(leading, ttyout);
804 #ifndef NO_QUAD
805 fprintf(fin, "Range: bytes=%lld-\r\n",
806 (long long)restart_point);
807 fprintf(ttyout, "restarting at %lld",
808 (long long)restart_point);
809 #else
810 fprintf(fin, "Range: bytes=%ld-\r\n",
811 (long)restart_point);
812 fprintf(ttyout, "restarting at %ld",
813 (long)restart_point);
814 #endif
815 leading = ", ";
816 hasleading++;
817 }
818 if (flushcache)
819 fprintf(fin, "Cache-Control: no-cache\r\n");
820 }
821 fprintf(fin, "User-Agent: %s/%s\r\n", FTP_PRODUCT, FTP_VERSION);
822 if (wwwauth) {
823 if (verbose) {
824 fprintf(ttyout, "%swith authorization",
825 leading);
826 leading = ", ";
827 hasleading++;
828 }
829 fprintf(fin, "Authorization: %s\r\n", wwwauth);
830 }
831 if (proxyauth) {
832 if (verbose) {
833 fprintf(ttyout,
834 "%swith proxy authorization", leading);
835 leading = ", ";
836 hasleading++;
837 }
838 fprintf(fin, "Proxy-Authorization: %s\r\n", proxyauth);
839 }
840 if (verbose && hasleading)
841 fputs(")\n", ttyout);
842 fprintf(fin, "\r\n");
843 if (fflush(fin) == EOF) {
844 warn("Writing HTTP request");
845 goto cleanup_fetch_url;
846 }
847
848 /* Read the response */
849 if ((buf = fparseln(fin, &len, NULL, "\0\0\0", 0)) == NULL) {
850 warn("Receiving HTTP reply");
851 goto cleanup_fetch_url;
852 }
853 while (len > 0 && (buf[len-1] == '\r' || buf[len-1] == '\n'))
854 buf[--len] = '\0';
855 if (debug)
856 fprintf(ttyout, "received `%s'\n", buf);
857
858 /* Determine HTTP response code */
859 cp = strchr(buf, ' ');
860 if (cp == NULL)
861 goto improper;
862 else
863 cp++;
864 hcode = strtol(cp, &ep, 10);
865 if (*ep != '\0' && !isspace((unsigned char)*ep))
866 goto improper;
867 message = xstrdup(cp);
868
869 /* Read the rest of the header. */
870 FREEPTR(buf);
871 while (1) {
872 if ((buf = fparseln(fin, &len, NULL, "\0\0\0", 0))
873 == NULL) {
874 warn("Receiving HTTP reply");
875 goto cleanup_fetch_url;
876 }
877 while (len > 0 &&
878 (buf[len-1] == '\r' || buf[len-1] == '\n'))
879 buf[--len] = '\0';
880 if (len == 0)
881 break;
882 if (debug)
883 fprintf(ttyout, "received `%s'\n", buf);
884
885 /* Look for some headers */
886 cp = buf;
887
888 #define CONTENTLEN "Content-Length: "
889 if (strncasecmp(cp, CONTENTLEN,
890 sizeof(CONTENTLEN) - 1) == 0) {
891 cp += sizeof(CONTENTLEN) - 1;
892 #ifndef NO_QUAD
893 filesize = strtoq(cp, &ep, 10);
894 #else
895 filesize = strtol(cp, &ep, 10);
896 #endif
897 if (filesize < 0 || *ep != '\0')
898 goto improper;
899 if (debug)
900 #ifndef NO_QUAD
901 fprintf(ttyout, "parsed len as: %lld\n",
902 (long long)filesize);
903 #else
904 fprintf(ttyout, "parsed len as: %ld\n",
905 (long)filesize);
906 #endif
907
908 #define CONTENTRANGE "Content-Range: bytes "
909 } else if (strncasecmp(cp, CONTENTRANGE,
910 sizeof(CONTENTRANGE) - 1) == 0) {
911 cp += sizeof(CONTENTRANGE) - 1;
912 #ifndef NO_QUAD
913 rangestart = strtoq(cp, &ep, 10);
914 #else
915 rangestart = strtol(cp, &ep, 10);
916 #endif
917 if (rangestart < 0 || *ep != '-')
918 goto improper;
919 cp = ep + 1;
920
921 #ifndef NO_QUAD
922 rangeend = strtoq(cp, &ep, 10);
923 #else
924 rangeend = strtol(cp, &ep, 10);
925 #endif
926 if (rangeend < 0 || *ep != '/' ||
927 rangeend < rangestart)
928 goto improper;
929 cp = ep + 1;
930
931 #ifndef NO_QUAD
932 entitylen = strtoq(cp, &ep, 10);
933 #else
934 entitylen = strtol(cp, &ep, 10);
935 #endif
936 if (entitylen < 0 || *ep != '\0')
937 goto improper;
938
939 if (debug)
940 #ifndef NO_QUAD
941 fprintf(ttyout,
942 "parsed range as: %lld-%lld/%lld\n",
943 (long long)rangestart,
944 (long long)rangeend,
945 (long long)entitylen);
946 #else
947 fprintf(ttyout,
948 "parsed range as: %ld-%ld/%ld\n",
949 (long)rangestart,
950 (long)rangeend,
951 (long)entitylen);
952 #endif
953 if (! restart_point) {
954 warnx(
955 "Received unexpected Content-Range header");
956 goto cleanup_fetch_url;
957 }
958
959 #define LASTMOD "Last-Modified: "
960 } else if (strncasecmp(cp, LASTMOD,
961 sizeof(LASTMOD) - 1) == 0) {
962 struct tm parsed;
963 char *t;
964
965 cp += sizeof(LASTMOD) - 1;
966 /* RFC 1123 */
967 if ((t = strptime(cp,
968 "%a, %d %b %Y %H:%M:%S GMT",
969 &parsed))
970 /* RFC 850 */
971 || (t = strptime(cp,
972 "%a, %d-%b-%y %H:%M:%S GMT",
973 &parsed))
974 /* asctime */
975 || (t = strptime(cp,
976 "%a, %b %d %H:%M:%S %Y",
977 &parsed))) {
978 parsed.tm_isdst = -1;
979 if (*t == '\0')
980 mtime = timegm(&parsed);
981 if (debug && mtime != -1) {
982 fprintf(ttyout,
983 "parsed date as: %s",
984 ctime(&mtime));
985 }
986 }
987
988 #define LOCATION "Location: "
989 } else if (strncasecmp(cp, LOCATION,
990 sizeof(LOCATION) - 1) == 0) {
991 cp += sizeof(LOCATION) - 1;
992 location = xstrdup(cp);
993 if (debug)
994 fprintf(ttyout,
995 "parsed location as: %s\n", cp);
996
997 #define TRANSENC "Transfer-Encoding: "
998 } else if (strncasecmp(cp, TRANSENC,
999 sizeof(TRANSENC) - 1) == 0) {
1000 cp += sizeof(TRANSENC) - 1;
1001 if (strcasecmp(cp, "chunked") != 0) {
1002 warnx(
1003 "Unsupported transfer encoding - `%s'",
1004 cp);
1005 goto cleanup_fetch_url;
1006 }
1007 ischunked++;
1008 if (debug)
1009 fprintf(ttyout,
1010 "using chunked encoding\n");
1011
1012 #define PROXYAUTH "Proxy-Authenticate: "
1013 } else if (strncasecmp(cp, PROXYAUTH,
1014 sizeof(PROXYAUTH) - 1) == 0) {
1015 cp += sizeof(PROXYAUTH) - 1;
1016 FREEPTR(auth);
1017 auth = xstrdup(cp);
1018 if (debug)
1019 fprintf(ttyout,
1020 "parsed proxy-auth as: %s\n", cp);
1021
1022 #define WWWAUTH "WWW-Authenticate: "
1023 } else if (strncasecmp(cp, WWWAUTH,
1024 sizeof(WWWAUTH) - 1) == 0) {
1025 cp += sizeof(WWWAUTH) - 1;
1026 FREEPTR(auth);
1027 auth = xstrdup(cp);
1028 if (debug)
1029 fprintf(ttyout,
1030 "parsed www-auth as: %s\n", cp);
1031
1032 }
1033
1034 }
1035 /* finished parsing header */
1036 FREEPTR(buf);
1037
1038 switch (hcode) {
1039 case 200:
1040 break;
1041 case 206:
1042 if (! restart_point) {
1043 warnx("Not expecting partial content header");
1044 goto cleanup_fetch_url;
1045 }
1046 break;
1047 case 300:
1048 case 301:
1049 case 302:
1050 case 303:
1051 case 305:
1052 if (EMPTYSTRING(location)) {
1053 warnx(
1054 "No redirection Location provided by server");
1055 goto cleanup_fetch_url;
1056 }
1057 if (redirect_loop++ > 5) {
1058 warnx("Too many redirections requested");
1059 goto cleanup_fetch_url;
1060 }
1061 if (hcode == 305) {
1062 if (verbose)
1063 fprintf(ttyout, "Redirected via %s\n",
1064 location);
1065 rval = fetch_url(url, location,
1066 proxyauth, wwwauth);
1067 } else {
1068 if (verbose)
1069 fprintf(ttyout, "Redirected to %s\n",
1070 location);
1071 rval = go_fetch(location);
1072 }
1073 goto cleanup_fetch_url;
1074 case 401:
1075 case 407:
1076 {
1077 char **authp;
1078 char *auser, *apass;
1079
1080 fprintf(ttyout, "%s\n", message);
1081 if (EMPTYSTRING(auth)) {
1082 warnx(
1083 "No authentication challenge provided by server");
1084 goto cleanup_fetch_url;
1085 }
1086 if (hcode == 401) {
1087 authp = &wwwauth;
1088 auser = user;
1089 apass = pass;
1090 } else {
1091 authp = &proxyauth;
1092 auser = puser;
1093 apass = ppass;
1094 }
1095 if (*authp != NULL) {
1096 char reply[10];
1097
1098 fprintf(ttyout,
1099 "Authorization failed. Retry (y/n)? ");
1100 if (fgets(reply, sizeof(reply), stdin)
1101 == NULL) {
1102 clearerr(stdin);
1103 goto cleanup_fetch_url;
1104 } else {
1105 if (tolower(reply[0]) != 'y')
1106 goto cleanup_fetch_url;
1107 }
1108 auser = NULL;
1109 apass = NULL;
1110 }
1111 if (auth_url(auth, authp, auser, apass) == 0) {
1112 rval = fetch_url(url, proxyenv,
1113 proxyauth, wwwauth);
1114 memset(*authp, 0, strlen(*authp));
1115 FREEPTR(*authp);
1116 }
1117 goto cleanup_fetch_url;
1118 }
1119 default:
1120 if (message)
1121 warnx("Error retrieving file - `%s'", message);
1122 else
1123 warnx("Unknown error retrieving file");
1124 goto cleanup_fetch_url;
1125 }
1126 } /* end of ftp:// or http:// specific setup */
1127
1128 /* Open the output file. */
1129 if (strcmp(savefile, "-") == 0) {
1130 fout = stdout;
1131 } else if (*savefile == '|') {
1132 oldintp = xsignal(SIGPIPE, SIG_IGN);
1133 fout = popen(savefile + 1, "w");
1134 if (fout == NULL) {
1135 warn("Can't run `%s'", savefile + 1);
1136 goto cleanup_fetch_url;
1137 }
1138 closefunc = pclose;
1139 } else {
1140 if (restart_point){
1141 if (entitylen != -1)
1142 filesize = entitylen;
1143 if (rangestart != -1 && rangestart != restart_point) {
1144 warnx(
1145 "Size of `%s' differs from save file `%s'",
1146 url, savefile);
1147 goto cleanup_fetch_url;
1148 }
1149 fout = fopen(savefile, "a");
1150 } else
1151 fout = fopen(savefile, "w");
1152 if (fout == NULL) {
1153 warn("Can't open `%s'", savefile);
1154 goto cleanup_fetch_url;
1155 }
1156 closefunc = fclose;
1157 }
1158
1159 /* Trap signals */
1160 if (sigsetjmp(httpabort, 1))
1161 goto cleanup_fetch_url;
1162 (void)xsignal(SIGQUIT, psummary);
1163 oldintr = xsignal(SIGINT, aborthttp);
1164
1165 if (rcvbuf_size > bufsize) {
1166 if (xferbuf)
1167 (void)free(xferbuf);
1168 bufsize = rcvbuf_size;
1169 xferbuf = xmalloc(bufsize);
1170 }
1171
1172 bytes = 0;
1173 hashbytes = mark;
1174 progressmeter(-1);
1175
1176 /* Finally, suck down the file. */
1177 do {
1178 long chunksize;
1179
1180 chunksize = 0;
1181 /* read chunksize */
1182 if (ischunked) {
1183 if (fgets(xferbuf, bufsize, fin) == NULL) {
1184 warnx("Unexpected EOF reading chunksize");
1185 goto cleanup_fetch_url;
1186 }
1187 chunksize = strtol(xferbuf, &ep, 16);
1188 if (strcmp(ep, "\r\n") != 0) {
1189 warnx("Unexpected data following chunksize");
1190 goto cleanup_fetch_url;
1191 }
1192 if (debug)
1193 fprintf(ttyout,
1194 #ifndef NO_QUAD
1195 "got chunksize of %lld\n",
1196 (long long)chunksize);
1197 #else
1198 "got chunksize of %ld\n",
1199 (long)chunksize);
1200 #endif
1201 if (chunksize == 0)
1202 break;
1203 }
1204 /* transfer file or chunk */
1205 while (1) {
1206 struct timeval then, now, td;
1207 off_t bufrem;
1208
1209 if (rate_get)
1210 (void)gettimeofday(&then, NULL);
1211 bufrem = rate_get ? rate_get : bufsize;
1212 while (bufrem > 0) {
1213 len = fread(xferbuf, sizeof(char),
1214 ischunked ? MIN(chunksize, bufrem)
1215 : bufsize, fin);
1216 if (len <= 0)
1217 goto chunkdone;
1218 bytes += len;
1219 bufrem -= len;
1220 if (fwrite(xferbuf, sizeof(char), len, fout)
1221 != len) {
1222 warn("Writing `%s'", savefile);
1223 goto cleanup_fetch_url;
1224 }
1225 }
1226 if (hash && !progress) {
1227 while (bytes >= hashbytes) {
1228 (void)putc('#', ttyout);
1229 hashbytes += mark;
1230 }
1231 (void)fflush(ttyout);
1232 }
1233 if (ischunked) {
1234 chunksize -= len;
1235 if (chunksize <= 0)
1236 goto chunkdone;
1237 }
1238 if (rate_get) {
1239 while (1) {
1240 (void)gettimeofday(&now, NULL);
1241 timersub(&now, &then, &td);
1242 if (td.tv_sec > 0)
1243 break;
1244 usleep(1000000 - td.tv_usec);
1245 }
1246 }
1247 }
1248 /* read CRLF after chunk*/
1249 chunkdone:
1250 if (ischunked) {
1251 if (fgets(xferbuf, bufsize, fin) == NULL)
1252 break;
1253 if (strcmp(xferbuf, "\r\n") != 0) {
1254 warnx("Unexpected data following chunk");
1255 goto cleanup_fetch_url;
1256 }
1257 }
1258 } while (ischunked);
1259 if (hash && !progress && bytes > 0) {
1260 if (bytes < mark)
1261 (void)putc('#', ttyout);
1262 (void)putc('\n', ttyout);
1263 }
1264 if (ferror(fin)) {
1265 warn("Reading file");
1266 goto cleanup_fetch_url;
1267 }
1268 progressmeter(1);
1269 bytes = 0;
1270 (void)fflush(fout);
1271 if (closefunc == fclose && mtime != -1) {
1272 struct timeval tval[2];
1273
1274 (void)gettimeofday(&tval[0], NULL);
1275 tval[1].tv_sec = mtime;
1276 tval[1].tv_usec = 0;
1277 (*closefunc)(fout);
1278 fout = NULL;
1279
1280 if (utimes(savefile, tval) == -1) {
1281 fprintf(ttyout,
1282 "Can't change modification time to %s",
1283 asctime(localtime(&mtime)));
1284 }
1285 }
1286 if (bytes > 0)
1287 ptransfer(0);
1288
1289 rval = 0;
1290 goto cleanup_fetch_url;
1291
1292 improper:
1293 warnx("Improper response from `%s'", host);
1294
1295 cleanup_fetch_url:
1296 if (oldintr)
1297 (void)xsignal(SIGINT, oldintr);
1298 if (oldintp)
1299 (void)xsignal(SIGPIPE, oldintp);
1300 if (fin != NULL)
1301 fclose(fin);
1302 else if (s != -1)
1303 close(s);
1304 if (closefunc != NULL && fout != NULL)
1305 (*closefunc)(fout);
1306 #ifdef NI_NUMERICHOST
1307 if (res != NULL)
1308 freeaddrinfo(res);
1309 #endif
1310 FREEPTR(savefile);
1311 FREEPTR(user);
1312 FREEPTR(pass);
1313 FREEPTR(host);
1314 FREEPTR(port);
1315 FREEPTR(path);
1316 FREEPTR(decodedpath);
1317 FREEPTR(puser);
1318 FREEPTR(ppass);
1319 FREEPTR(buf);
1320 FREEPTR(auth);
1321 FREEPTR(location);
1322 FREEPTR(message);
1323 return (rval);
1324 }
1325
1326 /*
1327 * Abort a HTTP retrieval
1328 */
1329 void
1330 aborthttp(notused)
1331 int notused;
1332 {
1333 char msgbuf[100];
1334 int len;
1335
1336 alarmtimer(0);
1337 len = strlcpy(msgbuf, "\nHTTP fetch aborted.\n", sizeof(msgbuf));
1338 write(fileno(ttyout), msgbuf, len);
1339 siglongjmp(httpabort, 1);
1340 }
1341
1342 /*
1343 * Retrieve ftp URL or classic ftp argument using FTP.
1344 * Returns 1 on failure, 0 on completed xfer, -1 if ftp connection
1345 * is still open (e.g, ftp xfer with trailing /)
1346 */
1347 static int
1348 fetch_ftp(url)
1349 const char *url;
1350 {
1351 char *cp, *xargv[5], rempath[MAXPATHLEN];
1352 char *host, *path, *dir, *file, *user, *pass;
1353 char *port;
1354 int dirhasglob, filehasglob, oautologin, rval, type, xargc;
1355 in_port_t portnum;
1356 url_t urltype;
1357
1358 host = path = dir = file = user = pass = NULL;
1359 port = NULL;
1360 rval = 1;
1361 type = TYPE_I;
1362
1363 if (strncasecmp(url, FTP_URL, sizeof(FTP_URL) - 1) == 0) {
1364 if ((parse_url(url, "URL", &urltype, &user, &pass,
1365 &host, &port, &portnum, &path) == -1) ||
1366 (user != NULL && *user == '\0') ||
1367 (pass != NULL && *pass == '\0') ||
1368 EMPTYSTRING(host)) {
1369 warnx("Invalid URL `%s'", url);
1370 goto cleanup_fetch_ftp;
1371 }
1372 url_decode(user);
1373 url_decode(pass);
1374 /*
1375 * Note: Don't url_decode(path) here. We need to keep the
1376 * distinction between "/" and "%2F" until later.
1377 */
1378
1379 /* check for trailing ';type=[aid]' */
1380 if (! EMPTYSTRING(path) && (cp = strrchr(path, ';')) != NULL) {
1381 if (strcasecmp(cp, ";type=a") == 0)
1382 type = TYPE_A;
1383 else if (strcasecmp(cp, ";type=i") == 0)
1384 type = TYPE_I;
1385 else if (strcasecmp(cp, ";type=d") == 0) {
1386 warnx(
1387 "Directory listing via a URL is not supported");
1388 goto cleanup_fetch_ftp;
1389 } else {
1390 warnx("Invalid suffix `%s' in URL `%s'", cp,
1391 url);
1392 goto cleanup_fetch_ftp;
1393 }
1394 *cp = 0;
1395 }
1396 } else { /* classic style `[user@]host:[file]' */
1397 urltype = CLASSIC_URL_T;
1398 host = xstrdup(url);
1399 cp = strchr(host, '@');
1400 if (cp != NULL) {
1401 *cp = '\0';
1402 user = host;
1403 anonftp = 0; /* disable anonftp */
1404 host = xstrdup(cp + 1);
1405 }
1406 cp = strchr(host, ':');
1407 if (cp != NULL) {
1408 *cp = '\0';
1409 path = xstrdup(cp + 1);
1410 }
1411 }
1412 if (EMPTYSTRING(host))
1413 goto cleanup_fetch_ftp;
1414
1415 /* Extract the file and (if present) directory name. */
1416 dir = path;
1417 if (! EMPTYSTRING(dir)) {
1418 /*
1419 * If we are dealing with classic `[user@]host:[path]' syntax,
1420 * then a path of the form `/file' (resulting from input of the
1421 * form `host:/file') means that we should do "CWD /" before
1422 * retrieving the file. So we set dir="/" and file="file".
1423 *
1424 * But if we are dealing with URLs like `ftp://host/path' then
1425 * a path of the form `/file' (resulting from a URL of the form
1426 * `ftp://host//file') means that we should do `CWD ' (with an
1427 * empty argument) before retrieving the file. So we set
1428 * dir="" and file="file".
1429 *
1430 * If the path does not contain / at all, we set dir=NULL.
1431 * (We get a path without any slashes if we are dealing with
1432 * classic `[user@]host:[file]' or URL `ftp://host/file'.)
1433 *
1434 * In all other cases, we set dir to a string that does not
1435 * include the final '/' that separates the dir part from the
1436 * file part of the path. (This will be the empty string if
1437 * and only if we are dealing with a path of the form `/file'
1438 * resulting from an URL of the form `ftp://host//file'.)
1439 */
1440 cp = strrchr(dir, '/');
1441 if (cp == dir && urltype == CLASSIC_URL_T) {
1442 file = cp + 1;
1443 dir = "/";
1444 } else if (cp != NULL) {
1445 *cp++ = '\0';
1446 file = cp;
1447 } else {
1448 file = dir;
1449 dir = NULL;
1450 }
1451 } else
1452 dir = NULL;
1453 if (urltype == FTP_URL_T && file != NULL) {
1454 url_decode(file);
1455 /* but still don't url_decode(dir) */
1456 }
1457 if (debug)
1458 fprintf(ttyout,
1459 "fetch_ftp: user `%s' pass `%s' host %s:%s path `%s' dir `%s' file `%s'\n",
1460 user ? user : "<null>", pass ? pass : "<null>",
1461 host ? host : "<null>", port ? port : "<null>",
1462 path ? path : "<null>",
1463 dir ? dir : "<null>", file ? file : "<null>");
1464
1465 dirhasglob = filehasglob = 0;
1466 if (doglob && urltype == CLASSIC_URL_T) {
1467 if (! EMPTYSTRING(dir) && strpbrk(dir, "*?[]{}") != NULL)
1468 dirhasglob = 1;
1469 if (! EMPTYSTRING(file) && strpbrk(file, "*?[]{}") != NULL)
1470 filehasglob = 1;
1471 }
1472
1473 /* Set up the connection */
1474 if (connected)
1475 disconnect(0, NULL);
1476 xargv[0] = __progname;
1477 xargv[1] = host;
1478 xargv[2] = NULL;
1479 xargc = 2;
1480 if (port) {
1481 xargv[2] = port;
1482 xargv[3] = NULL;
1483 xargc = 3;
1484 }
1485 oautologin = autologin;
1486 if (user != NULL)
1487 autologin = 0;
1488 setpeer(xargc, xargv);
1489 autologin = oautologin;
1490 if ((connected == 0) || ((connected == 1)
1491 && !ftp_login(host, user, pass))) {
1492 warnx("Can't connect or login to host `%s'", host);
1493 goto cleanup_fetch_ftp;
1494 }
1495
1496 switch (type) {
1497 case TYPE_A:
1498 setascii(0, NULL);
1499 break;
1500 case TYPE_I:
1501 setbinary(0, NULL);
1502 break;
1503 default:
1504 errx(1, "fetch_ftp: unknown transfer type %d", type);
1505 }
1506
1507 /*
1508 * Change directories, if necessary.
1509 *
1510 * Note: don't use EMPTYSTRING(dir) below, because
1511 * dir=="" means something different from dir==NULL.
1512 */
1513 if (dir != NULL && !dirhasglob) {
1514 char *nextpart;
1515
1516 /*
1517 * If we are dealing with a classic `[user@]host:[path]'
1518 * (urltype is CLASSIC_URL_T) then we have a raw directory
1519 * name (not encoded in any way) and we can change
1520 * directories in one step.
1521 *
1522 * If we are dealing with an `ftp://host/path' URL
1523 * (urltype is FTP_URL_T), then RFC 1738 says we need to
1524 * send a separate CWD command for each unescaped "/"
1525 * in the path, and we have to interpret %hex escaping
1526 * *after* we find the slashes. It's possible to get
1527 * empty components here, (from multiple adjacent
1528 * slashes in the path) and RFC 1738 says that we should
1529 * still do `CWD ' (with a null argument) in such cases.
1530 *
1531 * Many ftp servers don't support `CWD ', so if there's an
1532 * error performing that command, bail out with a descriptive
1533 * message.
1534 *
1535 * Examples:
1536 *
1537 * host: dir="", urltype=CLASSIC_URL_T
1538 * logged in (to default directory)
1539 * host:file dir=NULL, urltype=CLASSIC_URL_T
1540 * "RETR file"
1541 * host:dir/ dir="dir", urltype=CLASSIC_URL_T
1542 * "CWD dir", logged in
1543 * ftp://host/ dir="", urltype=FTP_URL_T
1544 * logged in (to default directory)
1545 * ftp://host/dir/ dir="dir", urltype=FTP_URL_T
1546 * "CWD dir", logged in
1547 * ftp://host/file dir=NULL, urltype=FTP_URL_T
1548 * "RETR file"
1549 * ftp://host//file dir="", urltype=FTP_URL_T
1550 * "CWD ", "RETR file"
1551 * host:/file dir="/", urltype=CLASSIC_URL_T
1552 * "CWD /", "RETR file"
1553 * ftp://host///file dir="/", urltype=FTP_URL_T
1554 * "CWD ", "CWD ", "RETR file"
1555 * ftp://host/%2F/file dir="%2F", urltype=FTP_URL_T
1556 * "CWD /", "RETR file"
1557 * ftp://host/foo/file dir="foo", urltype=FTP_URL_T
1558 * "CWD foo", "RETR file"
1559 * ftp://host/foo/bar/file dir="foo/bar"
1560 * "CWD foo", "CWD bar", "RETR file"
1561 * ftp://host//foo/bar/file dir="/foo/bar"
1562 * "CWD ", "CWD foo", "CWD bar", "RETR file"
1563 * ftp://host/foo//bar/file dir="foo//bar"
1564 * "CWD foo", "CWD ", "CWD bar", "RETR file"
1565 * ftp://host/%2F/foo/bar/file dir="%2F/foo/bar"
1566 * "CWD /", "CWD foo", "CWD bar", "RETR file"
1567 * ftp://host/%2Ffoo/bar/file dir="%2Ffoo/bar"
1568 * "CWD /foo", "CWD bar", "RETR file"
1569 * ftp://host/%2Ffoo%2Fbar/file dir="%2Ffoo%2Fbar"
1570 * "CWD /foo/bar", "RETR file"
1571 * ftp://host/%2Ffoo%2Fbar%2Ffile dir=NULL
1572 * "RETR /foo/bar/file"
1573 *
1574 * Note that we don't need `dir' after this point.
1575 */
1576 do {
1577 if (urltype == FTP_URL_T) {
1578 nextpart = strchr(dir, '/');
1579 if (nextpart) {
1580 *nextpart = '\0';
1581 nextpart++;
1582 }
1583 url_decode(dir);
1584 } else
1585 nextpart = NULL;
1586 if (debug)
1587 fprintf(ttyout, "dir `%s', nextpart `%s'\n",
1588 dir ? dir : "<null>",
1589 nextpart ? nextpart : "<null>");
1590 if (urltype == FTP_URL_T || *dir != '\0') {
1591 xargv[0] = "cd";
1592 xargv[1] = dir;
1593 xargv[2] = NULL;
1594 dirchange = 0;
1595 cd(2, xargv);
1596 if (! dirchange) {
1597 if (*dir == '\0' && code == 500)
1598 fprintf(stderr,
1599 "\n"
1600 "ftp: The `CWD ' command (without a directory), which is required by\n"
1601 " RFC 1738 to support the empty directory in the URL pathname (`//'),\n"
1602 " conflicts with the server's conformance to RFC 959.\n"
1603 " Try the same URL without the `//' in the URL pathname.\n"
1604 "\n");
1605 goto cleanup_fetch_ftp;
1606 }
1607 }
1608 dir = nextpart;
1609 } while (dir != NULL);
1610 }
1611
1612 if (EMPTYSTRING(file)) {
1613 rval = -1;
1614 goto cleanup_fetch_ftp;
1615 }
1616
1617 if (dirhasglob) {
1618 (void)strlcpy(rempath, dir, sizeof(rempath));
1619 (void)strlcat(rempath, "/", sizeof(rempath));
1620 (void)strlcat(rempath, file, sizeof(rempath));
1621 file = rempath;
1622 }
1623
1624 /* Fetch the file(s). */
1625 xargc = 2;
1626 xargv[0] = "get";
1627 xargv[1] = file;
1628 xargv[2] = NULL;
1629 if (dirhasglob || filehasglob) {
1630 int ointeractive;
1631
1632 ointeractive = interactive;
1633 interactive = 0;
1634 xargv[0] = "mget";
1635 mget(xargc, xargv);
1636 interactive = ointeractive;
1637 } else {
1638 if (outfile == NULL) {
1639 cp = strrchr(file, '/'); /* find savefile */
1640 if (cp != NULL)
1641 outfile = cp + 1;
1642 else
1643 outfile = file;
1644 }
1645 xargv[2] = (char *)outfile;
1646 xargv[3] = NULL;
1647 xargc++;
1648 if (restartautofetch)
1649 reget(xargc, xargv);
1650 else
1651 get(xargc, xargv);
1652 }
1653
1654 if ((code / 100) == COMPLETE)
1655 rval = 0;
1656
1657 cleanup_fetch_ftp:
1658 FREEPTR(host);
1659 FREEPTR(path);
1660 FREEPTR(user);
1661 FREEPTR(pass);
1662 return (rval);
1663 }
1664
1665 /*
1666 * Retrieve the given file to outfile.
1667 * Supports arguments of the form:
1668 * "host:path", "ftp://host/path" if $ftpproxy, call fetch_url() else
1669 * call fetch_ftp()
1670 * "http://host/path" call fetch_url() to use HTTP
1671 * "file:///path" call fetch_url() to copy
1672 * "about:..." print a message
1673 *
1674 * Returns 1 on failure, 0 on completed xfer, -1 if ftp connection
1675 * is still open (e.g, ftp xfer with trailing /)
1676 */
1677 static int
1678 go_fetch(url)
1679 const char *url;
1680 {
1681 char *proxy;
1682
1683 /*
1684 * Check for about:*
1685 */
1686 if (strncasecmp(url, ABOUT_URL, sizeof(ABOUT_URL) - 1) == 0) {
1687 url += sizeof(ABOUT_URL) -1;
1688 if (strcasecmp(url, "ftp") == 0) {
1689 fputs(
1690 "This version of ftp has been enhanced by Luke Mewburn <lukem (at) netbsd.org>\n"
1691 "for the NetBSD project. Execute `man ftp' for more details.\n", ttyout);
1692 } else if (strcasecmp(url, "lukem") == 0) {
1693 fputs(
1694 "Luke Mewburn is the author of most of the enhancements in this ftp client.\n"
1695 "Please email feedback to <lukem (at) netbsd.org>.\n", ttyout);
1696 } else if (strcasecmp(url, "netbsd") == 0) {
1697 fputs(
1698 "NetBSD is a freely available and redistributable UNIX-like operating system.\n"
1699 "For more information, see http://www.netbsd.org/index.html\n", ttyout);
1700 } else if (strcasecmp(url, "version") == 0) {
1701 fprintf(ttyout, "Version: %s %s\n",
1702 FTP_PRODUCT, FTP_VERSION);
1703 } else {
1704 fprintf(ttyout, "`%s' is an interesting topic.\n", url);
1705 }
1706 fputs("\n", ttyout);
1707 return (0);
1708 }
1709
1710 /*
1711 * Check for file:// and http:// URLs.
1712 */
1713 if (strncasecmp(url, HTTP_URL, sizeof(HTTP_URL) - 1) == 0 ||
1714 strncasecmp(url, FILE_URL, sizeof(FILE_URL) - 1) == 0)
1715 return (fetch_url(url, NULL, NULL, NULL));
1716
1717 /*
1718 * Try FTP URL-style and host:file arguments next.
1719 * If ftpproxy is set with an FTP URL, use fetch_url()
1720 * Othewise, use fetch_ftp().
1721 */
1722 proxy = getoptionvalue("ftp_proxy");
1723 if (!EMPTYSTRING(proxy) &&
1724 strncasecmp(url, FTP_URL, sizeof(FTP_URL) - 1) == 0)
1725 return (fetch_url(url, NULL, NULL, NULL));
1726
1727 return (fetch_ftp(url));
1728 }
1729
1730 /*
1731 * Retrieve multiple files from the command line,
1732 * calling go_fetch() for each file.
1733 *
1734 * If an ftp path has a trailing "/", the path will be cd-ed into and
1735 * the connection remains open, and the function will return -1
1736 * (to indicate the connection is alive).
1737 * If an error occurs the return value will be the offset+1 in
1738 * argv[] of the file that caused a problem (i.e, argv[x]
1739 * returns x+1)
1740 * Otherwise, 0 is returned if all files retrieved successfully.
1741 */
1742 int
1743 auto_fetch(argc, argv)
1744 int argc;
1745 char *argv[];
1746 {
1747 volatile int argpos;
1748 int rval;
1749
1750 argpos = 0;
1751
1752 if (sigsetjmp(toplevel, 1)) {
1753 if (connected)
1754 disconnect(0, NULL);
1755 return (argpos + 1);
1756 }
1757 (void)xsignal(SIGINT, intr);
1758 (void)xsignal(SIGPIPE, lostpeer);
1759
1760 /*
1761 * Loop through as long as there's files to fetch.
1762 */
1763 for (rval = 0; (rval == 0) && (argpos < argc); argpos++) {
1764 if (strchr(argv[argpos], ':') == NULL)
1765 break;
1766 redirect_loop = 0;
1767 if (!anonftp)
1768 anonftp = 2; /* Handle "automatic" transfers. */
1769 rval = go_fetch(argv[argpos]);
1770 if (outfile != NULL && strcmp(outfile, "-") != 0
1771 && outfile[0] != '|')
1772 outfile = NULL;
1773 if (rval > 0)
1774 rval = argpos + 1;
1775 }
1776
1777 if (connected && rval != -1)
1778 disconnect(0, NULL);
1779 return (rval);
1780 }
1781