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