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