fetch.c revision 1.236 1 /* $NetBSD: fetch.c,v 1.236 2023/02/25 12:07:25 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.236 2023/02/25 12:07:25 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 pui.path = ftp_strdup(url);
805
806 freeurlinfo(ui);
807 *ui = pui;
808
809 return 0;
810 }
811
812 static void
813 print_host(FETCH *fin, const struct urlinfo *ui)
814 {
815 char *h, *p;
816
817 if (strchr(ui->host, ':') == NULL) {
818 fetch_printf(fin, "Host: %s", ui->host);
819 } else {
820 /*
821 * strip off IPv6 scope identifier, since it is
822 * local to the node
823 */
824 h = ftp_strdup(ui->host);
825 if (isipv6addr(h) && (p = strchr(h, '%')) != NULL)
826 *p = '\0';
827
828 fetch_printf(fin, "Host: [%s]", h);
829 free(h);
830 }
831
832 if ((ui->utype == HTTP_URL_T && ui->portnum != HTTP_PORT) ||
833 (ui->utype == HTTPS_URL_T && ui->portnum != HTTPS_PORT))
834 fetch_printf(fin, ":%u", ui->portnum);
835 fetch_printf(fin, "\r\n");
836 }
837
838 static void
839 print_agent(FETCH *fin)
840 {
841 const char *useragent;
842 if ((useragent = getenv("FTPUSERAGENT")) != NULL) {
843 fetch_printf(fin, "User-Agent: %s\r\n", useragent);
844 } else {
845 fetch_printf(fin, "User-Agent: %s/%s\r\n",
846 FTP_PRODUCT, FTP_VERSION);
847 }
848 }
849
850 static void
851 print_cache(FETCH *fin, int isproxy)
852 {
853 fetch_printf(fin, isproxy ?
854 "Pragma: no-cache\r\n" :
855 "Cache-Control: no-cache\r\n");
856 }
857
858 static int
859 print_get(FETCH *fin, int hasleading, int isproxy, const struct urlinfo *oui,
860 const struct urlinfo *ui)
861 {
862 const char *leading = hasleading ? ", " : " (";
863
864 if (isproxy) {
865 if (verbose) {
866 fprintf(ttyout, "%svia %s:%u", leading,
867 ui->host, ui->portnum);
868 leading = ", ";
869 hasleading++;
870 }
871 fetch_printf(fin, "GET %s HTTP/1.0\r\n", ui->path);
872 print_host(fin, oui);
873 return hasleading;
874 }
875
876 fetch_printf(fin, "GET %s HTTP/1.1\r\n", ui->path);
877 print_host(fin, ui);
878 fetch_printf(fin, "Accept: */*\r\n");
879 fetch_printf(fin, "Connection: close\r\n");
880 if (restart_point) {
881 fputs(leading, ttyout);
882 fetch_printf(fin, "Range: bytes=" LLF "-\r\n",
883 (LLT)restart_point);
884 fprintf(ttyout, "restarting at " LLF, (LLT)restart_point);
885 hasleading++;
886 }
887 return hasleading;
888 }
889
890 static void
891 getmtime(const char *cp, time_t *mtime)
892 {
893 struct tm parsed;
894 const char *t;
895
896 memset(&parsed, 0, sizeof(parsed));
897 t = parse_rfc2616time(&parsed, cp);
898
899 if (t == NULL)
900 return;
901
902 parsed.tm_isdst = -1;
903 if (*t == '\0')
904 *mtime = timegm(&parsed);
905
906 #ifndef NO_DEBUG
907 if (ftp_debug && *mtime != -1) {
908 fprintf(ttyout, "parsed time as: %s",
909 rfc2822time(localtime(mtime)));
910 }
911 #endif
912 }
913
914 static int
915 print_proxy(FETCH *fin, int hasleading, const char *wwwauth,
916 const char *proxyauth)
917 {
918 const char *leading = hasleading ? ", " : " (";
919
920 if (wwwauth) {
921 if (verbose) {
922 fprintf(ttyout, "%swith authorization", leading);
923 hasleading++;
924 }
925 fetch_printf(fin, "Authorization: %s\r\n", wwwauth);
926 }
927 if (proxyauth) {
928 if (verbose) {
929 fprintf(ttyout, "%swith proxy authorization", leading);
930 hasleading++;
931 }
932 fetch_printf(fin, "Proxy-Authorization: %s\r\n", proxyauth);
933 }
934 return hasleading;
935 }
936
937 #ifdef WITH_SSL
938 static void
939 print_connect(FETCH *fin, const struct urlinfo *ui)
940 {
941 char hname[NI_MAXHOST], *p;
942 const char *h;
943
944 if (isipv6addr(ui->host)) {
945 /*
946 * strip off IPv6 scope identifier,
947 * since it is local to the node
948 */
949 if ((p = strchr(ui->host, '%')) == NULL)
950 snprintf(hname, sizeof(hname), "[%s]", ui->host);
951 else
952 snprintf(hname, sizeof(hname), "[%.*s]",
953 (int)(p - ui->host), ui->host);
954 h = hname;
955 } else
956 h = ui->host;
957
958 fetch_printf(fin, "CONNECT %s:%d HTTP/1.1\r\n", h, ui->portnum);
959 fetch_printf(fin, "Host: %s:%d\r\n", h, ui->portnum);
960 }
961 #endif
962
963 #define C_OK 0
964 #define C_CLEANUP 1
965 #define C_IMPROPER 2
966
967 static int
968 getresponseline(FETCH *fin, char *buf, size_t buflen, int *len)
969 {
970 const char *errormsg;
971
972 alarmtimer(quit_time ? quit_time : 60);
973 *len = fetch_getline(fin, buf, buflen, &errormsg);
974 alarmtimer(0);
975 if (*len < 0) {
976 if (*errormsg == '\n')
977 errormsg++;
978 warnx("Receiving HTTP reply: %s", errormsg);
979 return C_CLEANUP;
980 }
981 while (*len > 0 && (ISLWS(buf[*len-1])))
982 buf[--*len] = '\0';
983
984 if (*len)
985 DPRINTF("%s: received `%s'\n", __func__, buf);
986 return C_OK;
987 }
988
989 static int
990 getresponse(FETCH *fin, char **cp, size_t buflen, int *hcode)
991 {
992 int len, rv;
993 char *ep, *buf = *cp;
994
995 *hcode = 0;
996 if ((rv = getresponseline(fin, buf, buflen, &len)) != C_OK)
997 return rv;
998
999 /* Determine HTTP response code */
1000 *cp = strchr(buf, ' ');
1001 if (*cp == NULL)
1002 return C_IMPROPER;
1003
1004 (*cp)++;
1005
1006 *hcode = strtol(*cp, &ep, 10);
1007 if (*ep != '\0' && !isspace((unsigned char)*ep))
1008 return C_IMPROPER;
1009
1010 return C_OK;
1011 }
1012
1013 static int
1014 parse_posinfo(const char **cp, struct posinfo *pi)
1015 {
1016 char *ep;
1017 if (!match_token(cp, "bytes"))
1018 return -1;
1019
1020 if (**cp == '*')
1021 (*cp)++;
1022 else {
1023 pi->rangestart = STRTOLL(*cp, &ep, 10);
1024 if (pi->rangestart < 0 || *ep != '-')
1025 return -1;
1026 *cp = ep + 1;
1027 pi->rangeend = STRTOLL(*cp, &ep, 10);
1028 if (pi->rangeend < 0 || pi->rangeend < pi->rangestart)
1029 return -1;
1030 *cp = ep;
1031 }
1032 if (**cp != '/')
1033 return -1;
1034 (*cp)++;
1035 if (**cp == '*')
1036 (*cp)++;
1037 else {
1038 pi->entitylen = STRTOLL(*cp, &ep, 10);
1039 if (pi->entitylen < 0)
1040 return -1;
1041 *cp = ep;
1042 }
1043 if (**cp != '\0')
1044 return -1;
1045
1046 #ifndef NO_DEBUG
1047 if (ftp_debug) {
1048 fprintf(ttyout, "parsed range as: ");
1049 if (pi->rangestart == -1)
1050 fprintf(ttyout, "*");
1051 else
1052 fprintf(ttyout, LLF "-" LLF, (LLT)pi->rangestart,
1053 (LLT)pi->rangeend);
1054 fprintf(ttyout, "/" LLF "\n", (LLT)pi->entitylen);
1055 }
1056 #endif
1057 return 0;
1058 }
1059
1060 #ifndef NO_AUTH
1061 static void
1062 do_auth(int hcode, const char *url, const char *penv, struct authinfo *wauth,
1063 struct authinfo *pauth, char **auth, const char *message,
1064 volatile int *rval, struct urlinfo *ui)
1065 {
1066 struct authinfo aauth;
1067 char *response;
1068
1069 if (hcode == 401)
1070 aauth = *wauth;
1071 else
1072 aauth = *pauth;
1073
1074 if (verbose || aauth.auth == NULL ||
1075 aauth.user == NULL || aauth.pass == NULL)
1076 fprintf(ttyout, "%s\n", message);
1077 if (EMPTYSTRING(*auth)) {
1078 warnx("No authentication challenge provided by server");
1079 return;
1080 }
1081
1082 if (aauth.auth != NULL) {
1083 char reply[10];
1084
1085 fprintf(ttyout, "Authorization failed. Retry (y/n)? ");
1086 if (get_line(stdin, reply, sizeof(reply), NULL) < 0) {
1087 return;
1088 }
1089 if (tolower((unsigned char)reply[0]) != 'y')
1090 return;
1091
1092 aauth.user = NULL;
1093 aauth.pass = NULL;
1094 }
1095
1096 if (auth_url(*auth, &response, &aauth) == 0) {
1097 *rval = fetch_url(url, penv,
1098 hcode == 401 ? pauth->auth : response,
1099 hcode == 401 ? response : wauth->auth,
1100 ui);
1101 memset(response, 0, strlen(response));
1102 FREEPTR(response);
1103 }
1104 }
1105 #endif
1106
1107 static int
1108 negotiate_connection(FETCH *fin, const char *url, const char *penv,
1109 struct posinfo *pi, time_t *mtime, struct authinfo *wauth,
1110 struct authinfo *pauth, volatile int *rval, volatile int *ischunked,
1111 char **auth, struct urlinfo *ui)
1112 {
1113 int len, hcode, rv;
1114 char buf[FTPBUFLEN], *ep;
1115 const char *cp, *token;
1116 char *location, *message;
1117
1118 *auth = message = location = NULL;
1119
1120 /* Read the response */
1121 ep = buf;
1122 switch (getresponse(fin, &ep, sizeof(buf), &hcode)) {
1123 case C_CLEANUP:
1124 goto cleanup_fetch_url;
1125 case C_IMPROPER:
1126 goto improper;
1127 case C_OK:
1128 message = ftp_strdup(ep);
1129 break;
1130 }
1131
1132 /* Read the rest of the header. */
1133
1134 for (;;) {
1135 if ((rv = getresponseline(fin, buf, sizeof(buf), &len)) != C_OK)
1136 goto cleanup_fetch_url;
1137 if (len == 0)
1138 break;
1139
1140 /*
1141 * Look for some headers
1142 */
1143
1144 cp = buf;
1145
1146 if (match_token(&cp, "Content-Length:")) {
1147 filesize = STRTOLL(cp, &ep, 10);
1148 if (filesize < 0 || *ep != '\0')
1149 goto improper;
1150 DPRINTF("%s: parsed len as: " LLF "\n",
1151 __func__, (LLT)filesize);
1152
1153 } else if (match_token(&cp, "Content-Range:")) {
1154 if (parse_posinfo(&cp, pi) == -1)
1155 goto improper;
1156 if (! restart_point) {
1157 warnx(
1158 "Received unexpected Content-Range header");
1159 goto cleanup_fetch_url;
1160 }
1161
1162 } else if (match_token(&cp, "Last-Modified:")) {
1163 getmtime(cp, mtime);
1164
1165 } else if (match_token(&cp, "Location:")) {
1166 location = ftp_strdup(cp);
1167 DPRINTF("%s: parsed location as `%s'\n",
1168 __func__, cp);
1169
1170 } else if (match_token(&cp, "Transfer-Encoding:")) {
1171 if (match_token(&cp, "binary")) {
1172 warnx(
1173 "Bogus transfer encoding `binary' (fetching anyway)");
1174 continue;
1175 }
1176 if (! (token = match_token(&cp, "chunked"))) {
1177 warnx(
1178 "Unsupported transfer encoding `%s'",
1179 token);
1180 goto cleanup_fetch_url;
1181 }
1182 (*ischunked)++;
1183 DPRINTF("%s: using chunked encoding\n",
1184 __func__);
1185
1186 } else if (match_token(&cp, "Proxy-Authenticate:")
1187 || match_token(&cp, "WWW-Authenticate:")) {
1188 if (! (token = match_token(&cp, "Basic"))) {
1189 DPRINTF("%s: skipping unknown auth "
1190 "scheme `%s'\n", __func__, token);
1191 continue;
1192 }
1193 FREEPTR(*auth);
1194 *auth = ftp_strdup(token);
1195 DPRINTF("%s: parsed auth as `%s'\n",
1196 __func__, cp);
1197 }
1198
1199 }
1200 /* finished parsing header */
1201
1202 switch (hcode) {
1203 case 200:
1204 break;
1205 case 206:
1206 if (! restart_point) {
1207 warnx("Not expecting partial content header");
1208 goto cleanup_fetch_url;
1209 }
1210 break;
1211 case 300:
1212 case 301:
1213 case 302:
1214 case 303:
1215 case 305:
1216 case 307:
1217 if (EMPTYSTRING(location)) {
1218 warnx(
1219 "No redirection Location provided by server");
1220 goto cleanup_fetch_url;
1221 }
1222 if (redirect_loop++ > 5) {
1223 warnx("Too many redirections requested");
1224 goto cleanup_fetch_url;
1225 }
1226 if (hcode == 305) {
1227 if (verbose)
1228 fprintf(ttyout, "Redirected via %s\n",
1229 location);
1230 *rval = fetch_url(url, location,
1231 pauth->auth, wauth->auth, ui);
1232 } else {
1233 if (verbose)
1234 fprintf(ttyout, "Redirected to %s\n",
1235 location);
1236 *rval = go_fetch(location, ui);
1237 }
1238 goto cleanup_fetch_url;
1239 #ifndef NO_AUTH
1240 case 401:
1241 case 407:
1242 do_auth(hcode, url, penv, wauth, pauth, auth, message, rval,
1243 ui);
1244 goto cleanup_fetch_url;
1245 #endif
1246 default:
1247 if (message)
1248 warnx("Error retrieving file `%s'", message);
1249 else
1250 warnx("Unknown error retrieving file");
1251 goto cleanup_fetch_url;
1252 }
1253 rv = C_OK;
1254 goto out;
1255
1256 cleanup_fetch_url:
1257 rv = C_CLEANUP;
1258 goto out;
1259 improper:
1260 rv = C_IMPROPER;
1261 goto out;
1262 out:
1263 FREEPTR(message);
1264 FREEPTR(location);
1265 return rv;
1266 } /* end of ftp:// or http:// specific setup */
1267
1268 #ifdef WITH_SSL
1269 static int
1270 connectmethod(FETCH *fin, const char *url, const char *penv,
1271 struct urlinfo *oui, struct urlinfo *ui, struct authinfo *wauth,
1272 struct authinfo *pauth, char **auth, int *hasleading, volatile int *rval)
1273 {
1274 void *ssl;
1275 int hcode, rv;
1276 const char *cp;
1277 char buf[FTPBUFLEN], *ep;
1278 char *message = NULL;
1279
1280 print_connect(fin, oui);
1281
1282 print_agent(fin);
1283 *hasleading = print_proxy(fin, *hasleading, NULL, pauth->auth);
1284
1285 if (verbose && *hasleading)
1286 fputs(")\n", ttyout);
1287 *hasleading = 0;
1288
1289 fetch_printf(fin, "\r\n");
1290 if (fetch_flush(fin) == EOF) {
1291 warn("Writing HTTP request");
1292 alarmtimer(0);
1293 goto cleanup_fetch_url;
1294 }
1295 alarmtimer(0);
1296
1297 /* Read the response */
1298 ep = buf;
1299 switch (getresponse(fin, &ep, sizeof(buf), &hcode)) {
1300 case C_CLEANUP:
1301 goto cleanup_fetch_url;
1302 case C_IMPROPER:
1303 goto improper;
1304 case C_OK:
1305 message = ftp_strdup(ep);
1306 break;
1307 }
1308
1309 for (;;) {
1310 int len;
1311 if (getresponseline(fin, buf, sizeof(buf), &len) != C_OK)
1312 goto cleanup_fetch_url;
1313 if (len == 0)
1314 break;
1315
1316 cp = buf;
1317 if (match_token(&cp, "Proxy-Authenticate:")) {
1318 const char *token;
1319 if (!(token = match_token(&cp, "Basic"))) {
1320 DPRINTF(
1321 "%s: skipping unknown auth scheme `%s'\n",
1322 __func__, token);
1323 continue;
1324 }
1325 FREEPTR(*auth);
1326 *auth = ftp_strdup(token);
1327 DPRINTF("%s: parsed auth as " "`%s'\n", __func__, cp);
1328 }
1329 }
1330
1331 /* finished parsing header */
1332 switch (hcode) {
1333 case 200:
1334 break;
1335 #ifndef NO_AUTH
1336 case 407:
1337 do_auth(hcode, url, penv, wauth, pauth, auth, message, rval,
1338 ui);
1339 goto cleanup_fetch_url;
1340 #endif
1341 default:
1342 if (message)
1343 warnx("Error proxy connect " "`%s'", message);
1344 else
1345 warnx("Unknown error proxy " "connect");
1346 goto cleanup_fetch_url;
1347 }
1348
1349 if ((ssl = fetch_start_ssl(fetch_fileno(fin), oui->host)) == NULL)
1350 goto cleanup_fetch_url;
1351 fetch_set_ssl(fin, ssl);
1352
1353 rv = C_OK;
1354 goto out;
1355 improper:
1356 rv = C_IMPROPER;
1357 goto out;
1358 cleanup_fetch_url:
1359 rv = C_CLEANUP;
1360 goto out;
1361 out:
1362 FREEPTR(message);
1363 return rv;
1364 }
1365 #endif
1366
1367 /*
1368 * Retrieve URL, via a proxy if necessary, using HTTP.
1369 * If proxyenv is set, use that for the proxy, otherwise try ftp_proxy or
1370 * http_proxy/https_proxy as appropriate.
1371 * Supports HTTP redirects.
1372 * Returns 1 on failure, 0 on completed xfer, -1 if ftp connection
1373 * is still open (e.g, ftp xfer with trailing /)
1374 */
1375 static int
1376 fetch_url(const char *url, const char *proxyenv, char *proxyauth,
1377 char *wwwauth, struct urlinfo *rui)
1378 {
1379 sigfunc volatile oldint;
1380 sigfunc volatile oldpipe;
1381 sigfunc volatile oldalrm;
1382 sigfunc volatile oldquit;
1383 int volatile s;
1384 struct stat sb;
1385 int volatile isproxy;
1386 int volatile rval, ischunked;
1387 size_t flen;
1388 static size_t bufsize;
1389 static char *xferbuf;
1390 const char *cp;
1391 char *ep;
1392 char *volatile auth;
1393 char *volatile savefile;
1394 char *volatile location;
1395 char *volatile message;
1396 char *volatile decodedpath;
1397 struct authinfo wauth, pauth;
1398 struct posinfo pi;
1399 off_t hashbytes;
1400 int (*volatile closefunc)(FILE *);
1401 FETCH *volatile fin;
1402 FILE *volatile fout;
1403 const char *volatile penv = proxyenv;
1404 struct urlinfo ui, oui;
1405 time_t mtime;
1406 void *ssl = NULL;
1407
1408 DPRINTF("%s: `%s' proxyenv `%s'\n", __func__, url, STRorNULL(penv));
1409
1410 oldquit = oldalrm = oldint = oldpipe = SIG_ERR;
1411 closefunc = NULL;
1412 fin = NULL;
1413 fout = NULL;
1414 s = -1;
1415 savefile = NULL;
1416 auth = location = message = NULL;
1417 ischunked = isproxy = 0;
1418 rval = 1;
1419
1420 initurlinfo(&ui);
1421 initurlinfo(&oui);
1422 initauthinfo(&wauth, wwwauth);
1423 initauthinfo(&pauth, proxyauth);
1424
1425 decodedpath = NULL;
1426
1427 if (sigsetjmp(httpabort, 1))
1428 goto cleanup_fetch_url;
1429
1430 if (parse_url(url, "URL", &ui, &wauth, rui) == -1)
1431 goto cleanup_fetch_url;
1432
1433 copyurlinfo(&oui, &ui);
1434
1435 if (ui.utype == FILE_URL_T && ! EMPTYSTRING(ui.host)
1436 && strcasecmp(ui.host, "localhost") != 0) {
1437 warnx("No support for non local file URL `%s'", url);
1438 goto cleanup_fetch_url;
1439 }
1440
1441 if (EMPTYSTRING(ui.path)) {
1442 if (ui.utype == FTP_URL_T) {
1443 rval = fetch_ftp(url);
1444 goto cleanup_fetch_url;
1445 }
1446 if (!IS_HTTP_TYPE(ui.utype) || outfile == NULL) {
1447 warnx("Invalid URL (no file after host) `%s'", url);
1448 goto cleanup_fetch_url;
1449 }
1450 }
1451
1452 decodedpath = ftp_strdup(ui.path);
1453 url_decode(decodedpath);
1454
1455 if (outfile)
1456 savefile = outfile;
1457 else {
1458 cp = strrchr(decodedpath, '/'); /* find savefile */
1459 if (cp != NULL)
1460 savefile = ftp_strdup(cp + 1);
1461 else
1462 savefile = ftp_strdup(decodedpath);
1463 /*
1464 * Use the first URL we requested not the name after a
1465 * possible redirect, but careful to save it because our
1466 * "safety" check is the match to outfile.
1467 */
1468 outfile = ftp_strdup(savefile);
1469 }
1470 DPRINTF("%s: savefile `%s'\n", __func__, savefile);
1471 if (EMPTYSTRING(savefile)) {
1472 if (ui.utype == FTP_URL_T) {
1473 rval = fetch_ftp(url);
1474 goto cleanup_fetch_url;
1475 }
1476 warnx("No file after directory (you must specify an "
1477 "output file) `%s'", url);
1478 goto cleanup_fetch_url;
1479 }
1480
1481 restart_point = 0;
1482 filesize = -1;
1483 initposinfo(&pi);
1484 mtime = -1;
1485 if (restartautofetch) {
1486 if (stat(savefile, &sb) == 0)
1487 restart_point = sb.st_size;
1488 }
1489 if (ui.utype == FILE_URL_T) { /* file:// URLs */
1490 direction = "copied";
1491 fin = fetch_open(decodedpath, "r");
1492 if (fin == NULL) {
1493 warn("Can't open `%s'", decodedpath);
1494 goto cleanup_fetch_url;
1495 }
1496 if (fstat(fetch_fileno(fin), &sb) == 0) {
1497 mtime = sb.st_mtime;
1498 filesize = sb.st_size;
1499 }
1500 if (restart_point) {
1501 if (lseek(fetch_fileno(fin), restart_point, SEEK_SET)
1502 < 0) {
1503 warn("Can't seek to restart `%s'",
1504 decodedpath);
1505 goto cleanup_fetch_url;
1506 }
1507 }
1508 if (verbose) {
1509 fprintf(ttyout, "Copying %s", decodedpath);
1510 if (restart_point)
1511 fprintf(ttyout, " (restarting at " LLF ")",
1512 (LLT)restart_point);
1513 fputs("\n", ttyout);
1514 }
1515 if (0 == rcvbuf_size) {
1516 rcvbuf_size = 8 * 1024; /* XXX */
1517 }
1518 } else { /* ftp:// or http:// URLs */
1519 int hasleading;
1520 static char hostnamebuf[MAXHOSTNAMELEN];
1521
1522 (void)strlcpy(hostnamebuf, ui.host, sizeof(hostnamebuf));
1523 hostname = hostnamebuf;
1524
1525 if (penv == NULL) {
1526 #ifdef WITH_SSL
1527 if (ui.utype == HTTPS_URL_T)
1528 penv = getoptionvalue("https_proxy");
1529 #endif
1530 if (penv == NULL && IS_HTTP_TYPE(ui.utype))
1531 penv = getoptionvalue("http_proxy");
1532 else if (ui.utype == FTP_URL_T)
1533 penv = getoptionvalue("ftp_proxy");
1534 }
1535 direction = "retrieved";
1536 if (! EMPTYSTRING(penv)) { /* use proxy */
1537
1538 isproxy = handle_noproxy(ui.host, ui.portnum);
1539
1540 if (isproxy == 0 && ui.utype == FTP_URL_T) {
1541 rval = fetch_ftp(url);
1542 goto cleanup_fetch_url;
1543 }
1544
1545 if (isproxy) {
1546 if (restart_point) {
1547 warnx(
1548 "Can't restart via proxy URL `%s'",
1549 penv);
1550 goto cleanup_fetch_url;
1551 }
1552 if (handle_proxy(url, penv, &ui, &pauth) < 0)
1553 goto cleanup_fetch_url;
1554 }
1555 } /* ! EMPTYSTRING(penv) */
1556
1557 s = ftp_socket(&ui, &ssl, &wauth);
1558 if (s < 0) {
1559 warnx("Can't connect to `%s:%s'", ui.host, ui.port);
1560 goto cleanup_fetch_url;
1561 }
1562
1563 oldalrm = xsignal(SIGALRM, timeouthttp);
1564 alarmtimer(quit_time ? quit_time : 60);
1565 fin = fetch_fdopen(s, "r+");
1566 fetch_set_ssl(fin, ssl);
1567 alarmtimer(0);
1568
1569 alarmtimer(quit_time ? quit_time : 60);
1570 /*
1571 * Construct and send the request.
1572 */
1573 if (verbose)
1574 fprintf(ttyout, "Requesting %s\n", url);
1575
1576 hasleading = 0;
1577 #ifdef WITH_SSL
1578 if (isproxy && oui.utype == HTTPS_URL_T) {
1579 switch (connectmethod(fin, url, penv, &oui, &ui,
1580 &wauth, &pauth, __UNVOLATILE(&auth), &hasleading,
1581 &rval)) {
1582 case C_CLEANUP:
1583 goto cleanup_fetch_url;
1584 case C_IMPROPER:
1585 goto improper;
1586 case C_OK:
1587 break;
1588 default:
1589 abort();
1590 }
1591 }
1592 #endif
1593
1594 hasleading = print_get(fin, hasleading, isproxy, &oui, &ui);
1595
1596 if (flushcache)
1597 print_cache(fin, isproxy);
1598
1599 print_agent(fin);
1600 hasleading = print_proxy(fin, hasleading, wauth.auth,
1601 auth ? NULL : pauth.auth);
1602 if (hasleading) {
1603 hasleading = 0;
1604 if (verbose)
1605 fputs(")\n", ttyout);
1606 }
1607
1608 fetch_printf(fin, "\r\n");
1609 if (fetch_flush(fin) == EOF) {
1610 warn("Writing HTTP request");
1611 alarmtimer(0);
1612 goto cleanup_fetch_url;
1613 }
1614 alarmtimer(0);
1615
1616 switch (negotiate_connection(fin, url, penv, &pi,
1617 &mtime, &wauth, &pauth, &rval, &ischunked,
1618 __UNVOLATILE(&auth), &ui)) {
1619 case C_OK:
1620 break;
1621 case C_CLEANUP:
1622 goto cleanup_fetch_url;
1623 case C_IMPROPER:
1624 goto improper;
1625 default:
1626 abort();
1627 }
1628 }
1629
1630 /* Open the output file. */
1631
1632 /*
1633 * Only trust filenames with special meaning if they came from
1634 * the command line
1635 */
1636 if (outfile == savefile) {
1637 if (strcmp(savefile, "-") == 0) {
1638 fout = stdout;
1639 } else if (*savefile == '|') {
1640 oldpipe = xsignal(SIGPIPE, SIG_IGN);
1641 fout = popen(savefile + 1, "w");
1642 if (fout == NULL) {
1643 warn("Can't execute `%s'", savefile + 1);
1644 goto cleanup_fetch_url;
1645 }
1646 closefunc = pclose;
1647 }
1648 }
1649 if (fout == NULL) {
1650 if ((pi.rangeend != -1 && pi.rangeend <= restart_point) ||
1651 (pi.rangestart == -1 &&
1652 filesize != -1 && filesize <= restart_point)) {
1653 /* already done */
1654 if (verbose)
1655 fprintf(ttyout, "already done\n");
1656 rval = 0;
1657 goto cleanup_fetch_url;
1658 }
1659 if (restart_point && pi.rangestart != -1) {
1660 if (pi.entitylen != -1)
1661 filesize = pi.entitylen;
1662 if (pi.rangestart != restart_point) {
1663 warnx(
1664 "Size of `%s' differs from save file `%s'",
1665 url, savefile);
1666 goto cleanup_fetch_url;
1667 }
1668 fout = fopen(savefile, "a");
1669 } else
1670 fout = fopen(savefile, "w");
1671 if (fout == NULL) {
1672 warn("Can't open `%s'", savefile);
1673 goto cleanup_fetch_url;
1674 }
1675 closefunc = fclose;
1676 }
1677
1678 /* Trap signals */
1679 oldquit = xsignal(SIGQUIT, psummary);
1680 oldint = xsignal(SIGINT, aborthttp);
1681
1682 assert(rcvbuf_size > 0);
1683 if ((size_t)rcvbuf_size > bufsize) {
1684 if (xferbuf)
1685 (void)free(xferbuf);
1686 bufsize = rcvbuf_size;
1687 xferbuf = ftp_malloc(bufsize);
1688 }
1689
1690 bytes = 0;
1691 hashbytes = mark;
1692 if (oldalrm != SIG_ERR) {
1693 (void)xsignal(SIGALRM, oldalrm);
1694 oldalrm = SIG_ERR;
1695 }
1696 progressmeter(-1);
1697
1698 /* Finally, suck down the file. */
1699 do {
1700 long chunksize;
1701 short lastchunk;
1702
1703 chunksize = 0;
1704 lastchunk = 0;
1705 /* read chunk-size */
1706 if (ischunked) {
1707 if (fetch_getln(xferbuf, bufsize, fin) == NULL) {
1708 warnx("Unexpected EOF reading chunk-size");
1709 goto cleanup_fetch_url;
1710 }
1711 errno = 0;
1712 chunksize = strtol(xferbuf, &ep, 16);
1713 if (ep == xferbuf) {
1714 warnx("Invalid chunk-size");
1715 goto cleanup_fetch_url;
1716 }
1717 if (errno == ERANGE || chunksize < 0) {
1718 errno = ERANGE;
1719 warn("Chunk-size `%.*s'",
1720 (int)(ep-xferbuf), xferbuf);
1721 goto cleanup_fetch_url;
1722 }
1723
1724 /*
1725 * XXX: Work around bug in Apache 1.3.9 and
1726 * 1.3.11, which incorrectly put trailing
1727 * space after the chunk-size.
1728 */
1729 while (*ep == ' ')
1730 ep++;
1731
1732 /* skip [ chunk-ext ] */
1733 if (*ep == ';') {
1734 while (*ep && *ep != '\r')
1735 ep++;
1736 }
1737
1738 if (strcmp(ep, "\r\n") != 0) {
1739 warnx("Unexpected data following chunk-size");
1740 goto cleanup_fetch_url;
1741 }
1742 DPRINTF("%s: got chunk-size of " LLF "\n", __func__,
1743 (LLT)chunksize);
1744 if (chunksize == 0) {
1745 lastchunk = 1;
1746 goto chunkdone;
1747 }
1748 }
1749 /* transfer file or chunk */
1750 while (1) {
1751 struct timeval then, now, td;
1752 volatile off_t bufrem;
1753
1754 if (rate_get)
1755 (void)gettimeofday(&then, NULL);
1756 bufrem = rate_get ? rate_get : (off_t)bufsize;
1757 if (ischunked)
1758 bufrem = MIN(chunksize, bufrem);
1759 while (bufrem > 0) {
1760 size_t nr = MIN((off_t)bufsize, bufrem);
1761 flen = fetch_read(xferbuf, sizeof(char),
1762 nr, fin);
1763 if (flen == 0) {
1764 if (fetch_error(fin))
1765 goto chunkerror;
1766 goto chunkdone;
1767 }
1768 bytes += flen;
1769 bufrem -= flen;
1770 if (maxwrite(xferbuf, sizeof(char), flen, fout)
1771 != flen) {
1772 warn("Writing `%s'", savefile);
1773 goto cleanup_fetch_url;
1774 }
1775 if (hash && !progress) {
1776 while (bytes >= hashbytes) {
1777 (void)putc('#', ttyout);
1778 hashbytes += mark;
1779 }
1780 (void)fflush(ttyout);
1781 }
1782 if (ischunked) {
1783 chunksize -= flen;
1784 if (chunksize <= 0)
1785 break;
1786 }
1787 }
1788 if (rate_get) {
1789 while (1) {
1790 (void)gettimeofday(&now, NULL);
1791 timersub(&now, &then, &td);
1792 if (td.tv_sec > 0)
1793 break;
1794 usleep(1000000 - td.tv_usec);
1795 }
1796 }
1797 if (ischunked && chunksize <= 0)
1798 break;
1799 }
1800 /* read CRLF after chunk*/
1801 chunkdone:
1802 if (ischunked) {
1803 if (fetch_getln(xferbuf, bufsize, fin) == NULL) {
1804 alarmtimer(0);
1805 warnx("Unexpected EOF reading chunk CRLF");
1806 goto cleanup_fetch_url;
1807 }
1808 if (strcmp(xferbuf, "\r\n") != 0) {
1809 warnx("Unexpected data following chunk");
1810 goto cleanup_fetch_url;
1811 }
1812 if (lastchunk)
1813 break;
1814 }
1815 } while (ischunked);
1816
1817 /* XXX: deal with optional trailer & CRLF here? */
1818 chunkerror:
1819 if (hash && !progress && bytes > 0) {
1820 if (bytes < mark)
1821 (void)putc('#', ttyout);
1822 (void)putc('\n', ttyout);
1823 }
1824 if (fetch_error(fin)) {
1825 warn("Reading file");
1826 goto cleanup_fetch_url;
1827 }
1828 progressmeter(1);
1829 (void)fflush(fout);
1830 if (closefunc == fclose && mtime != -1) {
1831 struct timeval tval[2];
1832
1833 (void)gettimeofday(&tval[0], NULL);
1834 tval[1].tv_sec = mtime;
1835 tval[1].tv_usec = 0;
1836 (*closefunc)(fout);
1837 fout = NULL;
1838
1839 if (utimes(savefile, tval) == -1) {
1840 fprintf(ttyout,
1841 "Can't change modification time to %s",
1842 rfc2822time(localtime(&mtime)));
1843 }
1844 }
1845 if (bytes > 0)
1846 ptransfer(0);
1847 bytes = 0;
1848
1849 rval = 0;
1850 goto cleanup_fetch_url;
1851
1852 improper:
1853 warnx("Improper response from `%s:%s'", ui.host, ui.port);
1854
1855 cleanup_fetch_url:
1856 if (oldint != SIG_ERR)
1857 (void)xsignal(SIGINT, oldint);
1858 if (oldpipe != SIG_ERR)
1859 (void)xsignal(SIGPIPE, oldpipe);
1860 if (oldalrm != SIG_ERR)
1861 (void)xsignal(SIGALRM, oldalrm);
1862 if (oldquit != SIG_ERR)
1863 (void)xsignal(SIGQUIT, oldquit);
1864 if (fin != NULL)
1865 fetch_close(fin);
1866 else if (s != -1)
1867 close(s);
1868 if (closefunc != NULL && fout != NULL)
1869 (*closefunc)(fout);
1870 if (savefile != outfile)
1871 FREEPTR(savefile);
1872 freeurlinfo(&ui);
1873 freeurlinfo(&oui);
1874 freeauthinfo(&wauth);
1875 freeauthinfo(&pauth);
1876 FREEPTR(decodedpath);
1877 FREEPTR(auth);
1878 FREEPTR(location);
1879 FREEPTR(message);
1880 return (rval);
1881 }
1882
1883 /*
1884 * Abort a HTTP retrieval
1885 */
1886 static void
1887 aborthttp(int notused)
1888 {
1889 char msgbuf[100];
1890 int len;
1891
1892 sigint_raised = 1;
1893 alarmtimer(0);
1894 if (fromatty) {
1895 len = snprintf(msgbuf, sizeof(msgbuf),
1896 "\n%s: HTTP fetch aborted.\n", getprogname());
1897 if (len > 0)
1898 write(fileno(ttyout), msgbuf, len);
1899 }
1900 siglongjmp(httpabort, 1);
1901 }
1902
1903 static void
1904 timeouthttp(int notused)
1905 {
1906 char msgbuf[100];
1907 int len;
1908
1909 alarmtimer(0);
1910 if (fromatty) {
1911 len = snprintf(msgbuf, sizeof(msgbuf),
1912 "\n%s: HTTP fetch timeout.\n", getprogname());
1913 if (len > 0)
1914 write(fileno(ttyout), msgbuf, len);
1915 }
1916 siglongjmp(httpabort, 1);
1917 }
1918
1919 /*
1920 * Retrieve ftp URL or classic ftp argument using FTP.
1921 * Returns 1 on failure, 0 on completed xfer, -1 if ftp connection
1922 * is still open (e.g, ftp xfer with trailing /)
1923 */
1924 static int
1925 fetch_ftp(const char *url)
1926 {
1927 char *cp, *xargv[5], rempath[MAXPATHLEN];
1928 char *dir, *file;
1929 char cmdbuf[MAXPATHLEN];
1930 char dirbuf[4];
1931 int dirhasglob, filehasglob, rval, transtype, xargc;
1932 int oanonftp, oautologin;
1933 struct authinfo auth;
1934 struct urlinfo ui;
1935
1936 DPRINTF("%s: `%s'\n", __func__, url);
1937 dir = file = NULL;
1938 rval = 1;
1939 transtype = TYPE_I;
1940
1941 initurlinfo(&ui);
1942 initauthinfo(&auth, NULL);
1943
1944 if (STRNEQUAL(url, FTP_URL)) {
1945 if ((parse_url(url, "URL", &ui, &auth, NULL) == -1) ||
1946 (auth.user != NULL && *auth.user == '\0') ||
1947 EMPTYSTRING(ui.host)) {
1948 warnx("Invalid URL `%s'", url);
1949 goto cleanup_fetch_ftp;
1950 }
1951 /*
1952 * Note: Don't url_decode(path) here. We need to keep the
1953 * distinction between "/" and "%2F" until later.
1954 */
1955
1956 /* check for trailing ';type=[aid]' */
1957 if (! EMPTYSTRING(ui.path)
1958 && (cp = strrchr(ui.path, ';')) != NULL) {
1959 if (strcasecmp(cp, ";type=a") == 0)
1960 transtype = TYPE_A;
1961 else if (strcasecmp(cp, ";type=i") == 0)
1962 transtype = TYPE_I;
1963 else if (strcasecmp(cp, ";type=d") == 0) {
1964 warnx(
1965 "Directory listing via a URL is not supported");
1966 goto cleanup_fetch_ftp;
1967 } else {
1968 warnx("Invalid suffix `%s' in URL `%s'", cp,
1969 url);
1970 goto cleanup_fetch_ftp;
1971 }
1972 *cp = 0;
1973 }
1974 } else { /* classic style `[user@]host:[file]' */
1975 ui.utype = CLASSIC_URL_T;
1976 ui.host = ftp_strdup(url);
1977 cp = strchr(ui.host, '@');
1978 if (cp != NULL) {
1979 *cp = '\0';
1980 auth.user = ui.host;
1981 anonftp = 0; /* disable anonftp */
1982 ui.host = ftp_strdup(cp + 1);
1983 }
1984 cp = strchr(ui.host, ':');
1985 if (cp != NULL) {
1986 *cp = '\0';
1987 ui.path = ftp_strdup(cp + 1);
1988 }
1989 }
1990 if (EMPTYSTRING(ui.host))
1991 goto cleanup_fetch_ftp;
1992
1993 /* Extract the file and (if present) directory name. */
1994 dir = ui.path;
1995 if (! EMPTYSTRING(dir)) {
1996 /*
1997 * If we are dealing with classic `[user@]host:[path]' syntax,
1998 * then a path of the form `/file' (resulting from input of the
1999 * form `host:/file') means that we should do "CWD /" before
2000 * retrieving the file. So we set dir="/" and file="file".
2001 *
2002 * But if we are dealing with URLs like `ftp://host/path' then
2003 * a path of the form `/file' (resulting from a URL of the form
2004 * `ftp://host//file') means that we should do `CWD ' (with an
2005 * empty argument) before retrieving the file. So we set
2006 * dir="" and file="file".
2007 *
2008 * If the path does not contain / at all, we set dir=NULL.
2009 * (We get a path without any slashes if we are dealing with
2010 * classic `[user@]host:[file]' or URL `ftp://host/file'.)
2011 *
2012 * In all other cases, we set dir to a string that does not
2013 * include the final '/' that separates the dir part from the
2014 * file part of the path. (This will be the empty string if
2015 * and only if we are dealing with a path of the form `/file'
2016 * resulting from an URL of the form `ftp://host//file'.)
2017 */
2018 cp = strrchr(dir, '/');
2019 if (cp == dir && ui.utype == CLASSIC_URL_T) {
2020 file = cp + 1;
2021 (void)strlcpy(dirbuf, "/", sizeof(dirbuf));
2022 dir = dirbuf;
2023 } else if (cp != NULL) {
2024 *cp++ = '\0';
2025 file = cp;
2026 } else {
2027 file = dir;
2028 dir = NULL;
2029 }
2030 } else
2031 dir = NULL;
2032 if (ui.utype == FTP_URL_T && file != NULL) {
2033 url_decode(file);
2034 /* but still don't url_decode(dir) */
2035 }
2036 DPRINTF("%s: user `%s' pass `%s' host %s port %s "
2037 "path `%s' dir `%s' file `%s'\n", __func__,
2038 STRorNULL(auth.user), STRorNULL(auth.pass),
2039 STRorNULL(ui.host), STRorNULL(ui.port),
2040 STRorNULL(ui.path), STRorNULL(dir), STRorNULL(file));
2041
2042 dirhasglob = filehasglob = 0;
2043 if (doglob &&
2044 (ui.utype == CLASSIC_URL_T || ui.utype == FTP_URL_T)) {
2045 if (! EMPTYSTRING(dir) && strpbrk(dir, "*?[]{}") != NULL)
2046 dirhasglob = 1;
2047 if (! EMPTYSTRING(file) && strpbrk(file, "*?[]{}") != NULL)
2048 filehasglob = 1;
2049 }
2050
2051 /* Set up the connection */
2052 oanonftp = anonftp;
2053 if (connected)
2054 disconnect(0, NULL);
2055 anonftp = oanonftp;
2056 (void)strlcpy(cmdbuf, getprogname(), sizeof(cmdbuf));
2057 xargv[0] = cmdbuf;
2058 xargv[1] = ui.host;
2059 xargv[2] = NULL;
2060 xargc = 2;
2061 if (ui.port) {
2062 xargv[2] = ui.port;
2063 xargv[3] = NULL;
2064 xargc = 3;
2065 }
2066 oautologin = autologin;
2067 /* don't autologin in setpeer(), use ftp_login() below */
2068 autologin = 0;
2069 setpeer(xargc, xargv);
2070 autologin = oautologin;
2071 if ((connected == 0) ||
2072 (connected == 1 && !ftp_login(ui.host, auth.user, auth.pass))) {
2073 warnx("Can't connect or login to host `%s:%s'",
2074 ui.host, ui.port ? ui.port : "?");
2075 goto cleanup_fetch_ftp;
2076 }
2077
2078 switch (transtype) {
2079 case TYPE_A:
2080 setascii(1, xargv);
2081 break;
2082 case TYPE_I:
2083 setbinary(1, xargv);
2084 break;
2085 default:
2086 errx(1, "%s: unknown transfer type %d", __func__, transtype);
2087 }
2088
2089 /*
2090 * Change directories, if necessary.
2091 *
2092 * Note: don't use EMPTYSTRING(dir) below, because
2093 * dir=="" means something different from dir==NULL.
2094 */
2095 if (dir != NULL && !dirhasglob) {
2096 char *nextpart;
2097
2098 /*
2099 * If we are dealing with a classic `[user@]host:[path]'
2100 * (urltype is CLASSIC_URL_T) then we have a raw directory
2101 * name (not encoded in any way) and we can change
2102 * directories in one step.
2103 *
2104 * If we are dealing with an `ftp://host/path' URL
2105 * (urltype is FTP_URL_T), then RFC 3986 says we need to
2106 * send a separate CWD command for each unescaped "/"
2107 * in the path, and we have to interpret %hex escaping
2108 * *after* we find the slashes. It's possible to get
2109 * empty components here, (from multiple adjacent
2110 * slashes in the path) and RFC 3986 says that we should
2111 * still do `CWD ' (with a null argument) in such cases.
2112 *
2113 * Many ftp servers don't support `CWD ', so if there's an
2114 * error performing that command, bail out with a descriptive
2115 * message.
2116 *
2117 * Examples:
2118 *
2119 * host: dir="", urltype=CLASSIC_URL_T
2120 * logged in (to default directory)
2121 * host:file dir=NULL, urltype=CLASSIC_URL_T
2122 * "RETR file"
2123 * host:dir/ dir="dir", urltype=CLASSIC_URL_T
2124 * "CWD dir", logged in
2125 * ftp://host/ dir="", urltype=FTP_URL_T
2126 * logged in (to default directory)
2127 * ftp://host/dir/ dir="dir", urltype=FTP_URL_T
2128 * "CWD dir", logged in
2129 * ftp://host/file dir=NULL, urltype=FTP_URL_T
2130 * "RETR file"
2131 * ftp://host//file dir="", urltype=FTP_URL_T
2132 * "CWD ", "RETR file"
2133 * host:/file dir="/", urltype=CLASSIC_URL_T
2134 * "CWD /", "RETR file"
2135 * ftp://host///file dir="/", urltype=FTP_URL_T
2136 * "CWD ", "CWD ", "RETR file"
2137 * ftp://host/%2F/file dir="%2F", urltype=FTP_URL_T
2138 * "CWD /", "RETR file"
2139 * ftp://host/foo/file dir="foo", urltype=FTP_URL_T
2140 * "CWD foo", "RETR file"
2141 * ftp://host/foo/bar/file dir="foo/bar"
2142 * "CWD foo", "CWD bar", "RETR file"
2143 * ftp://host//foo/bar/file dir="/foo/bar"
2144 * "CWD ", "CWD foo", "CWD bar", "RETR file"
2145 * ftp://host/foo//bar/file dir="foo//bar"
2146 * "CWD foo", "CWD ", "CWD bar", "RETR file"
2147 * ftp://host/%2F/foo/bar/file dir="%2F/foo/bar"
2148 * "CWD /", "CWD foo", "CWD bar", "RETR file"
2149 * ftp://host/%2Ffoo/bar/file dir="%2Ffoo/bar"
2150 * "CWD /foo", "CWD bar", "RETR file"
2151 * ftp://host/%2Ffoo%2Fbar/file dir="%2Ffoo%2Fbar"
2152 * "CWD /foo/bar", "RETR file"
2153 * ftp://host/%2Ffoo%2Fbar%2Ffile dir=NULL
2154 * "RETR /foo/bar/file"
2155 *
2156 * Note that we don't need `dir' after this point.
2157 */
2158 do {
2159 if (ui.utype == FTP_URL_T) {
2160 nextpart = strchr(dir, '/');
2161 if (nextpart) {
2162 *nextpart = '\0';
2163 nextpart++;
2164 }
2165 url_decode(dir);
2166 } else
2167 nextpart = NULL;
2168 DPRINTF("%s: dir `%s', nextpart `%s'\n", __func__,
2169 STRorNULL(dir), STRorNULL(nextpart));
2170 if (ui.utype == FTP_URL_T || *dir != '\0') {
2171 (void)strlcpy(cmdbuf, "cd", sizeof(cmdbuf));
2172 xargv[0] = cmdbuf;
2173 xargv[1] = dir;
2174 xargv[2] = NULL;
2175 dirchange = 0;
2176 cd(2, xargv);
2177 if (! dirchange) {
2178 if (*dir == '\0' && code == 500)
2179 fprintf(stderr,
2180 "\n"
2181 "ftp: The `CWD ' command (without a directory), which is required by\n"
2182 " RFC 3986 to support the empty directory in the URL pathname (`//'),\n"
2183 " conflicts with the server's conformance to RFC 959.\n"
2184 " Try the same URL without the `//' in the URL pathname.\n"
2185 "\n");
2186 goto cleanup_fetch_ftp;
2187 }
2188 }
2189 dir = nextpart;
2190 } while (dir != NULL);
2191 }
2192
2193 if (EMPTYSTRING(file)) {
2194 rval = -1;
2195 goto cleanup_fetch_ftp;
2196 }
2197
2198 if (dirhasglob) {
2199 (void)strlcpy(rempath, dir, sizeof(rempath));
2200 (void)strlcat(rempath, "/", sizeof(rempath));
2201 (void)strlcat(rempath, file, sizeof(rempath));
2202 file = rempath;
2203 }
2204
2205 /* Fetch the file(s). */
2206 xargc = 2;
2207 (void)strlcpy(cmdbuf, "get", sizeof(cmdbuf));
2208 xargv[0] = cmdbuf;
2209 xargv[1] = file;
2210 xargv[2] = NULL;
2211 if (dirhasglob || filehasglob) {
2212 int ointeractive;
2213
2214 ointeractive = interactive;
2215 interactive = 0;
2216 if (restartautofetch)
2217 (void)strlcpy(cmdbuf, "mreget", sizeof(cmdbuf));
2218 else
2219 (void)strlcpy(cmdbuf, "mget", sizeof(cmdbuf));
2220 xargv[0] = cmdbuf;
2221 mget(xargc, xargv);
2222 interactive = ointeractive;
2223 } else {
2224 char *destfile = outfile;
2225 if (destfile == NULL) {
2226 cp = strrchr(file, '/'); /* find savefile */
2227 if (cp != NULL)
2228 destfile = cp + 1;
2229 else
2230 destfile = file;
2231 }
2232 xargv[2] = (char *)destfile;
2233 xargv[3] = NULL;
2234 xargc++;
2235 if (restartautofetch)
2236 reget(xargc, xargv);
2237 else
2238 get(xargc, xargv);
2239 }
2240
2241 if ((code / 100) == COMPLETE)
2242 rval = 0;
2243
2244 cleanup_fetch_ftp:
2245 freeurlinfo(&ui);
2246 freeauthinfo(&auth);
2247 return (rval);
2248 }
2249
2250 /*
2251 * Retrieve the given file to outfile.
2252 * Supports arguments of the form:
2253 * "host:path", "ftp://host/path" if $ftpproxy, call fetch_url() else
2254 * call fetch_ftp()
2255 * "http://host/path" call fetch_url() to use HTTP
2256 * "file:///path" call fetch_url() to copy
2257 * "about:..." print a message
2258 *
2259 * Returns 1 on failure, 0 on completed xfer, -1 if ftp connection
2260 * is still open (e.g, ftp xfer with trailing /)
2261 */
2262 static int
2263 go_fetch(const char *url, struct urlinfo *rui)
2264 {
2265 char *proxyenv;
2266 char *p;
2267
2268 #ifndef NO_ABOUT
2269 /*
2270 * Check for about:*
2271 */
2272 if (STRNEQUAL(url, ABOUT_URL)) {
2273 url += sizeof(ABOUT_URL) -1;
2274 if (strcasecmp(url, "ftp") == 0 ||
2275 strcasecmp(url, "tnftp") == 0) {
2276 fputs(
2277 "This version of ftp has been enhanced by Luke Mewburn <lukem (at) NetBSD.org>\n"
2278 "for the NetBSD project. Execute `man ftp' for more details.\n", ttyout);
2279 } else if (strcasecmp(url, "lukem") == 0) {
2280 fputs(
2281 "Luke Mewburn is the author of most of the enhancements in this ftp client.\n"
2282 "Please email feedback to <lukem (at) NetBSD.org>.\n", ttyout);
2283 } else if (strcasecmp(url, "netbsd") == 0) {
2284 fputs(
2285 "NetBSD is a freely available and redistributable UNIX-like operating system.\n"
2286 "For more information, see http://www.NetBSD.org/\n", ttyout);
2287 } else if (strcasecmp(url, "version") == 0) {
2288 fprintf(ttyout, "Version: %s %s%s\n",
2289 FTP_PRODUCT, FTP_VERSION,
2290 #ifdef INET6
2291 ""
2292 #else
2293 " (-IPv6)"
2294 #endif
2295 );
2296 } else {
2297 fprintf(ttyout, "`%s' is an interesting topic.\n", url);
2298 }
2299 fputs("\n", ttyout);
2300 return (0);
2301 }
2302 #endif
2303
2304 /*
2305 * Check for file:// and http:// URLs.
2306 */
2307 if (STRNEQUAL(url, HTTP_URL)
2308 #ifdef WITH_SSL
2309 || STRNEQUAL(url, HTTPS_URL)
2310 #endif
2311 || STRNEQUAL(url, FILE_URL))
2312 return (fetch_url(url, NULL, NULL, NULL, rui));
2313
2314 /*
2315 * If it contains "://" but does not begin with ftp://
2316 * or something that was already handled, then it's
2317 * unsupported.
2318 *
2319 * If it contains ":" but not "://" then we assume the
2320 * part before the colon is a host name, not an URL scheme,
2321 * so we don't try to match that here.
2322 */
2323 if ((p = strstr(url, "://")) != NULL && ! STRNEQUAL(url, FTP_URL))
2324 errx(1, "Unsupported URL scheme `%.*s'", (int)(p - url), url);
2325
2326 /*
2327 * Refer to previous urlinfo if provided. This makes relative
2328 * redirects work.
2329 */
2330 if (use_relative(rui))
2331 return fetch_url(url, NULL, NULL, NULL, rui);
2332
2333 /*
2334 * Try FTP URL-style and host:file arguments next.
2335 * If ftpproxy is set with an FTP URL, use fetch_url()
2336 * Otherwise, use fetch_ftp().
2337 */
2338 proxyenv = getoptionvalue("ftp_proxy");
2339 if (!EMPTYSTRING(proxyenv) && STRNEQUAL(url, FTP_URL))
2340 return (fetch_url(url, NULL, NULL, NULL, rui));
2341
2342 return (fetch_ftp(url));
2343 }
2344
2345 /*
2346 * Retrieve multiple files from the command line,
2347 * calling go_fetch() for each file.
2348 *
2349 * If an ftp path has a trailing "/", the path will be cd-ed into and
2350 * the connection remains open, and the function will return -1
2351 * (to indicate the connection is alive).
2352 * If an error occurs the return value will be the offset+1 in
2353 * argv[] of the file that caused a problem (i.e, argv[x]
2354 * returns x+1)
2355 * Otherwise, 0 is returned if all files retrieved successfully.
2356 */
2357 int
2358 auto_fetch(int argc, char *argv[])
2359 {
2360 volatile int argpos, rval;
2361
2362 argpos = rval = 0;
2363
2364 if (sigsetjmp(toplevel, 1)) {
2365 if (connected)
2366 disconnect(0, NULL);
2367 if (rval > 0)
2368 rval = argpos + 1;
2369 return (rval);
2370 }
2371 (void)xsignal(SIGINT, intr);
2372 (void)xsignal(SIGPIPE, lostpeer);
2373
2374 /*
2375 * Loop through as long as there's files to fetch.
2376 */
2377 for (; (rval == 0) && (argpos < argc); argpos++) {
2378 if (strchr(argv[argpos], ':') == NULL)
2379 break;
2380 redirect_loop = 0;
2381 if (!anonftp)
2382 anonftp = 2; /* Handle "automatic" transfers. */
2383 rval = go_fetch(argv[argpos], NULL);
2384 if (outfile != NULL && strcmp(outfile, "-") != 0
2385 && outfile[0] != '|') {
2386 FREEPTR(outfile);
2387 }
2388 if (rval > 0)
2389 rval = argpos + 1;
2390 }
2391
2392 if (connected && rval != -1)
2393 disconnect(0, NULL);
2394 return (rval);
2395 }
2396
2397
2398 /*
2399 * Upload multiple files from the command line.
2400 *
2401 * If an error occurs the return value will be the offset+1 in
2402 * argv[] of the file that caused a problem (i.e, argv[x]
2403 * returns x+1)
2404 * Otherwise, 0 is returned if all files uploaded successfully.
2405 */
2406 int
2407 auto_put(int argc, char **argv, const char *uploadserver)
2408 {
2409 char *uargv[4], *path, *pathsep;
2410 int uargc, rval, argpos;
2411 size_t len;
2412 char cmdbuf[MAX_C_NAME];
2413
2414 (void)strlcpy(cmdbuf, "mput", sizeof(cmdbuf));
2415 uargv[0] = cmdbuf;
2416 uargv[1] = argv[0];
2417 uargc = 2;
2418 uargv[2] = uargv[3] = NULL;
2419 pathsep = NULL;
2420 rval = 1;
2421
2422 DPRINTF("%s: target `%s'\n", __func__, uploadserver);
2423
2424 path = ftp_strdup(uploadserver);
2425 len = strlen(path);
2426 if (path[len - 1] != '/' && path[len - 1] != ':') {
2427 /*
2428 * make sure we always pass a directory to auto_fetch
2429 */
2430 if (argc > 1) { /* more than one file to upload */
2431 len = strlen(uploadserver) + 2; /* path + "/" + "\0" */
2432 free(path);
2433 path = (char *)ftp_malloc(len);
2434 (void)strlcpy(path, uploadserver, len);
2435 (void)strlcat(path, "/", len);
2436 } else { /* single file to upload */
2437 (void)strlcpy(cmdbuf, "put", sizeof(cmdbuf));
2438 uargv[0] = cmdbuf;
2439 pathsep = strrchr(path, '/');
2440 if (pathsep == NULL) {
2441 pathsep = strrchr(path, ':');
2442 if (pathsep == NULL) {
2443 warnx("Invalid URL `%s'", path);
2444 goto cleanup_auto_put;
2445 }
2446 pathsep++;
2447 uargv[2] = ftp_strdup(pathsep);
2448 pathsep[0] = '/';
2449 } else
2450 uargv[2] = ftp_strdup(pathsep + 1);
2451 pathsep[1] = '\0';
2452 uargc++;
2453 }
2454 }
2455 DPRINTF("%s: URL `%s' argv[2] `%s'\n", __func__,
2456 path, STRorNULL(uargv[2]));
2457
2458 /* connect and cwd */
2459 rval = auto_fetch(1, &path);
2460 if(rval >= 0)
2461 goto cleanup_auto_put;
2462
2463 rval = 0;
2464
2465 /* target filename provided; upload 1 file */
2466 /* XXX : is this the best way? */
2467 if (uargc == 3) {
2468 uargv[1] = argv[0];
2469 put(uargc, uargv);
2470 if ((code / 100) != COMPLETE)
2471 rval = 1;
2472 } else { /* otherwise a target dir: upload all files to it */
2473 for(argpos = 0; argv[argpos] != NULL; argpos++) {
2474 uargv[1] = argv[argpos];
2475 mput(uargc, uargv);
2476 if ((code / 100) != COMPLETE) {
2477 rval = argpos + 1;
2478 break;
2479 }
2480 }
2481 }
2482
2483 cleanup_auto_put:
2484 free(path);
2485 FREEPTR(uargv[2]);
2486 return (rval);
2487 }
2488