fetch.c revision 1.238 1 /* $NetBSD: fetch.c,v 1.238 2023/08/12 07:40:13 mlelstv Exp $ */
2
3 /*-
4 * Copyright (c) 1997-2015 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 * This code is derived from software contributed to The NetBSD Foundation
14 * by Thomas Klausner.
15 *
16 * Redistribution and use in source and binary forms, with or without
17 * modification, are permitted provided that the following conditions
18 * are met:
19 * 1. Redistributions of source code must retain the above copyright
20 * notice, this list of conditions and the following disclaimer.
21 * 2. Redistributions in binary form must reproduce the above copyright
22 * notice, this list of conditions and the following disclaimer in the
23 * documentation and/or other materials provided with the distribution.
24 *
25 * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
26 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
27 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
28 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
29 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
30 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
31 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
32 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
33 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
34 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
35 * POSSIBILITY OF SUCH DAMAGE.
36 */
37
38 #include <sys/cdefs.h>
39 #ifndef lint
40 __RCSID("$NetBSD: fetch.c,v 1.238 2023/08/12 07:40:13 mlelstv Exp $");
41 #endif /* not lint */
42
43 /*
44 * FTP User Program -- Command line file retrieval
45 */
46
47 #include <sys/types.h>
48 #include <sys/param.h>
49 #include <sys/socket.h>
50 #include <sys/stat.h>
51 #include <sys/time.h>
52
53 #include <netinet/in.h>
54
55 #include <arpa/ftp.h>
56 #include <arpa/inet.h>
57
58 #include <assert.h>
59 #include <ctype.h>
60 #include <err.h>
61 #include <errno.h>
62 #include <netdb.h>
63 #include <fcntl.h>
64 #include <stdio.h>
65 #include <stdlib.h>
66 #include <string.h>
67 #include <unistd.h>
68 #include <time.h>
69
70 #include "ssl.h"
71 #include "ftp_var.h"
72 #include "version.h"
73
74 typedef enum {
75 UNKNOWN_URL_T=-1,
76 HTTP_URL_T,
77 HTTPS_URL_T,
78 FTP_URL_T,
79 FILE_URL_T,
80 CLASSIC_URL_T
81 } url_t;
82
83 struct authinfo {
84 char *auth;
85 char *user;
86 char *pass;
87 };
88
89 struct urlinfo {
90 char *host;
91 char *port;
92 char *path;
93 url_t utype;
94 in_port_t portnum;
95 };
96
97 struct posinfo {
98 off_t rangestart;
99 off_t rangeend;
100 off_t entitylen;
101 };
102
103 __dead static void aborthttp(int);
104 __dead static void timeouthttp(int);
105 #ifndef NO_AUTH
106 static int auth_url(const char *, char **, const struct authinfo *);
107 static void base64_encode(const unsigned char *, size_t, unsigned char *);
108 #endif
109 static int go_fetch(const char *, struct urlinfo *);
110 static int fetch_ftp(const char *);
111 static int fetch_url(const char *, const char *, char *, char *,
112 struct urlinfo *);
113 static const char *match_token(const char **, const char *);
114 static int parse_url(const char *, const char *, struct urlinfo *,
115 struct authinfo *, struct urlinfo *);
116 static void url_decode(char *);
117 static void freeauthinfo(struct authinfo *);
118 static void freeurlinfo(struct urlinfo *);
119
120 static int redirect_loop;
121
122
123 #define STRNEQUAL(a,b) (strncasecmp((a), (b), sizeof((b))-1) == 0)
124 #define ISLWS(x) ((x)=='\r' || (x)=='\n' || (x)==' ' || (x)=='\t')
125 #define SKIPLWS(x) do { while (ISLWS((*x))) x++; } while (0)
126
127
128 #define ABOUT_URL "about:" /* propaganda */
129 #define FILE_URL "file://" /* file URL prefix */
130 #define FTP_URL "ftp://" /* ftp URL prefix */
131 #define HTTP_URL "http://" /* http URL prefix */
132 #ifdef WITH_SSL
133 #define HTTPS_URL "https://" /* https URL prefix */
134
135 #define IS_HTTP_TYPE(urltype) \
136 (((urltype) == HTTP_URL_T) || ((urltype) == HTTPS_URL_T))
137 #else
138 #define IS_HTTP_TYPE(urltype) \
139 ((urltype) == HTTP_URL_T)
140 #endif
141
142 /**
143 * fwrite(3) replacement that just uses write(2). Many stdio implementations
144 * don't handle interrupts properly and corrupt the output. We are taking
145 * alarm interrupts because of the progress bar.
146 *
147 * Assumes `fp' is pristine with no prior I/O calls on it.
148 */
149 static size_t
150 maxwrite(const void *buf, size_t size, size_t nmemb, FILE *fp)
151 {
152 const char *p = buf;
153 ssize_t nwr = 0;
154 ssize_t n;
155 int fd = fileno(fp);
156
157 size *= nmemb; /* assume no overflow */
158
159 while (size > 0) {
160 if ((n = write(fd, p, size)) == -1) {
161 switch (errno) {
162 case EINTR:
163 case EAGAIN:
164 #if defined(EWOULDBLOCK) && EWOULDBLOCK != EAGAIN
165 case EWOULDBLOCK:
166 #endif
167 continue;
168 default:
169 return nwr;
170 }
171 }
172 p += n;
173 nwr += n;
174 size -= n;
175 }
176 return nwr;
177 }
178
179 /*
180 * Determine if token is the next word in buf (case insensitive).
181 * If so, advance buf past the token and any trailing LWS, and
182 * return a pointer to the token (in buf). Otherwise, return NULL.
183 * token may be preceded by LWS.
184 * token must be followed by LWS or NUL. (I.e, don't partial match).
185 */
186 static const char *
187 match_token(const char **buf, const char *token)
188 {
189 const char *p, *orig;
190 size_t tlen;
191
192 tlen = strlen(token);
193 p = *buf;
194 SKIPLWS(p);
195 orig = p;
196 if (strncasecmp(p, token, tlen) != 0)
197 return NULL;
198 p += tlen;
199 if (*p != '\0' && !ISLWS(*p))
200 return NULL;
201 SKIPLWS(p);
202 orig = *buf;
203 *buf = p;
204 return orig;
205 }
206
207 static void
208 initposinfo(struct posinfo *pi)
209 {
210 pi->rangestart = pi->rangeend = pi->entitylen = -1;
211 }
212
213 static void
214 initauthinfo(struct authinfo *ai, char *auth)
215 {
216 ai->auth = auth;
217 ai->user = ai->pass = 0;
218 }
219
220 static void
221 freeauthinfo(struct authinfo *a)
222 {
223 FREEPTR(a->user);
224 if (a->pass != NULL)
225 memset(a->pass, 0, strlen(a->pass));
226 FREEPTR(a->pass);
227 }
228
229 static void
230 initurlinfo(struct urlinfo *ui)
231 {
232 ui->host = ui->port = ui->path = 0;
233 ui->utype = UNKNOWN_URL_T;
234 ui->portnum = 0;
235 }
236
237 static void
238 copyurlinfo(struct urlinfo *dui, struct urlinfo *sui)
239 {
240 dui->host = ftp_strdup(sui->host);
241 dui->port = ftp_strdup(sui->port);
242 dui->path = ftp_strdup(sui->path);
243 dui->utype = sui->utype;
244 dui->portnum = sui->portnum;
245 }
246
247 static void
248 freeurlinfo(struct urlinfo *ui)
249 {
250 FREEPTR(ui->host);
251 FREEPTR(ui->port);
252 FREEPTR(ui->path);
253 }
254
255 #ifndef NO_AUTH
256 /*
257 * Generate authorization response based on given authentication challenge.
258 * Returns -1 if an error occurred, otherwise 0.
259 * Sets response to a malloc(3)ed string; caller should free.
260 */
261 static int
262 auth_url(const char *challenge, char **response, const struct authinfo *auth)
263 {
264 const char *cp, *scheme, *errormsg;
265 char *ep, *clear, *realm;
266 char uuser[BUFSIZ], *gotpass;
267 const char *upass;
268 int rval;
269 size_t len, clen, rlen;
270
271 *response = NULL;
272 clear = realm = NULL;
273 rval = -1;
274 cp = challenge;
275 scheme = "Basic"; /* only support Basic authentication */
276 gotpass = NULL;
277
278 DPRINTF("%s: challenge `%s'\n", __func__, challenge);
279
280 if (! match_token(&cp, scheme)) {
281 warnx("Unsupported authentication challenge `%s'",
282 challenge);
283 goto cleanup_auth_url;
284 }
285
286 #define REALM "realm=\""
287 if (STRNEQUAL(cp, REALM))
288 cp += sizeof(REALM) - 1;
289 else {
290 warnx("Unsupported authentication challenge `%s'",
291 challenge);
292 goto cleanup_auth_url;
293 }
294 /* XXX: need to improve quoted-string parsing to support \ quoting, etc. */
295 if ((ep = strchr(cp, '\"')) != NULL) {
296 len = ep - cp;
297 realm = (char *)ftp_malloc(len + 1);
298 (void)strlcpy(realm, cp, len + 1);
299 } else {
300 warnx("Unsupported authentication challenge `%s'",
301 challenge);
302 goto cleanup_auth_url;
303 }
304
305 fprintf(ttyout, "Username for `%s': ", realm);
306 if (auth->user != NULL) {
307 (void)strlcpy(uuser, auth->user, sizeof(uuser));
308 fprintf(ttyout, "%s\n", uuser);
309 } else {
310 (void)fflush(ttyout);
311 if (get_line(stdin, uuser, sizeof(uuser), &errormsg) < 0) {
312 warnx("%s; can't authenticate", errormsg);
313 goto cleanup_auth_url;
314 }
315 }
316 if (auth->pass != NULL)
317 upass = auth->pass;
318 else {
319 gotpass = getpass("Password: ");
320 if (gotpass == NULL) {
321 warnx("Can't read password");
322 goto cleanup_auth_url;
323 }
324 upass = gotpass;
325 }
326
327 clen = strlen(uuser) + strlen(upass) + 2; /* user + ":" + pass + "\0" */
328 clear = (char *)ftp_malloc(clen);
329 (void)strlcpy(clear, uuser, clen);
330 (void)strlcat(clear, ":", clen);
331 (void)strlcat(clear, upass, clen);
332 if (gotpass)
333 memset(gotpass, 0, strlen(gotpass));
334
335 /* scheme + " " + enc + "\0" */
336 rlen = strlen(scheme) + 1 + (clen + 2) * 4 / 3 + 1;
337 *response = ftp_malloc(rlen);
338 (void)strlcpy(*response, scheme, rlen);
339 len = strlcat(*response, " ", rlen);
340 /* use `clen - 1' to not encode the trailing NUL */
341 base64_encode((unsigned char *)clear, clen - 1,
342 (unsigned char *)*response + len);
343 memset(clear, 0, clen);
344 rval = 0;
345
346 cleanup_auth_url:
347 FREEPTR(clear);
348 FREEPTR(realm);
349 return (rval);
350 }
351
352 /*
353 * Encode len bytes starting at clear using base64 encoding into encoded,
354 * which should be at least ((len + 2) * 4 / 3 + 1) in size.
355 */
356 static void
357 base64_encode(const unsigned char *clear, size_t len, unsigned char *encoded)
358 {
359 static const unsigned char enc[] =
360 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
361 unsigned char *cp;
362 size_t i;
363
364 cp = encoded;
365 for (i = 0; i < len; i += 3) {
366 *(cp++) = enc[((clear[i + 0] >> 2))];
367 *(cp++) = enc[((clear[i + 0] << 4) & 0x30)
368 | ((clear[i + 1] >> 4) & 0x0f)];
369 *(cp++) = enc[((clear[i + 1] << 2) & 0x3c)
370 | ((clear[i + 2] >> 6) & 0x03)];
371 *(cp++) = enc[((clear[i + 2] ) & 0x3f)];
372 }
373 *cp = '\0';
374 while (i-- > len)
375 *(--cp) = '=';
376 }
377 #endif
378
379 /*
380 * Decode %xx escapes in given string, `in-place'.
381 */
382 static void
383 url_decode(char *url)
384 {
385 unsigned char *p, *q;
386
387 if (EMPTYSTRING(url))
388 return;
389 p = q = (unsigned char *)url;
390
391 #define HEXTOINT(x) (x - (isdigit(x) ? '0' : (islower(x) ? 'a' : 'A') - 10))
392 while (*p) {
393 if (p[0] == '%'
394 && p[1] && isxdigit((unsigned char)p[1])
395 && p[2] && isxdigit((unsigned char)p[2])) {
396 *q++ = HEXTOINT(p[1]) * 16 + HEXTOINT(p[2]);
397 p+=3;
398 } else
399 *q++ = *p++;
400 }
401 *q = '\0';
402 }
403
404 static const char *
405 get_port(const struct urlinfo *ui)
406 {
407
408 switch(ui->utype) {
409 case HTTP_URL_T:
410 return httpport;
411 case FTP_URL_T:
412 return ftpport;
413 case FILE_URL_T:
414 return "";
415 #ifdef WITH_SSL
416 case HTTPS_URL_T:
417 return httpsport;
418 #endif
419 default:
420 return NULL;
421 }
422 }
423
424 static int
425 use_relative(const struct urlinfo *ui)
426 {
427 if (ui == NULL)
428 return 0;
429 switch (ui->utype) {
430 case HTTP_URL_T:
431 case FILE_URL_T:
432 #ifdef WITH_SSL
433 case HTTPS_URL_T:
434 #endif
435 return 1;
436 default:
437 return 0;
438 }
439 }
440
441 /*
442 * Parse URL of form (per RFC 3986):
443 * <type>://[<user>[:<password>]@]<host>[:<port>][/<path>]
444 * Returns -1 if a parse error occurred, otherwise 0.
445 * It's the caller's responsibility to url_decode() the returned
446 * user, pass and path.
447 *
448 * Sets type to url_t, each of the given char ** pointers to a
449 * malloc(3)ed strings of the relevant section, and port to
450 * the number given, or ftpport if ftp://, or httpport if http://.
451 *
452 * XXX: this is not totally RFC 3986 compliant; <path> will have the
453 * leading `/' unless it's an ftp:// URL, as this makes things easier
454 * for file:// and http:// URLs. ftp:// URLs have the `/' between the
455 * host and the URL-path removed, but any additional leading slashes
456 * in the URL-path are retained (because they imply that we should
457 * later do "CWD" with a null argument).
458 *
459 * Examples:
460 * input URL output path
461 * --------- -----------
462 * "http://host" "/"
463 * "http://host/" "/"
464 * "http://host/path" "/path"
465 * "file://host/dir/file" "dir/file"
466 * "ftp://host" ""
467 * "ftp://host/" ""
468 * "ftp://host//" "/"
469 * "ftp://host/dir/file" "dir/file"
470 * "ftp://host//dir/file" "/dir/file"
471 */
472
473 static int
474 parse_url(const char *url, const char *desc, struct urlinfo *ui,
475 struct authinfo *auth, struct urlinfo *rui)
476 {
477 const char *origurl, *tport;
478 char *cp, *ep, *thost;
479 size_t len;
480
481 if (url == NULL || desc == NULL || ui == NULL || auth == NULL)
482 errx(1, "parse_url: invoked with NULL argument!");
483 DPRINTF("parse_url: %s `%s'\n", desc, url);
484
485 origurl = url;
486
487 if (STRNEQUAL(url, HTTP_URL)) {
488 url += sizeof(HTTP_URL) - 1;
489 ui->utype = HTTP_URL_T;
490 ui->portnum = HTTP_PORT;
491 } else if (STRNEQUAL(url, FTP_URL)) {
492 url += sizeof(FTP_URL) - 1;
493 ui->utype = FTP_URL_T;
494 ui->portnum = FTP_PORT;
495 } else if (STRNEQUAL(url, FILE_URL)) {
496 url += sizeof(FILE_URL) - 1;
497 ui->utype = FILE_URL_T;
498 #ifdef WITH_SSL
499 } else if (STRNEQUAL(url, HTTPS_URL)) {
500 url += sizeof(HTTPS_URL) - 1;
501 ui->utype = HTTPS_URL_T;
502 ui->portnum = HTTPS_PORT;
503 #endif
504 } else if (rui != NULL) {
505 copyurlinfo(ui, rui);
506 } else {
507 warnx("Invalid %s `%s'", desc, url);
508 cleanup_parse_url:
509 freeauthinfo(auth);
510 freeurlinfo(ui);
511 return (-1);
512 }
513
514
515 if (*url == '\0')
516 return (0);
517
518 /* find [user[:pass]@]host[:port] */
519 ep = strchr(url, '/');
520 if (ep == NULL)
521 thost = ftp_strdup(url);
522 else {
523 len = ep - url;
524 thost = (char *)ftp_malloc(len + 1);
525 (void)strlcpy(thost, url, len + 1);
526 if (ui->utype == FTP_URL_T) /* skip first / for ftp URLs */
527 ep++;
528 ui->path = ftp_strdup(ep);
529 }
530
531 cp = strchr(thost, '@'); /* look for user[:pass]@ in URLs */
532 if (cp != NULL) {
533 if (ui->utype == FTP_URL_T)
534 anonftp = 0; /* disable anonftp */
535 auth->user = thost;
536 *cp = '\0';
537 thost = ftp_strdup(cp + 1);
538 cp = strchr(auth->user, ':');
539 if (cp != NULL) {
540 *cp = '\0';
541 auth->pass = ftp_strdup(cp + 1);
542 }
543 url_decode(auth->user);
544 if (auth->pass)
545 url_decode(auth->pass);
546 }
547
548 #ifdef INET6
549 /*
550 * Check if thost is an encoded IPv6 address, as per
551 * RFC 3986:
552 * `[' ipv6-address ']'
553 */
554 if (*thost == '[') {
555 cp = thost + 1;
556 if ((ep = strchr(cp, ']')) == NULL ||
557 (ep[1] != '\0' && ep[1] != ':')) {
558 warnx("Invalid address `%s' in %s `%s'",
559 thost, desc, origurl);
560 goto cleanup_parse_url;
561 }
562 len = ep - cp; /* change `[xyz]' -> `xyz' */
563 memmove(thost, thost + 1, len);
564 thost[len] = '\0';
565 if (! isipv6addr(thost)) {
566 warnx("Invalid IPv6 address `%s' in %s `%s'",
567 thost, desc, origurl);
568 goto cleanup_parse_url;
569 }
570 cp = ep + 1;
571 if (*cp == ':')
572 cp++;
573 else
574 cp = NULL;
575 } else
576 #endif /* INET6 */
577 if ((cp = strchr(thost, ':')) != NULL)
578 *cp++ = '\0';
579 if (*thost != '\0')
580 ui->host = thost;
581
582 /* look for [:port] */
583 if (cp != NULL) {
584 unsigned long nport;
585
586 nport = strtoul(cp, &ep, 10);
587 if (*cp == '\0' || *ep != '\0' ||
588 nport < 1 || nport > MAX_IN_PORT_T) {
589 warnx("Unknown port `%s' in %s `%s'",
590 cp, desc, origurl);
591 goto cleanup_parse_url;
592 }
593 ui->portnum = nport;
594 tport = cp;
595 } else
596 tport = get_port(ui);
597
598
599 if (tport != NULL)
600 ui->port = ftp_strdup(tport);
601 if (ui->path == NULL) {
602 const char *emptypath = "/";
603 if (ui->utype == FTP_URL_T) /* skip first / for ftp URLs */
604 emptypath++;
605 ui->path = ftp_strdup(emptypath);
606 }
607
608 DPRINTF("%s: user `%s' pass `%s' host %s port %s(%d) "
609 "path `%s'\n", __func__,
610 STRorNULL(auth->user), STRorNULL(auth->pass),
611 STRorNULL(ui->host), STRorNULL(ui->port),
612 ui->portnum ? ui->portnum : -1, STRorNULL(ui->path));
613
614 return (0);
615 }
616
617 sigjmp_buf httpabort;
618
619 static int
620 ftp_socket(const struct urlinfo *ui, void **ssl, struct authinfo *auth)
621 {
622 struct addrinfo hints, *res, *res0 = NULL;
623 int error;
624 int s;
625 const char *host = ui->host;
626 const char *port = ui->port;
627 char *fuser = NULL, *pass = NULL, *facct = NULL;
628 int n;
629
630 if (ui->utype != HTTPS_URL_T)
631 ssl = NULL;
632
633 memset(&hints, 0, sizeof(hints));
634 hints.ai_flags = 0;
635 hints.ai_family = family;
636 hints.ai_socktype = SOCK_STREAM;
637 hints.ai_protocol = 0;
638
639 error = getaddrinfo(host, port, &hints, &res0);
640 if (error) {
641 warnx("Can't LOOKUP `%s:%s': %s", host, port,
642 (error == EAI_SYSTEM) ? strerror(errno)
643 : gai_strerror(error));
644 return -1;
645 }
646
647 if (res0->ai_canonname)
648 host = res0->ai_canonname;
649
650 s = -1;
651 if (ssl)
652 *ssl = NULL;
653 for (res = res0; res; res = res->ai_next) {
654 char hname[NI_MAXHOST], sname[NI_MAXSERV];
655
656 ai_unmapped(res);
657 if (getnameinfo(res->ai_addr, res->ai_addrlen,
658 hname, sizeof(hname), sname, sizeof(sname),
659 NI_NUMERICHOST | NI_NUMERICSERV) != 0) {
660 strlcpy(hname, "?", sizeof(hname));
661 strlcpy(sname, "?", sizeof(sname));
662 }
663
664 if (verbose && res0->ai_next) {
665 #ifdef INET6
666 if(res->ai_family == AF_INET6) {
667 fprintf(ttyout, "Trying [%s]:%s ...\n",
668 hname, sname);
669 } else {
670 #endif
671 fprintf(ttyout, "Trying %s:%s ...\n",
672 hname, sname);
673 #ifdef INET6
674 }
675 #endif
676 }
677
678 s = socket(res->ai_family, SOCK_STREAM, res->ai_protocol);
679 if (s < 0) {
680 warn(
681 "Can't create socket for connection to "
682 "`%s:%s'", hname, sname);
683 continue;
684 }
685
686 if (ftp_connect(s, res->ai_addr, res->ai_addrlen,
687 verbose || !res->ai_next) < 0) {
688 close(s);
689 s = -1;
690 continue;
691 }
692
693 if (ruserpass("", &fuser, &pass, &facct) < 0) {
694 close(s);
695 s = -1;
696 continue;
697 }
698
699 if (autologin) {
700 if (fuser != NULL && auth->user == NULL)
701 auth->user = ftp_strdup(fuser);
702 if (pass != NULL && auth->pass == NULL)
703 auth->pass = ftp_strdup(pass);
704 }
705
706 for (n = 0; n < macnum; ++n) {
707 if (!strcmp("init", macros[n].mac_name)) {
708 (void)strlcpy(line, "$init", sizeof(line));
709 makeargv();
710 domacro(margc, margv);
711 break;
712 }
713 }
714
715 #ifdef WITH_SSL
716 if (ssl) {
717 if ((*ssl = fetch_start_ssl(s, host)) == NULL) {
718 close(s);
719 s = -1;
720 continue;
721 }
722 }
723 #endif
724 break;
725 }
726
727 FREEPTR(fuser);
728 if (pass != NULL)
729 memset(pass, 0, strlen(pass));
730 FREEPTR(pass);
731 if (facct != NULL)
732 memset(facct, 0, strlen(facct));
733 FREEPTR(facct);
734
735 if (res0)
736 freeaddrinfo(res0);
737 return s;
738 }
739
740 static int
741 handle_noproxy(const char *host, in_port_t portnum)
742 {
743
744 char *cp, *ep, *np, *np_copy, *np_iter, *no_proxy;
745 unsigned long np_port;
746 size_t hlen, plen;
747 int isproxy = 1;
748
749 /* check URL against list of no_proxied sites */
750 no_proxy = getoptionvalue("no_proxy");
751 if (EMPTYSTRING(no_proxy))
752 return isproxy;
753
754 np_iter = np_copy = ftp_strdup(no_proxy);
755 hlen = strlen(host);
756 while ((cp = strsep(&np_iter, " ,")) != NULL) {
757 if (*cp == '\0')
758 continue;
759 if ((np = strrchr(cp, ':')) != NULL) {
760 *np++ = '\0';
761 np_port = strtoul(np, &ep, 10);
762 if (*np == '\0' || *ep != '\0')
763 continue;
764 if (np_port != portnum)
765 continue;
766 }
767 plen = strlen(cp);
768 if (hlen < plen)
769 continue;
770 if (strncasecmp(host + hlen - plen, cp, plen) == 0) {
771 isproxy = 0;
772 break;
773 }
774 }
775 FREEPTR(np_copy);
776 return isproxy;
777 }
778
779 static int
780 handle_proxy(const char *url, const char *penv, struct urlinfo *ui,
781 struct authinfo *pauth)
782 {
783 struct urlinfo pui;
784
785 if (isipv6addr(ui->host) && strchr(ui->host, '%') != NULL) {
786 warnx("Scoped address notation `%s' disallowed via web proxy",
787 ui->host);
788 return -1;
789 }
790
791 initurlinfo(&pui);
792 if (parse_url(penv, "proxy URL", &pui, pauth, NULL) == -1)
793 return -1;
794
795 if ((!IS_HTTP_TYPE(pui.utype) && pui.utype != FTP_URL_T) ||
796 EMPTYSTRING(pui.host) ||
797 (! EMPTYSTRING(pui.path) && strcmp(pui.path, "/") != 0)) {
798 warnx("Malformed proxy URL `%s'", penv);
799 freeurlinfo(&pui);
800 return -1;
801 }
802
803 FREEPTR(pui.path);
804 #ifdef WITH_SSL
805 if (ui->utype == HTTPS_URL_T)
806 pui.path = ftp_strdup(ui->path);
807 else
808 #endif
809 pui.path = ftp_strdup(url);
810
811 freeurlinfo(ui);
812 *ui = pui;
813
814 return 0;
815 }
816
817 static void
818 print_host(FETCH *fin, const struct urlinfo *ui)
819 {
820 char *h, *p;
821
822 if (strchr(ui->host, ':') == NULL) {
823 fetch_printf(fin, "Host: %s", ui->host);
824 } else {
825 /*
826 * strip off IPv6 scope identifier, since it is
827 * local to the node
828 */
829 h = ftp_strdup(ui->host);
830 if (isipv6addr(h) && (p = strchr(h, '%')) != NULL)
831 *p = '\0';
832
833 fetch_printf(fin, "Host: [%s]", h);
834 free(h);
835 }
836
837 if ((ui->utype == HTTP_URL_T && ui->portnum != HTTP_PORT) ||
838 (ui->utype == HTTPS_URL_T && ui->portnum != HTTPS_PORT))
839 fetch_printf(fin, ":%u", ui->portnum);
840 fetch_printf(fin, "\r\n");
841 }
842
843 static void
844 print_agent(FETCH *fin)
845 {
846 const char *useragent;
847 if ((useragent = getenv("FTPUSERAGENT")) != NULL) {
848 fetch_printf(fin, "User-Agent: %s\r\n", useragent);
849 } else {
850 fetch_printf(fin, "User-Agent: %s/%s\r\n",
851 FTP_PRODUCT, FTP_VERSION);
852 }
853 }
854
855 static void
856 print_cache(FETCH *fin, int isproxy)
857 {
858 fetch_printf(fin, isproxy ?
859 "Pragma: no-cache\r\n" :
860 "Cache-Control: no-cache\r\n");
861 }
862
863 static int
864 print_get(FETCH *fin, int hasleading, int isproxy, const struct urlinfo *oui,
865 const struct urlinfo *ui)
866 {
867 const char *leading = hasleading ? ", " : " (";
868
869 if (isproxy) {
870 if (verbose) {
871 fprintf(ttyout, "%svia %s:%u", leading,
872 ui->host, ui->portnum);
873 leading = ", ";
874 hasleading++;
875 }
876 fetch_printf(fin, "GET %s HTTP/1.0\r\n", ui->path);
877 print_host(fin, oui);
878 return hasleading;
879 }
880
881 fetch_printf(fin, "GET %s HTTP/1.1\r\n", ui->path);
882 print_host(fin, ui);
883 fetch_printf(fin, "Accept: */*\r\n");
884 fetch_printf(fin, "Connection: close\r\n");
885 if (restart_point) {
886 fputs(leading, ttyout);
887 fetch_printf(fin, "Range: bytes=" LLF "-\r\n",
888 (LLT)restart_point);
889 fprintf(ttyout, "restarting at " LLF, (LLT)restart_point);
890 hasleading++;
891 }
892 return hasleading;
893 }
894
895 static void
896 getmtime(const char *cp, time_t *mtime)
897 {
898 struct tm parsed;
899 const char *t;
900
901 memset(&parsed, 0, sizeof(parsed));
902 t = parse_rfc2616time(&parsed, cp);
903
904 if (t == NULL)
905 return;
906
907 parsed.tm_isdst = -1;
908 if (*t == '\0')
909 *mtime = timegm(&parsed);
910
911 #ifndef NO_DEBUG
912 if (ftp_debug && *mtime != -1) {
913 fprintf(ttyout, "parsed time as: %s",
914 rfc2822time(localtime(mtime)));
915 }
916 #endif
917 }
918
919 static int
920 print_proxy(FETCH *fin, int hasleading, const char *wwwauth,
921 const char *proxyauth)
922 {
923 const char *leading = hasleading ? ", " : " (";
924
925 if (wwwauth) {
926 if (verbose) {
927 fprintf(ttyout, "%swith authorization", leading);
928 hasleading++;
929 }
930 fetch_printf(fin, "Authorization: %s\r\n", wwwauth);
931 }
932 if (proxyauth) {
933 if (verbose) {
934 fprintf(ttyout, "%swith proxy authorization", leading);
935 hasleading++;
936 }
937 fetch_printf(fin, "Proxy-Authorization: %s\r\n", proxyauth);
938 }
939 return hasleading;
940 }
941
942 #ifdef WITH_SSL
943 static void
944 print_connect(FETCH *fin, const struct urlinfo *ui)
945 {
946 char hname[NI_MAXHOST], *p;
947 const char *h;
948
949 if (isipv6addr(ui->host)) {
950 /*
951 * strip off IPv6 scope identifier,
952 * since it is local to the node
953 */
954 if ((p = strchr(ui->host, '%')) == NULL)
955 snprintf(hname, sizeof(hname), "[%s]", ui->host);
956 else
957 snprintf(hname, sizeof(hname), "[%.*s]",
958 (int)(p - ui->host), ui->host);
959 h = hname;
960 } else
961 h = ui->host;
962
963 fetch_printf(fin, "CONNECT %s:%d HTTP/1.1\r\n", h, ui->portnum);
964 fetch_printf(fin, "Host: %s:%d\r\n", h, ui->portnum);
965 }
966 #endif
967
968 #define C_OK 0
969 #define C_CLEANUP 1
970 #define C_IMPROPER 2
971
972 static int
973 getresponseline(FETCH *fin, char *buf, size_t buflen, int *len)
974 {
975 const char *errormsg;
976
977 alarmtimer(quit_time ? quit_time : 60);
978 *len = fetch_getline(fin, buf, buflen, &errormsg);
979 alarmtimer(0);
980 if (*len < 0) {
981 if (*errormsg == '\n')
982 errormsg++;
983 warnx("Receiving HTTP reply: %s", errormsg);
984 return C_CLEANUP;
985 }
986 while (*len > 0 && (ISLWS(buf[*len-1])))
987 buf[--*len] = '\0';
988
989 if (*len)
990 DPRINTF("%s: received `%s'\n", __func__, buf);
991 return C_OK;
992 }
993
994 static int
995 getresponse(FETCH *fin, char **cp, size_t buflen, int *hcode)
996 {
997 int len, rv;
998 char *ep, *buf = *cp;
999
1000 *hcode = 0;
1001 if ((rv = getresponseline(fin, buf, buflen, &len)) != C_OK)
1002 return rv;
1003
1004 /* Determine HTTP response code */
1005 *cp = strchr(buf, ' ');
1006 if (*cp == NULL)
1007 return C_IMPROPER;
1008
1009 (*cp)++;
1010
1011 *hcode = strtol(*cp, &ep, 10);
1012 if (*ep != '\0' && !isspace((unsigned char)*ep))
1013 return C_IMPROPER;
1014
1015 return C_OK;
1016 }
1017
1018 static int
1019 parse_posinfo(const char **cp, struct posinfo *pi)
1020 {
1021 char *ep;
1022 if (!match_token(cp, "bytes"))
1023 return -1;
1024
1025 if (**cp == '*')
1026 (*cp)++;
1027 else {
1028 pi->rangestart = STRTOLL(*cp, &ep, 10);
1029 if (pi->rangestart < 0 || *ep != '-')
1030 return -1;
1031 *cp = ep + 1;
1032 pi->rangeend = STRTOLL(*cp, &ep, 10);
1033 if (pi->rangeend < 0 || pi->rangeend < pi->rangestart)
1034 return -1;
1035 *cp = ep;
1036 }
1037 if (**cp != '/')
1038 return -1;
1039 (*cp)++;
1040 if (**cp == '*')
1041 (*cp)++;
1042 else {
1043 pi->entitylen = STRTOLL(*cp, &ep, 10);
1044 if (pi->entitylen < 0)
1045 return -1;
1046 *cp = ep;
1047 }
1048 if (**cp != '\0')
1049 return -1;
1050
1051 #ifndef NO_DEBUG
1052 if (ftp_debug) {
1053 fprintf(ttyout, "parsed range as: ");
1054 if (pi->rangestart == -1)
1055 fprintf(ttyout, "*");
1056 else
1057 fprintf(ttyout, LLF "-" LLF, (LLT)pi->rangestart,
1058 (LLT)pi->rangeend);
1059 fprintf(ttyout, "/" LLF "\n", (LLT)pi->entitylen);
1060 }
1061 #endif
1062 return 0;
1063 }
1064
1065 #ifndef NO_AUTH
1066 static void
1067 do_auth(int hcode, const char *url, const char *penv, struct authinfo *wauth,
1068 struct authinfo *pauth, char **auth, const char *message,
1069 volatile int *rval, struct urlinfo *ui)
1070 {
1071 struct authinfo aauth;
1072 char *response;
1073
1074 if (hcode == 401)
1075 aauth = *wauth;
1076 else
1077 aauth = *pauth;
1078
1079 if (verbose || aauth.auth == NULL ||
1080 aauth.user == NULL || aauth.pass == NULL)
1081 fprintf(ttyout, "%s\n", message);
1082 if (EMPTYSTRING(*auth)) {
1083 warnx("No authentication challenge provided by server");
1084 return;
1085 }
1086
1087 if (aauth.auth != NULL) {
1088 char reply[10];
1089
1090 fprintf(ttyout, "Authorization failed. Retry (y/n)? ");
1091 if (get_line(stdin, reply, sizeof(reply), NULL) < 0) {
1092 return;
1093 }
1094 if (tolower((unsigned char)reply[0]) != 'y')
1095 return;
1096
1097 aauth.user = NULL;
1098 aauth.pass = NULL;
1099 }
1100
1101 if (auth_url(*auth, &response, &aauth) == 0) {
1102 *rval = fetch_url(url, penv,
1103 hcode == 401 ? pauth->auth : response,
1104 hcode == 401 ? response : wauth->auth,
1105 ui);
1106 memset(response, 0, strlen(response));
1107 FREEPTR(response);
1108 }
1109 }
1110 #endif
1111
1112 static int
1113 negotiate_connection(FETCH *fin, const char *url, const char *penv,
1114 struct posinfo *pi, time_t *mtime, struct authinfo *wauth,
1115 struct authinfo *pauth, volatile int *rval, volatile int *ischunked,
1116 char **auth, struct urlinfo *ui)
1117 {
1118 int len, hcode, rv;
1119 char buf[FTPBUFLEN], *ep;
1120 const char *cp, *token;
1121 char *location, *message;
1122
1123 *auth = message = location = NULL;
1124
1125 /* Read the response */
1126 ep = buf;
1127 switch (getresponse(fin, &ep, sizeof(buf), &hcode)) {
1128 case C_CLEANUP:
1129 goto cleanup_fetch_url;
1130 case C_IMPROPER:
1131 goto improper;
1132 case C_OK:
1133 message = ftp_strdup(ep);
1134 break;
1135 }
1136
1137 /* Read the rest of the header. */
1138
1139 for (;;) {
1140 if ((rv = getresponseline(fin, buf, sizeof(buf), &len)) != C_OK)
1141 goto cleanup_fetch_url;
1142 if (len == 0)
1143 break;
1144
1145 /*
1146 * Look for some headers
1147 */
1148
1149 cp = buf;
1150
1151 if (match_token(&cp, "Content-Length:")) {
1152 filesize = STRTOLL(cp, &ep, 10);
1153 if (filesize < 0 || *ep != '\0')
1154 goto improper;
1155 DPRINTF("%s: parsed len as: " LLF "\n",
1156 __func__, (LLT)filesize);
1157
1158 } else if (match_token(&cp, "Content-Range:")) {
1159 if (parse_posinfo(&cp, pi) == -1)
1160 goto improper;
1161 if (! restart_point) {
1162 warnx(
1163 "Received unexpected Content-Range header");
1164 goto cleanup_fetch_url;
1165 }
1166
1167 } else if (match_token(&cp, "Last-Modified:")) {
1168 getmtime(cp, mtime);
1169
1170 } else if (match_token(&cp, "Location:")) {
1171 location = ftp_strdup(cp);
1172 DPRINTF("%s: parsed location as `%s'\n",
1173 __func__, cp);
1174
1175 } else if (match_token(&cp, "Transfer-Encoding:")) {
1176 if (match_token(&cp, "binary")) {
1177 warnx(
1178 "Bogus transfer encoding `binary' (fetching anyway)");
1179 continue;
1180 }
1181 if (! (token = match_token(&cp, "chunked"))) {
1182 warnx(
1183 "Unsupported transfer encoding `%s'",
1184 token);
1185 goto cleanup_fetch_url;
1186 }
1187 (*ischunked)++;
1188 DPRINTF("%s: using chunked encoding\n",
1189 __func__);
1190
1191 } else if (match_token(&cp, "Proxy-Authenticate:")
1192 || match_token(&cp, "WWW-Authenticate:")) {
1193 if (! (token = match_token(&cp, "Basic"))) {
1194 DPRINTF("%s: skipping unknown auth "
1195 "scheme `%s'\n", __func__, token);
1196 continue;
1197 }
1198 FREEPTR(*auth);
1199 *auth = ftp_strdup(token);
1200 DPRINTF("%s: parsed auth as `%s'\n",
1201 __func__, cp);
1202 }
1203
1204 }
1205 /* finished parsing header */
1206
1207 switch (hcode) {
1208 case 200:
1209 break;
1210 case 206:
1211 if (! restart_point) {
1212 warnx("Not expecting partial content header");
1213 goto cleanup_fetch_url;
1214 }
1215 break;
1216 case 300:
1217 case 301:
1218 case 302:
1219 case 303:
1220 case 305:
1221 case 307:
1222 if (EMPTYSTRING(location)) {
1223 warnx(
1224 "No redirection Location provided by server");
1225 goto cleanup_fetch_url;
1226 }
1227 if (redirect_loop++ > 5) {
1228 warnx("Too many redirections requested");
1229 goto cleanup_fetch_url;
1230 }
1231 if (hcode == 305) {
1232 if (verbose)
1233 fprintf(ttyout, "Redirected via %s\n",
1234 location);
1235 *rval = fetch_url(url, location,
1236 pauth->auth, wauth->auth, ui);
1237 } else {
1238 if (verbose)
1239 fprintf(ttyout, "Redirected to %s\n",
1240 location);
1241 *rval = go_fetch(location, ui);
1242 }
1243 goto cleanup_fetch_url;
1244 #ifndef NO_AUTH
1245 case 401:
1246 case 407:
1247 do_auth(hcode, url, penv, wauth, pauth, auth, message, rval,
1248 ui);
1249 goto cleanup_fetch_url;
1250 #endif
1251 default:
1252 if (message)
1253 warnx("Error retrieving file `%s'", message);
1254 else
1255 warnx("Unknown error retrieving file");
1256 goto cleanup_fetch_url;
1257 }
1258 rv = C_OK;
1259 goto out;
1260
1261 cleanup_fetch_url:
1262 rv = C_CLEANUP;
1263 goto out;
1264 improper:
1265 rv = C_IMPROPER;
1266 goto out;
1267 out:
1268 FREEPTR(message);
1269 FREEPTR(location);
1270 return rv;
1271 } /* end of ftp:// or http:// specific setup */
1272
1273 #ifdef WITH_SSL
1274 static int
1275 connectmethod(FETCH *fin, const char *url, const char *penv,
1276 struct urlinfo *oui, struct urlinfo *ui, struct authinfo *wauth,
1277 struct authinfo *pauth, char **auth, int *hasleading, volatile int *rval)
1278 {
1279 void *ssl;
1280 int hcode, rv;
1281 const char *cp;
1282 char buf[FTPBUFLEN], *ep;
1283 char *message = NULL;
1284
1285 print_connect(fin, oui);
1286
1287 print_agent(fin);
1288 *hasleading = print_proxy(fin, *hasleading, NULL, pauth->auth);
1289
1290 if (verbose && *hasleading)
1291 fputs(")\n", ttyout);
1292 *hasleading = 0;
1293
1294 fetch_printf(fin, "\r\n");
1295 if (fetch_flush(fin) == EOF) {
1296 warn("Writing HTTP request");
1297 alarmtimer(0);
1298 goto cleanup_fetch_url;
1299 }
1300 alarmtimer(0);
1301
1302 /* Read the response */
1303 ep = buf;
1304 switch (getresponse(fin, &ep, sizeof(buf), &hcode)) {
1305 case C_CLEANUP:
1306 goto cleanup_fetch_url;
1307 case C_IMPROPER:
1308 goto improper;
1309 case C_OK:
1310 message = ftp_strdup(ep);
1311 break;
1312 }
1313
1314 for (;;) {
1315 int len;
1316 if (getresponseline(fin, buf, sizeof(buf), &len) != C_OK)
1317 goto cleanup_fetch_url;
1318 if (len == 0)
1319 break;
1320
1321 cp = buf;
1322 if (match_token(&cp, "Proxy-Authenticate:")) {
1323 const char *token;
1324 if (!(token = match_token(&cp, "Basic"))) {
1325 DPRINTF(
1326 "%s: skipping unknown auth scheme `%s'\n",
1327 __func__, token);
1328 continue;
1329 }
1330 FREEPTR(*auth);
1331 *auth = ftp_strdup(token);
1332 DPRINTF("%s: parsed auth as " "`%s'\n", __func__, cp);
1333 }
1334 }
1335
1336 /* finished parsing header */
1337 switch (hcode) {
1338 case 200:
1339 break;
1340 #ifndef NO_AUTH
1341 case 407:
1342 do_auth(hcode, url, penv, wauth, pauth, auth, message, rval,
1343 ui);
1344 goto cleanup_fetch_url;
1345 #endif
1346 default:
1347 if (message)
1348 warnx("Error proxy connect " "`%s'", message);
1349 else
1350 warnx("Unknown error proxy " "connect");
1351 goto cleanup_fetch_url;
1352 }
1353
1354 if ((ssl = fetch_start_ssl(fetch_fileno(fin), oui->host)) == NULL)
1355 goto cleanup_fetch_url;
1356 fetch_set_ssl(fin, ssl);
1357
1358 rv = C_OK;
1359 goto out;
1360 improper:
1361 rv = C_IMPROPER;
1362 goto out;
1363 cleanup_fetch_url:
1364 rv = C_CLEANUP;
1365 goto out;
1366 out:
1367 FREEPTR(message);
1368 return rv;
1369 }
1370 #endif
1371
1372 /*
1373 * Retrieve URL, via a proxy if necessary, using HTTP.
1374 * If proxyenv is set, use that for the proxy, otherwise try ftp_proxy or
1375 * http_proxy/https_proxy as appropriate.
1376 * Supports HTTP redirects.
1377 * Returns 1 on failure, 0 on completed xfer, -1 if ftp connection
1378 * is still open (e.g, ftp xfer with trailing /)
1379 */
1380 static int
1381 fetch_url(const char *url, const char *proxyenv, char *proxyauth,
1382 char *wwwauth, struct urlinfo *rui)
1383 {
1384 sigfunc volatile oldint;
1385 sigfunc volatile oldpipe;
1386 sigfunc volatile oldalrm;
1387 sigfunc volatile oldquit;
1388 int volatile s;
1389 struct stat sb;
1390 int volatile isproxy;
1391 int volatile rval, ischunked;
1392 size_t flen;
1393 static size_t bufsize;
1394 static char *xferbuf;
1395 const char *cp;
1396 char *ep;
1397 char *volatile auth;
1398 char *volatile savefile;
1399 char *volatile location;
1400 char *volatile message;
1401 char *volatile decodedpath;
1402 struct authinfo wauth, pauth;
1403 struct posinfo pi;
1404 off_t hashbytes;
1405 int (*volatile closefunc)(FILE *);
1406 FETCH *volatile fin;
1407 FILE *volatile fout;
1408 const char *volatile penv = proxyenv;
1409 struct urlinfo ui, oui;
1410 time_t mtime;
1411 void *ssl = NULL;
1412
1413 DPRINTF("%s: `%s' proxyenv `%s'\n", __func__, url, STRorNULL(penv));
1414
1415 oldquit = oldalrm = oldint = oldpipe = SIG_ERR;
1416 closefunc = NULL;
1417 fin = NULL;
1418 fout = NULL;
1419 s = -1;
1420 savefile = NULL;
1421 auth = location = message = NULL;
1422 ischunked = isproxy = 0;
1423 rval = 1;
1424
1425 initurlinfo(&ui);
1426 initurlinfo(&oui);
1427 initauthinfo(&wauth, wwwauth);
1428 initauthinfo(&pauth, proxyauth);
1429
1430 decodedpath = NULL;
1431
1432 if (sigsetjmp(httpabort, 1))
1433 goto cleanup_fetch_url;
1434
1435 if (parse_url(url, "URL", &ui, &wauth, rui) == -1)
1436 goto cleanup_fetch_url;
1437
1438 copyurlinfo(&oui, &ui);
1439
1440 if (ui.utype == FILE_URL_T && ! EMPTYSTRING(ui.host)
1441 && strcasecmp(ui.host, "localhost") != 0) {
1442 warnx("No support for non local file URL `%s'", url);
1443 goto cleanup_fetch_url;
1444 }
1445
1446 if (EMPTYSTRING(ui.path)) {
1447 if (ui.utype == FTP_URL_T) {
1448 rval = fetch_ftp(url);
1449 goto cleanup_fetch_url;
1450 }
1451 if (!IS_HTTP_TYPE(ui.utype) || outfile == NULL) {
1452 warnx("Invalid URL (no file after host) `%s'", url);
1453 goto cleanup_fetch_url;
1454 }
1455 }
1456
1457 decodedpath = ftp_strdup(ui.path);
1458 url_decode(decodedpath);
1459
1460 if (outfile)
1461 savefile = outfile;
1462 else {
1463 cp = strrchr(decodedpath, '/'); /* find savefile */
1464 if (cp != NULL)
1465 savefile = ftp_strdup(cp + 1);
1466 else
1467 savefile = ftp_strdup(decodedpath);
1468 /*
1469 * Use the first URL we requested not the name after a
1470 * possible redirect, but careful to save it because our
1471 * "safety" check is the match to outfile.
1472 */
1473 outfile = ftp_strdup(savefile);
1474 }
1475 DPRINTF("%s: savefile `%s'\n", __func__, savefile);
1476 if (EMPTYSTRING(savefile)) {
1477 if (ui.utype == FTP_URL_T) {
1478 rval = fetch_ftp(url);
1479 goto cleanup_fetch_url;
1480 }
1481 warnx("No file after directory (you must specify an "
1482 "output file) `%s'", url);
1483 goto cleanup_fetch_url;
1484 }
1485
1486 restart_point = 0;
1487 filesize = -1;
1488 initposinfo(&pi);
1489 mtime = -1;
1490 if (restartautofetch) {
1491 if (stat(savefile, &sb) == 0)
1492 restart_point = sb.st_size;
1493 }
1494 if (ui.utype == FILE_URL_T) { /* file:// URLs */
1495 direction = "copied";
1496 fin = fetch_open(decodedpath, "r");
1497 if (fin == NULL) {
1498 warn("Can't open `%s'", decodedpath);
1499 goto cleanup_fetch_url;
1500 }
1501 if (fstat(fetch_fileno(fin), &sb) == 0) {
1502 mtime = sb.st_mtime;
1503 filesize = sb.st_size;
1504 }
1505 if (restart_point) {
1506 if (lseek(fetch_fileno(fin), restart_point, SEEK_SET)
1507 < 0) {
1508 warn("Can't seek to restart `%s'",
1509 decodedpath);
1510 goto cleanup_fetch_url;
1511 }
1512 }
1513 if (verbose) {
1514 fprintf(ttyout, "Copying %s", decodedpath);
1515 if (restart_point)
1516 fprintf(ttyout, " (restarting at " LLF ")",
1517 (LLT)restart_point);
1518 fputs("\n", ttyout);
1519 }
1520 if (0 == rcvbuf_size) {
1521 rcvbuf_size = 8 * 1024; /* XXX */
1522 }
1523 } else { /* ftp:// or http:// URLs */
1524 int hasleading;
1525 static char hostnamebuf[MAXHOSTNAMELEN];
1526
1527 (void)strlcpy(hostnamebuf, ui.host, sizeof(hostnamebuf));
1528 hostname = hostnamebuf;
1529
1530 if (penv == NULL) {
1531 #ifdef WITH_SSL
1532 if (ui.utype == HTTPS_URL_T)
1533 penv = getoptionvalue("https_proxy");
1534 #endif
1535 if (penv == NULL && IS_HTTP_TYPE(ui.utype))
1536 penv = getoptionvalue("http_proxy");
1537 else if (ui.utype == FTP_URL_T)
1538 penv = getoptionvalue("ftp_proxy");
1539 }
1540 direction = "retrieved";
1541 if (! EMPTYSTRING(penv)) { /* use proxy */
1542
1543 isproxy = handle_noproxy(ui.host, ui.portnum);
1544
1545 if (isproxy == 0 && ui.utype == FTP_URL_T) {
1546 rval = fetch_ftp(url);
1547 goto cleanup_fetch_url;
1548 }
1549
1550 if (isproxy) {
1551 if (restart_point) {
1552 warnx(
1553 "Can't restart via proxy URL `%s'",
1554 penv);
1555 goto cleanup_fetch_url;
1556 }
1557 if (handle_proxy(url, penv, &ui, &pauth) < 0)
1558 goto cleanup_fetch_url;
1559 }
1560 } /* ! EMPTYSTRING(penv) */
1561
1562 s = ftp_socket(&ui, &ssl, &wauth);
1563 if (s < 0) {
1564 warnx("Can't connect to `%s:%s'", ui.host, ui.port);
1565 goto cleanup_fetch_url;
1566 }
1567
1568 oldalrm = xsignal(SIGALRM, timeouthttp);
1569 alarmtimer(quit_time ? quit_time : 60);
1570 fin = fetch_fdopen(s, "r+");
1571 fetch_set_ssl(fin, ssl);
1572 alarmtimer(0);
1573
1574 alarmtimer(quit_time ? quit_time : 60);
1575 /*
1576 * Construct and send the request.
1577 */
1578 if (verbose)
1579 fprintf(ttyout, "Requesting %s\n", url);
1580
1581 hasleading = 0;
1582 #ifdef WITH_SSL
1583 if (isproxy && oui.utype == HTTPS_URL_T) {
1584 switch (connectmethod(fin, url, penv, &oui, &ui,
1585 &wauth, &pauth, __UNVOLATILE(&auth), &hasleading,
1586 &rval)) {
1587 case C_CLEANUP:
1588 goto cleanup_fetch_url;
1589 case C_IMPROPER:
1590 goto improper;
1591 case C_OK:
1592 break;
1593 default:
1594 abort();
1595 }
1596 }
1597 #endif
1598
1599 hasleading = print_get(fin, hasleading, isproxy, &oui, &ui);
1600
1601 if (flushcache)
1602 print_cache(fin, isproxy);
1603
1604 print_agent(fin);
1605 hasleading = print_proxy(fin, hasleading, wauth.auth,
1606 auth ? NULL : pauth.auth);
1607 if (hasleading) {
1608 hasleading = 0;
1609 if (verbose)
1610 fputs(")\n", ttyout);
1611 }
1612
1613 fetch_printf(fin, "\r\n");
1614 if (fetch_flush(fin) == EOF) {
1615 warn("Writing HTTP request");
1616 alarmtimer(0);
1617 goto cleanup_fetch_url;
1618 }
1619 alarmtimer(0);
1620
1621 switch (negotiate_connection(fin, url, penv, &pi,
1622 &mtime, &wauth, &pauth, &rval, &ischunked,
1623 __UNVOLATILE(&auth), &ui)) {
1624 case C_OK:
1625 break;
1626 case C_CLEANUP:
1627 goto cleanup_fetch_url;
1628 case C_IMPROPER:
1629 goto improper;
1630 default:
1631 abort();
1632 }
1633 }
1634
1635 /* Open the output file. */
1636
1637 /*
1638 * Only trust filenames with special meaning if they came from
1639 * the command line
1640 */
1641 if (outfile == savefile) {
1642 if (strcmp(savefile, "-") == 0) {
1643 fout = stdout;
1644 } else if (*savefile == '|') {
1645 oldpipe = xsignal(SIGPIPE, SIG_IGN);
1646 fout = popen(savefile + 1, "w");
1647 if (fout == NULL) {
1648 warn("Can't execute `%s'", savefile + 1);
1649 goto cleanup_fetch_url;
1650 }
1651 closefunc = pclose;
1652 }
1653 }
1654 if (fout == NULL) {
1655 if (restart_point && (
1656 (pi.rangeend != -1 && pi.rangeend <= restart_point) ||
1657 (pi.rangestart == -1 &&
1658 filesize != -1 && filesize <= restart_point))) {
1659 /* already done */
1660 if (verbose)
1661 fprintf(ttyout, "already done\n");
1662 rval = 0;
1663 goto cleanup_fetch_url;
1664 }
1665 if (restart_point && pi.rangestart != -1) {
1666 if (pi.entitylen != -1)
1667 filesize = pi.entitylen;
1668 if (pi.rangestart != restart_point) {
1669 warnx(
1670 "Size of `%s' differs from save file `%s'",
1671 url, savefile);
1672 goto cleanup_fetch_url;
1673 }
1674 fout = fopen(savefile, "a");
1675 } else
1676 fout = fopen(savefile, "w");
1677 if (fout == NULL) {
1678 warn("Can't open `%s'", savefile);
1679 goto cleanup_fetch_url;
1680 }
1681 closefunc = fclose;
1682 }
1683
1684 /* Trap signals */
1685 oldquit = xsignal(SIGQUIT, psummary);
1686 oldint = xsignal(SIGINT, aborthttp);
1687
1688 assert(rcvbuf_size > 0);
1689 if ((size_t)rcvbuf_size > bufsize) {
1690 if (xferbuf)
1691 (void)free(xferbuf);
1692 bufsize = rcvbuf_size;
1693 xferbuf = ftp_malloc(bufsize);
1694 }
1695
1696 bytes = 0;
1697 hashbytes = mark;
1698 if (oldalrm != SIG_ERR) {
1699 (void)xsignal(SIGALRM, oldalrm);
1700 oldalrm = SIG_ERR;
1701 }
1702 progressmeter(-1);
1703
1704 /* Finally, suck down the file. */
1705 do {
1706 long chunksize;
1707 short lastchunk;
1708
1709 chunksize = 0;
1710 lastchunk = 0;
1711 /* read chunk-size */
1712 if (ischunked) {
1713 if (fetch_getln(xferbuf, bufsize, fin) == NULL) {
1714 warnx("Unexpected EOF reading chunk-size");
1715 goto cleanup_fetch_url;
1716 }
1717 errno = 0;
1718 chunksize = strtol(xferbuf, &ep, 16);
1719 if (ep == xferbuf) {
1720 warnx("Invalid chunk-size");
1721 goto cleanup_fetch_url;
1722 }
1723 if (errno == ERANGE || chunksize < 0) {
1724 errno = ERANGE;
1725 warn("Chunk-size `%.*s'",
1726 (int)(ep-xferbuf), xferbuf);
1727 goto cleanup_fetch_url;
1728 }
1729
1730 /*
1731 * XXX: Work around bug in Apache 1.3.9 and
1732 * 1.3.11, which incorrectly put trailing
1733 * space after the chunk-size.
1734 */
1735 while (*ep == ' ')
1736 ep++;
1737
1738 /* skip [ chunk-ext ] */
1739 if (*ep == ';') {
1740 while (*ep && *ep != '\r')
1741 ep++;
1742 }
1743
1744 if (strcmp(ep, "\r\n") != 0) {
1745 warnx("Unexpected data following chunk-size");
1746 goto cleanup_fetch_url;
1747 }
1748 DPRINTF("%s: got chunk-size of " LLF "\n", __func__,
1749 (LLT)chunksize);
1750 if (chunksize == 0) {
1751 lastchunk = 1;
1752 goto chunkdone;
1753 }
1754 }
1755 /* transfer file or chunk */
1756 while (1) {
1757 struct timeval then, now, td;
1758 volatile off_t bufrem;
1759
1760 if (rate_get)
1761 (void)gettimeofday(&then, NULL);
1762 bufrem = rate_get ? rate_get : (off_t)bufsize;
1763 if (ischunked)
1764 bufrem = MIN(chunksize, bufrem);
1765 while (bufrem > 0) {
1766 size_t nr = MIN((off_t)bufsize, bufrem);
1767 flen = fetch_read(xferbuf, sizeof(char),
1768 nr, fin);
1769 if (flen == 0) {
1770 if (fetch_error(fin))
1771 goto chunkerror;
1772 goto chunkdone;
1773 }
1774 bytes += flen;
1775 bufrem -= flen;
1776 if (maxwrite(xferbuf, sizeof(char), flen, fout)
1777 != flen) {
1778 warn("Writing `%s'", savefile);
1779 goto cleanup_fetch_url;
1780 }
1781 if (hash && !progress) {
1782 while (bytes >= hashbytes) {
1783 (void)putc('#', ttyout);
1784 hashbytes += mark;
1785 }
1786 (void)fflush(ttyout);
1787 }
1788 if (ischunked) {
1789 chunksize -= flen;
1790 if (chunksize <= 0)
1791 break;
1792 }
1793 }
1794 if (rate_get) {
1795 while (1) {
1796 (void)gettimeofday(&now, NULL);
1797 timersub(&now, &then, &td);
1798 if (td.tv_sec > 0)
1799 break;
1800 usleep(1000000 - td.tv_usec);
1801 }
1802 }
1803 if (ischunked && chunksize <= 0)
1804 break;
1805 }
1806 /* read CRLF after chunk*/
1807 chunkdone:
1808 if (ischunked) {
1809 if (fetch_getln(xferbuf, bufsize, fin) == NULL) {
1810 alarmtimer(0);
1811 warnx("Unexpected EOF reading chunk CRLF");
1812 goto cleanup_fetch_url;
1813 }
1814 if (strcmp(xferbuf, "\r\n") != 0) {
1815 warnx("Unexpected data following chunk");
1816 goto cleanup_fetch_url;
1817 }
1818 if (lastchunk)
1819 break;
1820 }
1821 } while (ischunked);
1822
1823 /* XXX: deal with optional trailer & CRLF here? */
1824 chunkerror:
1825 if (hash && !progress && bytes > 0) {
1826 if (bytes < mark)
1827 (void)putc('#', ttyout);
1828 (void)putc('\n', ttyout);
1829 }
1830 if (fetch_error(fin)) {
1831 warn("Reading file");
1832 goto cleanup_fetch_url;
1833 }
1834 progressmeter(1);
1835 (void)fflush(fout);
1836 if (closefunc == fclose && mtime != -1) {
1837 struct timeval tval[2];
1838
1839 (void)gettimeofday(&tval[0], NULL);
1840 tval[1].tv_sec = mtime;
1841 tval[1].tv_usec = 0;
1842 (*closefunc)(fout);
1843 fout = NULL;
1844
1845 if (utimes(savefile, tval) == -1) {
1846 fprintf(ttyout,
1847 "Can't change modification time to %s",
1848 rfc2822time(localtime(&mtime)));
1849 }
1850 }
1851 if (bytes > 0)
1852 ptransfer(0);
1853 bytes = 0;
1854
1855 rval = 0;
1856 goto cleanup_fetch_url;
1857
1858 improper:
1859 warnx("Improper response from `%s:%s'", ui.host, ui.port);
1860
1861 cleanup_fetch_url:
1862 if (oldint != SIG_ERR)
1863 (void)xsignal(SIGINT, oldint);
1864 if (oldpipe != SIG_ERR)
1865 (void)xsignal(SIGPIPE, oldpipe);
1866 if (oldalrm != SIG_ERR)
1867 (void)xsignal(SIGALRM, oldalrm);
1868 if (oldquit != SIG_ERR)
1869 (void)xsignal(SIGQUIT, oldquit);
1870 if (fin != NULL)
1871 fetch_close(fin);
1872 else if (s != -1)
1873 close(s);
1874 if (closefunc != NULL && fout != NULL)
1875 (*closefunc)(fout);
1876 if (savefile != outfile)
1877 FREEPTR(savefile);
1878 freeurlinfo(&ui);
1879 freeurlinfo(&oui);
1880 freeauthinfo(&wauth);
1881 freeauthinfo(&pauth);
1882 FREEPTR(decodedpath);
1883 FREEPTR(auth);
1884 FREEPTR(location);
1885 FREEPTR(message);
1886 return (rval);
1887 }
1888
1889 /*
1890 * Abort a HTTP retrieval
1891 */
1892 static void
1893 aborthttp(int notused)
1894 {
1895 char msgbuf[100];
1896 int len;
1897
1898 sigint_raised = 1;
1899 alarmtimer(0);
1900 if (fromatty) {
1901 len = snprintf(msgbuf, sizeof(msgbuf),
1902 "\n%s: HTTP fetch aborted.\n", getprogname());
1903 if (len > 0)
1904 write(fileno(ttyout), msgbuf, len);
1905 }
1906 siglongjmp(httpabort, 1);
1907 }
1908
1909 static void
1910 timeouthttp(int notused)
1911 {
1912 char msgbuf[100];
1913 int len;
1914
1915 alarmtimer(0);
1916 if (fromatty) {
1917 len = snprintf(msgbuf, sizeof(msgbuf),
1918 "\n%s: HTTP fetch timeout.\n", getprogname());
1919 if (len > 0)
1920 write(fileno(ttyout), msgbuf, len);
1921 }
1922 siglongjmp(httpabort, 1);
1923 }
1924
1925 /*
1926 * Retrieve ftp URL or classic ftp argument using FTP.
1927 * Returns 1 on failure, 0 on completed xfer, -1 if ftp connection
1928 * is still open (e.g, ftp xfer with trailing /)
1929 */
1930 static int
1931 fetch_ftp(const char *url)
1932 {
1933 char *cp, *xargv[5], rempath[MAXPATHLEN];
1934 char *dir, *file;
1935 char cmdbuf[MAXPATHLEN];
1936 char dirbuf[4];
1937 int dirhasglob, filehasglob, rval, transtype, xargc;
1938 int oanonftp, oautologin;
1939 struct authinfo auth;
1940 struct urlinfo ui;
1941
1942 DPRINTF("%s: `%s'\n", __func__, url);
1943 dir = file = NULL;
1944 rval = 1;
1945 transtype = TYPE_I;
1946
1947 initurlinfo(&ui);
1948 initauthinfo(&auth, NULL);
1949
1950 if (STRNEQUAL(url, FTP_URL)) {
1951 if ((parse_url(url, "URL", &ui, &auth, NULL) == -1) ||
1952 (auth.user != NULL && *auth.user == '\0') ||
1953 EMPTYSTRING(ui.host)) {
1954 warnx("Invalid URL `%s'", url);
1955 goto cleanup_fetch_ftp;
1956 }
1957 /*
1958 * Note: Don't url_decode(path) here. We need to keep the
1959 * distinction between "/" and "%2F" until later.
1960 */
1961
1962 /* check for trailing ';type=[aid]' */
1963 if (! EMPTYSTRING(ui.path)
1964 && (cp = strrchr(ui.path, ';')) != NULL) {
1965 if (strcasecmp(cp, ";type=a") == 0)
1966 transtype = TYPE_A;
1967 else if (strcasecmp(cp, ";type=i") == 0)
1968 transtype = TYPE_I;
1969 else if (strcasecmp(cp, ";type=d") == 0) {
1970 warnx(
1971 "Directory listing via a URL is not supported");
1972 goto cleanup_fetch_ftp;
1973 } else {
1974 warnx("Invalid suffix `%s' in URL `%s'", cp,
1975 url);
1976 goto cleanup_fetch_ftp;
1977 }
1978 *cp = 0;
1979 }
1980 } else { /* classic style `[user@]host:[file]' */
1981 ui.utype = CLASSIC_URL_T;
1982 ui.host = ftp_strdup(url);
1983 cp = strchr(ui.host, '@');
1984 if (cp != NULL) {
1985 *cp = '\0';
1986 auth.user = ui.host;
1987 anonftp = 0; /* disable anonftp */
1988 ui.host = ftp_strdup(cp + 1);
1989 }
1990 cp = strchr(ui.host, ':');
1991 if (cp != NULL) {
1992 *cp = '\0';
1993 ui.path = ftp_strdup(cp + 1);
1994 }
1995 }
1996 if (EMPTYSTRING(ui.host))
1997 goto cleanup_fetch_ftp;
1998
1999 /* Extract the file and (if present) directory name. */
2000 dir = ui.path;
2001 if (! EMPTYSTRING(dir)) {
2002 /*
2003 * If we are dealing with classic `[user@]host:[path]' syntax,
2004 * then a path of the form `/file' (resulting from input of the
2005 * form `host:/file') means that we should do "CWD /" before
2006 * retrieving the file. So we set dir="/" and file="file".
2007 *
2008 * But if we are dealing with URLs like `ftp://host/path' then
2009 * a path of the form `/file' (resulting from a URL of the form
2010 * `ftp://host//file') means that we should do `CWD ' (with an
2011 * empty argument) before retrieving the file. So we set
2012 * dir="" and file="file".
2013 *
2014 * If the path does not contain / at all, we set dir=NULL.
2015 * (We get a path without any slashes if we are dealing with
2016 * classic `[user@]host:[file]' or URL `ftp://host/file'.)
2017 *
2018 * In all other cases, we set dir to a string that does not
2019 * include the final '/' that separates the dir part from the
2020 * file part of the path. (This will be the empty string if
2021 * and only if we are dealing with a path of the form `/file'
2022 * resulting from an URL of the form `ftp://host//file'.)
2023 */
2024 cp = strrchr(dir, '/');
2025 if (cp == dir && ui.utype == CLASSIC_URL_T) {
2026 file = cp + 1;
2027 (void)strlcpy(dirbuf, "/", sizeof(dirbuf));
2028 dir = dirbuf;
2029 } else if (cp != NULL) {
2030 *cp++ = '\0';
2031 file = cp;
2032 } else {
2033 file = dir;
2034 dir = NULL;
2035 }
2036 } else
2037 dir = NULL;
2038 if (ui.utype == FTP_URL_T && file != NULL) {
2039 url_decode(file);
2040 /* but still don't url_decode(dir) */
2041 }
2042 DPRINTF("%s: user `%s' pass `%s' host %s port %s "
2043 "path `%s' dir `%s' file `%s'\n", __func__,
2044 STRorNULL(auth.user), STRorNULL(auth.pass),
2045 STRorNULL(ui.host), STRorNULL(ui.port),
2046 STRorNULL(ui.path), STRorNULL(dir), STRorNULL(file));
2047
2048 dirhasglob = filehasglob = 0;
2049 if (doglob &&
2050 (ui.utype == CLASSIC_URL_T || ui.utype == FTP_URL_T)) {
2051 if (! EMPTYSTRING(dir) && strpbrk(dir, "*?[]{}") != NULL)
2052 dirhasglob = 1;
2053 if (! EMPTYSTRING(file) && strpbrk(file, "*?[]{}") != NULL)
2054 filehasglob = 1;
2055 }
2056
2057 /* Set up the connection */
2058 oanonftp = anonftp;
2059 if (connected)
2060 disconnect(0, NULL);
2061 anonftp = oanonftp;
2062 (void)strlcpy(cmdbuf, getprogname(), sizeof(cmdbuf));
2063 xargv[0] = cmdbuf;
2064 xargv[1] = ui.host;
2065 xargv[2] = NULL;
2066 xargc = 2;
2067 if (ui.port) {
2068 xargv[2] = ui.port;
2069 xargv[3] = NULL;
2070 xargc = 3;
2071 }
2072 oautologin = autologin;
2073 /* don't autologin in setpeer(), use ftp_login() below */
2074 autologin = 0;
2075 setpeer(xargc, xargv);
2076 autologin = oautologin;
2077 if ((connected == 0) ||
2078 (connected == 1 && !ftp_login(ui.host, auth.user, auth.pass))) {
2079 warnx("Can't connect or login to host `%s:%s'",
2080 ui.host, ui.port ? ui.port : "?");
2081 goto cleanup_fetch_ftp;
2082 }
2083
2084 switch (transtype) {
2085 case TYPE_A:
2086 setascii(1, xargv);
2087 break;
2088 case TYPE_I:
2089 setbinary(1, xargv);
2090 break;
2091 default:
2092 errx(1, "%s: unknown transfer type %d", __func__, transtype);
2093 }
2094
2095 /*
2096 * Change directories, if necessary.
2097 *
2098 * Note: don't use EMPTYSTRING(dir) below, because
2099 * dir=="" means something different from dir==NULL.
2100 */
2101 if (dir != NULL && !dirhasglob) {
2102 char *nextpart;
2103
2104 /*
2105 * If we are dealing with a classic `[user@]host:[path]'
2106 * (urltype is CLASSIC_URL_T) then we have a raw directory
2107 * name (not encoded in any way) and we can change
2108 * directories in one step.
2109 *
2110 * If we are dealing with an `ftp://host/path' URL
2111 * (urltype is FTP_URL_T), then RFC 3986 says we need to
2112 * send a separate CWD command for each unescaped "/"
2113 * in the path, and we have to interpret %hex escaping
2114 * *after* we find the slashes. It's possible to get
2115 * empty components here, (from multiple adjacent
2116 * slashes in the path) and RFC 3986 says that we should
2117 * still do `CWD ' (with a null argument) in such cases.
2118 *
2119 * Many ftp servers don't support `CWD ', so if there's an
2120 * error performing that command, bail out with a descriptive
2121 * message.
2122 *
2123 * Examples:
2124 *
2125 * host: dir="", urltype=CLASSIC_URL_T
2126 * logged in (to default directory)
2127 * host:file dir=NULL, urltype=CLASSIC_URL_T
2128 * "RETR file"
2129 * host:dir/ dir="dir", urltype=CLASSIC_URL_T
2130 * "CWD dir", logged in
2131 * ftp://host/ dir="", urltype=FTP_URL_T
2132 * logged in (to default directory)
2133 * ftp://host/dir/ dir="dir", urltype=FTP_URL_T
2134 * "CWD dir", logged in
2135 * ftp://host/file dir=NULL, urltype=FTP_URL_T
2136 * "RETR file"
2137 * ftp://host//file dir="", urltype=FTP_URL_T
2138 * "CWD ", "RETR file"
2139 * host:/file dir="/", urltype=CLASSIC_URL_T
2140 * "CWD /", "RETR file"
2141 * ftp://host///file dir="/", urltype=FTP_URL_T
2142 * "CWD ", "CWD ", "RETR file"
2143 * ftp://host/%2F/file dir="%2F", urltype=FTP_URL_T
2144 * "CWD /", "RETR file"
2145 * ftp://host/foo/file dir="foo", urltype=FTP_URL_T
2146 * "CWD foo", "RETR file"
2147 * ftp://host/foo/bar/file dir="foo/bar"
2148 * "CWD foo", "CWD bar", "RETR file"
2149 * ftp://host//foo/bar/file dir="/foo/bar"
2150 * "CWD ", "CWD foo", "CWD bar", "RETR file"
2151 * ftp://host/foo//bar/file dir="foo//bar"
2152 * "CWD foo", "CWD ", "CWD bar", "RETR file"
2153 * ftp://host/%2F/foo/bar/file dir="%2F/foo/bar"
2154 * "CWD /", "CWD foo", "CWD bar", "RETR file"
2155 * ftp://host/%2Ffoo/bar/file dir="%2Ffoo/bar"
2156 * "CWD /foo", "CWD bar", "RETR file"
2157 * ftp://host/%2Ffoo%2Fbar/file dir="%2Ffoo%2Fbar"
2158 * "CWD /foo/bar", "RETR file"
2159 * ftp://host/%2Ffoo%2Fbar%2Ffile dir=NULL
2160 * "RETR /foo/bar/file"
2161 *
2162 * Note that we don't need `dir' after this point.
2163 */
2164 do {
2165 if (ui.utype == FTP_URL_T) {
2166 nextpart = strchr(dir, '/');
2167 if (nextpart) {
2168 *nextpart = '\0';
2169 nextpart++;
2170 }
2171 url_decode(dir);
2172 } else
2173 nextpart = NULL;
2174 DPRINTF("%s: dir `%s', nextpart `%s'\n", __func__,
2175 STRorNULL(dir), STRorNULL(nextpart));
2176 if (ui.utype == FTP_URL_T || *dir != '\0') {
2177 (void)strlcpy(cmdbuf, "cd", sizeof(cmdbuf));
2178 xargv[0] = cmdbuf;
2179 xargv[1] = dir;
2180 xargv[2] = NULL;
2181 dirchange = 0;
2182 cd(2, xargv);
2183 if (! dirchange) {
2184 if (*dir == '\0' && code == 500)
2185 fprintf(stderr,
2186 "\n"
2187 "ftp: The `CWD ' command (without a directory), which is required by\n"
2188 " RFC 3986 to support the empty directory in the URL pathname (`//'),\n"
2189 " conflicts with the server's conformance to RFC 959.\n"
2190 " Try the same URL without the `//' in the URL pathname.\n"
2191 "\n");
2192 goto cleanup_fetch_ftp;
2193 }
2194 }
2195 dir = nextpart;
2196 } while (dir != NULL);
2197 }
2198
2199 if (EMPTYSTRING(file)) {
2200 rval = -1;
2201 goto cleanup_fetch_ftp;
2202 }
2203
2204 if (dirhasglob) {
2205 (void)strlcpy(rempath, dir, sizeof(rempath));
2206 (void)strlcat(rempath, "/", sizeof(rempath));
2207 (void)strlcat(rempath, file, sizeof(rempath));
2208 file = rempath;
2209 }
2210
2211 /* Fetch the file(s). */
2212 xargc = 2;
2213 (void)strlcpy(cmdbuf, "get", sizeof(cmdbuf));
2214 xargv[0] = cmdbuf;
2215 xargv[1] = file;
2216 xargv[2] = NULL;
2217 if (dirhasglob || filehasglob) {
2218 int ointeractive;
2219
2220 ointeractive = interactive;
2221 interactive = 0;
2222 if (restartautofetch)
2223 (void)strlcpy(cmdbuf, "mreget", sizeof(cmdbuf));
2224 else
2225 (void)strlcpy(cmdbuf, "mget", sizeof(cmdbuf));
2226 xargv[0] = cmdbuf;
2227 mget(xargc, xargv);
2228 interactive = ointeractive;
2229 } else {
2230 char *destfile = outfile;
2231 if (destfile == NULL) {
2232 cp = strrchr(file, '/'); /* find savefile */
2233 if (cp != NULL)
2234 destfile = cp + 1;
2235 else
2236 destfile = file;
2237 }
2238 xargv[2] = (char *)destfile;
2239 xargv[3] = NULL;
2240 xargc++;
2241 if (restartautofetch)
2242 reget(xargc, xargv);
2243 else
2244 get(xargc, xargv);
2245 }
2246
2247 if ((code / 100) == COMPLETE)
2248 rval = 0;
2249
2250 cleanup_fetch_ftp:
2251 freeurlinfo(&ui);
2252 freeauthinfo(&auth);
2253 return (rval);
2254 }
2255
2256 /*
2257 * Retrieve the given file to outfile.
2258 * Supports arguments of the form:
2259 * "host:path", "ftp://host/path" if $ftpproxy, call fetch_url() else
2260 * call fetch_ftp()
2261 * "http://host/path" call fetch_url() to use HTTP
2262 * "file:///path" call fetch_url() to copy
2263 * "about:..." print a message
2264 *
2265 * Returns 1 on failure, 0 on completed xfer, -1 if ftp connection
2266 * is still open (e.g, ftp xfer with trailing /)
2267 */
2268 static int
2269 go_fetch(const char *url, struct urlinfo *rui)
2270 {
2271 char *proxyenv;
2272 char *p;
2273
2274 #ifndef NO_ABOUT
2275 /*
2276 * Check for about:*
2277 */
2278 if (STRNEQUAL(url, ABOUT_URL)) {
2279 url += sizeof(ABOUT_URL) -1;
2280 if (strcasecmp(url, "ftp") == 0 ||
2281 strcasecmp(url, "tnftp") == 0) {
2282 fputs(
2283 "This version of ftp has been enhanced by Luke Mewburn <lukem (at) NetBSD.org>\n"
2284 "for the NetBSD project. Execute `man ftp' for more details.\n", ttyout);
2285 } else if (strcasecmp(url, "lukem") == 0) {
2286 fputs(
2287 "Luke Mewburn is the author of most of the enhancements in this ftp client.\n"
2288 "Please email feedback to <lukem (at) NetBSD.org>.\n", ttyout);
2289 } else if (strcasecmp(url, "netbsd") == 0) {
2290 fputs(
2291 "NetBSD is a freely available and redistributable UNIX-like operating system.\n"
2292 "For more information, see http://www.NetBSD.org/\n", ttyout);
2293 } else if (strcasecmp(url, "version") == 0) {
2294 fprintf(ttyout, "Version: %s %s%s\n",
2295 FTP_PRODUCT, FTP_VERSION,
2296 #ifdef INET6
2297 ""
2298 #else
2299 " (-IPv6)"
2300 #endif
2301 );
2302 } else {
2303 fprintf(ttyout, "`%s' is an interesting topic.\n", url);
2304 }
2305 fputs("\n", ttyout);
2306 return (0);
2307 }
2308 #endif
2309
2310 /*
2311 * Check for file:// and http:// URLs.
2312 */
2313 if (STRNEQUAL(url, HTTP_URL)
2314 #ifdef WITH_SSL
2315 || STRNEQUAL(url, HTTPS_URL)
2316 #endif
2317 || STRNEQUAL(url, FILE_URL))
2318 return (fetch_url(url, NULL, NULL, NULL, rui));
2319
2320 /*
2321 * If it contains "://" but does not begin with ftp://
2322 * or something that was already handled, then it's
2323 * unsupported.
2324 *
2325 * If it contains ":" but not "://" then we assume the
2326 * part before the colon is a host name, not an URL scheme,
2327 * so we don't try to match that here.
2328 */
2329 if ((p = strstr(url, "://")) != NULL && ! STRNEQUAL(url, FTP_URL))
2330 errx(1, "Unsupported URL scheme `%.*s'", (int)(p - url), url);
2331
2332 /*
2333 * Refer to previous urlinfo if provided. This makes relative
2334 * redirects work.
2335 */
2336 if (use_relative(rui))
2337 return fetch_url(url, NULL, NULL, NULL, rui);
2338
2339 /*
2340 * Try FTP URL-style and host:file arguments next.
2341 * If ftpproxy is set with an FTP URL, use fetch_url()
2342 * Otherwise, use fetch_ftp().
2343 */
2344 proxyenv = getoptionvalue("ftp_proxy");
2345 if (!EMPTYSTRING(proxyenv) && STRNEQUAL(url, FTP_URL))
2346 return (fetch_url(url, NULL, NULL, NULL, rui));
2347
2348 return (fetch_ftp(url));
2349 }
2350
2351 /*
2352 * Retrieve multiple files from the command line,
2353 * calling go_fetch() for each file.
2354 *
2355 * If an ftp path has a trailing "/", the path will be cd-ed into and
2356 * the connection remains open, and the function will return -1
2357 * (to indicate the connection is alive).
2358 * If an error occurs the return value will be the offset+1 in
2359 * argv[] of the file that caused a problem (i.e, argv[x]
2360 * returns x+1)
2361 * Otherwise, 0 is returned if all files retrieved successfully.
2362 */
2363 int
2364 auto_fetch(int argc, char *argv[])
2365 {
2366 volatile int argpos, rval;
2367
2368 argpos = rval = 0;
2369
2370 if (sigsetjmp(toplevel, 1)) {
2371 if (connected)
2372 disconnect(0, NULL);
2373 if (rval > 0)
2374 rval = argpos + 1;
2375 return (rval);
2376 }
2377 (void)xsignal(SIGINT, intr);
2378 (void)xsignal(SIGPIPE, lostpeer);
2379
2380 /*
2381 * Loop through as long as there's files to fetch.
2382 */
2383 for (; (rval == 0) && (argpos < argc); argpos++) {
2384 if (strchr(argv[argpos], ':') == NULL)
2385 break;
2386 redirect_loop = 0;
2387 if (!anonftp)
2388 anonftp = 2; /* Handle "automatic" transfers. */
2389 rval = go_fetch(argv[argpos], NULL);
2390 if (outfile != NULL && strcmp(outfile, "-") != 0
2391 && outfile[0] != '|') {
2392 FREEPTR(outfile);
2393 }
2394 if (rval > 0)
2395 rval = argpos + 1;
2396 }
2397
2398 if (connected && rval != -1)
2399 disconnect(0, NULL);
2400 return (rval);
2401 }
2402
2403
2404 /*
2405 * Upload multiple files from the command line.
2406 *
2407 * If an error occurs the return value will be the offset+1 in
2408 * argv[] of the file that caused a problem (i.e, argv[x]
2409 * returns x+1)
2410 * Otherwise, 0 is returned if all files uploaded successfully.
2411 */
2412 int
2413 auto_put(int argc, char **argv, const char *uploadserver)
2414 {
2415 char *uargv[4], *path, *pathsep;
2416 int uargc, rval, argpos;
2417 size_t len;
2418 char cmdbuf[MAX_C_NAME];
2419
2420 (void)strlcpy(cmdbuf, "mput", sizeof(cmdbuf));
2421 uargv[0] = cmdbuf;
2422 uargv[1] = argv[0];
2423 uargc = 2;
2424 uargv[2] = uargv[3] = NULL;
2425 pathsep = NULL;
2426 rval = 1;
2427
2428 DPRINTF("%s: target `%s'\n", __func__, uploadserver);
2429
2430 path = ftp_strdup(uploadserver);
2431 len = strlen(path);
2432 if (path[len - 1] != '/' && path[len - 1] != ':') {
2433 /*
2434 * make sure we always pass a directory to auto_fetch
2435 */
2436 if (argc > 1) { /* more than one file to upload */
2437 len = strlen(uploadserver) + 2; /* path + "/" + "\0" */
2438 free(path);
2439 path = (char *)ftp_malloc(len);
2440 (void)strlcpy(path, uploadserver, len);
2441 (void)strlcat(path, "/", len);
2442 } else { /* single file to upload */
2443 (void)strlcpy(cmdbuf, "put", sizeof(cmdbuf));
2444 uargv[0] = cmdbuf;
2445 pathsep = strrchr(path, '/');
2446 if (pathsep == NULL) {
2447 pathsep = strrchr(path, ':');
2448 if (pathsep == NULL) {
2449 warnx("Invalid URL `%s'", path);
2450 goto cleanup_auto_put;
2451 }
2452 pathsep++;
2453 uargv[2] = ftp_strdup(pathsep);
2454 pathsep[0] = '/';
2455 } else
2456 uargv[2] = ftp_strdup(pathsep + 1);
2457 pathsep[1] = '\0';
2458 uargc++;
2459 }
2460 }
2461 DPRINTF("%s: URL `%s' argv[2] `%s'\n", __func__,
2462 path, STRorNULL(uargv[2]));
2463
2464 /* connect and cwd */
2465 rval = auto_fetch(1, &path);
2466 if(rval >= 0)
2467 goto cleanup_auto_put;
2468
2469 rval = 0;
2470
2471 /* target filename provided; upload 1 file */
2472 /* XXX : is this the best way? */
2473 if (uargc == 3) {
2474 uargv[1] = argv[0];
2475 put(uargc, uargv);
2476 if ((code / 100) != COMPLETE)
2477 rval = 1;
2478 } else { /* otherwise a target dir: upload all files to it */
2479 for(argpos = 0; argv[argpos] != NULL; argpos++) {
2480 uargv[1] = argv[argpos];
2481 mput(uargc, uargv);
2482 if ((code / 100) != COMPLETE) {
2483 rval = argpos + 1;
2484 break;
2485 }
2486 }
2487 }
2488
2489 cleanup_auto_put:
2490 free(path);
2491 FREEPTR(uargv[2]);
2492 return (rval);
2493 }
2494