forked from greenplum-db/pxf-archive
-
Notifications
You must be signed in to change notification settings - Fork 2
/
libchurl.c
1375 lines (1161 loc) · 34.4 KB
/
libchurl.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
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
#if PG_VERSION_NUM >= 90600
#include "postgres.h"
#endif
#include "libchurl.h"
#if PG_VERSION_NUM >= 90600
#include "lib/stringinfo.h"
#endif
#include "miscadmin.h"
#include "utils/builtins.h"
#include "utils/fmgroids.h"
#include "utils/guc.h"
#include "utils/jsonapi.h"
/* include libcurl without typecheck.
* This allows wrapping curl_easy_setopt to be wrapped
* for readability. O/w an error is generated when anything
* other than the expected type is given as parameter
*/
#define CURL_DISABLE_TYPECHECK
#include <curl/curl.h>
#undef CURL_DISABLE_TYPECHECK
/*
* internal buffer for libchurl internal context
*/
typedef struct churl_buffer
{
char *ptr;
int max;
int bot,
top;
} churl_buffer;
/*
* internal context of libchurl
*/
typedef struct churl_handle
{
/* curl easy API handle */
CURL *curl_handle;
/*
* curl multi API handle used to allow non-blocking callbacks
*/
CURLM *multi_handle;
/*
* curl API puts internal errors in this buffer used for error reporting
*/
char curl_error_buffer[CURL_ERROR_SIZE];
/*
* perform() (libcurl API) lets us know if the session is over using this
* int
*/
int curl_still_running;
/* internal buffer for download */
churl_buffer *download_buffer;
/* internal buffer for upload */
churl_buffer *upload_buffer;
/*
* holds http error code returned from remote server
*/
char *last_http_reponse;
/* true on upload, false on download */
bool upload;
} churl_context;
/*
* holds http header properties
*/
typedef struct churl_settings
{
struct curl_slist *headers;
} churl_settings;
/* the null action object used for pure validation */
static JsonSemAction nullSemAction =
{
NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL
};
churl_context *churl_new_context(void);
static void create_curl_handle(churl_context *context);
static void set_curl_option(churl_context *context, CURLoption option, const void *data);
static size_t read_callback(void *ptr, size_t size, size_t nmemb, void *userdata);
static void setup_multi_handle(churl_context *context);
static void multi_perform(churl_context *context);
static bool internal_buffer_large_enough(churl_buffer *buffer, size_t required);
static void flush_internal_buffer(churl_context *context);
static char *get_dest_address(CURL * curl_handle);
static void enlarge_internal_buffer(churl_buffer *buffer, size_t required);
static void finish_upload(churl_context *context);
static void cleanup_curl_handle(churl_context *context);
static void multi_remove_handle(churl_context *context);
static void cleanup_internal_buffer(churl_buffer *buffer);
static void churl_cleanup_context(churl_context *context);
static size_t write_callback(char *buffer, size_t size, size_t nitems, void *userp);
static void fill_internal_buffer(churl_context *context, int want);
static void churl_headers_set(churl_context *context, CHURL_HEADERS settings);
static void check_response_status(churl_context *context);
static void check_response_code(churl_context *context);
static void check_response(churl_context *context);
static void clear_error_buffer(churl_context *context);
static size_t header_callback(char *buffer, size_t size, size_t nitems, void *userp);
static void free_http_response(churl_context *context);
static void compact_internal_buffer(churl_buffer *buffer);
static void realloc_internal_buffer(churl_buffer *buffer, size_t required);
static bool handle_special_error(long response, StringInfo err);
static char *get_http_error_msg(long http_ret_code, char *msg, char *curl_error_buffer, char **hint_message, char **trace_message);
static char *build_header_str(const char *format, const char *key, const char *value);
static bool IsValidJson(text *json);
CHURL_HEADERS
churl_headers_init(void)
{
churl_settings *settings = (churl_settings *) palloc0(sizeof(churl_settings));
return (CHURL_HEADERS) settings;
}
/*
* Build a header string, in the form of given format (e.g. "%s: %s"),
* and populate <key> and <value> in it.
* If value is empty, return <key>.
*/
static char *
build_header_str(const char *format, const char *key, const char *value)
{
char *header_option = NULL;
char *output = NULL;
if (value == NULL) /* the option is just a "key" */
header_option = pstrdup(key);
else /* the option is a "key: value" */
{
StringInfoData formatter;
initStringInfo(&formatter);
/* Only encode custom headers */
if (pg_strncasecmp("X-GP-", key, 5) == 0)
{
output = curl_easy_escape(NULL, value, strlen(value));
if (!output)
elog(ERROR, "internal error: curl_easy_escape failed for value %s", value);
appendStringInfo(&formatter, format, key, output);
curl_free(output);
}
else
{
appendStringInfo(&formatter, format, key, value);
}
header_option = formatter.data;
}
return header_option;
}
void
churl_headers_append(CHURL_HEADERS headers, const char *key, const char *value)
{
churl_settings *settings = (churl_settings *) headers;
char *header_option = NULL;
header_option = build_header_str("%s: %s", key, value);
settings->headers = curl_slist_append(settings->headers,
header_option);
pfree(header_option);
}
void
churl_headers_override(CHURL_HEADERS headers, const char *key, const char *value)
{
churl_settings *settings = (churl_settings *) headers;
struct curl_slist *header_cell = settings->headers;
char *key_option = NULL;
char *header_data = NULL;
/* key must not be empty */
Assert(key != NULL);
/* key to compare with in the headers */
key_option = build_header_str("%s:%s", key, value ? "" : NULL);
/* find key in headers list */
while (header_cell != NULL)
{
header_data = header_cell->data;
if (strncmp(key_option, header_data, strlen(key_option)) == 0)
{
elog(DEBUG2, "churl_headers_override: Found existing header %s with key %s (for new value %s)",
header_data, key_option, value);
break;
}
header_cell = header_cell->next;
}
if (header_cell != NULL) /* found key */
{
char *new_data = build_header_str("%s: %s", key, value);
char *old_data = header_cell->data;
header_cell->data = strdup(new_data);
elog(DEBUG4, "churl_headers_override: new data: %s, old data: %s", new_data, old_data);
free(old_data);
pfree(new_data);
}
else
{
churl_headers_append(headers, key, value);
}
pfree(key_option);
}
void
churl_headers_remove(CHURL_HEADERS headers, const char *key, bool has_value)
{
churl_settings *settings = (churl_settings *) headers;
struct curl_slist *to_del_cell = settings->headers;
struct curl_slist *prev_cell = NULL;
char *key_option = NULL;
char *header_data = NULL;
/* key must not be empty */
Assert(key != NULL);
/* key to compare with in the headers */
key_option = build_header_str("%s:%s", key, has_value ? "" : NULL);
/* find key in headers list */
while (to_del_cell != NULL)
{
header_data = to_del_cell->data;
if (strncmp(key_option, header_data, strlen(key_option)) == 0)
{
elog(DEBUG2, "churl_headers_remove: Found existing header %s with key %s",
header_data, key_option);
break;
}
prev_cell = to_del_cell;
to_del_cell = to_del_cell->next;
}
if (to_del_cell != NULL) /* found key */
{
/* skip this cell */
if (prev_cell != NULL)
{
/* not the header */
prev_cell->next = to_del_cell->next;
}
else
{
/* remove header - make the next cell header now */
settings->headers = to_del_cell->next;
}
/* remove header data and cell */
if (to_del_cell->data)
free(to_del_cell->data);
free(to_del_cell);
}
else
{
elog(DEBUG2, "churl_headers_remove: No header with key %s to remove",
key_option);
}
pfree(key_option);
}
void
churl_headers_cleanup(CHURL_HEADERS headers)
{
churl_settings *settings = (churl_settings *) headers;
if (!settings)
return;
if (settings->headers)
curl_slist_free_all(settings->headers);
pfree(settings);
}
/*
* debug callback for CURLOPT_DEBUGFUNCTION
* logs debug information via postgres' logging mechanism
*/
static int
log_curl_debug(CURL *handle, curl_infotype type, char *data, size_t size, void *userp)
{
static const char prefix_map[CURLINFO_END][13] = {
"info: ",
"header in: ",
"header out: ",
"data in: ",
"data out: ",
"data in: ",
"data out: "
};
switch(type) {
case CURLINFO_TEXT:
case CURLINFO_HEADER_IN:
case CURLINFO_HEADER_OUT:
ereport(DEBUG3,
(errmsg("curl debug - %s%s", prefix_map[type], data)));
break;
case CURLINFO_DATA_IN:
case CURLINFO_DATA_OUT:
case CURLINFO_SSL_DATA_IN:
case CURLINFO_SSL_DATA_OUT:
ereport(DEBUG3,
(errmsg("curl debug - %s%zu bytes", prefix_map[type], size)));
break;
default:
break;
}
return 0;
}
static CHURL_HANDLE
churl_init(const char *url, CHURL_HEADERS headers)
{
churl_context *context = churl_new_context();
create_curl_handle(context);
clear_error_buffer(context);
/* Required for resolving localhost on some docker environments that
* had intermittent networking issues when using pxf on HAWQ.
*/
if (strstr(url, LocalhostIpV4) != NULL)
{
struct curl_slist *resolve_hosts = NULL;
char *pxf_host_entry = (char *) palloc0(LOCAL_HOST_RESOLVE_STRING_MAX_LENGTH);
/* TODO: do not hardcode the port here */
snprintf(pxf_host_entry, LOCAL_HOST_RESOLVE_STRING_MAX_LENGTH, LOCAL_HOST_RESOLVE_STRING_FORMAT, 5888);
elog(DEBUG3, "adding CURLOPT_RESOLVE with entry '%s'", pxf_host_entry);
resolve_hosts = curl_slist_append(NULL, pxf_host_entry);
set_curl_option(context, CURLOPT_RESOLVE, resolve_hosts);
pfree(pxf_host_entry);
}
long curl_verbose = (DEBUG3 >= log_min_messages) || (DEBUG3 >= client_min_messages);
set_curl_option(context, CURLOPT_URL, url);
set_curl_option(context, CURLOPT_DEBUGFUNCTION, log_curl_debug);
set_curl_option(context, CURLOPT_VERBOSE, (const void *) curl_verbose);
set_curl_option(context, CURLOPT_ERRORBUFFER, context->curl_error_buffer);
set_curl_option(context, CURLOPT_IPRESOLVE, (const void *) CURL_IPRESOLVE_V4);
set_curl_option(context, CURLOPT_WRITEFUNCTION, write_callback);
set_curl_option(context, CURLOPT_WRITEDATA, context);
set_curl_option(context, CURLOPT_HEADERFUNCTION, header_callback);
set_curl_option(context, CURLOPT_HEADERDATA, context);
churl_headers_set(context, headers);
return (CHURL_HANDLE) context;
}
CHURL_HANDLE
churl_init_upload(const char *url, CHURL_HEADERS headers)
{
churl_context *context = churl_init(url, headers);
context->upload = true;
set_curl_option(context, CURLOPT_POST, (const void *) true);
set_curl_option(context, CURLOPT_READFUNCTION, read_callback);
set_curl_option(context, CURLOPT_READDATA, context);
churl_headers_append(headers, "Content-Type", "application/octet-stream");
churl_headers_append(headers, "Transfer-Encoding", "chunked");
churl_headers_append(headers, "Expect", "100-continue");
setup_multi_handle(context);
return (CHURL_HANDLE) context;
}
CHURL_HANDLE
churl_init_download(const char *url, CHURL_HEADERS headers)
{
churl_context *context = churl_init(url, headers);
context->upload = false;
setup_multi_handle(context);
return (CHURL_HANDLE) context;
}
void
churl_download_restart(CHURL_HANDLE handle, const char *url, CHURL_HEADERS headers)
{
churl_context *context = (churl_context *) handle;
Assert(!context->upload);
/* halt current transfer */
multi_remove_handle(context);
/* set a new url */
set_curl_option(context, CURLOPT_URL, url);
/* set headers again */
if (headers)
churl_headers_set(context, headers);
/* restart */
setup_multi_handle(context);
}
/*
* upload
*/
size_t
churl_write(CHURL_HANDLE handle, const char *buf, size_t bufsize)
{
churl_context *context = (churl_context *) handle;
churl_buffer *context_buffer = context->upload_buffer;
Assert(context->upload);
if (!internal_buffer_large_enough(context_buffer, bufsize))
{
flush_internal_buffer(context);
if (!internal_buffer_large_enough(context_buffer, bufsize))
enlarge_internal_buffer(context_buffer, bufsize);
}
memcpy(context_buffer->ptr + context_buffer->top, buf, bufsize);
context_buffer->top += bufsize;
return bufsize;
}
/*
* check that connection is ok, read a few bytes and check response.
*/
void
churl_read_check_connectivity(CHURL_HANDLE handle)
{
churl_context *context = (churl_context *) handle;
Assert(!context->upload);
fill_internal_buffer(context, 1);
}
/*
* download
*/
size_t
churl_read(CHURL_HANDLE handle, char *buf, size_t max_size)
{
int n = 0;
churl_context *context = (churl_context *) handle;
churl_buffer *context_buffer = context->download_buffer;
Assert(!context->upload);
fill_internal_buffer(context, max_size);
n = context_buffer->top - context_buffer->bot;
/*------
* TODO: this means we are done. Should we do something with it?
* if (n == 0 && !context->curl_still_running)
* context->eof = true;
*------
*/
if (n > max_size)
n = max_size;
memcpy(buf, context_buffer->ptr + context_buffer->bot, n);
context_buffer->bot += n;
return n;
}
void
churl_cleanup(CHURL_HANDLE handle, bool after_error)
{
churl_context *context = (churl_context *) handle;
if (!context)
return;
/* don't try to read/write data after an error */
if (!after_error)
{
if (context->upload)
finish_upload(context);
else
churl_read_check_connectivity(handle);
}
cleanup_curl_handle(context);
cleanup_internal_buffer(context->download_buffer);
cleanup_internal_buffer(context->upload_buffer);
churl_cleanup_context(context);
}
churl_context *
churl_new_context()
{
churl_context *context = palloc0(sizeof(churl_context));
context->download_buffer = palloc0(sizeof(churl_buffer));
context->upload_buffer = palloc0(sizeof(churl_buffer));
return context;
}
static void
clear_error_buffer(churl_context *context)
{
if (!context)
return;
context->curl_error_buffer[0] = 0;
}
static void
create_curl_handle(churl_context *context)
{
context->curl_handle = curl_easy_init();
if (!context->curl_handle)
elog(ERROR, "internal error: curl_easy_init failed");
}
static void
set_curl_option(churl_context *context, CURLoption option, const void *data)
{
int curl_error;
if (CURLE_OK != (curl_error = curl_easy_setopt(context->curl_handle, option, data)))
elog(ERROR, "internal error: curl_easy_setopt %d error (%d - %s)",
option, curl_error, curl_easy_strerror(curl_error));
}
/*
* Called by libcurl perform during an upload.
* Copies data from internal buffer to libcurl's buffer.
* Once zero is returned, libcurl knows upload is over
*/
static size_t
read_callback(void *ptr, size_t size, size_t nmemb, void *userdata)
{
churl_context *context = (churl_context *) userdata;
churl_buffer *context_buffer = context->upload_buffer;
int written = Min(size * nmemb, context_buffer->top - context_buffer->bot);
memcpy(ptr, context_buffer->ptr + context_buffer->bot, written);
context_buffer->bot += written;
return written;
}
/*
* Setups the libcurl multi API
*/
static void
setup_multi_handle(churl_context *context)
{
int curl_error;
/* Create multi handle on first use */
if (!context->multi_handle)
if (!(context->multi_handle = curl_multi_init()))
elog(ERROR, "internal error: curl_multi_init failed");
/* add the easy handle to the multi handle */
/* don't blame me, blame libcurl */
if (CURLM_OK != (curl_error = curl_multi_add_handle(context->multi_handle, context->curl_handle)))
if (CURLM_CALL_MULTI_PERFORM != curl_error)
elog(ERROR, "internal error: curl_multi_add_handle failed (%d - %s)",
curl_error, curl_easy_strerror(curl_error));
multi_perform(context);
}
/*
* Does the real work. Causes libcurl to do
* as little work as possible and return.
* During this functions execution,
* callbacks are called.
*/
static void
multi_perform(churl_context *context)
{
int curl_error;
while (CURLM_CALL_MULTI_PERFORM ==
(curl_error = curl_multi_perform(context->multi_handle, &context->curl_still_running)));
if (curl_error != CURLM_OK)
elog(ERROR, "internal error: curl_multi_perform failed (%d - %s)",
curl_error, curl_easy_strerror(curl_error));
check_response(context);
}
static bool
internal_buffer_large_enough(churl_buffer *buffer, size_t required)
{
return ((buffer->top + required) <= buffer->max);
}
static void
flush_internal_buffer(churl_context *context)
{
churl_buffer *context_buffer = context->upload_buffer;
if (context_buffer->top == 0)
return;
while ((context->curl_still_running != 0) &&
((context_buffer->top - context_buffer->bot) > 0))
{
/*
* Allow canceling a query while waiting for input from remote service
*/
CHECK_FOR_INTERRUPTS();
multi_perform(context);
}
check_response(context);
if ((context->curl_still_running == 0) &&
((context_buffer->top - context_buffer->bot) > 0))
elog(ERROR, "failed sending to remote component %s", get_dest_address(context->curl_handle));
context_buffer->top = 0;
context_buffer->bot = 0;
}
/*
* Returns the remote ip and port of the curl response.
* If it's not available, returns an empty string.
* The returned value should be free'd.
*/
static char *
get_dest_address(CURL *curl_handle)
{
char *dest_url = NULL;
/* add dest url, if any, and curl was nice to tell us */
if (CURLE_OK == curl_easy_getinfo(curl_handle, CURLINFO_PRIMARY_IP, &dest_url) && dest_url)
{
/* TODO: do not hardcode the port here */
return psprintf("'%s:%d'", dest_url, 5888);
}
return dest_url;
}
static void
enlarge_internal_buffer(churl_buffer *buffer, size_t required)
{
if (buffer->ptr != NULL)
pfree(buffer->ptr);
buffer->max = required + 1024;
buffer->ptr = palloc(buffer->max);
}
/*
* Let libcurl finish the upload by
* calling perform repeatedly
*/
static void
finish_upload(churl_context *context)
{
if (!context->multi_handle)
return;
flush_internal_buffer(context);
/*
* allow read_callback to say 'all done' by returning a zero thus ending
* the connection
*/
while (context->curl_still_running != 0)
multi_perform(context);
}
static void
cleanup_curl_handle(churl_context *context)
{
if (!context->curl_handle)
return;
if (context->multi_handle)
multi_remove_handle(context);
curl_easy_cleanup(context->curl_handle);
context->curl_handle = NULL;
curl_multi_cleanup(context->multi_handle);
context->multi_handle = NULL;
}
static void
multi_remove_handle(churl_context *context)
{
int curl_error;
Assert(context->curl_handle && context->multi_handle);
if (CURLM_OK !=
(curl_error = curl_multi_remove_handle(context->multi_handle, context->curl_handle)))
elog(ERROR, "internal error: curl_multi_remove_handle failed (%d - %s)",
curl_error, curl_easy_strerror(curl_error));
}
static void
cleanup_internal_buffer(churl_buffer *buffer)
{
if ((buffer) && (buffer->ptr))
{
pfree(buffer->ptr);
buffer->ptr = NULL;
buffer->bot = 0;
buffer->top = 0;
buffer->max = 0;
}
}
static void
churl_cleanup_context(churl_context *context)
{
if (context)
{
if (context->download_buffer)
{
if (context->download_buffer->ptr)
pfree(context->download_buffer->ptr);
pfree(context->download_buffer);
}
if (context->upload_buffer)
{
if (context->upload_buffer->ptr)
pfree(context->upload_buffer->ptr);
pfree(context->upload_buffer);
}
pfree(context);
}
}
/*
* Called by libcurl perform during a download.
* Stores data from libcurl's buffer into the internal buffer.
* If internal buffer is not large enough, increases it.
*/
static size_t
write_callback(char *buffer, size_t size, size_t nitems, void *userp)
{
churl_context *context = (churl_context *) userp;
churl_buffer *context_buffer = context->download_buffer;
const int nbytes = size * nitems;
if (!internal_buffer_large_enough(context_buffer, nbytes))
{
compact_internal_buffer(context_buffer);
if (!internal_buffer_large_enough(context_buffer, nbytes))
realloc_internal_buffer(context_buffer, nbytes);
}
/* enough space. copy buffer into curl->buf */
memcpy(context_buffer->ptr + context_buffer->top, buffer, nbytes);
context_buffer->top += nbytes;
return nbytes;
}
/*
* Fills internal buffer up to want bytes.
* returns when size reached or transfer ended
*/
static void
fill_internal_buffer(churl_context *context, int want)
{
fd_set fdread;
fd_set fdwrite;
fd_set fdexcep;
int maxfd;
int curl_error;
/* attempt to fill buffer */
while (context->curl_still_running &&
((context->download_buffer->top - context->download_buffer->bot) < want))
{
FD_ZERO(&fdread);
FD_ZERO(&fdwrite);
FD_ZERO(&fdexcep);
/* allow canceling a query while waiting for input from remote service */
CHECK_FOR_INTERRUPTS();
/* set a suitable timeout to fail on */
long curl_timeo = -1;
struct timeval timeout;
timeout.tv_sec = 1;
timeout.tv_usec = 0;
curl_multi_timeout(context->multi_handle, &curl_timeo);
if (curl_timeo >= 0)
{
timeout.tv_sec = curl_timeo / 1000;
if (timeout.tv_sec > 1)
timeout.tv_sec = 1;
else
timeout.tv_usec = (curl_timeo % 1000) * 1000;
}
/* get file descriptors from the transfers */
curl_error = curl_multi_fdset(context->multi_handle, &fdread, &fdwrite, &fdexcep, &maxfd);
if (CURLE_OK != curl_error)
elog(ERROR, "internal error: curl_multi_fdset failed (%d - %s)",
curl_error, curl_easy_strerror(curl_error));
/* curl is not ready if maxfd -1 is returned */
if (maxfd == -1)
pg_usleep(100);
else if (-1 == select(maxfd + 1, &fdread, &fdwrite, &fdexcep, &timeout))
{
int save_errno = errno;
if (errno == EINTR || errno == EAGAIN)
continue;
#if PG_VERSION_NUM >= 90600
elog(ERROR, "internal error: select failed on curl_multi_fdset (maxfd %d) (%d - %m)",
maxfd, save_errno);
#else
elog(ERROR, "internal error: select failed on curl_multi_fdset (maxfd %d) (%d - %s)",
maxfd, save_errno, strerror(errno));
#endif
}
multi_perform(context);
}
}
static void
churl_headers_set(churl_context *context, CHURL_HEADERS headers)
{
churl_settings *settings = (churl_settings *) headers;
set_curl_option(context, CURLOPT_HTTPHEADER, settings->headers);
}
/*
* Checks that the response finished successfully
* with a valid response status and code.
*/
static void
check_response(churl_context *context)
{
check_response_code(context);
check_response_status(context);
}
/*
* Checks that libcurl transfers completed successfully.
* This is different than the response code (HTTP code) -
* a message can have a response code 200 (OK), but end prematurely
* and so have an error status.
*/
static void
check_response_status(churl_context *context)
{
CURLMsg *msg; /* for picking up messages with the transfer
* status */
int msgs_left; /* how many messages are left */
long status;
while ((msg = curl_multi_info_read(context->multi_handle, &msgs_left)))
{
int i = 0;
/* CURLMSG_DONE is the only possible status. */
if (msg->msg != CURLMSG_DONE)
continue;
if (CURLE_OK != (status = msg->data.result))
{
char *addr = get_dest_address(msg->easy_handle);
StringInfoData err;
initStringInfo(&err);
/* if the request did not complete correctly, show the error
* information. If no detailed error information was written to errbuf
* show the more generic information from curl_easy_strerror instead.
*/
appendStringInfo(&err, "transfer error (%ld): %s",
status, curl_easy_strerror(status));
if (addr)
{
appendStringInfo(&err, " from %s", addr);
pfree(addr);
}
size_t len = strlen(context->curl_error_buffer);
if (len > 0)
{
ereport(ERROR,
(errmsg("%s", err.data),
errdetail("curl error buffer: %s", context->curl_error_buffer)));
}
else
{
ereport(ERROR,
(errmsg("%s", err.data)));
}
}
ereport(DEBUG2,
(errmsg("check_response_status: msg %d done with status OK", i++)));
}
}
/*
* Parses return code from libcurl operation and
* reports if different than 200 and 100
*/
static void
check_response_code(churl_context *context)
{
long response_code;
char *response_text = NULL;
int curl_error;
if (CURLE_OK != (curl_error = curl_easy_getinfo(context->curl_handle, CURLINFO_RESPONSE_CODE, &response_code)))
elog(ERROR, "internal error: curl_easy_getinfo failed(%d - %s)",
curl_error, curl_easy_strerror(curl_error));
elog(DEBUG2, "http response code: %ld", response_code);
if ((response_code == 0) && (context->curl_still_running > 0))
{
elog(DEBUG2, "check_response_code: curl is still running, but no data was received.");
}
else if (response_code != 200 && response_code != 100)
{
StringInfoData err;
char *hint_msg = NULL,
*http_error_msg,
*trace_msg = NULL;
initStringInfo(&err);
/* prepare response text if any */
if (context->download_buffer->ptr)
{
context->download_buffer->ptr[context->download_buffer->top] = '\0';
response_text = context->download_buffer->ptr + context->download_buffer->bot;
}
appendStringInfo(&err, "PXF server error");
if ((LOG >= log_min_messages) || (LOG >= client_min_messages))
{
/* add remote http error code */
appendStringInfo(&err, "(%ld)", response_code);
}
if (!handle_special_error(response_code, &err))