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