fetch.c revision 1.121 1 /* $NetBSD: fetch.c,v 1.121 2000/08/01 22:47:27 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.121 2000/08/01 22:47:27 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 struct addrinfo hints, *res, *res0 = NULL;
439 int error;
440 char hbuf[NI_MAXHOST];
441 volatile sigfunc oldintr, oldintp;
442 volatile int s;
443 struct stat sb;
444 int ischunked, isproxy, rval, hcode;
445 size_t len;
446 static size_t bufsize;
447 static char *xferbuf;
448 char *cp, *ep, *buf, *savefile;
449 char *auth, *location, *message;
450 char *user, *pass, *host, *port, *path, *decodedpath;
451 char *puser, *ppass;
452 off_t hashbytes, rangestart, rangeend, entitylen;
453 int (*closefunc)(FILE *);
454 FILE *fin, *fout;
455 time_t mtime;
456 url_t urltype;
457 in_port_t portnum;
458
459 oldintr = oldintp = NULL;
460 closefunc = NULL;
461 fin = fout = NULL;
462 s = -1;
463 buf = savefile = NULL;
464 auth = location = message = NULL;
465 ischunked = isproxy = hcode = 0;
466 rval = 1;
467 user = pass = host = path = decodedpath = puser = ppass = NULL;
468
469 #ifdef __GNUC__ /* shut up gcc warnings */
470 (void)&closefunc;
471 (void)&fin;
472 (void)&fout;
473 (void)&buf;
474 (void)&savefile;
475 (void)&rval;
476 (void)&isproxy;
477 (void)&hcode;
478 (void)&ischunked;
479 (void)&message;
480 (void)&location;
481 (void)&auth;
482 (void)&decodedpath;
483 #endif
484
485 if (parse_url(url, "URL", &urltype, &user, &pass, &host, &port,
486 &portnum, &path) == -1)
487 goto cleanup_fetch_url;
488
489 if (urltype == FILE_URL_T && ! EMPTYSTRING(host)
490 && strcasecmp(host, "localhost") != 0) {
491 warnx("No support for non local file URL `%s'", url);
492 goto cleanup_fetch_url;
493 }
494
495 if (EMPTYSTRING(path)) {
496 if (urltype == FTP_URL_T) {
497 rval = fetch_ftp(url);
498 goto cleanup_fetch_url;
499 }
500 if (urltype != HTTP_URL_T || outfile == NULL) {
501 warnx("Invalid URL (no file after host) `%s'", url);
502 goto cleanup_fetch_url;
503 }
504 }
505
506 decodedpath = xstrdup(path);
507 url_decode(decodedpath);
508
509 if (outfile)
510 savefile = xstrdup(outfile);
511 else {
512 cp = strrchr(decodedpath, '/'); /* find savefile */
513 if (cp != NULL)
514 savefile = xstrdup(cp + 1);
515 else
516 savefile = xstrdup(decodedpath);
517 }
518 if (EMPTYSTRING(savefile)) {
519 if (urltype == FTP_URL_T) {
520 rval = fetch_ftp(url);
521 goto cleanup_fetch_url;
522 }
523 warnx("Invalid URL (no file after directory) `%s'", url);
524 goto cleanup_fetch_url;
525 } else {
526 if (debug)
527 fprintf(ttyout, "got savefile as `%s'\n", savefile);
528 }
529
530 restart_point = 0;
531 filesize = -1;
532 rangestart = rangeend = entitylen = -1;
533 mtime = -1;
534 if (restartautofetch) {
535 if (strcmp(savefile, "-") != 0 && *savefile != '|' &&
536 stat(savefile, &sb) == 0)
537 restart_point = sb.st_size;
538 }
539 if (urltype == FILE_URL_T) { /* file:// URLs */
540 direction = "copied";
541 fin = fopen(decodedpath, "r");
542 if (fin == NULL) {
543 warn("Cannot open file `%s'", decodedpath);
544 goto cleanup_fetch_url;
545 }
546 if (fstat(fileno(fin), &sb) == 0) {
547 mtime = sb.st_mtime;
548 filesize = sb.st_size;
549 }
550 if (restart_point) {
551 if (lseek(fileno(fin), restart_point, SEEK_SET) < 0) {
552 warn("Can't lseek to restart `%s'",
553 decodedpath);
554 goto cleanup_fetch_url;
555 }
556 }
557 if (verbose) {
558 fprintf(ttyout, "Copying %s", decodedpath);
559 if (restart_point)
560 fprintf(ttyout, " (restarting at " LLF ")",
561 (LLT)restart_point);
562 fputs("\n", ttyout);
563 }
564 } else { /* ftp:// or http:// URLs */
565 char *leading;
566 int hasleading;
567
568 if (proxyenv == NULL) {
569 if (urltype == HTTP_URL_T)
570 proxyenv = getoptionvalue("http_proxy");
571 else if (urltype == FTP_URL_T)
572 proxyenv = getoptionvalue("ftp_proxy");
573 }
574 direction = "retrieved";
575 if (! EMPTYSTRING(proxyenv)) { /* use proxy */
576 url_t purltype;
577 char *phost, *ppath;
578 char *pport, *no_proxy;
579
580 isproxy = 1;
581
582 /* check URL against list of no_proxied sites */
583 no_proxy = getoptionvalue("no_proxy");
584 if (! EMPTYSTRING(no_proxy)) {
585 char *np, *np_copy;
586 long np_port;
587 size_t hlen, plen;
588
589 np_copy = xstrdup(no_proxy);
590 hlen = strlen(host);
591 while ((cp = strsep(&np_copy, " ,")) != NULL) {
592 if (*cp == '\0')
593 continue;
594 if ((np = strrchr(cp, ':')) != NULL) {
595 *np = '\0';
596 np_port =
597 strtol(np + 1, &ep, 10);
598 if (*ep != '\0')
599 continue;
600 if (np_port != portnum)
601 continue;
602 }
603 plen = strlen(cp);
604 if (hlen < plen)
605 continue;
606 if (strncasecmp(host + hlen - plen,
607 cp, plen) == 0) {
608 isproxy = 0;
609 break;
610 }
611 }
612 FREEPTR(np_copy);
613 }
614
615 if (isproxy) {
616 if (parse_url(proxyenv, "proxy URL", &purltype,
617 &puser, &ppass, &phost, &pport, &portnum,
618 &ppath) == -1)
619 goto cleanup_fetch_url;
620
621 if ((purltype != HTTP_URL_T
622 && purltype != FTP_URL_T) ||
623 EMPTYSTRING(phost) ||
624 (! EMPTYSTRING(ppath)
625 && strcmp(ppath, "/") != 0)) {
626 warnx("Malformed proxy URL `%s'",
627 proxyenv);
628 FREEPTR(phost);
629 FREEPTR(pport);
630 FREEPTR(ppath);
631 goto cleanup_fetch_url;
632 }
633 if (isipv6addr(host) &&
634 strchr(host, '%') != NULL) {
635 warnx(
636 "Scoped address notation `%s' disallowed via web proxy",
637 host);
638 FREEPTR(phost);
639 FREEPTR(pport);
640 FREEPTR(ppath);
641 goto cleanup_fetch_url;
642 }
643
644 FREEPTR(host);
645 host = phost;
646 FREEPTR(port);
647 port = pport;
648 FREEPTR(path);
649 path = xstrdup(url);
650 FREEPTR(ppath);
651 }
652 } /* ! EMPTYSTRING(proxyenv) */
653
654 memset(&hints, 0, sizeof(hints));
655 hints.ai_flags = 0;
656 hints.ai_family = AF_UNSPEC;
657 hints.ai_socktype = SOCK_STREAM;
658 hints.ai_protocol = 0;
659 error = getaddrinfo(host, port, &hints, &res0);
660 if (error) {
661 warnx("%s", gai_strerror(error));
662 goto cleanup_fetch_url;
663 }
664 if (res0->ai_canonname)
665 host = res0->ai_canonname;
666
667 s = -1;
668 for (res = res0; res; res = res->ai_next) {
669 /*
670 * see comment in hookup()
671 */
672 ai_unmapped(res);
673 if (getnameinfo(res->ai_addr, res->ai_addrlen,
674 hbuf, sizeof(hbuf), NULL, 0,
675 NI_NUMERICHOST) != 0)
676 strncpy(hbuf, "invalid", sizeof(hbuf));
677
678 if (verbose && res != res0)
679 fprintf(ttyout, "Trying %s...\n", hbuf);
680
681 s = socket(res->ai_family, res->ai_socktype,
682 res->ai_protocol);
683 if (s < 0) {
684 warn("Can't create socket");
685 continue;
686 }
687
688 if (xconnect(s, res->ai_addr, res->ai_addrlen) < 0) {
689 warn("Connect to address `%s'", hbuf);
690 close(s);
691 s = -1;
692 continue;
693 }
694
695 /* success */
696 break;
697 }
698 freeaddrinfo(res0);
699
700 if (s < 0) {
701 warn("Can't connect to %s", host);
702 goto cleanup_fetch_url;
703 }
704
705 fin = fdopen(s, "r+");
706 /*
707 * Construct and send the request.
708 */
709 if (verbose)
710 fprintf(ttyout, "Requesting %s\n", url);
711 leading = " (";
712 hasleading = 0;
713 if (isproxy) {
714 if (verbose) {
715 fprintf(ttyout, "%svia %s:%s", leading,
716 host, port);
717 leading = ", ";
718 hasleading++;
719 }
720 fprintf(fin, "GET %s HTTP/1.0\r\n", path);
721 if (flushcache)
722 fprintf(fin, "Pragma: no-cache\r\n");
723 } else {
724 fprintf(fin, "GET %s HTTP/1.1\r\n", path);
725 if (strchr(host, ':')) {
726 char *h, *p;
727
728 /*
729 * strip off IPv6 scope identifier, since it is
730 * local to the node
731 */
732 h = xstrdup(host);
733 if (isipv6addr(h) &&
734 (p = strchr(h, '%')) != NULL) {
735 *p = '\0';
736 }
737 fprintf(fin, "Host: [%s]:%d\r\n", h, portnum);
738 free(h);
739 } else
740 fprintf(fin, "Host: %s:%d\r\n", host, portnum);
741 fprintf(fin, "Accept: */*\r\n");
742 fprintf(fin, "Connection: close\r\n");
743 if (restart_point) {
744 fputs(leading, ttyout);
745 fprintf(fin, "Range: bytes=" LLF "-\r\n",
746 (LLT)restart_point);
747 fprintf(ttyout, "restarting at " LLF,
748 (LLT)restart_point);
749 leading = ", ";
750 hasleading++;
751 }
752 if (flushcache)
753 fprintf(fin, "Cache-Control: no-cache\r\n");
754 }
755 fprintf(fin, "User-Agent: %s/%s\r\n", FTP_PRODUCT, FTP_VERSION);
756 if (wwwauth) {
757 if (verbose) {
758 fprintf(ttyout, "%swith authorization",
759 leading);
760 leading = ", ";
761 hasleading++;
762 }
763 fprintf(fin, "Authorization: %s\r\n", wwwauth);
764 }
765 if (proxyauth) {
766 if (verbose) {
767 fprintf(ttyout,
768 "%swith proxy authorization", leading);
769 leading = ", ";
770 hasleading++;
771 }
772 fprintf(fin, "Proxy-Authorization: %s\r\n", proxyauth);
773 }
774 if (verbose && hasleading)
775 fputs(")\n", ttyout);
776 fprintf(fin, "\r\n");
777 if (fflush(fin) == EOF) {
778 warn("Writing HTTP request");
779 goto cleanup_fetch_url;
780 }
781
782 /* Read the response */
783 if ((buf = fparseln(fin, &len, NULL, "\0\0\0", 0)) == NULL) {
784 warn("Receiving HTTP reply");
785 goto cleanup_fetch_url;
786 }
787 while (len > 0 && (buf[len-1] == '\r' || buf[len-1] == '\n'))
788 buf[--len] = '\0';
789 if (debug)
790 fprintf(ttyout, "received `%s'\n", buf);
791
792 /* Determine HTTP response code */
793 cp = strchr(buf, ' ');
794 if (cp == NULL)
795 goto improper;
796 else
797 cp++;
798 hcode = strtol(cp, &ep, 10);
799 if (*ep != '\0' && !isspace((unsigned char)*ep))
800 goto improper;
801 message = xstrdup(cp);
802
803 /* Read the rest of the header. */
804 FREEPTR(buf);
805 while (1) {
806 if ((buf = fparseln(fin, &len, NULL, "\0\0\0", 0))
807 == NULL) {
808 warn("Receiving HTTP reply");
809 goto cleanup_fetch_url;
810 }
811 while (len > 0 &&
812 (buf[len-1] == '\r' || buf[len-1] == '\n'))
813 buf[--len] = '\0';
814 if (len == 0)
815 break;
816 if (debug)
817 fprintf(ttyout, "received `%s'\n", buf);
818
819 /* Look for some headers */
820 cp = buf;
821
822 #define CONTENTLEN "Content-Length: "
823 if (strncasecmp(cp, CONTENTLEN,
824 sizeof(CONTENTLEN) - 1) == 0) {
825 cp += sizeof(CONTENTLEN) - 1;
826 filesize = STRTOLL(cp, &ep, 10);
827 if (filesize < 0 || *ep != '\0')
828 goto improper;
829 if (debug)
830 fprintf(ttyout,
831 "parsed len as: " LLF "\n",
832 (LLT)filesize);
833
834 #define CONTENTRANGE "Content-Range: bytes "
835 } else if (strncasecmp(cp, CONTENTRANGE,
836 sizeof(CONTENTRANGE) - 1) == 0) {
837 cp += sizeof(CONTENTRANGE) - 1;
838 rangestart = STRTOLL(cp, &ep, 10);
839 if (rangestart < 0 || *ep != '-')
840 goto improper;
841 cp = ep + 1;
842 rangeend = STRTOLL(cp, &ep, 10);
843 if (rangeend < 0 || *ep != '/' ||
844 rangeend < rangestart)
845 goto improper;
846 cp = ep + 1;
847 entitylen = STRTOLL(cp, &ep, 10);
848 if (entitylen < 0 || *ep != '\0')
849 goto improper;
850
851 if (debug)
852 fprintf(ttyout,
853 "parsed range as: "
854 LLF "-" LLF "/" LLF "\n",
855 (LLT)rangestart,
856 (LLT)rangeend,
857 (LLT)entitylen);
858 if (! restart_point) {
859 warnx(
860 "Received unexpected Content-Range header");
861 goto cleanup_fetch_url;
862 }
863
864 #define LASTMOD "Last-Modified: "
865 } else if (strncasecmp(cp, LASTMOD,
866 sizeof(LASTMOD) - 1) == 0) {
867 struct tm parsed;
868 char *t;
869
870 cp += sizeof(LASTMOD) - 1;
871 /* RFC 1123 */
872 if ((t = strptime(cp,
873 "%a, %d %b %Y %H:%M:%S GMT",
874 &parsed))
875 /* RFC 850 */
876 || (t = strptime(cp,
877 "%a, %d-%b-%y %H:%M:%S GMT",
878 &parsed))
879 /* asctime */
880 || (t = strptime(cp,
881 "%a, %b %d %H:%M:%S %Y",
882 &parsed))) {
883 parsed.tm_isdst = -1;
884 if (*t == '\0')
885 mtime = timegm(&parsed);
886 if (debug && mtime != -1) {
887 fprintf(ttyout,
888 "parsed date as: %s",
889 ctime(&mtime));
890 }
891 }
892
893 #define LOCATION "Location: "
894 } else if (strncasecmp(cp, LOCATION,
895 sizeof(LOCATION) - 1) == 0) {
896 cp += sizeof(LOCATION) - 1;
897 location = xstrdup(cp);
898 if (debug)
899 fprintf(ttyout,
900 "parsed location as: %s\n", cp);
901
902 #define TRANSENC "Transfer-Encoding: "
903 } else if (strncasecmp(cp, TRANSENC,
904 sizeof(TRANSENC) - 1) == 0) {
905 cp += sizeof(TRANSENC) - 1;
906 if (strcasecmp(cp, "binary") == 0) {
907 warnx(
908 "Bogus transfer encoding - `%s' (fetching anyway)",
909 cp);
910 continue;
911 }
912 if (strcasecmp(cp, "chunked") != 0) {
913 warnx(
914 "Unsupported transfer encoding - `%s'",
915 cp);
916 goto cleanup_fetch_url;
917 }
918 ischunked++;
919 if (debug)
920 fprintf(ttyout,
921 "using chunked encoding\n");
922
923 #define PROXYAUTH "Proxy-Authenticate: "
924 } else if (strncasecmp(cp, PROXYAUTH,
925 sizeof(PROXYAUTH) - 1) == 0) {
926 cp += sizeof(PROXYAUTH) - 1;
927 FREEPTR(auth);
928 auth = xstrdup(cp);
929 if (debug)
930 fprintf(ttyout,
931 "parsed proxy-auth as: %s\n", cp);
932
933 #define WWWAUTH "WWW-Authenticate: "
934 } else if (strncasecmp(cp, WWWAUTH,
935 sizeof(WWWAUTH) - 1) == 0) {
936 cp += sizeof(WWWAUTH) - 1;
937 FREEPTR(auth);
938 auth = xstrdup(cp);
939 if (debug)
940 fprintf(ttyout,
941 "parsed www-auth as: %s\n", cp);
942
943 }
944
945 }
946 /* finished parsing header */
947 FREEPTR(buf);
948
949 switch (hcode) {
950 case 200:
951 break;
952 case 206:
953 if (! restart_point) {
954 warnx("Not expecting partial content header");
955 goto cleanup_fetch_url;
956 }
957 break;
958 case 300:
959 case 301:
960 case 302:
961 case 303:
962 case 305:
963 if (EMPTYSTRING(location)) {
964 warnx(
965 "No redirection Location provided by server");
966 goto cleanup_fetch_url;
967 }
968 if (redirect_loop++ > 5) {
969 warnx("Too many redirections requested");
970 goto cleanup_fetch_url;
971 }
972 if (hcode == 305) {
973 if (verbose)
974 fprintf(ttyout, "Redirected via %s\n",
975 location);
976 rval = fetch_url(url, location,
977 proxyauth, wwwauth);
978 } else {
979 if (verbose)
980 fprintf(ttyout, "Redirected to %s\n",
981 location);
982 rval = go_fetch(location);
983 }
984 goto cleanup_fetch_url;
985 case 401:
986 case 407:
987 {
988 char **authp;
989 char *auser, *apass;
990
991 fprintf(ttyout, "%s\n", message);
992 if (EMPTYSTRING(auth)) {
993 warnx(
994 "No authentication challenge provided by server");
995 goto cleanup_fetch_url;
996 }
997 if (hcode == 401) {
998 authp = &wwwauth;
999 auser = user;
1000 apass = pass;
1001 } else {
1002 authp = &proxyauth;
1003 auser = puser;
1004 apass = ppass;
1005 }
1006 if (*authp != NULL) {
1007 char reply[10];
1008
1009 fprintf(ttyout,
1010 "Authorization failed. Retry (y/n)? ");
1011 if (fgets(reply, sizeof(reply), stdin)
1012 == NULL) {
1013 clearerr(stdin);
1014 goto cleanup_fetch_url;
1015 } else {
1016 if (tolower(reply[0]) != 'y')
1017 goto cleanup_fetch_url;
1018 }
1019 auser = NULL;
1020 apass = NULL;
1021 }
1022 if (auth_url(auth, authp, auser, apass) == 0) {
1023 rval = fetch_url(url, proxyenv,
1024 proxyauth, wwwauth);
1025 memset(*authp, 0, strlen(*authp));
1026 FREEPTR(*authp);
1027 }
1028 goto cleanup_fetch_url;
1029 }
1030 default:
1031 if (message)
1032 warnx("Error retrieving file - `%s'", message);
1033 else
1034 warnx("Unknown error retrieving file");
1035 goto cleanup_fetch_url;
1036 }
1037 } /* end of ftp:// or http:// specific setup */
1038
1039 /* Open the output file. */
1040 if (strcmp(savefile, "-") == 0) {
1041 fout = stdout;
1042 } else if (*savefile == '|') {
1043 oldintp = xsignal(SIGPIPE, SIG_IGN);
1044 fout = popen(savefile + 1, "w");
1045 if (fout == NULL) {
1046 warn("Can't run `%s'", savefile + 1);
1047 goto cleanup_fetch_url;
1048 }
1049 closefunc = pclose;
1050 } else {
1051 if (restart_point){
1052 if (entitylen != -1)
1053 filesize = entitylen;
1054 if (rangestart != -1 && rangestart != restart_point) {
1055 warnx(
1056 "Size of `%s' differs from save file `%s'",
1057 url, savefile);
1058 goto cleanup_fetch_url;
1059 }
1060 fout = fopen(savefile, "a");
1061 } else
1062 fout = fopen(savefile, "w");
1063 if (fout == NULL) {
1064 warn("Can't open `%s'", savefile);
1065 goto cleanup_fetch_url;
1066 }
1067 closefunc = fclose;
1068 }
1069
1070 /* Trap signals */
1071 if (sigsetjmp(httpabort, 1))
1072 goto cleanup_fetch_url;
1073 (void)xsignal(SIGQUIT, psummary);
1074 oldintr = xsignal(SIGINT, aborthttp);
1075
1076 if (rcvbuf_size > bufsize) {
1077 if (xferbuf)
1078 (void)free(xferbuf);
1079 bufsize = rcvbuf_size;
1080 xferbuf = xmalloc(bufsize);
1081 }
1082
1083 bytes = 0;
1084 hashbytes = mark;
1085 progressmeter(-1);
1086
1087 /* Finally, suck down the file. */
1088 do {
1089 long chunksize;
1090
1091 chunksize = 0;
1092 /* read chunksize */
1093 if (ischunked) {
1094 if (fgets(xferbuf, bufsize, fin) == NULL) {
1095 warnx("Unexpected EOF reading chunksize");
1096 goto cleanup_fetch_url;
1097 }
1098 chunksize = strtol(xferbuf, &ep, 16);
1099
1100 /*
1101 * XXX: Work around bug in Apache 1.3.9, which
1102 * incorrectly puts a trailing space after
1103 * the chunksize.
1104 */
1105 if (*ep == ' ')
1106 ep++;
1107
1108 if (strcmp(ep, "\r\n") != 0) {
1109 warnx("Unexpected data following chunksize");
1110 goto cleanup_fetch_url;
1111 }
1112 if (debug)
1113 fprintf(ttyout, "got chunksize of " LLF "\n",
1114 (LLT)chunksize);
1115 if (chunksize == 0)
1116 break;
1117 }
1118 /* transfer file or chunk */
1119 while (1) {
1120 struct timeval then, now, td;
1121 off_t bufrem;
1122
1123 if (rate_get)
1124 (void)gettimeofday(&then, NULL);
1125 bufrem = rate_get ? rate_get : bufsize;
1126 if (ischunked)
1127 bufrem = MIN(chunksize, bufrem);
1128 while (bufrem > 0) {
1129 len = fread(xferbuf, sizeof(char),
1130 MIN(bufsize, bufrem), fin);
1131 if (len <= 0)
1132 goto chunkdone;
1133 bytes += len;
1134 bufrem -= len;
1135 if (fwrite(xferbuf, sizeof(char), len, fout)
1136 != len) {
1137 warn("Writing `%s'", savefile);
1138 goto cleanup_fetch_url;
1139 }
1140 if (hash && !progress) {
1141 while (bytes >= hashbytes) {
1142 (void)putc('#', ttyout);
1143 hashbytes += mark;
1144 }
1145 (void)fflush(ttyout);
1146 }
1147 if (ischunked) {
1148 chunksize -= len;
1149 if (chunksize <= 0)
1150 break;
1151 }
1152 }
1153 if (rate_get) {
1154 while (1) {
1155 (void)gettimeofday(&now, NULL);
1156 timersub(&now, &then, &td);
1157 if (td.tv_sec > 0)
1158 break;
1159 usleep(1000000 - td.tv_usec);
1160 }
1161 }
1162 if (ischunked && chunksize <= 0)
1163 break;
1164 }
1165 /* read CRLF after chunk*/
1166 chunkdone:
1167 if (ischunked) {
1168 if (fgets(xferbuf, bufsize, fin) == NULL)
1169 break;
1170 if (strcmp(xferbuf, "\r\n") != 0) {
1171 warnx("Unexpected data following chunk");
1172 goto cleanup_fetch_url;
1173 }
1174 }
1175 } while (ischunked);
1176 if (hash && !progress && bytes > 0) {
1177 if (bytes < mark)
1178 (void)putc('#', ttyout);
1179 (void)putc('\n', ttyout);
1180 }
1181 if (ferror(fin)) {
1182 warn("Reading file");
1183 goto cleanup_fetch_url;
1184 }
1185 progressmeter(1);
1186 bytes = 0;
1187 (void)fflush(fout);
1188 if (closefunc == fclose && mtime != -1) {
1189 struct timeval tval[2];
1190
1191 (void)gettimeofday(&tval[0], NULL);
1192 tval[1].tv_sec = mtime;
1193 tval[1].tv_usec = 0;
1194 (*closefunc)(fout);
1195 fout = NULL;
1196
1197 if (utimes(savefile, tval) == -1) {
1198 fprintf(ttyout,
1199 "Can't change modification time to %s",
1200 asctime(localtime(&mtime)));
1201 }
1202 }
1203 if (bytes > 0)
1204 ptransfer(0);
1205
1206 rval = 0;
1207 goto cleanup_fetch_url;
1208
1209 improper:
1210 warnx("Improper response from `%s'", host);
1211
1212 cleanup_fetch_url:
1213 if (oldintr)
1214 (void)xsignal(SIGINT, oldintr);
1215 if (oldintp)
1216 (void)xsignal(SIGPIPE, oldintp);
1217 if (fin != NULL)
1218 fclose(fin);
1219 else if (s != -1)
1220 close(s);
1221 if (closefunc != NULL && fout != NULL)
1222 (*closefunc)(fout);
1223 FREEPTR(savefile);
1224 FREEPTR(user);
1225 FREEPTR(pass);
1226 FREEPTR(host);
1227 FREEPTR(port);
1228 FREEPTR(path);
1229 FREEPTR(decodedpath);
1230 FREEPTR(puser);
1231 FREEPTR(ppass);
1232 FREEPTR(buf);
1233 FREEPTR(auth);
1234 FREEPTR(location);
1235 FREEPTR(message);
1236 return (rval);
1237 }
1238
1239 /*
1240 * Abort a HTTP retrieval
1241 */
1242 void
1243 aborthttp(int notused)
1244 {
1245 char msgbuf[100];
1246 int len;
1247
1248 alarmtimer(0);
1249 len = strlcpy(msgbuf, "\nHTTP fetch aborted.\n", sizeof(msgbuf));
1250 write(fileno(ttyout), msgbuf, len);
1251 siglongjmp(httpabort, 1);
1252 }
1253
1254 /*
1255 * Retrieve ftp URL or classic ftp argument using FTP.
1256 * Returns 1 on failure, 0 on completed xfer, -1 if ftp connection
1257 * is still open (e.g, ftp xfer with trailing /)
1258 */
1259 static int
1260 fetch_ftp(const char *url)
1261 {
1262 char *cp, *xargv[5], rempath[MAXPATHLEN];
1263 char *host, *path, *dir, *file, *user, *pass;
1264 char *port;
1265 int dirhasglob, filehasglob, oautologin, rval, type, xargc;
1266 in_port_t portnum;
1267 url_t urltype;
1268
1269 host = path = dir = file = user = pass = NULL;
1270 port = NULL;
1271 rval = 1;
1272 type = TYPE_I;
1273
1274 if (strncasecmp(url, FTP_URL, sizeof(FTP_URL) - 1) == 0) {
1275 if ((parse_url(url, "URL", &urltype, &user, &pass,
1276 &host, &port, &portnum, &path) == -1) ||
1277 (user != NULL && *user == '\0') ||
1278 (pass != NULL && *pass == '\0') ||
1279 EMPTYSTRING(host)) {
1280 warnx("Invalid URL `%s'", url);
1281 goto cleanup_fetch_ftp;
1282 }
1283 url_decode(user);
1284 url_decode(pass);
1285 /*
1286 * Note: Don't url_decode(path) here. We need to keep the
1287 * distinction between "/" and "%2F" until later.
1288 */
1289
1290 /* check for trailing ';type=[aid]' */
1291 if (! EMPTYSTRING(path) && (cp = strrchr(path, ';')) != NULL) {
1292 if (strcasecmp(cp, ";type=a") == 0)
1293 type = TYPE_A;
1294 else if (strcasecmp(cp, ";type=i") == 0)
1295 type = TYPE_I;
1296 else if (strcasecmp(cp, ";type=d") == 0) {
1297 warnx(
1298 "Directory listing via a URL is not supported");
1299 goto cleanup_fetch_ftp;
1300 } else {
1301 warnx("Invalid suffix `%s' in URL `%s'", cp,
1302 url);
1303 goto cleanup_fetch_ftp;
1304 }
1305 *cp = 0;
1306 }
1307 } else { /* classic style `[user@]host:[file]' */
1308 urltype = CLASSIC_URL_T;
1309 host = xstrdup(url);
1310 cp = strchr(host, '@');
1311 if (cp != NULL) {
1312 *cp = '\0';
1313 user = host;
1314 anonftp = 0; /* disable anonftp */
1315 host = xstrdup(cp + 1);
1316 }
1317 cp = strchr(host, ':');
1318 if (cp != NULL) {
1319 *cp = '\0';
1320 path = xstrdup(cp + 1);
1321 }
1322 }
1323 if (EMPTYSTRING(host))
1324 goto cleanup_fetch_ftp;
1325
1326 /* Extract the file and (if present) directory name. */
1327 dir = path;
1328 if (! EMPTYSTRING(dir)) {
1329 /*
1330 * If we are dealing with classic `[user@]host:[path]' syntax,
1331 * then a path of the form `/file' (resulting from input of the
1332 * form `host:/file') means that we should do "CWD /" before
1333 * retrieving the file. So we set dir="/" and file="file".
1334 *
1335 * But if we are dealing with URLs like `ftp://host/path' then
1336 * a path of the form `/file' (resulting from a URL of the form
1337 * `ftp://host//file') means that we should do `CWD ' (with an
1338 * empty argument) before retrieving the file. So we set
1339 * dir="" and file="file".
1340 *
1341 * If the path does not contain / at all, we set dir=NULL.
1342 * (We get a path without any slashes if we are dealing with
1343 * classic `[user@]host:[file]' or URL `ftp://host/file'.)
1344 *
1345 * In all other cases, we set dir to a string that does not
1346 * include the final '/' that separates the dir part from the
1347 * file part of the path. (This will be the empty string if
1348 * and only if we are dealing with a path of the form `/file'
1349 * resulting from an URL of the form `ftp://host//file'.)
1350 */
1351 cp = strrchr(dir, '/');
1352 if (cp == dir && urltype == CLASSIC_URL_T) {
1353 file = cp + 1;
1354 dir = "/";
1355 } else if (cp != NULL) {
1356 *cp++ = '\0';
1357 file = cp;
1358 } else {
1359 file = dir;
1360 dir = NULL;
1361 }
1362 } else
1363 dir = NULL;
1364 if (urltype == FTP_URL_T && file != NULL) {
1365 url_decode(file);
1366 /* but still don't url_decode(dir) */
1367 }
1368 if (debug)
1369 fprintf(ttyout,
1370 "fetch_ftp: user `%s' pass `%s' host %s port %s "
1371 "path `%s' dir `%s' file `%s'\n",
1372 user ? user : "<null>", pass ? pass : "<null>",
1373 host ? host : "<null>", port ? port : "<null>",
1374 path ? path : "<null>",
1375 dir ? dir : "<null>", file ? file : "<null>");
1376
1377 dirhasglob = filehasglob = 0;
1378 if (doglob && urltype == CLASSIC_URL_T) {
1379 if (! EMPTYSTRING(dir) && strpbrk(dir, "*?[]{}") != NULL)
1380 dirhasglob = 1;
1381 if (! EMPTYSTRING(file) && strpbrk(file, "*?[]{}") != NULL)
1382 filehasglob = 1;
1383 }
1384
1385 /* Set up the connection */
1386 if (connected)
1387 disconnect(0, NULL);
1388 xargv[0] = __progname;
1389 xargv[1] = host;
1390 xargv[2] = NULL;
1391 xargc = 2;
1392 if (port) {
1393 xargv[2] = port;
1394 xargv[3] = NULL;
1395 xargc = 3;
1396 }
1397 oautologin = autologin;
1398 /* don't autologin in setpeer(), use ftp_login() below */
1399 autologin = 0;
1400 setpeer(xargc, xargv);
1401 autologin = oautologin;
1402 if ((connected == 0) ||
1403 (connected == 1 && !ftp_login(host, user, pass))) {
1404 warnx("Can't connect or login to host `%s'", host);
1405 goto cleanup_fetch_ftp;
1406 }
1407
1408 switch (type) {
1409 case TYPE_A:
1410 setascii(1, xargv);
1411 break;
1412 case TYPE_I:
1413 setbinary(1, xargv);
1414 break;
1415 default:
1416 errx(1, "fetch_ftp: unknown transfer type %d", type);
1417 }
1418
1419 /*
1420 * Change directories, if necessary.
1421 *
1422 * Note: don't use EMPTYSTRING(dir) below, because
1423 * dir=="" means something different from dir==NULL.
1424 */
1425 if (dir != NULL && !dirhasglob) {
1426 char *nextpart;
1427
1428 /*
1429 * If we are dealing with a classic `[user@]host:[path]'
1430 * (urltype is CLASSIC_URL_T) then we have a raw directory
1431 * name (not encoded in any way) and we can change
1432 * directories in one step.
1433 *
1434 * If we are dealing with an `ftp://host/path' URL
1435 * (urltype is FTP_URL_T), then RFC 1738 says we need to
1436 * send a separate CWD command for each unescaped "/"
1437 * in the path, and we have to interpret %hex escaping
1438 * *after* we find the slashes. It's possible to get
1439 * empty components here, (from multiple adjacent
1440 * slashes in the path) and RFC 1738 says that we should
1441 * still do `CWD ' (with a null argument) in such cases.
1442 *
1443 * Many ftp servers don't support `CWD ', so if there's an
1444 * error performing that command, bail out with a descriptive
1445 * message.
1446 *
1447 * Examples:
1448 *
1449 * host: dir="", urltype=CLASSIC_URL_T
1450 * logged in (to default directory)
1451 * host:file dir=NULL, urltype=CLASSIC_URL_T
1452 * "RETR file"
1453 * host:dir/ dir="dir", urltype=CLASSIC_URL_T
1454 * "CWD dir", logged in
1455 * ftp://host/ dir="", urltype=FTP_URL_T
1456 * logged in (to default directory)
1457 * ftp://host/dir/ dir="dir", urltype=FTP_URL_T
1458 * "CWD dir", logged in
1459 * ftp://host/file dir=NULL, urltype=FTP_URL_T
1460 * "RETR file"
1461 * ftp://host//file dir="", urltype=FTP_URL_T
1462 * "CWD ", "RETR file"
1463 * host:/file dir="/", urltype=CLASSIC_URL_T
1464 * "CWD /", "RETR file"
1465 * ftp://host///file dir="/", urltype=FTP_URL_T
1466 * "CWD ", "CWD ", "RETR file"
1467 * ftp://host/%2F/file dir="%2F", urltype=FTP_URL_T
1468 * "CWD /", "RETR file"
1469 * ftp://host/foo/file dir="foo", urltype=FTP_URL_T
1470 * "CWD foo", "RETR file"
1471 * ftp://host/foo/bar/file dir="foo/bar"
1472 * "CWD foo", "CWD bar", "RETR file"
1473 * ftp://host//foo/bar/file dir="/foo/bar"
1474 * "CWD ", "CWD foo", "CWD bar", "RETR file"
1475 * ftp://host/foo//bar/file dir="foo//bar"
1476 * "CWD foo", "CWD ", "CWD bar", "RETR file"
1477 * ftp://host/%2F/foo/bar/file dir="%2F/foo/bar"
1478 * "CWD /", "CWD foo", "CWD bar", "RETR file"
1479 * ftp://host/%2Ffoo/bar/file dir="%2Ffoo/bar"
1480 * "CWD /foo", "CWD bar", "RETR file"
1481 * ftp://host/%2Ffoo%2Fbar/file dir="%2Ffoo%2Fbar"
1482 * "CWD /foo/bar", "RETR file"
1483 * ftp://host/%2Ffoo%2Fbar%2Ffile dir=NULL
1484 * "RETR /foo/bar/file"
1485 *
1486 * Note that we don't need `dir' after this point.
1487 */
1488 do {
1489 if (urltype == FTP_URL_T) {
1490 nextpart = strchr(dir, '/');
1491 if (nextpart) {
1492 *nextpart = '\0';
1493 nextpart++;
1494 }
1495 url_decode(dir);
1496 } else
1497 nextpart = NULL;
1498 if (debug)
1499 fprintf(ttyout, "dir `%s', nextpart `%s'\n",
1500 dir ? dir : "<null>",
1501 nextpart ? nextpart : "<null>");
1502 if (urltype == FTP_URL_T || *dir != '\0') {
1503 xargv[0] = "cd";
1504 xargv[1] = dir;
1505 xargv[2] = NULL;
1506 dirchange = 0;
1507 cd(2, xargv);
1508 if (! dirchange) {
1509 if (*dir == '\0' && code == 500)
1510 fprintf(stderr,
1511 "\n"
1512 "ftp: The `CWD ' command (without a directory), which is required by\n"
1513 " RFC 1738 to support the empty directory in the URL pathname (`//'),\n"
1514 " conflicts with the server's conformance to RFC 959.\n"
1515 " Try the same URL without the `//' in the URL pathname.\n"
1516 "\n");
1517 goto cleanup_fetch_ftp;
1518 }
1519 }
1520 dir = nextpart;
1521 } while (dir != NULL);
1522 }
1523
1524 if (EMPTYSTRING(file)) {
1525 rval = -1;
1526 goto cleanup_fetch_ftp;
1527 }
1528
1529 if (dirhasglob) {
1530 (void)strlcpy(rempath, dir, sizeof(rempath));
1531 (void)strlcat(rempath, "/", sizeof(rempath));
1532 (void)strlcat(rempath, file, sizeof(rempath));
1533 file = rempath;
1534 }
1535
1536 /* Fetch the file(s). */
1537 xargc = 2;
1538 xargv[0] = "get";
1539 xargv[1] = file;
1540 xargv[2] = NULL;
1541 if (dirhasglob || filehasglob) {
1542 int ointeractive;
1543
1544 ointeractive = interactive;
1545 interactive = 0;
1546 xargv[0] = "mget";
1547 mget(xargc, xargv);
1548 interactive = ointeractive;
1549 } else {
1550 if (outfile == NULL) {
1551 cp = strrchr(file, '/'); /* find savefile */
1552 if (cp != NULL)
1553 outfile = cp + 1;
1554 else
1555 outfile = file;
1556 }
1557 xargv[2] = (char *)outfile;
1558 xargv[3] = NULL;
1559 xargc++;
1560 if (restartautofetch)
1561 reget(xargc, xargv);
1562 else
1563 get(xargc, xargv);
1564 }
1565
1566 if ((code / 100) == COMPLETE)
1567 rval = 0;
1568
1569 cleanup_fetch_ftp:
1570 FREEPTR(host);
1571 FREEPTR(path);
1572 FREEPTR(user);
1573 FREEPTR(pass);
1574 return (rval);
1575 }
1576
1577 /*
1578 * Retrieve the given file to outfile.
1579 * Supports arguments of the form:
1580 * "host:path", "ftp://host/path" if $ftpproxy, call fetch_url() else
1581 * call fetch_ftp()
1582 * "http://host/path" call fetch_url() to use HTTP
1583 * "file:///path" call fetch_url() to copy
1584 * "about:..." print a message
1585 *
1586 * Returns 1 on failure, 0 on completed xfer, -1 if ftp connection
1587 * is still open (e.g, ftp xfer with trailing /)
1588 */
1589 static int
1590 go_fetch(const char *url)
1591 {
1592 char *proxy;
1593
1594 /*
1595 * Check for about:*
1596 */
1597 if (strncasecmp(url, ABOUT_URL, sizeof(ABOUT_URL) - 1) == 0) {
1598 url += sizeof(ABOUT_URL) -1;
1599 if (strcasecmp(url, "ftp") == 0) {
1600 fputs(
1601 "This version of ftp has been enhanced by Luke Mewburn <lukem (at) netbsd.org>\n"
1602 "for the NetBSD project. Execute `man ftp' for more details.\n", ttyout);
1603 } else if (strcasecmp(url, "lukem") == 0) {
1604 fputs(
1605 "Luke Mewburn is the author of most of the enhancements in this ftp client.\n"
1606 "Please email feedback to <lukem (at) netbsd.org>.\n", ttyout);
1607 } else if (strcasecmp(url, "netbsd") == 0) {
1608 fputs(
1609 "NetBSD is a freely available and redistributable UNIX-like operating system.\n"
1610 "For more information, see http://www.netbsd.org/index.html\n", ttyout);
1611 } else if (strcasecmp(url, "version") == 0) {
1612 fprintf(ttyout, "Version: %s %s%s\n",
1613 FTP_PRODUCT, FTP_VERSION,
1614 #ifdef INET6
1615 ""
1616 #else
1617 " (-IPv6)"
1618 #endif
1619 );
1620 } else {
1621 fprintf(ttyout, "`%s' is an interesting topic.\n", url);
1622 }
1623 fputs("\n", ttyout);
1624 return (0);
1625 }
1626
1627 /*
1628 * Check for file:// and http:// URLs.
1629 */
1630 if (strncasecmp(url, HTTP_URL, sizeof(HTTP_URL) - 1) == 0 ||
1631 strncasecmp(url, FILE_URL, sizeof(FILE_URL) - 1) == 0)
1632 return (fetch_url(url, NULL, NULL, NULL));
1633
1634 /*
1635 * Try FTP URL-style and host:file arguments next.
1636 * If ftpproxy is set with an FTP URL, use fetch_url()
1637 * Othewise, use fetch_ftp().
1638 */
1639 proxy = getoptionvalue("ftp_proxy");
1640 if (!EMPTYSTRING(proxy) &&
1641 strncasecmp(url, FTP_URL, sizeof(FTP_URL) - 1) == 0)
1642 return (fetch_url(url, NULL, NULL, NULL));
1643
1644 return (fetch_ftp(url));
1645 }
1646
1647 /*
1648 * Retrieve multiple files from the command line,
1649 * calling go_fetch() for each file.
1650 *
1651 * If an ftp path has a trailing "/", the path will be cd-ed into and
1652 * the connection remains open, and the function will return -1
1653 * (to indicate the connection is alive).
1654 * If an error occurs the return value will be the offset+1 in
1655 * argv[] of the file that caused a problem (i.e, argv[x]
1656 * returns x+1)
1657 * Otherwise, 0 is returned if all files retrieved successfully.
1658 */
1659 int
1660 auto_fetch(int argc, char *argv[])
1661 {
1662 volatile int argpos;
1663 int rval;
1664
1665 argpos = 0;
1666
1667 if (sigsetjmp(toplevel, 1)) {
1668 if (connected)
1669 disconnect(0, NULL);
1670 return (argpos + 1);
1671 }
1672 (void)xsignal(SIGINT, intr);
1673 (void)xsignal(SIGPIPE, lostpeer);
1674
1675 /*
1676 * Loop through as long as there's files to fetch.
1677 */
1678 for (rval = 0; (rval == 0) && (argpos < argc); argpos++) {
1679 if (strchr(argv[argpos], ':') == NULL)
1680 break;
1681 redirect_loop = 0;
1682 if (!anonftp)
1683 anonftp = 2; /* Handle "automatic" transfers. */
1684 rval = go_fetch(argv[argpos]);
1685 if (outfile != NULL && strcmp(outfile, "-") != 0
1686 && outfile[0] != '|')
1687 outfile = NULL;
1688 if (rval > 0)
1689 rval = argpos + 1;
1690 }
1691
1692 if (connected && rval != -1)
1693 disconnect(0, NULL);
1694 return (rval);
1695 }
1696
1697
1698 int
1699 auto_put(int argc, char **argv, const char *uploadserver)
1700 {
1701 char *uargv[4], *path, *pathsep;
1702 int uargc, rval, len;
1703
1704 uargc = 0;
1705 uargv[uargc++] = "mput";
1706 uargv[uargc++] = argv[0];
1707 uargv[2] = uargv[3] = NULL;
1708 pathsep = NULL;
1709 rval = 1;
1710
1711 if (debug)
1712 fprintf(ttyout, "auto_put: target `%s'\n", uploadserver);
1713
1714 path = xstrdup(uploadserver);
1715 len = strlen(path);
1716 if (path[len - 1] != '/' && path[len - 1] != ':') {
1717 /*
1718 * make sure we always pass a directory to auto_fetch
1719 */
1720 if (argc > 1) { /* more than one file to upload */
1721 int len;
1722
1723 len = strlen(uploadserver) + 2; /* path + "/" + "\0" */
1724 free(path);
1725 path = (char *)xmalloc(len);
1726 (void)strlcpy(path, uploadserver, len);
1727 (void)strlcat(path, "/", len);
1728 } else { /* single file to upload */
1729 uargv[0] = "put";
1730 pathsep = strrchr(path, '/');
1731 if (pathsep == NULL) {
1732 pathsep = strrchr(path, ':');
1733 if (pathsep == NULL) {
1734 warnx("Invalid URL `%s'", path);
1735 goto cleanup_auto_put;
1736 }
1737 pathsep++;
1738 uargv[2] = xstrdup(pathsep);
1739 pathsep[0] = '/';
1740 } else
1741 uargv[2] = xstrdup(pathsep + 1);
1742 pathsep[1] = '\0';
1743 uargc++;
1744 }
1745 }
1746 if (debug)
1747 fprintf(ttyout, "autoput: url `%s' argv[2] `%s'\n",
1748 path, uargv[2] ? uargv[2] : "<null>");
1749
1750 /* connect and cwd */
1751 rval = auto_fetch(1, &path);
1752 free(path);
1753 if(rval >= 0)
1754 goto cleanup_auto_put;
1755
1756 /* XXX : is this the best way? */
1757 if (uargc == 3) {
1758 uargv[1] = argv[0];
1759 put(uargc, uargv);
1760 goto cleanup_auto_put;
1761 }
1762
1763 for(; argv[0] != NULL; argv++) {
1764 uargv[1] = argv[0];
1765 mput(uargc, uargv);
1766 }
1767 rval = 0;
1768
1769 cleanup_auto_put:
1770 FREEPTR(uargv[2]);
1771 return (rval);
1772 }
1773