-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtool_operate.c
3022 lines (2656 loc) · 96.7 KB
/
tool_operate.c
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
/***************************************************************************
* _ _ ____ _
* Project ___| | | | _ \| |
* / __| | | | |_) | |
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
* Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
*
* You may opt to use, copy, modify, merge, publish, distribute and/or sell
* copies of the Software, and permit persons to whom the Software is
* furnished to do so, under the terms of the COPYING file.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
* SPDX-License-Identifier: curl
*
***************************************************************************/
#include "tool_setup.h"
#ifdef HAVE_FCNTL_H
# include <fcntl.h>
#endif
#ifdef HAVE_LOCALE_H
# include <locale.h>
#endif
#ifdef HAVE_SYS_SELECT_H
# include <sys/select.h>
#elif defined(HAVE_UNISTD_H)
# include <unistd.h>
#endif
#ifdef __VMS
# include <fabdef.h>
#endif
#ifdef __AMIGA__
# include <proto/dos.h>
#endif
#define ENABLE_CURLX_PRINTF
/* use our own printf() functions */
#include "curlx.h"
#include "tool_binmode.h"
#include "tool_cfgable.h"
#include "tool_cb_dbg.h"
#include "tool_cb_hdr.h"
#include "tool_cb_prg.h"
#include "tool_cb_rea.h"
#include "tool_cb_see.h"
#include "tool_cb_wrt.h"
#include "tool_dirhie.h"
#include "tool_doswin.h"
#include "tool_easysrc.h"
#include "tool_filetime.h"
#include "tool_getparam.h"
#include "tool_helpers.h"
#include "tool_findfile.h"
#include "tool_libinfo.h"
#include "tool_main.h"
#include "tool_msgs.h"
#include "tool_operate.h"
#include "tool_operhlp.h"
#include "tool_paramhlp.h"
#include "tool_parsecfg.h"
#include "tool_setopt.h"
#include "tool_sleep.h"
#include "tool_urlglob.h"
#include "tool_util.h"
#include "tool_writeout.h"
#include "tool_xattr.h"
#include "tool_vms.h"
#include "tool_help.h"
#include "tool_hugehelp.h"
#include "tool_progress.h"
#include "dynbuf.h"
#include "memdebug.h" /* keep this as LAST include */
#ifdef CURLDEBUG
/* libcurl's debug builds provide an extra function */
CURLcode curl_easy_perform_ev(CURL *easy);
#endif
#ifndef O_BINARY
/* since O_BINARY as used in bitmasks, setting it to zero makes it usable in
source code but yet it doesn't ruin anything */
# define O_BINARY 0
#endif
#define CURL_CA_CERT_ERRORMSG \
"More details here: https://curl.se/docs/sslcerts.html\n\n" \
"curl failed to verify the legitimacy of the server and therefore " \
"could not\nestablish a secure connection to it. To learn more about " \
"this situation and\nhow to fix it, please visit the web page mentioned " \
"above.\n"
static CURLcode single_transfer(struct GlobalConfig *global,
struct OperationConfig *config,
CURLSH *share,
bool capath_from_env,
bool *added);
static CURLcode create_transfer(struct GlobalConfig *global,
CURLSH *share,
bool *added);
static bool is_fatal_error(CURLcode code)
{
switch(code) {
case CURLE_FAILED_INIT:
case CURLE_OUT_OF_MEMORY:
case CURLE_UNKNOWN_OPTION:
case CURLE_FUNCTION_NOT_FOUND:
case CURLE_BAD_FUNCTION_ARGUMENT:
/* critical error */
return TRUE;
default:
break;
}
/* no error or not critical */
return FALSE;
}
/*
* Check if a given string is a PKCS#11 URI
*/
static bool is_pkcs11_uri(const char *string)
{
if(curl_strnequal(string, "pkcs11:", 7)) {
return TRUE;
}
else {
return FALSE;
}
}
#ifdef __VMS
/*
* get_vms_file_size does what it takes to get the real size of the file
*
* For fixed files, find out the size of the EOF block and adjust.
*
* For all others, have to read the entire file in, discarding the contents.
* Most posted text files will be small, and binary files like zlib archives
* and CD/DVD images should be either a STREAM_LF format or a fixed format.
*
*/
static curl_off_t vms_realfilesize(const char *name,
const struct_stat *stat_buf)
{
char buffer[8192];
curl_off_t count;
int ret_stat;
FILE * file;
/* !checksrc! disable FOPENMODE 1 */
file = fopen(name, "r"); /* VMS */
if(!file) {
return 0;
}
count = 0;
ret_stat = 1;
while(ret_stat > 0) {
ret_stat = fread(buffer, 1, sizeof(buffer), file);
if(ret_stat)
count += ret_stat;
}
fclose(file);
return count;
}
/*
*
* VmsSpecialSize checks to see if the stat st_size can be trusted and
* if not to call a routine to get the correct size.
*
*/
static curl_off_t VmsSpecialSize(const char *name,
const struct_stat *stat_buf)
{
switch(stat_buf->st_fab_rfm) {
case FAB$C_VAR:
case FAB$C_VFC:
return vms_realfilesize(name, stat_buf);
break;
default:
return stat_buf->st_size;
}
}
#endif /* __VMS */
#define BUFFER_SIZE (100*1024)
struct per_transfer *transfers; /* first node */
static struct per_transfer *transfersl; /* last node */
static curl_off_t all_pers;
/* add_per_transfer creates a new 'per_transfer' node in the linked
list of transfers */
static CURLcode add_per_transfer(struct per_transfer **per)
{
struct per_transfer *p;
p = calloc(sizeof(struct per_transfer), 1);
if(!p)
return CURLE_OUT_OF_MEMORY;
if(!transfers)
/* first entry */
transfersl = transfers = p;
else {
/* make the last node point to the new node */
transfersl->next = p;
/* make the new node point back to the formerly last node */
p->prev = transfersl;
/* move the last node pointer to the new entry */
transfersl = p;
}
*per = p;
all_xfers++; /* count total number of transfers added */
all_pers++;
return CURLE_OK;
}
/* Remove the specified transfer from the list (and free it), return the next
in line */
static struct per_transfer *del_per_transfer(struct per_transfer *per)
{
struct per_transfer *n;
struct per_transfer *p;
DEBUGASSERT(transfers);
DEBUGASSERT(transfersl);
DEBUGASSERT(per);
n = per->next;
p = per->prev;
if(p)
p->next = n;
else
transfers = n;
if(n)
n->prev = p;
else
transfersl = p;
free(per);
all_pers--;
return n;
}
static CURLcode pre_transfer(struct GlobalConfig *global,
struct per_transfer *per)
{
curl_off_t uploadfilesize = -1;
struct_stat fileinfo;
CURLcode result = CURLE_OK;
if(per->uploadfile && !stdin_upload(per->uploadfile)) {
/* VMS Note:
*
* Reading binary from files can be a problem... Only FIXED, VAR
* etc WITHOUT implied CC will work. Others need a \n appended to
* a line
*
* - Stat gives a size but this is UNRELIABLE in VMS. E.g.
* a fixed file with implied CC needs to have a byte added for every
* record processed, this can be derived from Filesize & recordsize
* for VARiable record files the records need to be counted! for
* every record add 1 for linefeed and subtract 2 for the record
* header for VARIABLE header files only the bare record data needs
* to be considered with one appended if implied CC
*/
#ifdef __VMS
/* Calculate the real upload size for VMS */
per->infd = -1;
if(stat(per->uploadfile, &fileinfo) == 0) {
fileinfo.st_size = VmsSpecialSize(uploadfile, &fileinfo);
switch(fileinfo.st_fab_rfm) {
case FAB$C_VAR:
case FAB$C_VFC:
case FAB$C_STMCR:
per->infd = open(per->uploadfile, O_RDONLY | O_BINARY);
break;
default:
per->infd = open(per->uploadfile, O_RDONLY | O_BINARY,
"rfm=stmlf", "ctx=stm");
}
}
if(per->infd == -1)
#else
per->infd = open(per->uploadfile, O_RDONLY | O_BINARY);
if((per->infd == -1) || fstat(per->infd, &fileinfo))
#endif
{
helpf(stderr, "Can't open '%s'", per->uploadfile);
if(per->infd != -1) {
close(per->infd);
per->infd = STDIN_FILENO;
}
return CURLE_READ_ERROR;
}
per->infdopen = TRUE;
/* we ignore file size for char/block devices, sockets, etc. */
if(S_ISREG(fileinfo.st_mode))
uploadfilesize = fileinfo.st_size;
#ifdef DEBUGBUILD
/* allow dedicated test cases to override */
{
char *ev = getenv("CURL_UPLOAD_SIZE");
if(ev) {
int sz = atoi(ev);
uploadfilesize = (curl_off_t)sz;
}
}
#endif
if(uploadfilesize != -1) {
struct OperationConfig *config = per->config; /* for the macro below */
#ifdef CURL_DISABLE_LIBCURL_OPTION
(void)config;
(void)global;
#endif
my_setopt(per->curl, CURLOPT_INFILESIZE_LARGE, uploadfilesize);
}
}
per->uploadfilesize = uploadfilesize;
per->start = tvnow();
return result;
}
#ifdef __AMIGA__
static void AmigaSetComment(struct per_transfer *per,
CURLcode result)
{
struct OutStruct *outs = &per->outs;
if(!result && outs->s_isreg && outs->filename) {
/* Set the url (up to 80 chars) as comment for the file */
if(strlen(per->this_url) > 78)
per->this_url[79] = '\0';
SetComment(outs->filename, per->this_url);
}
}
#else
#define AmigaSetComment(x,y) Curl_nop_stmt
#endif
/* When doing serial transfers, we use a single fixed error area */
static char global_errorbuffer[CURL_ERROR_SIZE];
void single_transfer_cleanup(struct OperationConfig *config)
{
if(config) {
struct State *state = &config->state;
if(state->urls) {
/* Free list of remaining URLs */
glob_cleanup(state->urls);
state->urls = NULL;
}
Curl_safefree(state->outfiles);
Curl_safefree(state->httpgetfields);
Curl_safefree(state->uploadfile);
if(state->inglob) {
/* Free list of globbed upload files */
glob_cleanup(state->inglob);
state->inglob = NULL;
}
}
}
/*
* Call this after a transfer has completed.
*/
static CURLcode post_per_transfer(struct GlobalConfig *global,
struct per_transfer *per,
CURLcode result,
bool *retryp,
long *delay) /* milliseconds! */
{
struct OutStruct *outs = &per->outs;
CURL *curl = per->curl;
struct OperationConfig *config = per->config;
int rc;
if(!curl || !config)
return result;
*retryp = FALSE;
*delay = 0; /* for no retry, keep it zero */
if(per->infdopen)
close(per->infd);
#ifdef __VMS
if(is_vms_shell()) {
/* VMS DCL shell behavior */
if(global->silent && !global->showerror)
vms_show = VMSSTS_HIDE;
}
else
#endif
if(!config->synthetic_error && result &&
(!global->silent || global->showerror)) {
const char *msg = per->errorbuffer;
fprintf(stderr, "curl: (%d) %s\n", result,
(msg && msg[0]) ? msg : curl_easy_strerror(result));
if(result == CURLE_PEER_FAILED_VERIFICATION)
fputs(CURL_CA_CERT_ERRORMSG, stderr);
}
else if(config->failwithbody) {
/* if HTTP response >= 400, return error */
long code = 0;
curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &code);
if(code >= 400) {
if(!global->silent || global->showerror)
fprintf(stderr,
"curl: (%d) The requested URL returned error: %ld\n",
CURLE_HTTP_RETURNED_ERROR, code);
result = CURLE_HTTP_RETURNED_ERROR;
}
}
/* Set file extended attributes */
if(!result && config->xattr && outs->fopened && outs->stream) {
rc = fwrite_xattr(curl, per->this_url, fileno(outs->stream));
if(rc)
warnf(config->global, "Error setting extended attributes on '%s': %s",
outs->filename, strerror(errno));
}
if(!result && !outs->stream && !outs->bytes) {
/* we have received no data despite the transfer was successful
==> force creation of an empty output file (if an output file
was specified) */
long cond_unmet = 0L;
/* do not create (or even overwrite) the file in case we get no
data because of unmet condition */
curl_easy_getinfo(curl, CURLINFO_CONDITION_UNMET, &cond_unmet);
if(!cond_unmet && !tool_create_output_file(outs, config))
result = CURLE_WRITE_ERROR;
}
if(!outs->s_isreg && outs->stream) {
/* Dump standard stream buffered data */
rc = fflush(outs->stream);
if(!result && rc) {
/* something went wrong in the writing process */
result = CURLE_WRITE_ERROR;
errorf(global, "Failed writing body");
}
}
#ifdef WIN32
/* Discard incomplete UTF-8 sequence buffered from body */
if(outs->utf8seq[0])
memset(outs->utf8seq, 0, sizeof(outs->utf8seq));
#endif
/* if retry-max-time is non-zero, make sure we haven't exceeded the
time */
if(per->retry_numretries &&
(!config->retry_maxtime ||
(tvdiff(tvnow(), per->retrystart) <
config->retry_maxtime*1000L)) ) {
enum {
RETRY_NO,
RETRY_ALL_ERRORS,
RETRY_TIMEOUT,
RETRY_CONNREFUSED,
RETRY_HTTP,
RETRY_FTP,
RETRY_LAST /* not used */
} retry = RETRY_NO;
long response = 0;
if((CURLE_OPERATION_TIMEDOUT == result) ||
(CURLE_COULDNT_RESOLVE_HOST == result) ||
(CURLE_COULDNT_RESOLVE_PROXY == result) ||
(CURLE_FTP_ACCEPT_TIMEOUT == result))
/* retry timeout always */
retry = RETRY_TIMEOUT;
else if(config->retry_connrefused &&
(CURLE_COULDNT_CONNECT == result)) {
long oserrno = 0;
curl_easy_getinfo(curl, CURLINFO_OS_ERRNO, &oserrno);
if(ECONNREFUSED == oserrno)
retry = RETRY_CONNREFUSED;
}
else if((CURLE_OK == result) ||
((config->failonerror || config->failwithbody) &&
(CURLE_HTTP_RETURNED_ERROR == result))) {
/* If it returned OK. _or_ failonerror was enabled and it
returned due to such an error, check for HTTP transient
errors to retry on. */
const char *scheme;
curl_easy_getinfo(curl, CURLINFO_SCHEME, &scheme);
scheme = proto_token(scheme);
if(scheme == proto_http || scheme == proto_https) {
/* This was HTTP(S) */
curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &response);
switch(response) {
case 408: /* Request Timeout */
case 429: /* Too Many Requests (RFC6585) */
case 500: /* Internal Server Error */
case 502: /* Bad Gateway */
case 503: /* Service Unavailable */
case 504: /* Gateway Timeout */
retry = RETRY_HTTP;
/*
* At this point, we have already written data to the output
* file (or terminal). If we write to a file, we must rewind
* or close/re-open the file so that the next attempt starts
* over from the beginning.
*
* TODO: similar action for the upload case. We might need
* to start over reading from a previous point if we have
* uploaded something when this was returned.
*/
break;
}
}
} /* if CURLE_OK */
else if(result) {
const char *scheme;
curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &response);
curl_easy_getinfo(curl, CURLINFO_SCHEME, &scheme);
scheme = proto_token(scheme);
if((scheme == proto_ftp || scheme == proto_ftps) && response / 100 == 4)
/*
* This is typically when the FTP server only allows a certain
* amount of users and we are not one of them. All 4xx codes
* are transient.
*/
retry = RETRY_FTP;
}
if(result && !retry && config->retry_all_errors)
retry = RETRY_ALL_ERRORS;
if(retry) {
long sleeptime = 0;
curl_off_t retry_after = 0;
static const char * const m[]={
NULL,
"(retrying all errors)",
": timeout",
": connection refused",
": HTTP error",
": FTP error"
};
sleeptime = per->retry_sleep;
if(RETRY_HTTP == retry) {
curl_easy_getinfo(curl, CURLINFO_RETRY_AFTER, &retry_after);
if(retry_after) {
/* store in a 'long', make sure it doesn't overflow */
if(retry_after > LONG_MAX/1000)
sleeptime = LONG_MAX;
else
sleeptime = (long)retry_after * 1000; /* milliseconds */
/* if adding retry_after seconds to the process would exceed the
maximum time allowed for retrying, then exit the retries right
away */
if(config->retry_maxtime) {
curl_off_t seconds = tvdiff(tvnow(), per->retrystart)/1000;
if((CURL_OFF_T_MAX - retry_after < seconds) ||
(seconds + retry_after > config->retry_maxtime)) {
warnf(config->global, "The Retry-After: time would "
"make this command line exceed the maximum allowed time "
"for retries.");
goto noretry;
}
}
}
}
warnf(config->global, "Problem %s. "
"Will retry in %ld seconds. "
"%ld retries left.",
m[retry], sleeptime/1000L, per->retry_numretries);
per->retry_numretries--;
if(!config->retry_delay) {
per->retry_sleep *= 2;
if(per->retry_sleep > RETRY_SLEEP_MAX)
per->retry_sleep = RETRY_SLEEP_MAX;
}
if(outs->bytes && outs->filename && outs->stream) {
/* We have written data to an output file, we truncate file
*/
notef(config->global,
"Throwing away %" CURL_FORMAT_CURL_OFF_T " bytes",
outs->bytes);
fflush(outs->stream);
/* truncate file at the position where we started appending */
#ifdef HAVE_FTRUNCATE
if(ftruncate(fileno(outs->stream), outs->init)) {
/* when truncate fails, we can't just append as then we'll
create something strange, bail out */
errorf(config->global, "Failed to truncate file");
return CURLE_WRITE_ERROR;
}
/* now seek to the end of the file, the position where we
just truncated the file in a large file-safe way */
rc = fseek(outs->stream, 0, SEEK_END);
#else
/* ftruncate is not available, so just reposition the file
to the location we would have truncated it. This won't
work properly with large files on 32-bit systems, but
most of those will have ftruncate. */
rc = fseek(outs->stream, (long)outs->init, SEEK_SET);
#endif
if(rc) {
errorf(config->global, "Failed seeking to end of file");
return CURLE_WRITE_ERROR;
}
outs->bytes = 0; /* clear for next round */
}
*retryp = TRUE;
*delay = sleeptime;
return CURLE_OK;
}
} /* if retry_numretries */
noretry:
if((global->progressmode == CURL_PROGRESS_BAR) &&
per->progressbar.calls)
/* if the custom progress bar has been displayed, we output a
newline here */
fputs("\n", per->progressbar.out);
/* Close the outs file */
if(outs->fopened && outs->stream) {
rc = fclose(outs->stream);
if(!result && rc) {
/* something went wrong in the writing process */
result = CURLE_WRITE_ERROR;
errorf(config->global, "curl: (%d) Failed writing body", result);
}
if(result && config->rm_partial) {
notef(global, "Removing output file: %s", outs->filename);
unlink(outs->filename);
}
}
AmigaSetComment(per, result);
/* File time can only be set _after_ the file has been closed */
if(!result && config->remote_time && outs->s_isreg && outs->filename) {
/* Ask libcurl if we got a remote file time */
curl_off_t filetime = -1;
curl_easy_getinfo(curl, CURLINFO_FILETIME_T, &filetime);
setfiletime(filetime, outs->filename, global);
}
/* Write the --write-out data before cleanup but after result is final */
if(config->writeout)
ourWriteOut(config, per, result);
/* Close function-local opened file descriptors */
if(per->heads.fopened && per->heads.stream)
fclose(per->heads.stream);
if(per->heads.alloc_filename)
Curl_safefree(per->heads.filename);
if(per->etag_save.fopened && per->etag_save.stream)
fclose(per->etag_save.stream);
if(per->etag_save.alloc_filename)
Curl_safefree(per->etag_save.filename);
curl_easy_cleanup(per->curl);
if(outs->alloc_filename)
free(outs->filename);
free(per->this_url);
free(per->outfile);
free(per->uploadfile);
if(global->parallel)
free(per->errorbuffer);
return result;
}
static char *ipfs_gateway(void)
{
char *gateway = NULL;
char *ipfs_path = NULL;
char *gateway_composed_file_path = NULL;
FILE *gateway_file = NULL;
gateway = curlx_getenv("IPFS_GATEWAY");
/* Gateway is found from environment variable. */
if(gateway && strlen(gateway)) {
char *composed_gateway = NULL;
bool add_slash = (gateway[strlen(gateway) - 1] == '/') ? FALSE : TRUE;
composed_gateway = aprintf("%s%s", gateway, (add_slash) ? "/" : "");
Curl_safefree(gateway);
gateway = aprintf("%s", composed_gateway);
Curl_safefree(composed_gateway);
return gateway;
}
/* Try to find the gateway in the IPFS data folder. */
ipfs_path = curlx_getenv("IPFS_PATH");
if(!ipfs_path) {
char *home = NULL;
home = curlx_getenv("HOME");
/* Empty path, fallback to "~/.ipfs", as that's the default location. */
ipfs_path = aprintf("%s/.ipfs/", home);
Curl_safefree(home);
}
if(!ipfs_path) {
Curl_safefree(gateway);
Curl_safefree(ipfs_path);
return NULL;
}
gateway_composed_file_path = aprintf("%sgateway", ipfs_path);
if(!gateway_composed_file_path) {
Curl_safefree(gateway);
Curl_safefree(ipfs_path);
return NULL;
}
gateway_file = fopen(gateway_composed_file_path, FOPEN_READTEXT);
Curl_safefree(gateway_composed_file_path);
if(gateway_file) {
char *gateway_buffer = NULL;
if((PARAM_OK == file2string(&gateway_buffer, gateway_file)) &&
gateway_buffer) {
bool add_slash = (gateway_buffer[strlen(gateway_buffer) - 1] == '/')
? FALSE
: TRUE;
gateway = aprintf("%s%s", gateway_buffer, (add_slash) ? "/" : "");
Curl_safefree(gateway_buffer);
}
if(gateway_file)
fclose(gateway_file);
if(!gateway) {
Curl_safefree(gateway);
Curl_safefree(ipfs_path);
return NULL;
}
Curl_safefree(ipfs_path);
return gateway;
}
Curl_safefree(gateway);
Curl_safefree(ipfs_path);
return NULL;
}
/*
* Rewrite ipfs://<cid> and ipns://<cid> to a HTTP(S)
* URL that can be handled by an IPFS gateway.
*/
static CURLcode ipfs_url_rewrite(CURLU *uh, const char *protocol, char **url,
struct OperationConfig *config)
{
CURLcode result = CURLE_URL_MALFORMAT;
CURLUcode urlGetResult;
char *gateway = NULL;
char *cid = NULL;
char *pathbuffer = NULL;
CURLU *ipfsurl = curl_url();
if(!ipfsurl) {
result = CURLE_FAILED_INIT;
goto clean;
}
urlGetResult = curl_url_get(uh, CURLUPART_HOST, &cid, CURLU_URLDECODE);
if(urlGetResult) {
goto clean;
}
if(!cid) {
goto clean;
}
/* We might have a --ipfs-gateway argument. Check it first and use it. Error
* if we do have something but if it's an invalid url.
*/
if(config->ipfs_gateway) {
if(curl_url_set(ipfsurl, CURLUPART_URL, config->ipfs_gateway,
CURLU_GUESS_SCHEME)
== CURLUE_OK) {
gateway = strdup(config->ipfs_gateway);
if(!gateway) {
result = CURLE_URL_MALFORMAT;
goto clean;
}
}
else {
result = CURLE_BAD_FUNCTION_ARGUMENT;
goto clean;
}
}
else {
gateway = ipfs_gateway();
if(!gateway) {
result = CURLE_FILE_COULDNT_READ_FILE;
goto clean;
}
if(curl_url_set(ipfsurl, CURLUPART_URL, gateway, CURLU_GUESS_SCHEME
| CURLU_NON_SUPPORT_SCHEME) != CURLUE_OK) {
goto clean;
}
}
pathbuffer = aprintf("%s/%s", protocol, cid);
if(!pathbuffer) {
goto clean;
}
if(curl_url_set(ipfsurl, CURLUPART_PATH, pathbuffer, CURLU_URLENCODE)
!= CURLUE_OK) {
goto clean;
}
/* Free whatever it has now, rewriting is next */
Curl_safefree(*url);
if(curl_url_get(ipfsurl, CURLUPART_URL, url, CURLU_URLENCODE)
!= CURLUE_OK) {
goto clean;
}
result = CURLE_OK;
clean:
curl_free(gateway);
curl_free(cid);
curl_free(pathbuffer);
if(ipfsurl) {
curl_url_cleanup(ipfsurl);
}
switch(result) {
case CURLE_URL_MALFORMAT:
helpf(stderr, "malformed URL. Visit https://curl.se/"
"docs/ipfs.html#Gateway-file-and-"
"environment-variable for more "
"information for more information");
break;
case CURLE_FILE_COULDNT_READ_FILE:
helpf(stderr, "IPFS automatic gateway detection "
"failure. Visit https://curl.se/docs/"
"ipfs.html#Malformed-gateway-URL for "
"more information for more "
"information");
break;
case CURLE_BAD_FUNCTION_ARGUMENT:
helpf(stderr, "--ipfs-gateway argument results in "
"malformed URL. Visit https://curl.se/"
"docs/ipfs.html#Malformed-gateway-URL "
"for more information for more "
"information");
break;
default:
break;
}
return result;
}
/*
* Return the protocol token for the scheme used in the given URL
*/
static CURLcode url_proto(char **url,
struct OperationConfig *config,
char **scheme)
{
CURLcode result = CURLE_OK;
CURLU *uh = curl_url();
const char *proto = NULL;
*scheme = NULL;
if(uh) {
if(*url) {
char *schemep = NULL;
if(!curl_url_set(uh, CURLUPART_URL, *url,
CURLU_GUESS_SCHEME | CURLU_NON_SUPPORT_SCHEME) &&
!curl_url_get(uh, CURLUPART_SCHEME, &schemep,
CURLU_DEFAULT_SCHEME)) {
if(curl_strequal(schemep, proto_ipfs) ||
curl_strequal(schemep, proto_ipns)) {
result = ipfs_url_rewrite(uh, schemep, url, config);
/* short-circuit proto_token, we know it's ipfs or ipns */
if(curl_strequal(schemep, proto_ipfs))
proto = proto_ipfs;
else if(curl_strequal(schemep, proto_ipns))
proto = proto_ipns;
}
else
proto = proto_token(schemep);
curl_free(schemep);
}
}
curl_url_cleanup(uh);
}
*scheme = (char *) (proto? proto: "???"); /* Never match if not found. */
return result;
}
/* create the next (singular) transfer */
static CURLcode single_transfer(struct GlobalConfig *global,
struct OperationConfig *config,
CURLSH *share,
bool capath_from_env,
bool *added)
{
CURLcode result = CURLE_OK;
struct getout *urlnode;
bool orig_noprogress = global->noprogress;
bool orig_isatty = global->isatty;
struct State *state = &config->state;
char *httpgetfields = state->httpgetfields;
*added = FALSE; /* not yet */
if(config->postfields) {
if(config->use_httpget) {
if(!httpgetfields) {
/* Use the postfields data for an HTTP get */
httpgetfields = state->httpgetfields = strdup(config->postfields);
Curl_safefree(config->postfields);
if(!httpgetfields) {
errorf(global, "out of memory");
result = CURLE_OUT_OF_MEMORY;
}
else if(SetHTTPrequest(config,
(config->no_body?HTTPREQ_HEAD:HTTPREQ_GET),
&config->httpreq)) {
result = CURLE_FAILED_INIT;
}
}
}
else {
if(SetHTTPrequest(config, HTTPREQ_SIMPLEPOST, &config->httpreq))
result = CURLE_FAILED_INIT;
}
if(result) {
single_transfer_cleanup(config);
return result;
}
}
if(!state->urlnode) {
/* first time caller, setup things */
state->urlnode = config->url_list;
state->infilenum = 1;
}
while(config->state.urlnode) {
static bool warn_more_options = FALSE;
char *infiles; /* might be a glob pattern */
struct URLGlob *inglob = state->inglob;
urlnode = config->state.urlnode;
/* urlnode->url is the full URL (it might be NULL) */
if(!urlnode->url) {
/* This node has no URL. Free node data without destroying the
node itself nor modifying next pointer and continue to next */
Curl_safefree(urlnode->outfile);