fetch.c revision 1.47 1 /* $NetBSD: fetch.c,v 1.47 1999/01/23 15:46:24 lukem Exp $ */
2
3 /*-
4 * Copyright (c) 1997, 1998 The NetBSD Foundation, Inc.
5 * All rights reserved.
6 *
7 * This code is derived from software contributed to The NetBSD Foundation
8 * by Jason Thorpe and 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.47 1999/01/23 15:46:24 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 <signal.h>
66 #include <stdio.h>
67 #include <stdlib.h>
68 #include <string.h>
69 #include <unistd.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 } url_t;
80
81 static int auth_url __P((const char *, char **));
82 static void base64_enc __P((const char *, size_t, char *));
83 static int go_fetch __P((const char *, const char *));
84 static int fetch_ftp __P((const char *, const char *));
85 static int fetch_url __P((const char *, const char *, const char *,
86 char *, char *));
87 static int parse_url __P((const char *, const char *, url_t *, char **,
88 char **, char **, in_port_t *, char **));
89 void aborthttp __P((int));
90
91 static int redirect_loop;
92
93
94 #define ABOUT_URL "about:" /* propaganda */
95 #define FILE_URL "file://" /* file URL prefix */
96 #define FTP_URL "ftp://" /* ftp URL prefix */
97 #define HTTP_URL "http://" /* http URL prefix */
98
99
100 #define EMPTYSTRING(x) ((x) == NULL || (*(x) == '\0'))
101 #define FREEPTR(x) if ((x) != NULL) { free(x); (x) = NULL; }
102
103 /*
104 * Generate authorization response based on given authentication challenge.
105 * Returns -1 if an error occurred, otherwise 0.
106 * Sets response to a malloc(3)ed string; caller should free.
107 */
108 static int
109 auth_url(challenge, response)
110 const char *challenge;
111 char **response;
112 {
113 char *cp, *ep, *clear, *line, *realm, *scheme;
114 char user[BUFSIZ], *pass;
115 int rval;
116 size_t len;
117
118 *response = NULL;
119 clear = realm = scheme = NULL;
120 rval = -1;
121 line = xstrdup(challenge);
122 cp = line;
123
124 if (debug)
125 fprintf(ttyout, "auth_url: challenge `%s'\n", challenge);
126
127 scheme = strsep(&cp, " ");
128 #define SCHEME_BASIC "Basic"
129 if (strncasecmp(scheme, SCHEME_BASIC, sizeof(SCHEME_BASIC) - 1) != 0) {
130 warnx("Unsupported WWW Authentication challenge - `%s'",
131 challenge);
132 goto cleanup_auth_url;
133 }
134 cp += strspn(cp, " ");
135
136 #define REALM "realm=\""
137 if (strncasecmp(cp, REALM, sizeof(REALM) - 1) == 0)
138 cp += sizeof(REALM) - 1;
139 else {
140 warnx("Unsupported WWW Authentication challenge - `%s'",
141 challenge);
142 goto cleanup_auth_url;
143 }
144 if ((ep = strchr(cp, '\"')) != NULL) {
145 size_t len = ep - cp;
146
147 realm = (char *)xmalloc(len + 1);
148 strncpy(realm, cp, len);
149 realm[len] = '\0';
150 } else {
151 warnx("Unsupported WWW Authentication challenge - `%s'",
152 challenge);
153 goto cleanup_auth_url;
154 }
155
156 fprintf(ttyout, "Username for `%s': ", realm);
157 (void)fflush(ttyout);
158 if (fgets(user, sizeof(user) - 1, stdin) == NULL)
159 goto cleanup_auth_url;
160 user[strlen(user) - 1] = '\0';
161 pass = getpass("Password: ");
162
163 len = strlen(user) + strlen(pass) + 1; /* user + ":" + pass */
164 clear = (char *)xmalloc(len + 1);
165 sprintf(clear, "%s:%s", user, pass);
166 memset(pass, '\0', strlen(pass));
167
168 /* scheme + " " + enc */
169 len = strlen(scheme) + 1 + (len + 2) * 4 / 3;
170 *response = (char *)xmalloc(len + 1);
171 len = sprintf(*response, "%s ", scheme);
172 base64_enc(clear, strlen(clear), *response + len);
173 rval = 0;
174
175 cleanup_auth_url:
176 FREEPTR(clear);
177 FREEPTR(line);
178 FREEPTR(realm);
179 return (rval);
180 }
181
182 /*
183 * Encode len bytes starting at clear using base64 encoding into encoded,
184 * which should be at least ((len + 2) * 4 / 3 + 1) in size.
185 */
186 void
187 base64_enc(clear, len, encoded)
188 const char *clear;
189 size_t len;
190 char *encoded;
191 {
192 static const char enc[] =
193 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
194 char *cp;
195 int i;
196
197 cp = encoded;
198 for (i = 0; i < len; i += 3) {
199 *(cp++) = enc[((clear[i + 0] >> 2))];
200 *(cp++) = enc[((clear[i + 0] << 4) & 0x30)
201 | ((clear[i + 1] >> 4) & 0x0f)];
202 *(cp++) = enc[((clear[i + 1] << 2) & 0x3c)
203 | ((clear[i + 2] >> 6) & 0x03)];
204 *(cp++) = enc[((clear[i + 2] ) & 0x3f)];
205 }
206 *cp = '\0';
207 while (i-- > len)
208 *(--cp) = '=';
209 }
210
211
212 /*
213 * Parse URL of form:
214 * <type>://[<user>[:<password>@]]<host>[:<port>]/<url-path>
215 * Returns -1 if a parse error occurred, otherwise 0.
216 * Sets type to url_t, each of the given char ** pointers to a
217 * malloc(3)ed strings of the relevant section, and port to
218 * the number given, or ftpport if ftp://, or httpport if http://.
219 */
220 static int
221 parse_url(url, desc, type, user, pass, host, port, path)
222 const char *url;
223 const char *desc;
224 url_t *type;
225 char **user;
226 char **pass;
227 char **host;
228 in_port_t *port;
229 char **path;
230 {
231 char *cp, *ep, *thost;
232
233 if (url == NULL || desc == NULL || type == NULL || user == NULL
234 || pass == NULL || host == NULL || port == NULL || path == NULL)
235 errx(1, "parse_url: invoked with NULL argument!");
236
237 *type = UNKNOWN_URL_T;
238 *user = *pass = *host = *path = NULL;
239 *port = 0;
240
241 if (strncasecmp(url, HTTP_URL, sizeof(HTTP_URL) - 1) == 0) {
242 url += sizeof(HTTP_URL) - 1;
243 *type = HTTP_URL_T;
244 *port = httpport;
245 } else if (strncasecmp(url, FTP_URL, sizeof(FTP_URL) - 1) == 0) {
246 url += sizeof(FTP_URL) - 1;
247 *type = FTP_URL_T;
248 *port = ftpport;
249 } else if (strncasecmp(url, FILE_URL, sizeof(FILE_URL) - 1) == 0) {
250 url += sizeof(FILE_URL) - 1;
251 *type = FILE_URL_T;
252 } else {
253 warnx("Invalid %s `%s'", desc, url);
254 cleanup_parse_url:
255 FREEPTR(*user);
256 FREEPTR(*pass);
257 FREEPTR(*host);
258 FREEPTR(*path);
259 return (-1);
260 }
261
262 if (*url == '\0')
263 return (0);
264
265 /* find [user[:pass]@]host[:port] */
266 ep = strchr(url, '/');
267 if (ep == NULL)
268 thost = xstrdup(url);
269 else {
270 size_t len = ep - url;
271 thost = (char *)xmalloc(len + 1);
272 strncpy(thost, url, len);
273 thost[len] = '\0';
274 *path = xstrdup(ep);
275 }
276
277 cp = strchr(thost, '@');
278 if (cp != NULL) {
279 *user = thost;
280 *cp = '\0';
281 *host = xstrdup(cp + 1);
282 cp = strchr(*user, ':');
283 if (cp != NULL) {
284 *cp = '\0';
285 *pass = xstrdup(cp + 1);
286 }
287 } else
288 *host = thost;
289
290 /* look for [:port] */
291 cp = strrchr(*host, ':');
292 if (cp != NULL) {
293 long nport;
294
295 *cp = '\0';
296 nport = strtol(cp + 1, &ep, 10);
297 if (nport < 1 || nport > MAX_IN_PORT_T || *ep != '\0') {
298 warnx("Invalid port `%s' in %s `%s'", cp, desc, url);
299 goto cleanup_parse_url;
300 }
301 *port = htons((in_port_t)nport);
302 }
303
304 if (debug)
305 fprintf(ttyout,
306 "parse_url: user `%s', pass `%s', host %s:%d, path `%s'\n",
307 *user ? *user : "", *pass ? *pass : "", *host ? *host : "",
308 ntohs(*port), *path ? *path : "");
309
310 return (0);
311 }
312
313
314 jmp_buf httpabort;
315
316 /*
317 * Retrieve URL, via a proxy if necessary. If proxyenv is set, use that for
318 * the proxy, otherwise try ftp_proxy or http_proxy as appropriate.
319 * Supports http redirects.
320 * Returns -1 on failure, 0 on completed xfer, 1 if ftp connection
321 * is still open (e.g, ftp xfer with trailing /)
322 */
323 static int
324 fetch_url(url, outfile, proxyenv, proxyauth, wwwauth)
325 const char *url;
326 const char *outfile;
327 const char *proxyenv;
328 char *proxyauth;
329 char *wwwauth;
330 {
331 struct sockaddr_in sin;
332 struct hostent *hp;
333 volatile sig_t oldintr, oldintp;
334 volatile int s;
335 int ischunked, isproxy, rval, hcode;
336 size_t len;
337 char *cp, *ep, *buf, *savefile;
338 char *auth, *location, *message;
339 char *user, *pass, *host, *path;
340 off_t hashbytes;
341 int (*closefunc) __P((FILE *));
342 FILE *fin, *fout;
343 time_t mtime;
344 url_t urltype;
345 in_port_t port;
346
347 closefunc = NULL;
348 fin = fout = NULL;
349 s = -1;
350 buf = savefile = NULL;
351 auth = location = message = NULL;
352 ischunked = isproxy = 0;
353 rval = 1;
354 hp = NULL;
355
356 #ifdef __GNUC__ /* shut up gcc warnings */
357 (void)&closefunc;
358 (void)&fin;
359 (void)&fout;
360 (void)&buf;
361 (void)&savefile;
362 (void)&rval;
363 (void)&isproxy;
364 #endif
365
366 if (parse_url(url, "URL", &urltype, &user, &pass, &host, &port, &path)
367 == -1)
368 goto cleanup_fetch_url;
369
370 if (urltype == FILE_URL_T && ! EMPTYSTRING(host)
371 && strcasecmp(host, "localhost") != 0) {
372 warnx("No support for non local file URL `%s'", url);
373 goto cleanup_fetch_url;
374 }
375
376 if (EMPTYSTRING(path)) {
377 if (urltype == FTP_URL_T) {
378 rval = fetch_ftp(url, outfile);
379 goto cleanup_fetch_url;
380 }
381 if (urltype != HTTP_URL_T || outfile == NULL) {
382 warnx("Invalid URL (no file after host) `%s'", url);
383 goto cleanup_fetch_url;
384 }
385 }
386
387 if (outfile)
388 savefile = xstrdup(outfile);
389 else {
390 cp = strrchr(path, '/'); /* find savefile */
391 if (cp != NULL)
392 savefile = xstrdup(cp + 1);
393 else
394 savefile = xstrdup(path);
395 }
396 if (EMPTYSTRING(savefile)) {
397 if (urltype == FTP_URL_T) {
398 rval = fetch_ftp(url, outfile);
399 goto cleanup_fetch_url;
400 }
401 warnx("Invalid URL (no file after directory) `%s'", url);
402 goto cleanup_fetch_url;
403 }
404
405 filesize = -1;
406 mtime = -1;
407 if (urltype == FILE_URL_T) { /* file:// URLs */
408 struct stat sb;
409
410 direction = "copied";
411 fin = fopen(path, "r");
412 if (fin == NULL) {
413 warn("Cannot open file `%s'", path);
414 goto cleanup_fetch_url;
415 }
416 if (fstat(fileno(fin), &sb) == 0) {
417 mtime = sb.st_mtime;
418 filesize = sb.st_size;
419 }
420 fprintf(ttyout, "Copying %s\n", path);
421 } else { /* ftp:// or http:// URLs */
422 if (proxyenv == NULL) {
423 if (urltype == HTTP_URL_T)
424 proxyenv = httpproxy;
425 else if (urltype == FTP_URL_T)
426 proxyenv = ftpproxy;
427 }
428 direction = "retrieved";
429 if (proxyenv != NULL) { /* use proxy */
430 url_t purltype;
431 char *puser, *ppass, *phost;
432 char *ppath;
433
434 isproxy = 1;
435
436 /* check URL against list of no_proxied sites */
437 if (no_proxy != NULL) {
438 char *np, *np_copy;
439 long np_port;
440 size_t hlen, plen;
441
442 np_copy = xstrdup(no_proxy);
443 hlen = strlen(host);
444 while ((cp = strsep(&np_copy, " ,")) != NULL) {
445 if (*cp == '\0')
446 continue;
447 if ((np = strchr(cp, ':')) != NULL) {
448 *np = '\0';
449 np_port =
450 strtol(np + 1, &ep, 10);
451 if (*ep != '\0')
452 continue;
453 if (port !=
454 htons((in_port_t)np_port))
455 continue;
456 }
457 plen = strlen(cp);
458 if (strncasecmp(host + hlen - plen,
459 cp, plen) == 0) {
460 isproxy = 0;
461 break;
462 }
463 }
464 FREEPTR(np_copy);
465 }
466
467 if (isproxy) {
468 if (parse_url(proxyenv, "proxy URL", &purltype,
469 &puser, &ppass, &phost, &port, &ppath)
470 == -1)
471 goto cleanup_fetch_url;
472
473 if ((purltype != HTTP_URL_T
474 && purltype != FTP_URL_T) ||
475 EMPTYSTRING(phost) ||
476 (! EMPTYSTRING(ppath)
477 && strcmp(ppath, "/") != 0)) {
478 warnx("Malformed proxy URL `%s'",
479 proxyenv);
480 FREEPTR(puser);
481 FREEPTR(ppass);
482 FREEPTR(phost);
483 FREEPTR(ppath);
484 goto cleanup_fetch_url;
485 }
486
487 FREEPTR(user);
488 user = puser;
489 FREEPTR(pass);
490 pass = ppass;
491 FREEPTR(host);
492 host = phost;
493 FREEPTR(path);
494 FREEPTR(ppath);
495 path = xstrdup(url);
496 }
497 } /* proxyenv != NULL */
498
499 memset(&sin, 0, sizeof(sin));
500 sin.sin_family = AF_INET;
501
502 if (isdigit((unsigned char)host[0])) {
503 if (inet_aton(host, &sin.sin_addr) == 0) {
504 warnx("Invalid IP address `%s'", host);
505 goto cleanup_fetch_url;
506 }
507 } else {
508 hp = gethostbyname(host);
509 if (hp == NULL) {
510 warnx("%s: %s", host, hstrerror(h_errno));
511 goto cleanup_fetch_url;
512 }
513 if (hp->h_addrtype != AF_INET) {
514 warnx("`%s': not an Internet address?", host);
515 goto cleanup_fetch_url;
516 }
517 memcpy(&sin.sin_addr, hp->h_addr, hp->h_length);
518 }
519
520 if (port == 0) {
521 warnx("Unknown port for URL `%s'", url);
522 goto cleanup_fetch_url;
523 }
524 sin.sin_port = port;
525
526 s = socket(AF_INET, SOCK_STREAM, 0);
527 if (s == -1) {
528 warn("Can't create socket");
529 goto cleanup_fetch_url;
530 }
531
532 while (xconnect(s, (struct sockaddr *)&sin,
533 sizeof(sin)) == -1) {
534 if (errno == EINTR)
535 continue;
536 if (hp && hp->h_addr_list[1]) {
537 int oerrno = errno;
538 char *ia;
539
540 ia = inet_ntoa(sin.sin_addr);
541 errno = oerrno;
542 warn("Connect to address `%s'", ia);
543 hp->h_addr_list++;
544 memcpy(&sin.sin_addr, hp->h_addr_list[0],
545 (size_t)hp->h_length);
546 fprintf(ttyout, "Trying %s...\n",
547 inet_ntoa(sin.sin_addr));
548 (void)close(s);
549 s = socket(AF_INET, SOCK_STREAM, 0);
550 if (s < 0) {
551 warn("Can't create socket");
552 goto cleanup_fetch_url;
553 }
554 continue;
555 }
556 warn("Can't connect to `%s'", host);
557 goto cleanup_fetch_url;
558 }
559
560 fin = fdopen(s, "r+");
561 /*
562 * Construct and send the request.
563 * Proxy requests don't want leading /.
564 */
565 if (isproxy) {
566 fprintf(ttyout, "Requesting %s\n (via %s)\n",
567 url, proxyenv);
568 fprintf(fin, "GET %s HTTP/1.0\r\n", path);
569 if (flushcache)
570 fprintf(fin, "Pragma: no-cache\r\n");
571 } else {
572 struct utsname unam;
573
574 fprintf(ttyout, "Requesting %s\n", url);
575 fprintf(fin, "GET %s HTTP/1.1\r\n", path);
576 fprintf(fin, "Host: %s\r\n", host);
577 fprintf(fin, "Accept: */*\r\n");
578 if (uname(&unam) != -1) {
579 fprintf(fin, "User-Agent: %s-%s/ftp\r\n",
580 unam.sysname, unam.release);
581 }
582 fprintf(fin, "Connection: close\r\n");
583 if (flushcache)
584 fprintf(fin, "Cache-Control: no-cache\r\n");
585 }
586 if (wwwauth) {
587 fprintf(ttyout, " (with authorization)\n");
588 fprintf(fin, "Authorization: %s\r\n", wwwauth);
589 }
590 if (proxyauth) {
591 fprintf(ttyout, " (with proxy authorization)\n");
592 fprintf(fin, "Proxy-Authorization: %s\r\n", proxyauth);
593 }
594 fprintf(fin, "\r\n");
595 if (fflush(fin) == EOF) {
596 warn("Writing HTTP request");
597 goto cleanup_fetch_url;
598 }
599
600 /* Read the response */
601 if ((buf = fparseln(fin, &len, NULL, "\0\0\0", 0)) == NULL) {
602 warn("Receiving HTTP reply");
603 goto cleanup_fetch_url;
604 }
605 while (len > 0 && (buf[len-1] == '\r' || buf[len-1] == '\n'))
606 buf[--len] = '\0';
607 if (debug)
608 fprintf(ttyout, "received `%s'\n", buf);
609
610 /* Determine HTTP response code */
611 cp = strchr(buf, ' ');
612 if (cp == NULL)
613 goto improper;
614 else
615 cp++;
616 hcode = strtol(cp, &ep, 10);
617 if (*ep != '\0' && !isspace((unsigned char)*ep))
618 goto improper;
619 message = xstrdup(cp);
620
621 /* Read the rest of the header. */
622 FREEPTR(buf);
623 while (1) {
624 if ((buf = fparseln(fin, &len, NULL, "\0\0\0", 0))
625 == NULL) {
626 warn("Receiving HTTP reply");
627 goto cleanup_fetch_url;
628 }
629 while (len > 0 &&
630 (buf[len-1] == '\r' || buf[len-1] == '\n'))
631 buf[--len] = '\0';
632 if (len == 0)
633 break;
634 if (debug)
635 fprintf(ttyout, "received `%s'\n", buf);
636
637 /* Look for some headers */
638 cp = buf;
639
640 #define CONTENTLEN "Content-Length: "
641 if (strncasecmp(cp, CONTENTLEN,
642 sizeof(CONTENTLEN) - 1) == 0) {
643 cp += sizeof(CONTENTLEN) - 1;
644 filesize = strtol(cp, &ep, 10);
645 if (filesize < 1 || *ep != '\0')
646 goto improper;
647 if (debug)
648 fprintf(ttyout,
649 #ifndef NO_QUAD
650 "parsed length as: %qd\n",
651 (long long)filesize);
652 #else
653 "parsed length as: %ld\n",
654 (long)filesize);
655 #endif
656
657 #define LASTMOD "Last-Modified: "
658 } else if (strncasecmp(cp, LASTMOD,
659 sizeof(LASTMOD) - 1) == 0) {
660 struct tm parsed;
661 char *t;
662
663 cp += sizeof(LASTMOD) - 1;
664 /* RFC 1123 */
665 if ((t = strptime(cp,
666 "%a, %d %b %Y %H:%M:%S GMT",
667 &parsed))
668 /* RFC 850 */
669 || (t = strptime(cp,
670 "%a, %d-%b-%y %H:%M:%S GMT",
671 &parsed))
672 /* asctime */
673 || (t = strptime(cp,
674 "%a, %b %d %H:%M:%S %Y",
675 &parsed))) {
676 parsed.tm_isdst = -1;
677 if (*t == '\0')
678 mtime = mkgmtime(&parsed);
679 if (debug && mtime != -1) {
680 fprintf(ttyout,
681 "parsed date as: %s",
682 ctime(&mtime));
683 }
684 }
685
686 #define LOCATION "Location: "
687 } else if (strncasecmp(cp, LOCATION,
688 sizeof(LOCATION) - 1) == 0) {
689 cp += sizeof(LOCATION) - 1;
690 location = xstrdup(cp);
691 if (debug)
692 fprintf(ttyout,
693 "parsed location as: %s\n", cp);
694
695 #define TRANSENC "Transfer-Encoding: "
696 } else if (strncasecmp(cp, TRANSENC,
697 sizeof(TRANSENC) - 1) == 0) {
698 cp += sizeof(TRANSENC) - 1;
699 if (strcasecmp(cp, "chunked") != 0) {
700 warnx(
701 "Unsupported transfer encoding - `%s'",
702 cp);
703 goto cleanup_fetch_url;
704 }
705 ischunked++;
706 if (debug)
707 fprintf(ttyout,
708 "using chunked encoding\n");
709
710 #define PROXYAUTH "Proxy-Authenticate: "
711 } else if (strncasecmp(cp, PROXYAUTH,
712 sizeof(PROXYAUTH) - 1) == 0) {
713 cp += sizeof(PROXYAUTH) - 1;
714 FREEPTR(auth);
715 auth = xstrdup(cp);
716 if (debug)
717 fprintf(ttyout,
718 "parsed proxy-auth as: %s\n", cp);
719
720 #define WWWAUTH "WWW-Authenticate: "
721 } else if (strncasecmp(cp, WWWAUTH,
722 sizeof(WWWAUTH) - 1) == 0) {
723 cp += sizeof(WWWAUTH) - 1;
724 FREEPTR(auth);
725 auth = xstrdup(cp);
726 if (debug)
727 fprintf(ttyout,
728 "parsed www-auth as: %s\n", cp);
729
730 }
731
732 }
733 FREEPTR(buf);
734 }
735
736 switch (hcode) {
737 case 200:
738 break;
739 case 300:
740 case 301:
741 case 302:
742 case 303:
743 case 305:
744 if (EMPTYSTRING(location)) {
745 warnx("No redirection Location provided by server");
746 goto cleanup_fetch_url;
747 }
748 if (redirect_loop++ > 5) {
749 warnx("Too many redirections requested");
750 goto cleanup_fetch_url;
751 }
752 if (hcode == 305) {
753 if (verbose)
754 fprintf(ttyout, "Redirected via %s\n",
755 location);
756 rval = fetch_url(url, outfile, location, proxyauth,
757 wwwauth);
758 } else {
759 if (verbose)
760 fprintf(ttyout, "Redirected to %s\n", location);
761 rval = go_fetch(location, outfile);
762 }
763 goto cleanup_fetch_url;
764 case 401:
765 case 407:
766 {
767 char **authp;
768
769 fprintf(ttyout, "%s\n", message);
770 if (EMPTYSTRING(auth)) {
771 warnx("No authentication challenge provided by server");
772 goto cleanup_fetch_url;
773 }
774 authp = (hcode == 401) ? &wwwauth : &proxyauth;
775 if (*authp != NULL) {
776 char reply[10];
777
778 fprintf(ttyout, "Authorization failed. Retry (y/n)? ");
779 if (fgets(reply, sizeof(reply), stdin) != NULL &&
780 tolower(reply[0]) != 'y')
781 goto cleanup_fetch_url;
782 }
783 if (auth_url(auth, authp) == 0) {
784 rval = fetch_url(url, outfile, proxyenv, proxyauth,
785 wwwauth);
786 memset(*authp, '\0', strlen(*authp));
787 FREEPTR(*authp);
788 }
789 goto cleanup_fetch_url;
790 }
791 default:
792 warnx("Error retrieving file - `%s'", message);
793 goto cleanup_fetch_url;
794 }
795
796 oldintr = oldintp = NULL;
797
798 /* Open the output file. */
799 if (strcmp(savefile, "-") == 0) {
800 fout = stdout;
801 } else if (*savefile == '|') {
802 oldintp = signal(SIGPIPE, SIG_IGN);
803 fout = popen(savefile + 1, "w");
804 if (fout == NULL) {
805 warn("Can't run `%s'", savefile + 1);
806 goto cleanup_fetch_url;
807 }
808 closefunc = pclose;
809 } else {
810 fout = fopen(savefile, "w");
811 if (fout == NULL) {
812 warn("Can't open `%s'", savefile);
813 goto cleanup_fetch_url;
814 }
815 closefunc = fclose;
816 }
817
818 /* Trap signals */
819 if (setjmp(httpabort)) {
820 if (oldintr)
821 (void)signal(SIGINT, oldintr);
822 if (oldintp)
823 (void)signal(SIGPIPE, oldintp);
824 goto cleanup_fetch_url;
825 }
826 oldintr = signal(SIGINT, aborthttp);
827
828 bytes = 0;
829 hashbytes = mark;
830 progressmeter(-1);
831
832 /* Finally, suck down the file. */
833 buf = xmalloc(BUFSIZ + 1);
834 do {
835 ssize_t chunksize;
836
837 chunksize = 0;
838 /* read chunksize */
839 if (ischunked) {
840 if (fgets(buf, BUFSIZ, fin) == NULL) {
841 warnx("Unexpected EOF reading chunksize");
842 goto cleanup_fetch_url;
843 }
844 chunksize = strtol(buf, &ep, 16);
845 if (strcmp(ep, "\r\n") != 0) {
846 warnx("Unexpected data following chunksize");
847 goto cleanup_fetch_url;
848 }
849 if (debug)
850 fprintf(ttyout, "got chunksize of %qd\n",
851 (long long)chunksize);
852 if (chunksize == 0)
853 break;
854 }
855 while ((len = fread(buf, sizeof(char),
856 ischunked ? MIN(chunksize, BUFSIZ) : BUFSIZ, fin)) > 0) {
857 bytes += len;
858 if (fwrite(buf, sizeof(char), len, fout) != len) {
859 warn("Writing `%s'", savefile);
860 goto cleanup_fetch_url;
861 }
862 if (hash && !progress) {
863 while (bytes >= hashbytes) {
864 (void)putc('#', ttyout);
865 hashbytes += mark;
866 }
867 (void)fflush(ttyout);
868 }
869 if (ischunked)
870 chunksize -= len;
871 }
872 /* read CRLF after chunk*/
873 if (ischunked) {
874 if (fgets(buf, BUFSIZ, fin) == NULL)
875 break;
876 if (strcmp(buf, "\r\n") != 0) {
877 warnx("Unexpected data following chunk");
878 goto cleanup_fetch_url;
879 }
880 }
881 } while (ischunked);
882 if (hash && !progress && bytes > 0) {
883 if (bytes < mark)
884 (void)putc('#', ttyout);
885 (void)putc('\n', ttyout);
886 (void)fflush(ttyout);
887 }
888 if (ferror(fin)) {
889 warn("Reading file");
890 goto cleanup_fetch_url;
891 }
892 progressmeter(1);
893 (void)fflush(fout);
894 (void)signal(SIGINT, oldintr);
895 if (oldintp)
896 (void)signal(SIGPIPE, oldintp);
897 if (closefunc == fclose && mtime != -1) {
898 struct timeval tval[2];
899
900 (void)gettimeofday(&tval[0], NULL);
901 tval[1].tv_sec = mtime;
902 tval[1].tv_usec = 0;
903 (*closefunc)(fout);
904 fout = NULL;
905
906 if (utimes(savefile, tval) == -1) {
907 fprintf(ttyout,
908 "Can't change modification time to %s",
909 asctime(localtime(&mtime)));
910 }
911 }
912 if (bytes > 0)
913 ptransfer(0);
914
915 rval = 0;
916 goto cleanup_fetch_url;
917
918 improper:
919 warnx("Improper response from `%s'", host);
920
921 cleanup_fetch_url:
922 resetsockbufsize();
923 if (fin != NULL)
924 fclose(fin);
925 else if (s != -1)
926 close(s);
927 if (closefunc != NULL && fout != NULL)
928 (*closefunc)(fout);
929 FREEPTR(savefile);
930 FREEPTR(user);
931 FREEPTR(pass);
932 FREEPTR(host);
933 FREEPTR(path);
934 FREEPTR(buf);
935 FREEPTR(auth);
936 FREEPTR(location);
937 FREEPTR(message);
938 return (rval);
939 }
940
941 /*
942 * Abort a http retrieval
943 */
944 void
945 aborthttp(notused)
946 int notused;
947 {
948
949 alarmtimer(0);
950 fputs("\nHTTP fetch aborted.\n", ttyout);
951 (void)fflush(ttyout);
952 longjmp(httpabort, 1);
953 }
954
955 /*
956 * Retrieve ftp URL or classic ftp argument.
957 * Returns -1 on failure, 0 on completed xfer, 1 if ftp connection
958 * is still open (e.g, ftp xfer with trailing /)
959 */
960 static int
961 fetch_ftp(url, outfile)
962 const char *url;
963 const char *outfile;
964 {
965 static char lasthost[MAXHOSTNAMELEN];
966 char *cp, *xargv[5], rempath[MAXPATHLEN];
967 char portnum[6]; /* large enough for "65535\0" */
968 char *host, *path, *dir, *file, *user, *pass;
969 in_port_t port;
970 int dirhasglob, filehasglob, rval, xargc;
971
972 host = path = dir = file = user = pass = NULL;
973 port = 0;
974 rval = 1;
975
976 if (strncasecmp(url, FTP_URL, sizeof(FTP_URL) - 1) == 0) {
977 url_t urltype;
978
979 if ((parse_url(url, "URL", &urltype, &user, &pass,
980 &host, &port, &path) == -1) ||
981 (user != NULL && *user == '\0') ||
982 (pass != NULL && *pass == '\0') ||
983 EMPTYSTRING(host)) {
984 warnx("Invalid URL `%s'", url);
985 goto cleanup_fetch_ftp;
986 }
987 } else { /* classic style `host:file' */
988 host = xstrdup(url);
989 cp = strchr(host, ':');
990 if (cp != NULL) {
991 *cp = '\0';
992 path = xstrdup(cp + 1);
993 }
994 }
995 if (EMPTYSTRING(host))
996 goto cleanup_fetch_ftp;
997
998 /*
999 * Extract the file and (if present) directory name.
1000 */
1001 dir = path;
1002 if (! EMPTYSTRING(dir)) {
1003 if (*dir == '/')
1004 dir++; /* skip leading / */
1005 cp = strrchr(dir, '/');
1006 if (cp != NULL) {
1007 *cp++ = '\0';
1008 file = cp;
1009 } else {
1010 file = dir;
1011 dir = NULL;
1012 }
1013 }
1014 if (debug)
1015 fprintf(ttyout,
1016 "fetch_ftp: user `%s', pass `%s', host %s:%d, path, `%s', dir `%s', file `%s'\n",
1017 user ? user : "", pass ? pass : "",
1018 host ? host : "", ntohs(port), path ? path : "",
1019 dir ? dir : "", file ? file : "");
1020
1021 dirhasglob = filehasglob = 0;
1022 if (doglob) {
1023 if (! EMPTYSTRING(dir) && strpbrk(dir, "*?[]{}") != NULL)
1024 dirhasglob = 1;
1025 if (! EMPTYSTRING(file) && strpbrk(file, "*?[]{}") != NULL)
1026 filehasglob = 1;
1027 }
1028
1029 /*
1030 * Set up the connection if we don't have one.
1031 */
1032 if (strcasecmp(host, lasthost) != 0) {
1033 int oautologin;
1034
1035 (void)strcpy(lasthost, host);
1036 if (connected)
1037 disconnect(0, NULL);
1038 xargv[0] = __progname;
1039 xargv[1] = host;
1040 xargv[2] = NULL;
1041 xargc = 2;
1042 if (port) {
1043 snprintf(portnum, sizeof(portnum), "%d", ntohs(port));
1044 xargv[2] = portnum;
1045 xargv[3] = NULL;
1046 xargc = 3;
1047 }
1048 oautologin = autologin;
1049 if (user != NULL)
1050 autologin = 0;
1051 setpeer(xargc, xargv);
1052 autologin = oautologin;
1053 if ((connected == 0)
1054 || ((connected == 1) && !ftp_login(host, user, pass)) ) {
1055 warnx("Can't connect or login to host `%s'",
1056 host);
1057 goto cleanup_fetch_ftp;
1058 }
1059
1060 /* Always use binary transfers. */
1061 setbinary(0, NULL);
1062 } else {
1063 /* connection exists, cd back to `/' */
1064 xargv[0] = "cd";
1065 xargv[1] = "/";
1066 xargv[2] = NULL;
1067 dirchange = 0;
1068 cd(2, xargv);
1069 if (! dirchange)
1070 goto cleanup_fetch_ftp;
1071 }
1072
1073 /* Change directories, if necessary. */
1074 if (! EMPTYSTRING(dir) && !dirhasglob) {
1075 xargv[0] = "cd";
1076 xargv[1] = dir;
1077 xargv[2] = NULL;
1078 dirchange = 0;
1079 cd(2, xargv);
1080 if (! dirchange)
1081 goto cleanup_fetch_ftp;
1082 }
1083
1084 if (EMPTYSTRING(file)) {
1085 rval = -1;
1086 goto cleanup_fetch_ftp;
1087 }
1088
1089 if (!verbose)
1090 fprintf(ttyout, "Retrieving %s/%s\n", dir ? dir : "", file);
1091
1092 if (dirhasglob) {
1093 snprintf(rempath, sizeof(rempath), "%s/%s", dir, file);
1094 file = rempath;
1095 }
1096
1097 /* Fetch the file(s). */
1098 xargc = 2;
1099 xargv[0] = "get";
1100 xargv[1] = file;
1101 xargv[2] = NULL;
1102 if (dirhasglob || filehasglob) {
1103 int ointeractive;
1104
1105 ointeractive = interactive;
1106 interactive = 0;
1107 xargv[0] = "mget";
1108 mget(xargc, xargv);
1109 interactive = ointeractive;
1110 } else {
1111 if (outfile != NULL) {
1112 xargv[2] = (char *)outfile;
1113 xargv[3] = NULL;
1114 xargc++;
1115 }
1116 get(xargc, xargv);
1117 if (outfile != NULL && strcmp(outfile, "-") != 0
1118 && outfile[0] != '|')
1119 outfile = NULL;
1120 }
1121
1122 if ((code / 100) == COMPLETE)
1123 rval = 0;
1124
1125 cleanup_fetch_ftp:
1126 FREEPTR(host);
1127 FREEPTR(path);
1128 FREEPTR(user);
1129 FREEPTR(pass);
1130 return (rval);
1131 }
1132
1133 /*
1134 * Retrieve the given file to outfile.
1135 * Supports arguments of the form:
1136 * "host:path", "ftp://host/path" if $ftpproxy, call fetch_url() else
1137 * call fetch_ftp()
1138 * "http://host/path" call fetch_url() to use http
1139 * "file:///path" call fetch_url() to copy
1140 * "about:..." print a message
1141 *
1142 * Returns 1 on failure, 0 on completed xfer, -1 if ftp connection
1143 * is still open (e.g, ftp xfer with trailing /)
1144 */
1145 static int
1146 go_fetch(url, outfile)
1147 const char *url;
1148 const char *outfile;
1149 {
1150
1151 #ifndef SMALL
1152 /*
1153 * Check for about:*
1154 */
1155 if (strncasecmp(url, ABOUT_URL, sizeof(ABOUT_URL) - 1) == 0) {
1156 url += sizeof(ABOUT_URL) -1;
1157 if (strcasecmp(url, "ftp") == 0) {
1158 fprintf(ttyout, "%s\n%s\n",
1159 "This version of ftp has been enhanced by Luke Mewburn <lukem (at) netbsd.org>.",
1160 "Execute 'man ftp' for more details");
1161 } else if (strcasecmp(url, "netbsd") == 0) {
1162 fprintf(ttyout, "%s\n%s\n",
1163 "NetBSD is a freely available and redistributable UNIX-like operating system.",
1164 "For more information, see http://www.netbsd.org/index.html");
1165 } else {
1166 fprintf(ttyout, "`%s' is an interesting topic.\n", url);
1167 }
1168 return (0);
1169 }
1170 #endif /* SMALL */
1171
1172 /*
1173 * Check for file:// and http:// URLs.
1174 */
1175 if (strncasecmp(url, HTTP_URL, sizeof(HTTP_URL) - 1) == 0 ||
1176 strncasecmp(url, FILE_URL, sizeof(FILE_URL) - 1) == 0)
1177 return (fetch_url(url, outfile, NULL, NULL, NULL));
1178
1179 /*
1180 * Try FTP URL-style and host:file arguments next.
1181 * If ftpproxy is set with an FTP URL, use fetch_url()
1182 * Othewise, use fetch_ftp().
1183 */
1184 if (ftpproxy && strncasecmp(url, FTP_URL, sizeof(FTP_URL) - 1) == 0)
1185 return (fetch_url(url, outfile, NULL, NULL, NULL));
1186
1187 return (fetch_ftp(url, outfile));
1188 }
1189
1190 /*
1191 * Retrieve multiple files from the command line,
1192 * calling go_fetch() for each file.
1193 *
1194 * If an ftp path has a trailing "/", the path will be cd-ed into and
1195 * the connection remains open, and the function will return -1
1196 * (to indicate the connection is alive).
1197 * If an error occurs the return value will be the offset+1 in
1198 * argv[] of the file that caused a problem (i.e, argv[x]
1199 * returns x+1)
1200 * Otherwise, 0 is returned if all files retrieved successfully.
1201 */
1202 int
1203 auto_fetch(argc, argv, outfile)
1204 int argc;
1205 char *argv[];
1206 char *outfile;
1207 {
1208 volatile int argpos;
1209 int rval;
1210
1211 argpos = 0;
1212
1213 if (setjmp(toplevel)) {
1214 if (connected)
1215 disconnect(0, NULL);
1216 return (argpos + 1);
1217 }
1218 (void)signal(SIGINT, (sig_t)intr);
1219 (void)signal(SIGPIPE, (sig_t)lostpeer);
1220
1221 /*
1222 * Loop through as long as there's files to fetch.
1223 */
1224 for (rval = 0; (rval == 0) && (argpos < argc); argpos++) {
1225 if (strchr(argv[argpos], ':') == NULL)
1226 break;
1227 redirect_loop = 0;
1228 rval = go_fetch(argv[argpos], outfile);
1229 if (rval > 0)
1230 rval = argpos + 1;
1231 }
1232
1233 if (connected && rval != -1)
1234 disconnect(0, NULL);
1235 return (rval);
1236 }
1237