fetch.c revision 1.44 1 /* $NetBSD: fetch.c,v 1.44 1999/01/01 10:00:46 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.44 1999/01/01 10:00:46 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 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 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 } else {
570 struct utsname unam;
571
572 fprintf(ttyout, "Requesting %s\n", url);
573 fprintf(fin, "GET %s HTTP/1.1\r\n", path);
574 fprintf(fin, "Host: %s\r\n", host);
575 fprintf(fin, "Accept: */*\r\n");
576 if (uname(&unam) != -1) {
577 fprintf(fin, "User-Agent: %s-%s/ftp\r\n",
578 unam.sysname, unam.release);
579 }
580 fprintf(fin, "Connection: close\r\n");
581 }
582 if (wwwauth) {
583 fprintf(ttyout, " (with authorization)\n");
584 fprintf(fin, "Authorization: %s\r\n", wwwauth);
585 }
586 if (proxyauth)
587 fprintf(ttyout, " (with proxy authorization)\n");
588 fprintf(fin, "Proxy-Authorization: %s\r\n", proxyauth);
589 fprintf(fin, "\r\n");
590 if (fflush(fin) == EOF) {
591 warn("Writing HTTP request");
592 goto cleanup_fetch_url;
593 }
594
595 /* Read the response */
596 if ((buf = fparseln(fin, &len, NULL, "\0\0\0", 0)) == NULL) {
597 warn("Receiving HTTP reply");
598 goto cleanup_fetch_url;
599 }
600 while (len > 0 && (buf[len-1] == '\r' || buf[len-1] == '\n'))
601 buf[--len] = '\0';
602 if (debug)
603 fprintf(ttyout, "received `%s'\n", buf);
604
605 /* Determine HTTP response code */
606 cp = strchr(buf, ' ');
607 if (cp == NULL)
608 goto improper;
609 else
610 cp++;
611 hcode = strtol(cp, &ep, 10);
612 if (*ep != '\0' && !isspace((unsigned char)*ep))
613 goto improper;
614 message = xstrdup(cp);
615
616 /* Read the rest of the header. */
617 FREEPTR(buf);
618 while (1) {
619 if ((buf = fparseln(fin, &len, NULL, "\0\0\0", 0))
620 == NULL) {
621 warn("Receiving HTTP reply");
622 goto cleanup_fetch_url;
623 }
624 while (len > 0 &&
625 (buf[len-1] == '\r' || buf[len-1] == '\n'))
626 buf[--len] = '\0';
627 if (len == 0)
628 break;
629 if (debug)
630 fprintf(ttyout, "received `%s'\n", buf);
631
632 /* Look for some headers */
633 cp = buf;
634
635 #define CONTENTLEN "Content-Length: "
636 if (strncasecmp(cp, CONTENTLEN,
637 sizeof(CONTENTLEN) - 1) == 0) {
638 cp += sizeof(CONTENTLEN) - 1;
639 filesize = strtol(cp, &ep, 10);
640 if (filesize < 1 || *ep != '\0')
641 goto improper;
642 if (debug)
643 fprintf(ttyout,
644 #ifndef NO_QUAD
645 "parsed length as: %qd\n",
646 (long long)filesize);
647 #else
648 "parsed length as: %ld\n",
649 (long)filesize);
650 #endif
651
652 #define LASTMOD "Last-Modified: "
653 } else if (strncasecmp(cp, LASTMOD,
654 sizeof(LASTMOD) - 1) == 0) {
655 struct tm parsed;
656 char *t;
657
658 cp += sizeof(LASTMOD) - 1;
659 /* RFC 1123 */
660 if ((t = strptime(cp,
661 "%a, %d %b %Y %H:%M:%S GMT",
662 &parsed))
663 /* RFC 850 */
664 || (t = strptime(cp,
665 "%a, %d-%b-%y %H:%M:%S GMT",
666 &parsed))
667 /* asctime */
668 || (t = strptime(cp,
669 "%a, %b %d %H:%M:%S %Y",
670 &parsed))) {
671 parsed.tm_isdst = -1;
672 if (*t == '\0')
673 mtime = mkgmtime(&parsed);
674 if (debug && mtime != -1) {
675 fprintf(ttyout,
676 "parsed date as: %s",
677 ctime(&mtime));
678 }
679 }
680
681 #define LOCATION "Location: "
682 } else if (strncasecmp(cp, LOCATION,
683 sizeof(LOCATION) - 1) == 0) {
684 cp += sizeof(LOCATION) - 1;
685 location = xstrdup(cp);
686 if (debug)
687 fprintf(ttyout,
688 "parsed location as: %s\n", cp);
689
690 #define PROXYAUTH "Proxy-Authenticate: "
691 } else if (strncasecmp(cp, PROXYAUTH,
692 sizeof(PROXYAUTH) - 1) == 0) {
693 cp += sizeof(PROXYAUTH) - 1;
694 FREEPTR(auth);
695 auth = xstrdup(cp);
696 if (debug)
697 fprintf(ttyout,
698 "parsed proxy-auth as: %s\n", cp);
699
700 #define WWWAUTH "WWW-Authenticate: "
701 } else if (strncasecmp(cp, WWWAUTH,
702 sizeof(WWWAUTH) - 1) == 0) {
703 cp += sizeof(WWWAUTH) - 1;
704 FREEPTR(auth);
705 auth = xstrdup(cp);
706 if (debug)
707 fprintf(ttyout,
708 "parsed www-auth as: %s\n", cp);
709
710 }
711
712 }
713 FREEPTR(buf);
714 }
715
716 switch (hcode) {
717 case 200:
718 break;
719 case 300:
720 case 301:
721 case 302:
722 case 303:
723 case 305:
724 if (EMPTYSTRING(location)) {
725 warnx("No redirection Location provided by server");
726 goto cleanup_fetch_url;
727 }
728 if (redirect_loop++ > 5) {
729 warnx("Too many redirections requested");
730 goto cleanup_fetch_url;
731 }
732 if (hcode == 305) {
733 if (verbose)
734 fprintf(ttyout, "Redirected via %s\n",
735 location);
736 rval = fetch_url(url, outfile, location, proxyauth,
737 wwwauth);
738 } else {
739 if (verbose)
740 fprintf(ttyout, "Redirected to %s\n", location);
741 rval = go_fetch(location, outfile);
742 }
743 goto cleanup_fetch_url;
744 case 401:
745 case 407:
746 {
747 char **authp;
748
749 fprintf(ttyout, "%s\n", message);
750 if (EMPTYSTRING(auth)) {
751 warnx("No authentication challenge provided by server");
752 goto cleanup_fetch_url;
753 }
754 authp = (hcode == 401) ? &wwwauth : &proxyauth;
755 if (*authp != NULL) {
756 char reply[10];
757
758 fprintf(ttyout, "Authorization failed. Retry (y/n)? ");
759 if (fgets(reply, sizeof(reply), stdin) != NULL &&
760 tolower(reply[0]) != 'y')
761 goto cleanup_fetch_url;
762 }
763 if (auth_url(auth, authp) == 0) {
764 rval = fetch_url(url, outfile, proxyenv, proxyauth,
765 wwwauth);
766 memset(*authp, '\0', strlen(*authp));
767 FREEPTR(*authp);
768 }
769 goto cleanup_fetch_url;
770 }
771 default:
772 warnx("Error retrieving file - `%s'", message);
773 goto cleanup_fetch_url;
774 }
775
776 oldintr = oldintp = NULL;
777
778 /* Open the output file. */
779 if (strcmp(savefile, "-") == 0) {
780 fout = stdout;
781 } else if (*savefile == '|') {
782 oldintp = signal(SIGPIPE, SIG_IGN);
783 fout = popen(savefile + 1, "w");
784 if (fout == NULL) {
785 warn("Can't run `%s'", savefile + 1);
786 goto cleanup_fetch_url;
787 }
788 closefunc = pclose;
789 } else {
790 fout = fopen(savefile, "w");
791 if (fout == NULL) {
792 warn("Can't open `%s'", savefile);
793 goto cleanup_fetch_url;
794 }
795 closefunc = fclose;
796 }
797
798 /* Trap signals */
799 if (setjmp(httpabort)) {
800 if (oldintr)
801 (void)signal(SIGINT, oldintr);
802 if (oldintp)
803 (void)signal(SIGPIPE, oldintp);
804 goto cleanup_fetch_url;
805 }
806 oldintr = signal(SIGINT, aborthttp);
807
808 bytes = 0;
809 hashbytes = mark;
810 progressmeter(-1);
811
812 /* Finally, suck down the file. */
813 buf = xmalloc(BUFSIZ);
814 while ((len = fread(buf, sizeof(char), BUFSIZ, fin)) > 0) {
815 bytes += len;
816 if (fwrite(buf, sizeof(char), len, fout) != len) {
817 warn("Writing `%s'", savefile);
818 goto cleanup_fetch_url;
819 }
820 if (hash && !progress) {
821 while (bytes >= hashbytes) {
822 (void)putc('#', ttyout);
823 hashbytes += mark;
824 }
825 (void)fflush(ttyout);
826 }
827 }
828 if (hash && !progress && bytes > 0) {
829 if (bytes < mark)
830 (void)putc('#', ttyout);
831 (void)putc('\n', ttyout);
832 (void)fflush(ttyout);
833 }
834 if (ferror(fin)) {
835 warn("Reading file");
836 goto cleanup_fetch_url;
837 }
838 progressmeter(1);
839 (void)fflush(fout);
840 (void)signal(SIGINT, oldintr);
841 if (oldintp)
842 (void)signal(SIGPIPE, oldintp);
843 if (closefunc == fclose && mtime != -1) {
844 struct timeval tval[2];
845
846 (void)gettimeofday(&tval[0], NULL);
847 tval[1].tv_sec = mtime;
848 tval[1].tv_usec = 0;
849 (*closefunc)(fout);
850 fout = NULL;
851
852 if (utimes(savefile, tval) == -1) {
853 fprintf(ttyout,
854 "Can't change modification time to %s",
855 asctime(localtime(&mtime)));
856 }
857 }
858 if (bytes > 0)
859 ptransfer(0);
860
861 rval = 0;
862 goto cleanup_fetch_url;
863
864 improper:
865 warnx("Improper response from `%s'", host);
866
867 cleanup_fetch_url:
868 resetsockbufsize();
869 if (fin != NULL)
870 fclose(fin);
871 else if (s != -1)
872 close(s);
873 if (closefunc != NULL && fout != NULL)
874 (*closefunc)(fout);
875 FREEPTR(savefile);
876 FREEPTR(user);
877 FREEPTR(pass);
878 FREEPTR(host);
879 FREEPTR(path);
880 FREEPTR(buf);
881 FREEPTR(auth);
882 FREEPTR(location);
883 FREEPTR(message);
884 return (rval);
885 }
886
887 /*
888 * Abort a http retrieval
889 */
890 void
891 aborthttp(notused)
892 int notused;
893 {
894
895 alarmtimer(0);
896 fputs("\nHTTP fetch aborted.\n", ttyout);
897 (void)fflush(ttyout);
898 longjmp(httpabort, 1);
899 }
900
901 /*
902 * Retrieve ftp URL or classic ftp argument.
903 * Returns -1 on failure, 0 on completed xfer, 1 if ftp connection
904 * is still open (e.g, ftp xfer with trailing /)
905 */
906 static int
907 fetch_ftp(url, outfile)
908 const char *url;
909 const char *outfile;
910 {
911 static char lasthost[MAXHOSTNAMELEN];
912 char *cp, *xargv[5], rempath[MAXPATHLEN];
913 char portnum[6]; /* large enough for "65535\0" */
914 char *host, *path, *dir, *file, *user, *pass;
915 in_port_t port;
916 int dirhasglob, filehasglob, rval, xargc;
917
918 host = path = dir = file = user = pass = NULL;
919 port = 0;
920 rval = 1;
921
922 if (strncasecmp(url, FTP_URL, sizeof(FTP_URL) - 1) == 0) {
923 url_t urltype;
924
925 if ((parse_url(url, "URL", &urltype, &user, &pass,
926 &host, &port, &path) == -1) ||
927 (user != NULL && *user == '\0') ||
928 (pass != NULL && *pass == '\0') ||
929 EMPTYSTRING(host)) {
930 warnx("Invalid URL `%s'", url);
931 goto cleanup_fetch_ftp;
932 }
933 } else { /* classic style `host:file' */
934 host = xstrdup(url);
935 cp = strchr(host, ':');
936 if (cp != NULL) {
937 *cp = '\0';
938 path = xstrdup(cp + 1);
939 }
940 }
941 if (EMPTYSTRING(host))
942 goto cleanup_fetch_ftp;
943
944 /*
945 * Extract the file and (if present) directory name.
946 */
947 dir = path;
948 if (! EMPTYSTRING(dir)) {
949 if (*dir == '/')
950 dir++; /* skip leading / */
951 cp = strrchr(dir, '/');
952 if (cp != NULL) {
953 *cp++ = '\0';
954 file = cp;
955 } else {
956 file = dir;
957 dir = NULL;
958 }
959 }
960 if (debug)
961 fprintf(ttyout,
962 "fetch_ftp: user `%s', pass `%s', host %s:%d, path, `%s', dir `%s', file `%s'\n",
963 user ? user : "", pass ? pass : "",
964 host ? host : "", ntohs(port), path ? path : "",
965 dir ? dir : "", file ? file : "");
966
967 dirhasglob = filehasglob = 0;
968 if (doglob) {
969 if (! EMPTYSTRING(dir) && strpbrk(dir, "*?[]{}") != NULL)
970 dirhasglob = 1;
971 if (! EMPTYSTRING(file) && strpbrk(file, "*?[]{}") != NULL)
972 filehasglob = 1;
973 }
974
975 /*
976 * Set up the connection if we don't have one.
977 */
978 if (strcasecmp(host, lasthost) != 0) {
979 int oautologin;
980
981 (void)strcpy(lasthost, host);
982 if (connected)
983 disconnect(0, NULL);
984 xargv[0] = __progname;
985 xargv[1] = host;
986 xargv[2] = NULL;
987 xargc = 2;
988 if (port) {
989 snprintf(portnum, sizeof(portnum), "%d", ntohs(port));
990 xargv[2] = portnum;
991 xargv[3] = NULL;
992 xargc = 3;
993 }
994 oautologin = autologin;
995 if (user != NULL)
996 autologin = 0;
997 setpeer(xargc, xargv);
998 autologin = oautologin;
999 if ((connected == 0)
1000 || ((connected == 1) && !ftp_login(host, user, pass)) ) {
1001 warnx("Can't connect or login to host `%s'",
1002 host);
1003 goto cleanup_fetch_ftp;
1004 }
1005
1006 /* Always use binary transfers. */
1007 setbinary(0, NULL);
1008 } else {
1009 /* connection exists, cd back to `/' */
1010 xargv[0] = "cd";
1011 xargv[1] = "/";
1012 xargv[2] = NULL;
1013 dirchange = 0;
1014 cd(2, xargv);
1015 if (! dirchange)
1016 goto cleanup_fetch_ftp;
1017 }
1018
1019 /* Change directories, if necessary. */
1020 if (! EMPTYSTRING(dir) && !dirhasglob) {
1021 xargv[0] = "cd";
1022 xargv[1] = dir;
1023 xargv[2] = NULL;
1024 dirchange = 0;
1025 cd(2, xargv);
1026 if (! dirchange)
1027 goto cleanup_fetch_ftp;
1028 }
1029
1030 if (EMPTYSTRING(file)) {
1031 rval = -1;
1032 goto cleanup_fetch_ftp;
1033 }
1034
1035 if (!verbose)
1036 fprintf(ttyout, "Retrieving %s/%s\n", dir ? dir : "", file);
1037
1038 if (dirhasglob) {
1039 snprintf(rempath, sizeof(rempath), "%s/%s", dir, file);
1040 file = rempath;
1041 }
1042
1043 /* Fetch the file(s). */
1044 xargc = 2;
1045 xargv[0] = "get";
1046 xargv[1] = file;
1047 xargv[2] = NULL;
1048 if (dirhasglob || filehasglob) {
1049 int ointeractive;
1050
1051 ointeractive = interactive;
1052 interactive = 0;
1053 xargv[0] = "mget";
1054 mget(xargc, xargv);
1055 interactive = ointeractive;
1056 } else {
1057 if (outfile != NULL) {
1058 xargv[2] = (char *)outfile;
1059 xargv[3] = NULL;
1060 xargc++;
1061 }
1062 get(xargc, xargv);
1063 if (outfile != NULL && strcmp(outfile, "-") != 0
1064 && outfile[0] != '|')
1065 outfile = NULL;
1066 }
1067
1068 if ((code / 100) == COMPLETE)
1069 rval = 0;
1070
1071 cleanup_fetch_ftp:
1072 FREEPTR(host);
1073 FREEPTR(path);
1074 FREEPTR(user);
1075 FREEPTR(pass);
1076 return (rval);
1077 }
1078
1079 /*
1080 * Retrieve the given file to outfile.
1081 * Supports arguments of the form:
1082 * "host:path", "ftp://host/path" if $ftpproxy, call fetch_url() else
1083 * call fetch_ftp()
1084 * "http://host/path" call fetch_url() to use http
1085 * "file:///path" call fetch_url() to copy
1086 * "about:..." print a message
1087 *
1088 * Returns 1 on failure, 0 on completed xfer, -1 if ftp connection
1089 * is still open (e.g, ftp xfer with trailing /)
1090 */
1091 static int
1092 go_fetch(url, outfile)
1093 const char *url;
1094 const char *outfile;
1095 {
1096
1097 #ifndef SMALL
1098 /*
1099 * Check for about:*
1100 */
1101 if (strncasecmp(url, ABOUT_URL, sizeof(ABOUT_URL) - 1) == 0) {
1102 url += sizeof(ABOUT_URL) -1;
1103 if (strcasecmp(url, "ftp") == 0) {
1104 fprintf(ttyout, "%s\n%s\n",
1105 "This version of ftp has been enhanced by Luke Mewburn <lukem (at) netbsd.org>.",
1106 "Execute 'man ftp' for more details");
1107 } else if (strcasecmp(url, "netbsd") == 0) {
1108 fprintf(ttyout, "%s\n%s\n",
1109 "NetBSD is a freely available and redistributable UNIX-like operating system.",
1110 "For more information, see http://www.netbsd.org/index.html");
1111 } else {
1112 fprintf(ttyout, "`%s' is an interesting topic.\n", url);
1113 }
1114 return (0);
1115 }
1116 #endif /* SMALL */
1117
1118 /*
1119 * Check for file:// and http:// URLs.
1120 */
1121 if (strncasecmp(url, HTTP_URL, sizeof(HTTP_URL) - 1) == 0 ||
1122 strncasecmp(url, FILE_URL, sizeof(FILE_URL) - 1) == 0)
1123 return (fetch_url(url, outfile, NULL, NULL, NULL));
1124
1125 /*
1126 * Try FTP URL-style and host:file arguments next.
1127 * If ftpproxy is set with an FTP URL, use fetch_url()
1128 * Othewise, use fetch_ftp().
1129 */
1130 if (ftpproxy && strncasecmp(url, FTP_URL, sizeof(FTP_URL) - 1) == 0)
1131 return (fetch_url(url, outfile, NULL, NULL, NULL));
1132
1133 return (fetch_ftp(url, outfile));
1134 }
1135
1136 /*
1137 * Retrieve multiple files from the command line,
1138 * calling go_fetch() for each file.
1139 *
1140 * If an ftp path has a trailing "/", the path will be cd-ed into and
1141 * the connection remains open, and the function will return -1
1142 * (to indicate the connection is alive).
1143 * If an error occurs the return value will be the offset+1 in
1144 * argv[] of the file that caused a problem (i.e, argv[x]
1145 * returns x+1)
1146 * Otherwise, 0 is returned if all files retrieved successfully.
1147 */
1148 int
1149 auto_fetch(argc, argv, outfile)
1150 int argc;
1151 char *argv[];
1152 char *outfile;
1153 {
1154 volatile int argpos;
1155 int rval;
1156
1157 argpos = 0;
1158
1159 if (setjmp(toplevel)) {
1160 if (connected)
1161 disconnect(0, NULL);
1162 return (argpos + 1);
1163 }
1164 (void)signal(SIGINT, (sig_t)intr);
1165 (void)signal(SIGPIPE, (sig_t)lostpeer);
1166
1167 /*
1168 * Loop through as long as there's files to fetch.
1169 */
1170 for (rval = 0; (rval == 0) && (argpos < argc); argpos++) {
1171 if (strchr(argv[argpos], ':') == NULL)
1172 break;
1173 redirect_loop = 0;
1174 rval = go_fetch(argv[argpos], outfile);
1175 if (rval > 0)
1176 rval = argpos + 1;
1177 }
1178
1179 if (connected && rval != -1)
1180 disconnect(0, NULL);
1181 return (rval);
1182 }
1183