Repository navigation
Expand file tree
/
Copy pathfetch.c
More file actions
1999 lines (1848 loc) · 49.8 KB
/
Copy pathfetch.c
File metadata and controls
1999 lines (1848 loc) · 49.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* $NetBSD: fetch.c,v 1.205 2013/11/07 02:06:51 christos Exp $ */
/*-
* Copyright (c) 1997-2009 The NetBSD Foundation, Inc.
* All rights reserved.
*
* This code is derived from software contributed to The NetBSD Foundation
* by Luke Mewburn.
*
* This code is derived from software contributed to The NetBSD Foundation
* by Scott Aaron Bamford.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
* ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include <sys/cdefs.h>
#ifndef lint
__RCSID("$NetBSD: fetch.c,v 1.205 2013/11/07 02:06:51 christos Exp $");
#endif /* not lint */
/*
* FTP User Program -- Command line file retrieval
*/
#include <sys/types.h>
#include <sys/param.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <sys/time.h>
#include <netinet/in.h>
#include <arpa/ftp.h>
#include <arpa/inet.h>
#include <assert.h>
#include <ctype.h>
#include <err.h>
#include <errno.h>
#include <netdb.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <time.h>
#include "ssl.h"
#include "ftp_var.h"
#include "version.h"
typedef enum {
UNKNOWN_URL_T=-1,
HTTP_URL_T,
#ifdef WITH_SSL
HTTPS_URL_T,
#endif
FTP_URL_T,
FILE_URL_T,
CLASSIC_URL_T
} url_t;
__dead static void aborthttp(int);
__dead static void timeouthttp(int);
#ifndef NO_AUTH
static int auth_url(const char *, char **, const char *, const char *);
static void base64_encode(const unsigned char *, size_t, unsigned char *);
#endif
static int go_fetch(const char *);
static int fetch_ftp(const char *);
static int fetch_url(const char *, const char *, char *, char *);
static const char *match_token(const char **, const char *);
static int parse_url(const char *, const char *, url_t *, char **,
char **, char **, char **, in_port_t *, char **);
static void url_decode(char *);
static int redirect_loop;
#define STRNEQUAL(a,b) (strncasecmp((a), (b), sizeof((b))-1) == 0)
#define ISLWS(x) ((x)=='\r' || (x)=='\n' || (x)==' ' || (x)=='\t')
#define SKIPLWS(x) do { while (ISLWS((*x))) x++; } while (0)
#define ABOUT_URL "about:" /* propaganda */
#define FILE_URL "file://" /* file URL prefix */
#define FTP_URL "ftp://" /* ftp URL prefix */
#define HTTP_URL "http://" /* http URL prefix */
#ifdef WITH_SSL
#define HTTPS_URL "https://" /* https URL prefix */
#define IS_HTTP_TYPE(urltype) \
(((urltype) == HTTP_URL_T) || ((urltype) == HTTPS_URL_T))
#else
#define IS_HTTP_TYPE(urltype) \
((urltype) == HTTP_URL_T)
#endif
/*
* Determine if token is the next word in buf (case insensitive).
* If so, advance buf past the token and any traili
F438
ng LWS, and
* return a pointer to the token (in buf). Otherwise, return NULL.
* token may be preceded by LWS.
* token must be followed by LWS or NUL. (I.e, don't partial match).
*/
static const char *
match_token(const char **buf, const char *token)
{
const char *p, *orig;
size_t tlen;
tlen = strlen(token);
p = *buf;
SKIPLWS(p);
orig = p;
if (strncasecmp(p, token, tlen) != 0)
return NULL;
p += tlen;
if (*p != '\0' && !ISLWS(*p))
return NULL;
SKIPLWS(p);
orig = *buf;
*buf = p;
return orig;
}
#ifndef NO_AUTH
/*
* Generate authorization response based on given authentication challenge.
* Returns -1 if an error occurred, otherwise 0.
* Sets response to a malloc(3)ed string; caller should free.
*/
static int
auth_url(const char *challenge, char **response, const char *guser,
const char *gpass)
{
const char *cp, *scheme, *errormsg;
char *ep, *clear, *realm;
char uuser[BUFSIZ], *gotpass;
const char *upass;
int rval;
size_t len, clen, rlen;
*response = NULL;
clear = realm = NULL;
rval = -1;
cp = challenge;
scheme = "Basic"; /* only support Basic authentication */
gotpass = NULL;
DPRINTF("auth_url: challenge `%s'\n", challenge);
if (! match_token(&cp, scheme)) {
warnx("Unsupported authentication challenge `%s'",
challenge);
goto cleanup_auth_url;
}
#define REALM "realm=\""
if (STRNEQUAL(cp, REALM))
cp += sizeof(REALM) - 1;
else {
warnx("Unsupported authentication challenge `%s'",
challenge);
goto cleanup_auth_url;
}
/* XXX: need to improve quoted-string parsing to support \ quoting, etc. */
if ((ep = strchr(cp, '\"')) != NULL) {
len = ep - cp;
realm = (char *)ftp_malloc(len + 1);
(void)strlcpy(realm, cp, len + 1);
} else {
warnx("Unsupported authentication challenge `%s'",
challenge);
goto cleanup_auth_url;
}
fprintf(ttyout, "Username for `%s': ", realm);
if (guser != NULL) {
(void)strlcpy(uuser, guser, sizeof(uuser));
fprintf(ttyout, "%s\n", uuser);
} else {
(void)fflush(ttyout);
if (get_line(stdin, uuser, sizeof(uuser), &errormsg) < 0) {
warnx("%s; can't authenticate", errormsg);
goto cleanup_auth_url;
}
}
if (gpass != NULL)
upass = gpass;
else {
gotpass = getpass("Password: ");
if (gotpass == NULL) {
warnx("Can't read password");
goto cleanup_auth_url;
}
upass = gotpass;
}
clen = strlen(uuser) + strlen(upass) + 2; /* user + ":" + pass + "\0" */
clear = (char *)ftp_malloc(clen);
(void)strlcpy(clear, uuser, clen);
(void)strlcat(clear, ":", clen);
(void)strlcat(clear, upass, clen);
if (gotpass)
memset(gotpass, 0, strlen(gotpass));
/* scheme + " " + enc + "\0" */
rlen = strlen(scheme) + 1 + (clen + 2) * 4 / 3 + 1;
*response = (char *)ftp_malloc(rlen);
(void)strlcpy(*response, scheme, rlen);
len = strlcat(*response, " ", rlen);
/* use `clen - 1' to not encode the trailing NUL */
base64_encode((unsigned char *)clear, clen - 1,
(unsigned char *)*response + len);
memset(clear, 0, clen);
rval = 0;
cleanup_auth_url:
FREEPTR(clear);
FREEPTR(realm);
return (rval);
}
/*
* Encode len bytes starting at clear using base64 encoding into encoded,
* which should be at least ((len + 2) * 4 / 3 + 1) in size.
*/
static void
base64_encode(const unsigned char *clear, size_t len, unsigned char *encoded)
{
static const unsigned char enc[] =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
unsigned char *cp;
size_t i;
cp = encoded;
for (i = 0; i < len; i += 3) {
*(cp++) = enc[((clear[i + 0] >> 2))];
*(cp++) = enc[((clear[i + 0] << 4) & 0x30)
| ((clear[i + 1] >> 4) & 0x0f)];
*(cp++) = enc[((clear[i + 1] << 2) & 0x3c)
| ((clear[i + 2] >> 6) & 0x03)];
*(cp++) = enc[((clear[i + 2] ) & 0x3f)];
}
*cp = '\0';
while (i-- > len)
*(--cp) = '=';
}
#endif
/*
* Decode %xx escapes in given string, `in-place'.
*/
static void
url_decode(char *url)
{
unsigned char *p, *q;
if (EMPTYSTRING(url))
return;
p = q = (unsigned char *)url;
#define HEXTOINT(x) (x - (isdigit(x) ? '0' : (islower(x) ? 'a' : 'A') - 10))
while (*p) {
if (p[0] == '%'
&& p[1] && isxdigit((unsigned char)p[1])
&& p[2] && isxdigit((unsigned char)p[2])) {
*q++ = HEXTOINT(p[1]) * 16 + HEXTOINT(p[2]);
p+=3;
} else
*q++ = *p++;
}
*q = '\0';
}
/*
* Parse URL of form (per RFC 3986):
* <type>://[<user>[:<password>]@]<host>[:<port>][/<path>]
* Returns -1 if a parse error occurred, otherwise 0.
* It's the caller's responsibility to url_decode() the returned
* user, pass and path.
*
* Sets type to url_t, each of the given char ** pointers to a
* malloc(3)ed strings of the relevant section, and port to
* the number given, or ftpport if ftp://, or httpport if http://.
*
* XXX: this is not totally RFC 3986 compliant; <path> will have the
* leading `/' unless it's an ftp:// URL, as this makes things easier
* for file:// and http:// URLs. ftp:// URLs have the `/' between the
* host and the URL-path removed, but any additional leading slashes
* in the URL-path are retained (because they imply that we should
* later do "CWD" with a null argument).
*
* Examples:
* input URL output path
* --------- -----------
* "http://host" "/"
* "http://host/" "/"
* "http://host/path" "/path"
* "file://host/dir/file" "dir/file"
* "ftp://host" ""
* "ftp://host/" ""
* "ftp://host//" "/"
* "ftp://host/dir/file" "dir/file"
* "ftp://host//dir/file" "/dir/file"
*/
static int
parse_url(const char *url, const char *desc, url_t *utype,
char **uuser, char **pass, char **host, char **port,
in_port_t *portnum, char **path)
{
const char *origurl, *tport;
char *cp, *ep, *thost;
size_t len;
if (url == NULL || desc == NULL || utype == NULL || uuser == NULL
|| pass == NULL || host == NULL || port == NULL || portnum == NULL
|| path == NULL)
errx(1, "parse_url: invoked with NULL argument!");
DPRINTF("parse_url: %s `%s'\n", desc, url);
origurl = url;
*utype = UNKNOWN_URL_T;
*uuser = *pass = *host = *port = *path = NULL;
*portnum = 0;
tport = NULL;
if (STRNEQUAL(url, HTTP_URL)) {
url += sizeof(HTTP_URL) - 1;
*utype = HTTP_URL_T;
*portnum = HTTP_PORT;
tport = httpport;
} else if (STRNEQUAL(url, FTP_URL)) {
url += sizeof(FTP_URL) - 1;
*utype = FTP_URL_T;
*portnum = FTP_PORT;
tport = ftpport;
} else if (STRNEQUAL(url, FILE_URL)) {
url += sizeof(FILE_URL) - 1;
*utype = FILE_URL_T;
#ifdef WITH_SSL
} else if (STRNEQUAL(url, HTTPS_URL)) {
url += sizeof(HTTPS_URL) - 1;
*utype = HTTPS_URL_T;
*portnum = HTTPS_PORT;
tport = httpsport;
#endif
} else {
warnx("Invalid %s `%s'", desc, url);
cleanup_parse_url:
FREEPTR(*uuser);
if (*pass != NULL)
memset(*pass, 0, strlen(*pass));
FREEPTR(*pass);
FREEPTR(*host);
FREEPTR(*port);
FREEPTR(*path);
return (-1);
}
if (*url == '\0')
return (0);
/* find [user[:pass]@]host[:port] */
ep = strchr(url, '/');
if (ep == NULL)
thost = ftp_strdup(url);
else {
len = ep - url;
thost = (char *)ftp_malloc(len + 1);
(void)strlcpy(thost, url, len + 1);
if (*utype == FTP_URL_T) /* skip first / for ftp URLs */
ep++;
*path = ftp_strdup(ep);
}
cp = strchr(thost, '@'); /* look for user[:pass]@ in URLs */
if (cp != NULL) {
if (*utype == FTP_URL_T)
anonftp = 0; /* disable anonftp */
*uuser = thost;
*cp = '\0';
thost = ftp_strdup(cp + 1);
cp = strchr(*uuser, ':');
if (cp != NULL) {
*cp = '\0';
*pass = ftp_strdup(cp + 1);
}
url_decode(*uuser);
if (*pass)
url_decode(*pass);
}
#ifdef INET6
/*
* Check if thost is an encoded IPv6 address, as per
* RFC 3986:
* `[' ipv6-address ']'
*/
if (*thost == '[') {
cp = thost + 1;
if ((ep = strchr(cp, ']')) == NULL ||
(ep[1] != '\0' && ep[1] != ':')) {
warnx("Invalid address `%s' in %s `%s'",
thost, desc, origurl);
goto cleanup_parse_url;
}
len = ep - cp; /* change `[xyz]' -> `xyz' */
memmove(thost, thost + 1, len);
thost[len] = '\0';
if (! isipv6addr(thost)) {
warnx("Invalid IPv6 address `%s' in %s `%s'",
thost, desc, origurl);
goto cleanup_parse_url;
}
cp = ep + 1;
if (*cp == ':')
cp++;
else
cp = NULL;
} else
#endif /* INET6 */
if ((cp = strchr(thost, ':')) != NULL)
*cp++ = '\0';
*host = thost;
/* look for [:port] */
if (cp != NULL) {
unsigned long nport;
nport = strtoul(cp, &ep, 10);
if (*cp == '\0' || *ep != '\0' ||
nport < 1 || nport > MAX_IN_PORT_T) {
warnx("Unknown port `%s' in %s `%s'",
cp, desc, origurl);
goto cleanup_parse_url;
}
*portnum = nport;
tport = cp;
}
if (tport != NULL)
*port = ftp_strdup(tport);
if (*path == NULL) {
const char *emptypath = "/";
if (*utype == FTP_URL_T) /* skip first / for ftp URLs */
emptypath++;
*path = ftp_strdup(emptypath);
}
DPRINTF("parse_url: user `%s' pass `%s' host %s port %s(%d) "
"path `%s'\n",
STRorNULL(*uuser), STRorNULL(*pass),
STRorNULL(*host), STRorNULL(*port),
*portnum ? *portnum : -1, STRorNULL(*path));
return (0);
}
sigjmp_buf httpabort;
/*
* Retrieve URL, via a proxy if necessary, using HTTP.
* If proxyenv is set, use that for the proxy, otherwise try ftp_proxy or
* http_proxy/https_proxy as appropriate.
* Supports HTTP redirects.
* Returns 1 on failure, 0 on completed xfer, -1 if ftp connection
* is still open (e.g, ftp xfer with trailing /)
*/
static int
fetch_url(const char *url, const char *proxyenv, char *proxyauth, char *wwwauth)
{
struct addrinfo hints, *res, *res0 = NULL;
int error;
sigfunc volatile oldint;
sigfunc volatile oldpipe;
sigfunc volatile oldalrm;
sigfunc volatile oldquit;
int volatile s;
struct stat sb;
int volatile ischunked;
int volatile isproxy;
int volatile rval;
int volatile hcode;
int len;
size_t flen;
static size_t bufsize;
static char *xferbuf;
const char *cp, *token;
char *ep;
char buf[FTPBUFLEN];
const char *errormsg;
char *volatile savefile;
char *volatile auth;
char *volatile location;
char *volatile message;
char *uuser, *pass, *host, *port, *path;
char *volatile decodedpath;
char *puser, *ppass, *useragent;
off_t hashbytes, rangestart, rangeend, entitylen;
int (*volatile closefunc)(FILE *);
FETCH *volatile fin;
FILE *volatile fout;
const char *volatile penv = proxyenv;
time_t mtime;
url_t urltype;
in_port_t portnum;
#ifdef WITH_SSL
void *ssl;
#endif
DPRINTF("%s: `%s' proxyenv `%s'\n", __func__, url, STRorNULL(penv));
oldquit = oldalrm = oldint = oldpipe = NULL;
closefunc = NULL;
fin = NULL;
fout = NULL;
s = -1;
savefile = NULL;
auth = location = message = NULL;
ischunked = isproxy = hcode = 0;
rval = 1;
uuser = pass = host = path = decodedpath = puser = ppass = NULL;
if (sigsetjmp(httpabort, 1))
goto cleanup_fetch_url;
if (parse_url(url, "URL", &urltype, &uuser, &pass, &host, &port,
&portnum, &path) == -1)
goto cleanup_fetch_url;
if (urltype == FILE_URL_T && ! EMPTYSTRING(host)
&& strcasecmp(host, "localhost") != 0) {
warnx("No support for non local file URL `%s'", url);
goto cleanup_fetch_url;
}
if (EMPTYSTRING(path)) {
if (urltype == FTP_URL_T) {
rval = fetch_ftp(url);
goto cleanup_fetch_url;
}
if (!IS_HTTP_TYPE(urltype) || outfile == NULL) {
warnx("Invalid URL (no file after host) `%s'", url);
goto cleanup_fetch_url;
}
}
decodedpath = ftp_strdup(path);
url_decode(decodedpath);
if (outfile)
savefile = ftp_strdup(outfile);
else {
cp = strrchr(decodedpath, '/'); /* find savefile */
if (cp != NULL)
savefile = ftp_strdup(cp + 1);
else
savefile = ftp_strdup(decodedpath);
}
DPRINTF("%s: savefile `%s'\n", __func__, savefile);
if (EMPTYSTRING(savefile)) {
if (urltype == FTP_URL_T) {
rval = fetch_ftp(url);
goto cleanup_fetch_url;
}
warnx("No file after directory (you must specify an "
"output file) `%s'", url);
goto cleanup_fetch_url;
}
restart_point = 0;
filesize = -1;
rangestart = rangeend = entitylen = -1;
mtime = -1;
if (restartautofetch) {
if (strcmp(savefile, "-") != 0 && *savefile != '|' &&
stat(savefile, &sb) == 0)
restart_point = sb.st_size;
}
if (urltype == FILE_URL_T) { /* file:// URLs */
direction = "copied";
fin = fetch_open(decodedpath, "r");
if (fin == NULL) {
warn("Can't open `%s'", decodedpath);
goto cleanup_fetch_url;
}
if (fstat(fetch_fileno(fin), &sb) == 0) {
mtime = sb.st_mtime;
filesize = sb.st_size;
}
if (restart_point) {
if (lseek(fetch_fileno(fin), restart_point, SEEK_SET) < 0) {
warn("Can't seek to restart `%s'",
decodedpath);
goto cleanup_fetch_url;
}
}
if (verbose) {
fprintf(ttyout, "Copying %s", decodedpath);
if (restart_point)
fprintf(ttyout, " (restarting at " LLF ")",
(LLT)restart_point);
fputs("\n", ttyout);
}
if (0 == rcvbuf_size) {
rcvbuf_size = 8 * 1024; /* XXX */
}
} else { /* ftp:// or http:// URLs */
const char *leading;
int hasleading;
if (penv == NULL) {
#ifdef WITH_SSL
if (urltype == HTTPS_URL_T)
penv = getoptionvalue("https_proxy");
#endif
if (penv == NULL && IS_HTTP_TYPE(urltype))
penv = getoptionvalue("http_proxy");
else if (urltype == FTP_URL_T)
penv = getoptionvalue("ftp_proxy");
}
direction = "retrieved";
if (! EMPTYSTRING(penv)) { /* use proxy */
url_t purltype;
char *phost, *ppath;
char *pport, *no_proxy;
in_port_t pportnum;
isproxy = 1;
/* check URL against list of no_proxied sites */
no_proxy = getoptionvalue("no_proxy");
if (! EMPTYSTRING(no_proxy)) {
char *np, *np_copy, *np_iter;
unsigned long np_port;
size_t hlen, plen;
np_iter = np_copy = ftp_strdup(no_proxy);
hlen = strlen(host);
while ((cp = strsep(&np_iter, " ,")) != NULL) {
if (*cp == '\0')
continue;
if ((np = strrchr(cp, ':')) != NULL) {
*np++ = '\0';
np_port = strtoul(np, &ep, 10);
if (*np == '\0' || *ep != '\0')
continue;
if (np_port != portnum)
continue;
}
plen = strlen(cp);
if (hlen < plen)
continue;
if (strncasecmp(host + hlen - plen,
cp, plen) == 0) {
isproxy = 0;
break;
}
}
FREEPTR(np_copy);
if (isproxy == 0 && urltype == FTP_URL_T) {
rval = fetch_ftp(url);
goto cleanup_fetch_url;
}
}
if (isproxy) {
if (restart_point) {
warnx("Can't restart via proxy URL `%s'",
penv);
goto cleanup_fetch_url;
}
if (parse_url(penv, "proxy URL", &purltype,
&puser, &ppass, &phost, &pport, &pportnum,
&ppath) == -1)
goto cleanup_fetch_url;
if ((!IS_HTTP_TYPE(purltype)
&& purltype != FTP_URL_T) ||
EMPTYSTRING(phost) ||
(! EMPTYSTRING(ppath)
&& strcmp(ppath, "/") != 0)) {
warnx("Malformed proxy URL `%s'", penv);
FREEPTR(phost);
FREEPTR(pport);
FREEPTR(ppath);
goto cleanup_fetch_url;
}
if (isipv6addr(host) &&
strchr(host, '%') != NULL) {
warnx(
"Scoped address notation `%s' disallowed via web proxy",
host);
FREEPTR(phost);
FREEPTR(pport);
FREEPTR(ppath);
goto cleanup_fetch_url;
}
FREEPTR(host);
host = phost;
FREEPTR(port);
port = pport;
FREEPTR(path);
path = ftp_strdup(url);
FREEPTR(ppath);
urltype = purltype;
}
} /* ! EMPTYSTRING(penv) */
memset(&hints, 0, sizeof(hints));
hints.ai_flags = 0;
hints.ai_family = family;
hints.ai_socktype = SOCK_STREAM;
hints.ai_protocol = 0;
error = getaddrinfo(host, port, &hints, &res0);
if (error) {
warnx("Can't LOOKUP `%s:%s': %s", host, port,
(error == EAI_SYSTEM) ? strerror(errno)
: gai_strerror(error));
goto cleanup_fetch_url;
}
if (res0->ai_canonname)
host = res0->ai_canonname;
s = -1;
#ifdef WITH_SSL
ssl = NULL;
#endif
for (res = res0; res; res = res->ai_next) {
char hname[NI_MAXHOST], sname[NI_MAXSERV];
ai_unmapped(res);
if (getnameinfo(res->ai_addr, res->ai_addrlen,
hname, sizeof(hname), sname, sizeof(sname),
NI_NUMERICHOST | NI_NUMERICSERV) != 0) {
strlcpy(hname, "?", sizeof(hname));
strlcpy(sname, "?", sizeof(sname));
}
if (verbose && res0->ai_next) {
fprintf(ttyout, "Trying %s:%s ...\n",
hname, sname);
}
s = socket(res->ai_family, SOCK_STREAM,
res->ai_protocol);
if (s < 0) {
warn(
"Can't create socket for connection to "
"`%s:%s'", hname, sname);
continue;
}
if (ftp_connect(s, res->ai_addr, res->ai_addrlen,
verbose || !res->ai_next) < 0) {
close(s);
s = -1;
continue;
}
#ifdef WITH_SSL
if (urltype == HTTPS_URL_T) {
if ((ssl = fetch_start_ssl(s)) == NULL) {
close(s);
s = -1;
continue;
}
}
#endif
/* success */
break;
}
if (s < 0) {
warnx("Can't connect to `%s:%s'", host, port);
goto cleanup_fetch_url;
}
oldalrm = xsignal(SIGALRM, timeouthttp);
alarmtimer(quit_time ? quit_time : 60);
fin = fetch_fdopen(s, "r+");
fetch_set_ssl(fin, ssl);
alarmtimer(0);
alarmtimer(quit_time ? quit_time : 60);
/*
* Construct and send the request.
*/
if (verbose)
fprintf(ttyout, "Requesting %s\n", url);
leading = " (";
hasleading = 0;
if (isproxy) {
if (verbose) {
fprintf(ttyout, "%svia %s:%s", leading,
host, port);
leading = ", ";
hasleading++;
}
fetch_printf(fin, "GET %s HTTP/1.0\r\n", path);
if (flushcache)
fetch_printf(fin, "Pragma: no-cache\r\n");
} else {
fetch_printf(fin, "GET %s HTTP/1.1\r\n", path);
if (strchr(host, ':')) {
char *h, *p;
/*
* strip off IPv6 scope identifier, since it is
* local to the node
*/
h = ftp_strdup(host);
if (isipv6addr(h) &&
(p = strchr(h, '%')) != NULL) {
*p = '\0';
}
fetch_printf(fin, "Host: [%s]", h);
free(h);
} else
fetch_printf(fin, "Host: %s", host);
#ifdef WITH_SSL
if ((urltype == HTTP_URL_T && portnum != HTTP_PORT) ||
(urltype == HTTPS_URL_T && portnum != HTTPS_PORT))
#else
if (portnum != HTTP_PORT)
#endif
fetch_printf(fin, ":%u", portnum);
fetch_printf(fin, "\r\n");
fetch_printf(fin, "Accept: */*\r\n");
fetch_printf(fin, "Connection: close\r\n");
if (restart_point) {
fputs(leading, ttyout);
fetch_printf(fin, "Range: bytes=" LLF "-\r\n",
(LLT)restart_point);
fprintf(ttyout, "restarting at " LLF,
(LLT)restart_point);
leading = ", ";
hasleading++;
}
if (flushcache)
fetch_printf(fin, "Cache-Control: no-cache\r\n");
}
if ((useragent=getenv("FTPUSERAGENT")) != NULL) {
fetch_printf(fin, "User-Agent: %s\r\n", useragent);
} else {
fetch_printf(fin, "User-Agent: %s/%s\r\n",
FTP_PRODUCT, FTP_VERSION);
}
if (wwwauth) {
if (verbose) {
fprintf(ttyout, "%swith authorization",
leading);
leading = ", ";
hasleading++;
}
fetch_printf(fin, "Authorization: %s\r\n", wwwauth);
}
if (proxyauth) {
if (verbose) {
fprintf(ttyout,
"%swith proxy authorization", leading);
leading = ", ";
hasleading++;
}
fetch_printf(fin, "Proxy-Authorization: %s\r\n", proxyauth);
}
if (verbose && hasleading)
fputs(")\n", ttyout);
fetch_printf(fin, "\r\n");
if (fetch_flush(fin) == EOF) {
warn("Writing HTTP request");
alarmtimer(0);
goto cleanup_fetch_url;
}
alarmtimer(0);
/* Read the response */
alarmtimer(quit_time ? quit_time : 60);
len = fetch_getline(fin, buf, sizeof(buf), &errormsg);
alarmtimer(0);
if (len < 0) {
if (*errormsg == '\n')
errormsg++;
warnx("Receiving HTTP reply: %s", errormsg);
goto cleanup_fetch_url;
}
while (len > 0 && (ISLWS(buf[len-1])))
buf[--len] = '\0';
DPRINTF("%s: received `%s'\n", __func__, buf);
/* Determine HTTP response code */
cp = strchr(buf, ' ');
if (cp == NULL)
goto improper;
else
cp++;
hcode = strtol(cp, &ep, 10);
if (*ep != '\0' && !isspace((unsigned char)*ep))
goto improper;
message = ftp_strdup(cp);
/* Read the rest of the header. */
while (1) {
alarmtimer(quit_time ? quit_time : 60);
len = fetch_getline(fin, buf, sizeof(buf), &errormsg);
alarmtimer(0);
if (len < 0) {
if (*errormsg == '\n')
errormsg++;
warnx("Receiving HTTP reply: %s", errormsg);
goto cleanup_fetch_url;
}
while (len > 0 && (ISLWS(buf[len-1])))
buf[--len] = '\0';
if (len == 0)
break;
DPRINTF("%s: received `%s'\n", __func__, buf);
/*
* Look for some headers
*/
cp = buf;
if (match_token(&cp, "Content-Length:")) {
filesize = STRTOLL(cp, &ep, 10);
if (filesize < 0 || *ep != '\0')
goto improper;
DPRINTF("%s: parsed len as: " LLF "\n",
__func__, (LLT)filesize);
} else if (match_token(&cp, "Content-Range:")) {
if (! match_token(&cp, "bytes"))
goto improper;
if (*cp == '*')
cp++;
else {
rangestart = STRTOLL(cp, &ep, 10);
if (rangestart < 0 || *ep != '-')
goto improper;
cp = ep + 1;
rangeend = STRTOLL(cp, &ep, 10);
if (rangeend < 0 || rangeend < rangestart)
goto improper;
cp = ep;
}
if (*cp != '/')
goto improper;
cp++;
if (*cp == '*')
cp++;
else {
entitylen = STRTOLL(cp, &ep, 10);
if (entitylen < 0)
goto improper;
cp = ep;
}
if (*cp != '\0')
goto improper;
#ifndef NO_DEBUG
if (ftp_debug) {
fprintf(ttyout, "parsed range as: ");
if (rangestart == -1)
fprintf(ttyout, "*");
else
fprintf(ttyout, LLF "-" LLF,
(LLT)rangestart,
(LLT)rangeend);
fprintf(ttyout, "/" LLF "\n", (LLT)entitylen);
}
#endif
if (! restart_point) {
warnx(
"Received unexpected Content-Range header");