-
Notifications
You must be signed in to change notification settings - Fork 116
/
http.c
1662 lines (1443 loc) · 43.9 KB
/
http.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: PgSQL HTTP
* Purpose: Main file.
*
***********************************************************************
* Copyright 2015 Paul Ramsey <[email protected]>
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
***********************************************************************/
/* Constants */
#define HTTP_VERSION "1.6.1"
#define HTTP_ENCODING "gzip"
#define CURL_MIN_VERSION 0x071400 /* 7.20.0 */
/* System */
#include <regex.h>
#include <string.h>
#include <stdlib.h>
#include <limits.h> /* INT_MAX */
#include <signal.h> /* SIGINT */
/* PostgreSQL */
#include <postgres.h>
#include <fmgr.h>
#include <funcapi.h>
#include <access/genam.h>
#include <access/htup.h>
#include <access/sysattr.h>
#include <catalog/namespace.h>
#include <catalog/pg_type.h>
#include <catalog/pg_extension.h>
#include <catalog/dependency.h>
#include <catalog/indexing.h>
#include <commands/extension.h>
#include <lib/stringinfo.h>
#include <mb/pg_wchar.h>
#include <nodes/pg_list.h>
#include <utils/array.h>
#include <utils/builtins.h>
#include <utils/catcache.h>
#include <utils/jsonb.h>
#include <utils/lsyscache.h>
#include <utils/syscache.h>
#include <utils/typcache.h>
#include <utils/fmgroids.h>
#include <utils/guc.h>
#if PG_VERSION_NUM >= 90300
# include <access/htup_details.h>
#endif
#if PG_VERSION_NUM >= 100000
# include <utils/varlena.h>
#endif
#if PG_VERSION_NUM >= 120000
# include <access/table.h>
#else
# define table_open(rel, lock) heap_open((rel), (lock))
# define table_close(rel, lock) heap_close((rel), (lock))
#endif
#if PG_VERSION_NUM < 110000
#define PG_GETARG_JSONB_P(x) DatumGetJsonb(PG_GETARG_DATUM(x))
#endif
/* CURL */
#include <curl/curl.h>
/* Set up PgSQL */
PG_MODULE_MAGIC;
/* HTTP request methods we support */
typedef enum {
HTTP_GET,
HTTP_POST,
HTTP_DELETE,
HTTP_PUT,
HTTP_HEAD,
HTTP_PATCH,
HTTP_UNKNOWN
} http_method;
/* Components (and postitions) of the http_request tuple type */
enum {
REQ_METHOD = 0,
REQ_URI = 1,
REQ_HEADERS = 2,
REQ_CONTENT_TYPE = 3,
REQ_CONTENT = 4
} http_request_type;
/* Components (and postitions) of the http_response tuple type */
enum {
RESP_STATUS = 0,
RESP_CONTENT_TYPE = 1,
RESP_HEADERS = 2,
RESP_CONTENT = 3
} http_response_type;
/* Components (and postitions) of the http_header tuple type */
enum {
HEADER_FIELD = 0,
HEADER_VALUE = 1
} http_header_type;
/*
* String/Long for strings and numbers, blob only for
* CURLOPT_SSLKEY_BLOB and CURLOPT_SSLCERT_BLOB
*/
typedef enum {
CURLOPT_STRING,
CURLOPT_LONG,
CURLOPT_BLOB
} http_curlopt_type;
/* CURLOPT string/enum value mapping */
typedef struct {
char *curlopt_str;
char *curlopt_val;
CURLoption curlopt;
http_curlopt_type curlopt_type;
bool superuser_only;
} http_curlopt;
/* CURLOPT values we allow user to set at run-time */
/* Be careful adding these, as they can be a security risk */
static http_curlopt settable_curlopts[] = {
{ "CURLOPT_CAINFO", NULL, CURLOPT_CAINFO, CURLOPT_STRING, false },
{ "CURLOPT_TIMEOUT", NULL, CURLOPT_TIMEOUT, CURLOPT_LONG, false },
{ "CURLOPT_TIMEOUT_MS", NULL, CURLOPT_TIMEOUT_MS, CURLOPT_LONG, false },
{ "CURLOPT_CONNECTTIMEOUT", NULL, CURLOPT_CONNECTTIMEOUT, CURLOPT_LONG, false },
{ "CURLOPT_CONNECTTIMEOUT_MS", NULL, CURLOPT_CONNECTTIMEOUT_MS, CURLOPT_LONG, false },
{ "CURLOPT_USERAGENT", NULL, CURLOPT_USERAGENT, CURLOPT_STRING, false },
{ "CURLOPT_USERPWD", NULL, CURLOPT_USERPWD, CURLOPT_STRING, false },
{ "CURLOPT_IPRESOLVE", NULL, CURLOPT_IPRESOLVE, CURLOPT_LONG, false },
#if LIBCURL_VERSION_NUM >= 0x070903 /* 7.9.3 */
{ "CURLOPT_SSLCERTTYPE", NULL, CURLOPT_SSLCERTTYPE, CURLOPT_STRING, false },
#endif
#if LIBCURL_VERSION_NUM >= 0x070e01 /* 7.14.1 */
{ "CURLOPT_PROXY", NULL, CURLOPT_PROXY, CURLOPT_STRING, false },
{ "CURLOPT_PROXYPORT", NULL, CURLOPT_PROXYPORT, CURLOPT_LONG, false },
#endif
#if LIBCURL_VERSION_NUM >= 0x071301 /* 7.19.1 */
{ "CURLOPT_PROXYUSERNAME", NULL, CURLOPT_PROXYUSERNAME, CURLOPT_STRING, false },
{ "CURLOPT_PROXYPASSWORD", NULL, CURLOPT_PROXYPASSWORD, CURLOPT_STRING, false },
#endif
#if LIBCURL_VERSION_NUM >= 0x071504 /* 7.21.4 */
{ "CURLOPT_TLSAUTH_USERNAME", NULL, CURLOPT_TLSAUTH_USERNAME, CURLOPT_STRING, false },
{ "CURLOPT_TLSAUTH_PASSWORD", NULL, CURLOPT_TLSAUTH_PASSWORD, CURLOPT_STRING, false },
{ "CURLOPT_TLSAUTH_TYPE", NULL, CURLOPT_TLSAUTH_TYPE, CURLOPT_STRING, false },
#endif
#if LIBCURL_VERSION_NUM >= 0x071800 /* 7.24.0 */
{ "CURLOPT_DNS_SERVERS", NULL, CURLOPT_DNS_SERVERS, CURLOPT_STRING, false },
#endif
#if LIBCURL_VERSION_NUM >= 0x071900 /* 7.25.0 */
{ "CURLOPT_TCP_KEEPALIVE", NULL, CURLOPT_TCP_KEEPALIVE, CURLOPT_LONG, false },
{ "CURLOPT_TCP_KEEPIDLE", NULL, CURLOPT_TCP_KEEPIDLE, CURLOPT_LONG, false },
#endif
#if LIBCURL_VERSION_NUM >= 0x072500 /* 7.37.0 */
{ "CURLOPT_SSL_VERIFYHOST", NULL, CURLOPT_SSL_VERIFYHOST, CURLOPT_LONG, false },
{ "CURLOPT_SSL_VERIFYPEER", NULL, CURLOPT_SSL_VERIFYPEER, CURLOPT_LONG, false },
#endif
{ "CURLOPT_SSLCERT", NULL, CURLOPT_SSLCERT, CURLOPT_STRING, false },
{ "CURLOPT_SSLKEY", NULL, CURLOPT_SSLKEY, CURLOPT_STRING, false },
#if LIBCURL_VERSION_NUM >= 0x073400 /* 7.52.0 */
{ "CURLOPT_PRE_PROXY", NULL, CURLOPT_PRE_PROXY, CURLOPT_STRING, false },
{ "CURLOPT_PROXY_CAINFO", NULL, CURLOPT_PROXY_TLSAUTH_USERNAME, CURLOPT_STRING, false },
{ "CURLOPT_PROXY_TLSAUTH_USERNAME", NULL, CURLOPT_PROXY_TLSAUTH_USERNAME, CURLOPT_STRING, false },
{ "CURLOPT_PROXY_TLSAUTH_PASSWORD", NULL, CURLOPT_PROXY_TLSAUTH_PASSWORD, CURLOPT_STRING, false },
{ "CURLOPT_PROXY_TLSAUTH_TYPE", NULL, CURLOPT_PROXY_TLSAUTH_TYPE, CURLOPT_STRING, false },
#endif
#if LIBCURL_VERSION_NUM >= 0x074700 /* 7.71.0 */
{ "CURLOPT_SSLKEY_BLOB", NULL, CURLOPT_SSLKEY_BLOB, CURLOPT_BLOB, false },
{ "CURLOPT_SSLCERT_BLOB", NULL, CURLOPT_SSLCERT_BLOB, CURLOPT_BLOB, false },
#endif
{ NULL, NULL, 0, 0, false } /* Array null terminator */
};
/* Function signatures */
void _PG_init(void);
void _PG_fini(void);
static size_t http_writeback(void *contents, size_t size, size_t nmemb, void *userp);
static size_t http_readback(void *buffer, size_t size, size_t nitems, void *instream);
/* Global variables */
bool g_use_keepalive;
int g_timeout_msec;
CURL * g_http_handle = NULL;
List * g_curl_opts = NIL;
/*
* Interrupt support is dependent on CURLOPT_XFERINFOFUNCTION which is
* only available from 7.32.0 and up
*/
#if LIBCURL_VERSION_NUM >= 0x072700 /* 7.39.0 */
pqsigfunc pgsql_interrupt_handler = NULL;
int http_interrupt_requested = 0;
/*
* To support request interruption, we have libcurl run the progress meter
* callback frequently, and here we watch to see if PgSQL has flipped our
* global 'http_interrupt_requested' flag. If it has been flipped,
* the non-zero return value will cue libcurl to abort the transfer,
* leading to a CURLE_ABORTED_BY_CALLBACK return on the curl_easy_perform()
*/
static int
http_progress_callback(void *clientp, curl_off_t dltotal, curl_off_t dlnow, curl_off_t ultotal, curl_off_t ulnow)
{
#ifdef WIN32
if (UNBLOCKED_SIGNAL_QUEUE())
{
pgwin32_dispatch_queued_signals();
}
#endif
/* elog(DEBUG3, "http_interrupt_requested = %d", http_interrupt_requested); */
return http_interrupt_requested;
}
/*
* We register this callback with the PgSQL signal handler to
* capture SIGINT and set our local interupt flag so that
* libcurl will eventually notice that a cancel is requested
*/
static void
http_interrupt_handler(int sig)
{
/* Handle the signal here */
elog(DEBUG2, "http_interrupt_handler: sig=%d", sig);
http_interrupt_requested = sig;
pgsql_interrupt_handler(sig);
return;
}
#endif /* 7.39.0 */
#undef HTTP_MEM_CALLBACKS
#ifdef HTTP_MEM_CALLBACKS
static void *
http_calloc(size_t a, size_t b)
{
if (a>0 && b>0)
return palloc0(a*b);
else
return NULL;
}
static void
http_free(void *a)
{
if (a)
pfree(a);
}
static void *
http_realloc(void *a, size_t sz)
{
if (a && sz)
return repalloc(a, sz);
else if (sz)
return palloc(sz);
else
return a;
}
static void *
http_malloc(size_t sz)
{
return sz ? palloc(sz) : NULL;
}
#endif
/* Startup */
void _PG_init(void)
{
DefineCustomBoolVariable("http.keepalive",
"reuse existing connections with keepalive",
NULL,
&g_use_keepalive,
false,
PGC_USERSET,
GUC_NOT_IN_SAMPLE,
NULL,
NULL,
NULL);
DefineCustomIntVariable("http.timeout_msec",
"request completion timeout in milliseconds",
NULL,
&g_timeout_msec,
0,
0,
INT_MAX,
PGC_USERSET,
GUC_NOT_IN_SAMPLE | GUC_UNIT_MS,
NULL,
NULL,
NULL);
#ifdef HTTP_MEM_CALLBACKS
/*
* Use PgSQL memory management in Curl
* Warning, https://curl.se/libcurl/c/curl_global_init_mem.html
* notes "If you are using libcurl from multiple threads or libcurl
* was built with the threaded resolver option then the callback
* functions must be thread safe." PgSQL isn't multi-threaded,
* but we have no control over whether the "threaded resolver" is
* in use. We may need a semaphor to ensure our callbacks are
* accessed sequentially only.
*/
curl_global_init_mem(CURL_GLOBAL_ALL, http_malloc, http_free, http_realloc, pstrdup, http_calloc);
#else
/* Set up Curl! */
curl_global_init(CURL_GLOBAL_ALL);
#endif
#if LIBCURL_VERSION_NUM >= 0x072700 /* 7.39.0 */
/* Register our interrupt handler (http_handle_interrupt) */
/* and store the existing one so we can call it when we're */
/* through with our work */
pgsql_interrupt_handler = pqsignal(SIGINT, http_interrupt_handler);
http_interrupt_requested = 0;
#endif
}
/* Tear-down */
void _PG_fini(void)
{
#if LIBCURL_VERSION_NUM >= 0x072700
/* Re-register the original signal handler */
pqsignal(SIGINT, pgsql_interrupt_handler);
#endif
if (g_http_handle)
{
curl_easy_cleanup(g_http_handle);
g_http_handle = NULL;
}
curl_global_cleanup();
elog(NOTICE, "Goodbye from HTTP %s", HTTP_VERSION);
}
/**
* This function is passed into CURL as the CURLOPT_WRITEFUNCTION,
* this allows the return values to be held in memory, in our case in a string.
*/
static size_t
http_writeback(void *contents, size_t size, size_t nmemb, void *userp)
{
size_t realsize = size * nmemb;
StringInfo si = (StringInfo)userp;
appendBinaryStringInfo(si, (const char*)contents, (int)realsize);
return realsize;
}
/**
* This function is passed into CURL as the CURLOPT_READFUNCTION,
* this allows the PUT operation to read the data it needs. We
* pass a StringInfo as our input, and per the callback contract
* return the number of bytes read at each call.
*/
static size_t
http_readback(void *buffer, size_t size, size_t nitems, void *instream)
{
size_t reqsize = size * nitems;
StringInfo si = (StringInfo)instream;
size_t remaining = si->len - si->cursor;
size_t readsize = Min(reqsize, remaining);
memcpy(buffer, si->data + si->cursor, readsize);
si->cursor += readsize;
return readsize;
}
static void
http_error(CURLcode err, const char *error_buffer)
{
if ( strlen(error_buffer) > 0 )
ereport(ERROR, (errmsg("%s", error_buffer)));
else
ereport(ERROR, (errmsg("%s", curl_easy_strerror(err))));
}
/* Utility macro to try a setopt and catch an error */
#define CURL_SETOPT(handle, opt, value) do { \
err = curl_easy_setopt((handle), (opt), (value)); \
if ( err != CURLE_OK ) \
{ \
http_error(err, http_error_buffer); \
PG_RETURN_NULL(); \
} \
} while (0);
/**
* Convert a request type string into the appropriate enumeration value.
*/
static http_method
request_type(const char *method)
{
if ( strcasecmp(method, "GET") == 0 )
return HTTP_GET;
else if ( strcasecmp(method, "POST") == 0 )
return HTTP_POST;
else if ( strcasecmp(method, "PUT") == 0 )
return HTTP_PUT;
else if ( strcasecmp(method, "DELETE") == 0 )
return HTTP_DELETE;
else if ( strcasecmp(method, "HEAD") == 0 )
return HTTP_HEAD;
else if ( strcasecmp(method, "PATCH") == 0 )
return HTTP_PATCH;
else
return HTTP_UNKNOWN;
}
/**
* Given a field name and value, output a http_header tuple.
*/
static Datum
header_tuple(TupleDesc header_tuple_desc, const char *field, const char *value)
{
HeapTuple header_tuple;
int ncolumns;
Datum *header_values;
bool *header_nulls;
/* Prepare our return object */
ncolumns = header_tuple_desc->natts;
header_values = palloc0(sizeof(Datum)*ncolumns);
header_nulls = palloc0(sizeof(bool)*ncolumns);
header_values[HEADER_FIELD] = CStringGetTextDatum(field);
header_nulls[HEADER_FIELD] = false;
header_values[HEADER_VALUE] = CStringGetTextDatum(value);
header_nulls[HEADER_VALUE] = false;
/* Build up a tuple from values/nulls lists */
header_tuple = heap_form_tuple(header_tuple_desc, header_values, header_nulls);
return HeapTupleGetDatum(header_tuple);
}
/**
* Our own implementation of strcasestr.
*/
static char *
http_strcasestr(const char *s, const char *find)
{
char c, sc;
size_t len;
if ((c = *find++) != 0)
{
c = tolower((unsigned char)c);
len = strlen(find);
do
{
do
{
if ((sc = *s++) == 0)
return (NULL);
}
while ((char)tolower((unsigned char)sc) != c);
}
while (strncasecmp(s, find, len) != 0);
s--;
}
return ((char *)s);
}
/**
* Quick and dirty, remove all \r from a StringInfo.
*/
static void
string_info_remove_cr(StringInfo si)
{
int i = 0, j = 0;
while ( si->data[i] )
{
if ( si->data[i] != '\r' )
si->data[j++] = si->data[i++];
else
i++;
}
si->data[j] = '\0';
si->len -= i-j;
return;
}
/**
* Add an array of http_header tuples into a Curl string list.
*/
static struct curl_slist *
header_array_to_slist(ArrayType *array, struct curl_slist *headers)
{
ArrayIterator iterator;
Datum value;
bool isnull;
#if PG_VERSION_NUM >= 90500
iterator = array_create_iterator(array, 0, NULL);
#else
iterator = array_create_iterator(array, 0);
#endif
while (array_iterate(iterator, &value, &isnull))
{
HeapTupleHeader rec;
HeapTupleData tuple;
Oid tup_type;
int32 tup_typmod, ncolumns;
TupleDesc tup_desc;
size_t tup_len;
Datum *values;
bool *nulls;
/* Skip null array items */
if ( isnull )
continue;
rec = DatumGetHeapTupleHeader(value);
tup_type = HeapTupleHeaderGetTypeId(rec);
tup_typmod = HeapTupleHeaderGetTypMod(rec);
tup_len = HeapTupleHeaderGetDatumLength(rec);
tup_desc = lookup_rowtype_tupdesc(tup_type, tup_typmod);
ncolumns = tup_desc->natts;
/* Prepare for values / nulls to hold the data */
values = (Datum *) palloc0(ncolumns * sizeof(Datum));
nulls = (bool *) palloc0(ncolumns * sizeof(bool));
/* Build a temporary HeapTuple control structure */
tuple.t_len = tup_len;
ItemPointerSetInvalid(&(tuple.t_self));
tuple.t_tableOid = InvalidOid;
tuple.t_data = rec;
/* Break down the tuple into values/nulls lists */
heap_deform_tuple(&tuple, tup_desc, values, nulls);
/* Convert the data into a header */
/* TODO: Ensure the header list is unique? Or leave that to the */
/* server to deal with. */
if ( ! nulls[HEADER_FIELD] )
{
size_t total_len = 0;
char *buffer = NULL;
char *header_val;
char *header_fld = TextDatumGetCString(values[HEADER_FIELD]);
/* Don't process "content-type" in the optional headers */
if ( strlen(header_fld) <= 0 || strncasecmp(header_fld, "Content-Type", 12) == 0 )
{
elog(NOTICE, "'Content-Type' is not supported as an optional header");
continue;
}
if ( nulls[HEADER_VALUE] )
header_val = pstrdup("");
else
header_val = TextDatumGetCString(values[HEADER_VALUE]);
total_len = strlen(header_val) + strlen(header_fld) + sizeof(char) + sizeof(": ");
buffer = palloc(total_len);
if (buffer)
{
snprintf(buffer, total_len, "%s: %s", header_fld, header_val);
elog(DEBUG2, "pgsql-http: optional request header '%s'", buffer);
headers = curl_slist_append(headers, buffer);
pfree(buffer);
}
else
{
elog(ERROR, "pgsql-http: palloc(%zu) failure", total_len);
}
pfree(header_fld);
pfree(header_val);
}
/* Free all the temporary structures */
ReleaseTupleDesc(tup_desc);
pfree(values);
pfree(nulls);
}
array_free_iterator(iterator);
return headers;
}
/**
* This function is now exposed in PG16 and above
* so no need to redefine it for PG16 and above
*/
#if PG_VERSION_NUM < 160000
/**
* Look up the namespace the extension is installed in
*/
static Oid
get_extension_schema(Oid ext_oid)
{
Oid result;
SysScanDesc scandesc;
HeapTuple tuple;
ScanKeyData entry[1];
#if PG_VERSION_NUM >= 120000
Oid pg_extension_oid = Anum_pg_extension_oid;
#else
Oid pg_extension_oid = ObjectIdAttributeNumber;
#endif
Relation rel = table_open(ExtensionRelationId, AccessShareLock);
ScanKeyInit(&entry[0],
pg_extension_oid,
BTEqualStrategyNumber, F_OIDEQ,
ObjectIdGetDatum(ext_oid));
scandesc = systable_beginscan(rel, ExtensionOidIndexId, true,
NULL, 1, entry);
tuple = systable_getnext(scandesc);
/* We assume that there can be at most one matching tuple */
if (HeapTupleIsValid(tuple))
result = ((Form_pg_extension) GETSTRUCT(tuple))->extnamespace;
else
result = InvalidOid;
systable_endscan(scandesc);
table_close(rel, AccessShareLock);
return result;
}
#endif
/**
* Look up the tuple description for a extension-defined type,
* avoiding the pitfalls of using relations that are not part
* of the extension, but share the same name as the relation
* of interest.
*/
static TupleDesc
typname_get_tupledesc(const char *extname, const char *typname)
{
Oid extoid = get_extension_oid(extname, true);
Oid extschemaoid;
Oid typoid;
if ( ! OidIsValid(extoid) )
elog(ERROR, "could not lookup '%s' extension oid", extname);
extschemaoid = get_extension_schema(extoid);
#if PG_VERSION_NUM >= 120000
typoid = GetSysCacheOid2(TYPENAMENSP, Anum_pg_type_oid,
PointerGetDatum(typname),
ObjectIdGetDatum(extschemaoid));
#else
typoid = GetSysCacheOid2(TYPENAMENSP,
PointerGetDatum(typname),
ObjectIdGetDatum(extschemaoid));
#endif
if ( OidIsValid(typoid) )
{
// Oid typ_oid = get_typ_typrelid(rel_oid);
Oid relextoid = getExtensionOfObject(TypeRelationId, typoid);
if ( relextoid == extoid )
{
return TypeGetTupleDesc(typoid, NIL);
}
}
elog(ERROR, "could not lookup '%s' tuple desc", typname);
}
#define RVSZ 8192 /* Max length of header element */
/**
* Convert a string of headers separated by newlines/CRs into an
* array of http_header tuples.
*/
static ArrayType *
header_string_to_array(StringInfo si)
{
/* Array building */
size_t arr_nelems = 0;
size_t arr_elems_size = 8;
Datum *arr_elems = palloc0(arr_elems_size*sizeof(Datum));
Oid elem_type;
int16 elem_len;
bool elem_byval;
char elem_align;
/* Header handling */
TupleDesc header_tuple_desc = NULL;
/* Regex support */
const char *regex_pattern = "^([^ \t\r\n\v\f]+): ?([^ \t\r\n\v\f]+.*)$";
regex_t regex;
regmatch_t pmatch[3];
int reti;
char rv1[RVSZ];
char rv2[RVSZ];
/* Compile the regular expression */
reti = regcomp(®ex, regex_pattern, REG_ICASE | REG_EXTENDED | REG_NEWLINE );
if ( reti )
elog(ERROR, "Unable to compile regex pattern '%s'", regex_pattern);
/* Lookup the tuple defn */
header_tuple_desc = typname_get_tupledesc("http", "http_header");
/* Prepare array building metadata */
elem_type = header_tuple_desc->tdtypeid;
get_typlenbyvalalign(elem_type, &elem_len, &elem_byval, &elem_align);
/* Loop through string, matching regex pattern */
si->cursor = 0;
while ( ! regexec(®ex, si->data+si->cursor, 3, pmatch, 0) )
{
/* Read the regex match results */
int eo0 = pmatch[0].rm_eo;
int so1 = pmatch[1].rm_so;
int eo1 = pmatch[1].rm_eo;
int so2 = pmatch[2].rm_so;
int eo2 = pmatch[2].rm_eo;
/* Copy the matched portions out of the string */
memcpy(rv1, si->data+si->cursor+so1, Min(eo1-so1, RVSZ));
rv1[eo1-so1] = '\0';
memcpy(rv2, si->data+si->cursor+so2, Min(eo2-so2, RVSZ));
rv2[eo2-so2] = '\0';
/* Move forward for next match */
si->cursor += eo0;
/* Increase elements array size if necessary */
if ( arr_nelems >= arr_elems_size )
{
arr_elems_size *= 2;
arr_elems = repalloc(arr_elems, arr_elems_size*sizeof(Datum));
}
arr_elems[arr_nelems] = header_tuple(header_tuple_desc, rv1, rv2);
arr_nelems++;
}
regfree(®ex);
ReleaseTupleDesc(header_tuple_desc);
return construct_array(arr_elems, arr_nelems, elem_type, elem_len, elem_byval, elem_align);
}
/* Check/log version info */
static void
http_check_curl_version(const curl_version_info_data *version_info)
{
elog(DEBUG2, "pgsql-http: curl version %s", version_info->version);
elog(DEBUG2, "pgsql-http: curl version number 0x%x", version_info->version_num);
elog(DEBUG2, "pgsql-http: ssl version %s", version_info->ssl_version);
if ( version_info->version_num < CURL_MIN_VERSION )
{
elog(ERROR, "pgsql-http requires Curl version 0.7.20 or higher");
}
}
static bool
set_curlopt(CURL* handle, const http_curlopt *opt)
{
CURLcode err = CURLE_OK;
char http_error_buffer[CURL_ERROR_SIZE] = "\0";
memset(http_error_buffer, 0, sizeof(http_error_buffer));
/* Argument is a string */
if (opt->curlopt_type == CURLOPT_STRING)
{
err = curl_easy_setopt(handle, opt->curlopt, opt->curlopt_val);
elog(DEBUG2, "pgsql-http: set '%s' to value '%s', return value = %d", opt->curlopt_str, opt->curlopt_val, err);
}
/* Argument is a long */
else if (opt->curlopt_type == CURLOPT_LONG)
{
long value_long;
errno = 0;
value_long = strtol(opt->curlopt_val, NULL, 10);
if ( errno == EINVAL || errno == ERANGE )
elog(ERROR, "invalid integer provided for '%s'", opt->curlopt_str);
err = curl_easy_setopt(handle, opt->curlopt, value_long);
elog(DEBUG2, "pgsql-http: set '%s' to value '%ld', return value = %d", opt->curlopt_str, value_long, err);
}
/* Only used for CURLOPT_SSLKEY_BLOB and CURLOPT_SSLCERT_BLOB */
else if (opt->curlopt_type == CURLOPT_BLOB)
{
struct curl_blob blob;
blob.len = strlen(opt->curlopt_val) + 1;
blob.data = opt->curlopt_val;
blob.flags = CURL_BLOB_COPY;
err = curl_easy_setopt(handle, CURLOPT_SSLKEYTYPE, "PEM");
elog(DEBUG2, "pgsql-http: set 'CURLOPT_SSLKEYTYPE' to value 'PEM', return value = %d", err);
err = curl_easy_setopt(handle, opt->curlopt, &blob);
elog(DEBUG2, "pgsql-http: set '%s' to value '%s', return value = %d", opt->curlopt_str, opt->curlopt_val, err);
}
else
{
/* Never get here */
elog(ERROR, "invalid curlopt_type");
}
if ( err != CURLE_OK )
{
http_error(err, http_error_buffer);
return false;
}
return true;
}
/* Check/create the global CURL* handle */
static CURL *
http_get_handle()
{
http_curlopt opt;
CURL *handle = g_http_handle;
size_t i = 0;
/* Initialize the global handle if needed */
if (!handle)
{
handle = curl_easy_init();
}
/* Always reset because we are going to fill in the user */
/* set options down below */
else
{
curl_easy_reset(handle);
}
/* Always want a default fast (1 second) connection timeout */
/* User can over-ride with http_set_curlopt() if they wish */
curl_easy_setopt(handle, CURLOPT_CONNECTTIMEOUT_MS, 1000);
curl_easy_setopt(handle, CURLOPT_TIMEOUT_MS, 5000);
/* Set the user agent. If not set, use PG_VERSION as default */
curl_easy_setopt(handle, CURLOPT_USERAGENT, PG_VERSION_STR);
if (!handle)
ereport(ERROR, (errmsg("Unable to initialize CURL")));
/* Bring in any options the user has set this session */
while (1)
{
opt = settable_curlopts[i++];
if (!opt.curlopt_str) break;
/* Option value is already set */
if (opt.curlopt_val)
set_curlopt(handle, &opt);
}
g_http_handle = handle;
return handle;
}
/**
* User-defined Curl option reset.
*/
Datum http_reset_curlopt(PG_FUNCTION_ARGS);
PG_FUNCTION_INFO_V1(http_reset_curlopt);
Datum http_reset_curlopt(PG_FUNCTION_ARGS)
{
size_t i = 0;
/* Set up global HTTP handle */
CURL * handle = http_get_handle();
curl_easy_reset(handle);
/* Clean out the settable_curlopts global cache */
while (1)
{
http_curlopt *opt = settable_curlopts + i++;
if (!opt->curlopt_str) break;
if (opt->curlopt_val) pfree(opt->curlopt_val);
opt->curlopt_val = NULL;
}
PG_RETURN_BOOL(true);
}
Datum http_list_curlopt(PG_FUNCTION_ARGS);
PG_FUNCTION_INFO_V1(http_list_curlopt);
Datum http_list_curlopt(PG_FUNCTION_ARGS)
{
struct list_state {
size_t i; /* read position */
};
MemoryContext oldcontext, newcontext;
FuncCallContext *funcctx;
struct list_state *state;
Datum vals[2];
bool nulls[2];
if (SRF_IS_FIRSTCALL())
{
funcctx = SRF_FIRSTCALL_INIT();
newcontext = funcctx->multi_call_memory_ctx;
oldcontext = MemoryContextSwitchTo(newcontext);
state = palloc0(sizeof(*state));
funcctx->user_fctx = state;
if(get_call_result_type(fcinfo, 0, &funcctx->tuple_desc) != TYPEFUNC_COMPOSITE)
ereport(ERROR, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
errmsg("composite-returning function called in context that cannot accept a composite")));
BlessTupleDesc(funcctx->tuple_desc);
MemoryContextSwitchTo(oldcontext);
}
funcctx = SRF_PERCALL_SETUP();
state = funcctx->user_fctx;
while (1)
{
Datum result;
HeapTuple tuple;
text *option, *value;
http_curlopt *opt = settable_curlopts + state->i++;
if (!opt->curlopt_str)
break;
if (!opt->curlopt_val)
continue;
option = cstring_to_text(opt->curlopt_str);
value = cstring_to_text(opt->curlopt_val);
vals[0] = PointerGetDatum(option);
vals[1] = PointerGetDatum(value);
nulls[0] = nulls[1] = 0;
tuple = heap_form_tuple(funcctx->tuple_desc, vals, nulls);
result = HeapTupleGetDatum(tuple);
SRF_RETURN_NEXT(funcctx, result);
}
SRF_RETURN_DONE(funcctx);
}
/**
* User-defined Curl option handling.
*/
Datum http_set_curlopt(PG_FUNCTION_ARGS);
PG_FUNCTION_INFO_V1(http_set_curlopt);
Datum http_set_curlopt(PG_FUNCTION_ARGS)
{
size_t i = 0;
char *curlopt, *value;
text *curlopt_txt, *value_txt;
CURL *handle;
/* Version check */
http_check_curl_version(curl_version_info(CURLVERSION_NOW));
/* We cannot handle null arguments */
if ( PG_ARGISNULL(0) || PG_ARGISNULL(1) )
PG_RETURN_BOOL(false);
/* Set up global HTTP handle */
handle = http_get_handle();
/* Read arguments */
curlopt_txt = PG_GETARG_TEXT_P(0);
value_txt = PG_GETARG_TEXT_P(1);
curlopt = text_to_cstring(curlopt_txt);
value = text_to_cstring(value_txt);
while (1)
{
http_curlopt *opt = settable_curlopts + i++;
if (!opt->curlopt_str) break;