-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclient-http.cxx
1458 lines (1242 loc) · 39.4 KB
/
client-http.cxx
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
// -*- C++ -*-
// Copyright (C) 2017, 2018 Red Hat Inc.
//
// This file is part of systemtap, and is free software. You can
// redistribute it and/or modify it under the terms of the GNU General
// Public License (GPL); either version 2, or (at your option) any
// later version.
#include "config.h"
#ifdef HAVE_HTTP_SUPPORT
#include "session.h"
#include "client-http.h"
#include "util.h"
#include "staptree.h"
#include "elaborate.h"
#include "nsscommon.h"
#include <iostream>
#include <sstream>
#include <fstream>
#include <map>
#include <vector>
extern "C" {
#include <string.h>
#include <curl/curl.h>
#include <curl/easy.h>
#include <json-c/json.h>
#include <sys/stat.h>
#include <rpm/rpmlib.h>
#include <rpm/header.h>
#include <rpm/rpmts.h>
#include <rpm/rpmdb.h>
#include <search.h>
#include <elfutils/libdwfl.h>
#include <elfutils/libdw.h>
#include <fcntl.h>
#include <nss3/nss.h>
}
using namespace std;
class http_client
{
public:
http_client (systemtap_session &s):
root(0),
s(s),
curl(0),
retry(0),
location(nullptr) { }
~http_client () {if (curl) curl_easy_cleanup(curl);
remove_file_or_dir (pem_cert_file.c_str());}
json_object *root;
std::map<std::string, std::string> header_values;
std::vector<std::tuple<std::string, std::string>> env_vars;
enum download_type {json_type, file_type};
std::string pem_cert_file;
std::string host;
enum cert_type {signer_trust, ssl_trust};
bool download (const std::string & url, enum download_type type, bool report_errors);
bool download_pem_cert (const std::string & url, std::string & certs);
bool post (const string & url, vector<tuple<string, string>> & request_parameters);
void add_file (std::string filename);
void add_module (std::string module);
void get_header_field (const std::string & data, const std::string & field);
static size_t get_data_shim (void *ptr, size_t size, size_t nitems, void *client);
static size_t get_file (void *ptr, size_t size, size_t nitems, FILE * stream);
static size_t get_header_shim (void *ptr, size_t size, size_t nitems, void *client);
std::string get_rpmname (std::string & pathname);
void get_buildid (string fname);
void get_kernel_buildid (void);
long get_response_code (void);
bool add_server_cert_to_client (std::string & tmpdir, bool init_db);
static int trace (CURL *, curl_infotype type, unsigned char *data, size_t size, void *);
bool delete_op (const std::string & url);
bool check_trust (enum cert_type, vector<compile_server_info> &specified_servers);
private:
size_t get_header (void *ptr, size_t size, size_t nitems);
size_t get_data (void *ptr, size_t size, size_t nitems);
static int process_buildid_shim (Dwfl_Module *dwflmod, void **userdata, const char *name,
Dwarf_Addr base, void *client);
int process_buildid (Dwfl_Module *dwflmod);
std::vector<std::string> files;
std::vector<std::string> modules;
std::vector<std::tuple<std::string, std::string>> buildids;
systemtap_session &s;
CURL *curl;
int retry;
std::string *location;
std::string buildid;
};
// TODO is there a better way than making this static?
static http_client *http;
size_t
http_client::get_data_shim (void *ptr, size_t size, size_t nitems, void *client)
{
http_client *http = static_cast<http_client *>(client);
return http->get_data (ptr, size, nitems);
}
// Parse the json data at PTR having SIZE and NITEMS into root
size_t
http_client::get_data (void *ptr, size_t size, size_t nitems)
{
string data ((const char *) ptr, (size_t) size * nitems);
// Process the JSON data.
if (data.front () == '{')
{
enum json_tokener_error json_error;
root = json_tokener_parse_verbose (data.c_str(), &json_error);
if (root == NULL)
throw SEMANTIC_ERROR (json_tokener_error_desc (json_error));
}
else
{
clog << "Malformed JSON data: '" << data << "'" << endl;
}
return size * nitems;
}
size_t
http_client::get_header_shim (void *ptr, size_t size, size_t nitems, void *client)
{
http_client *http = static_cast<http_client *>(client);
return http->get_header (ptr, size, nitems);
}
// Extract header values at PTR having SIZE and NITEMS into header_values
size_t
http_client::get_header (void *ptr, size_t size, size_t nitems)
{
string data ((const char *) ptr, (size_t) size * nitems);
unsigned long colon = data.find(':');
if (colon != string::npos)
{
string key = data.substr (0, colon);
string value = data.substr (colon + 2, data.length() - colon - 4);
header_values[key] = value;
}
return size * nitems;
}
// Put the data, e.g. <module>.ko at PTR having SIZE and NITEMS into STREAM
size_t
http_client::get_file (void *ptr, size_t size, size_t nitems, std::FILE * stream)
{
size_t written;
written = fwrite (ptr, size, nitems, stream);
std::fflush (stream);
return written;
}
// Trace sent and received packets
int
http_client::trace(CURL *, curl_infotype type, unsigned char *data, size_t size, void *)
{
string text;
switch(type)
{
case CURLINFO_TEXT:
clog << "== Info: " << data;
return 0;
case CURLINFO_HEADER_OUT:
text = "=> Send header";
break;
case CURLINFO_DATA_OUT:
text = "=> Send data";
break;
case CURLINFO_HEADER_IN:
text = "<= Recv header";
break;
case CURLINFO_DATA_IN:
text = "<= Recv data";
break;
default:
return 0;
}
size_t i;
size_t c;
const unsigned int width = 64;
// Packet contents exceeding this size are probably downloaded file components
const unsigned int max_size = 0x2000;
clog << text << " " << size << " bytes (" << showbase << hex << size << ")" << dec << noshowbase << endl;
if (size > max_size)
return 0;
for (i = 0; i < size; i += width)
{
clog << setw(4) << setfill('0') << hex << i << dec << setfill(' ') << ": ";
for (c = 0; (c < width) && (i + c < size); c++)
{
if ((i + c + 1 < size) && data[i + c] == '\r' && data[i + c + 1] == '\n')
{
i += (c + 2 - width);
break;
}
clog << (char)(isprint (data[i + c]) ? data[i + c] : '.');
if ((i + c + 2 < size) && data[i + c + 1] == '\r' && data[i + c + 2] == '\n')
{
i += (c + 3 - width);
break;
}
}
clog << endl;
}
return 0;
}
static size_t
null_writefunction (void *ptr, size_t size, size_t nmemb, void *stream)
{
(void)stream;
(void)ptr;
return size * nmemb;
}
// Read the certificate bundle corresponding to 'url into 'certs'
bool
http_client::download_pem_cert (const std::string & url, string & certs)
{
CURL *dpc_curl;
CURLcode res;
bool have_certs = false;
struct curl_certinfo *certinfo;
// Get the certificate info for the url
curl_global_init (CURL_GLOBAL_DEFAULT);
dpc_curl = curl_easy_init ();
curl_easy_setopt(dpc_curl, CURLOPT_URL, url.c_str());
curl_easy_setopt(dpc_curl, CURLOPT_WRITEFUNCTION, null_writefunction);
curl_easy_setopt(dpc_curl, CURLOPT_SSL_VERIFYPEER, 0L);
curl_easy_setopt(dpc_curl, CURLOPT_SSL_VERIFYHOST, 0L);
curl_easy_setopt(dpc_curl, CURLOPT_VERBOSE, 0L);
curl_easy_setopt(dpc_curl, CURLOPT_CERTINFO, 1L);
res = curl_easy_perform (dpc_curl);
if (res)
return false;
res = curl_easy_getinfo (dpc_curl, CURLINFO_CERTINFO, &certinfo);
// Create a certificate bundle from the certificate info
if (!res && certinfo)
{
for (int i = 0; i < certinfo->num_of_certs; i++)
{
struct curl_slist *slist;
for (slist = certinfo->certinfo[i]; slist; slist = slist->next)
{
string one_cert;
string slist_data = string (slist->data);
size_t cert_begin, cert_end;
if ((cert_begin = slist_data.find("-----BEGIN CERTIFICATE-----")) == string::npos)
continue;
if ((cert_end = slist_data.find("-----END CERTIFICATE-----", cert_begin)) == string::npos)
continue;
certs += string (slist_data.substr(cert_begin, cert_end - cert_begin + 28));
have_certs = true;
}
}
}
if (s.verbose >= 2)
clog << "Server returned certificate chain with: " << certinfo->num_of_certs << " members" << endl;
curl_easy_cleanup(dpc_curl);
curl_global_cleanup();
return have_certs;
}
bool
http_client::download (const std::string & url, http_client::download_type type, bool report_errors)
{
struct curl_slist *headers = NULL;
if (curl)
curl_easy_reset (curl);
curl = curl_easy_init ();
curl_global_init (CURL_GLOBAL_ALL);
if (s.verbose > 2)
{
curl_easy_setopt (curl, CURLOPT_VERBOSE, 1L);
curl_easy_setopt (curl, CURLOPT_DEBUGFUNCTION, trace);
}
curl_easy_setopt (curl, CURLOPT_URL, url.c_str ());
curl_easy_setopt (curl, CURLOPT_NOSIGNAL, 1); //Prevent "longjmp causes uninitialized stack frame" bug
curl_easy_setopt (curl, CURLOPT_ACCEPT_ENCODING, "deflate");
headers = curl_slist_append (headers, "Accept: */*");
headers = curl_slist_append (headers, "Content-Type: text/html");
curl_easy_setopt (curl, CURLOPT_HTTPHEADER, headers);
curl_easy_setopt (curl, CURLOPT_HTTPGET, 1);
curl_easy_setopt (curl, CURLOPT_SSLCERTTYPE, "PEM");
curl_easy_setopt (curl, CURLOPT_SSL_VERIFYPEER, 1L);
// Enabling verifyhost causes a mismatch between "hostname" in the
// server cert db and "hostname.domain" given as the client url
curl_easy_setopt (curl, CURLOPT_SSL_VERIFYHOST, 0L);
curl_easy_setopt (curl, CURLOPT_CAINFO, pem_cert_file.c_str());
if (type == json_type)
{
curl_easy_setopt (curl, CURLOPT_WRITEDATA, http);
curl_easy_setopt (curl, CURLOPT_WRITEFUNCTION,
http_client::get_data_shim);
}
else if (type == file_type)
{
std::string filename = url;
std::string filepath;
if (filename.back() == '/')
filename.erase(filename.length()-1);
filepath = s.tmpdir + "/" + filename.substr (filename.rfind ('/')+1);
if (s.verbose >= 3)
clog << "Downloaded " + filepath << endl;
std::FILE *File = std::fopen (filepath.c_str(), "wb");
curl_easy_setopt (curl, CURLOPT_WRITEDATA, File);
curl_easy_setopt (curl, CURLOPT_WRITEFUNCTION, http_client::get_file);
}
curl_easy_setopt (curl, CURLOPT_HEADERDATA, http);
curl_easy_setopt (curl, CURLOPT_HEADERFUNCTION, http_client::get_header_shim);
CURLcode res = curl_easy_perform (curl);
if (res != CURLE_OK && res != CURLE_GOT_NOTHING)
{
if (report_errors)
clog << "curl_easy_perform() failed: " << curl_easy_strerror (res) << endl;
return false;
}
else
return true;
}
// Get the rpm corresponding to SEARCH_FILE
std::string
http_client::get_rpmname (std::string &search_file)
{
rpmts ts = NULL;
Header hdr;
rpmdbMatchIterator mi;
rpmtd td;
td = rpmtdNew ();
ts = rpmtsCreate ();
rpmReadConfigFiles (NULL, NULL);
int metrics[] =
{ RPMTAG_NAME, RPMTAG_EVR, RPMTAG_ARCH, RPMTAG_FILENAMES, };
struct
{
string name;
string evr;
string arch;
} rpmhdr;
bool found = false;
mi = rpmtsInitIterator (ts, RPMDBI_PACKAGES, NULL, 0);
while (NULL != (hdr = rpmdbNextIterator (mi)))
{
hdr = headerLink(hdr);
for (unsigned int i = 0; i < (sizeof (metrics) / sizeof (int)); i++)
{
headerGet (hdr, metrics[i], td, HEADERGET_EXT);
switch (td->type)
{
case RPM_STRING_TYPE:
{
const char *rpmval = rpmtdGetString (td);
switch (metrics[i])
{
case RPMTAG_NAME:
rpmhdr.name = rpmval;
break;
case RPMTAG_EVR:
rpmhdr.evr = rpmval;
break;
case RPMTAG_ARCH:
rpmhdr.arch = rpmval;
break;
}
break;
}
case RPM_STRING_ARRAY_TYPE:
while (rpmtdNext(td) >= 0)
{
const char *rpmval = rpmtdGetString (td);
if (strcmp (rpmval, search_file.c_str()) == 0)
{
found = true;
break;
}
}
break;
}
rpmtdFreeData (td);
rpmtdReset (td);
}
headerFree (hdr);
if (found)
break;
}
rpmdbFreeIterator (mi);
rpmtsFree (ts);
rpmtdFree (td);
if (found)
{
return rpmhdr.name + "-" + rpmhdr.evr + "." + rpmhdr.arch;
}
// There wasn't an rpm that contains SEARCH_FILE. Return the empty
// string.
return "";
}
// Put the buildid for DWFLMOD into buildids
int
http_client::process_buildid (Dwfl_Module *dwflmod)
{
const char *fname;
dwfl_module_info (dwflmod, NULL, NULL, NULL, NULL, NULL, &fname, NULL);
GElf_Addr bias;
int build_id_len = 0;
unsigned char *build_id_bits;
GElf_Addr build_id_vaddr;
string build_id;
char *result = NULL;
int code;
dwfl_module_getelf (dwflmod, &bias);
build_id_len = dwfl_module_build_id (dwflmod,
(const unsigned char **)&build_id_bits,
&build_id_vaddr);
for (int i = 0; i < build_id_len; i++)
{
if (result)
code = asprintf (&result, "%s%02x", result, *(build_id_bits+i));
else
code = asprintf (&result, "%02x", *(build_id_bits+i));
if (code < 0)
return 1;
}
http->buildids.push_back(make_tuple(fname, result));
return DWARF_CB_OK;
}
int
http_client::process_buildid_shim (Dwfl_Module *dwflmod,
void **userdata __attribute__ ((unused)),
const char *name __attribute__ ((unused)),
Dwarf_Addr base __attribute__ ((unused)),
void *client)
{
http_client *http = static_cast<http_client *>(client);
return http->process_buildid (dwflmod);
}
// Do the setup for getting the buildid for FNAME
void
http_client::get_buildid (string fname)
{
int fd;
if ((fd = open (fname.c_str(), O_RDONLY)) < 0)
{
clog << "can't open " << fname;
return;
}
static const Dwfl_Callbacks callbacks =
{
dwfl_build_id_find_elf,
dwfl_standard_find_debuginfo,
dwfl_offline_section_address,
NULL
};
Dwfl *dwfl = dwfl_begin (&callbacks);
if (dwfl == NULL)
return;
if (dwfl_report_offline (dwfl, fname.c_str(), fname.c_str(), fd) == NULL)
return;
else
{
dwfl_report_end (dwfl, NULL, NULL);
dwfl_getmodules (dwfl, process_buildid_shim, http, 0);
}
dwfl_end (dwfl);
close (fd);
}
void
http_client::get_kernel_buildid (void)
{
const char *notesfile = "/sys/kernel/notes";
int fd = open (notesfile, O_RDONLY);
if (fd < 0)
return;
union
{
GElf_Nhdr nhdr;
unsigned char data[8192];
} buf;
ssize_t n = read (fd, buf.data, sizeof buf);
close (fd);
if (n <= 0)
return;
unsigned char *p = buf.data;
while (p < &buf.data[n])
{
/* No translation required since we are reading the native kernel. */
GElf_Nhdr *nhdr = (GElf_Nhdr *) p;
p += sizeof *nhdr;
unsigned char *name = p;
p += (nhdr->n_namesz + 3) & -4U;
unsigned char *bits = p;
p += (nhdr->n_descsz + 3) & -4U;
if (p <= &buf.data[n]
&& nhdr->n_type == NT_GNU_BUILD_ID
&& nhdr->n_namesz == sizeof "GNU"
&& !memcmp (name, "GNU", sizeof "GNU"))
{
char *result = NULL;
int code;
for (unsigned int i = 0; i < nhdr->n_descsz; i++)
{
if (result)
code = asprintf (&result, "%s%02x", result, *(bits+i));
else
code = asprintf (&result, "%02x", *(bits+i));
if (code < 0)
return;
}
http->buildids.push_back(make_tuple("kernel", result));
break;
}
}
}
long
http_client::get_response_code (void)
{
long response_code = 0;
curl_easy_getinfo (curl, CURLINFO_RESPONSE_CODE, &response_code);
return response_code;
}
// Post REQUEST_PARAMETERS, files, modules, buildids to URL
bool
http_client::post (const string & url,
vector<tuple<string, string>> & request_parameters)
{
struct curl_slist *headers = NULL;
int still_running = false;
struct curl_httppost *formpost = NULL;
struct curl_httppost *lastptr = NULL;
struct json_object *jobj = json_object_new_object();
// Add parameter info
// "cmd_args": ["script\/\/path\/linetimes.stp","-v","-v",
// "-c\/path\/bench.x","--","process(\"\/path\/bench.x\")","main"]
string previous_parm_type;
string previous_json_data;
auto it = request_parameters.begin ();
while (it != request_parameters.end ())
{
string parm_type = get<0>(*it);
string parm_data = get<1>(*it);
struct json_object *json_data = json_object_new_string(parm_data.c_str());
if (parm_type == previous_parm_type)
{
// convert original singleton to an array
struct json_object *jarr = json_object_new_array();
json_data = json_object_new_string(previous_json_data.c_str());
json_object_array_add(jarr, json_data);
while (parm_type == previous_parm_type)
{
json_data = json_object_new_string(parm_data.c_str());
json_object_array_add(jarr, json_data);
previous_parm_type = parm_type;
previous_json_data = parm_data;
it++;
parm_type = get<0>(*it);
parm_data = get<1>(*it);
}
json_object_object_add(jobj, previous_parm_type.c_str(), jarr);
continue;
}
else
json_object_object_add(jobj, parm_type.c_str(), json_data);
previous_parm_type = parm_type;
previous_json_data = parm_data;
it++;
}
// Fill in the file upload field; libcurl will load data from the
// given file name.
for (auto it = files.begin (); it != files.end (); ++it)
{
string filename = (*it);
string filebase = basename (filename.c_str());
curl_formadd (&formpost, &lastptr,
CURLFORM_COPYNAME, filebase.c_str(),
CURLFORM_FILE, filename.c_str(),
CURLFORM_END);
curl_formadd (&formpost, &lastptr,
CURLFORM_COPYNAME, "files",
CURLFORM_COPYCONTENTS, filename.c_str(),
CURLFORM_END);
}
// Add package info
// "file_info": [ { "file_pkg": "kernel-4.14.0-0.rc4.git4.1.fc28.x86_64",
// "file_name": "kernel",
// "build_id": "ef7210ee3a447c798c3548102b82665f03ef241f" },
// { "file_pkg": "foo-1.1.x86_64",
// "file_name": "/usr/bin/foo",
// "build_id": "deadbeef" }
// ]
int bid_idx = 0;
struct json_object *jarr = json_object_new_array();
for (auto it = modules.begin (); it != modules.end (); ++it, ++bid_idx)
{
struct json_object *jfobj = json_object_new_object();
string pkg = (*it);
string name = std::get<0>(buildids[bid_idx]);
string build_id = std::get<1>(buildids[bid_idx]);
json_object_object_add (jfobj, "file_name", json_object_new_string (name.c_str()));
json_object_object_add (jfobj, "file_pkg", json_object_new_string (pkg.c_str()));
json_object_object_add (jfobj, "build_id", json_object_new_string (build_id.c_str()));
json_object_array_add (jarr, jfobj);
}
json_object_object_add(jobj, "file_info", jarr);
// Add environment variables info
// "env_vars": {"LANG":"en_US.UTF-8","LC_MESSAGES":"en_US.UTF-8"}
if (! http->env_vars.empty())
{
struct json_object *jlvobj = json_object_new_object();
for (auto i = http->env_vars.begin();
i != http->env_vars.end();
++i)
{
string name = get<0>(*i);
string value = get<1>(*i);
json_object_object_add (jlvobj, name.c_str(), json_object_new_string(value.c_str()));
}
if (http->env_vars.size())
json_object_object_add (jobj, "env_vars", jlvobj);
}
curl_formadd (&formpost, &lastptr,
CURLFORM_COPYNAME, "command_environment",
CURLFORM_CONTENTTYPE, "application/json",
CURLFORM_COPYCONTENTS,
json_object_to_json_string_ext (jobj, JSON_C_TO_STRING_PLAIN),
CURLFORM_END);
json_object_put(jobj);
headers = curl_slist_append (headers, "Expect:");
curl_easy_setopt (curl, CURLOPT_URL, url.c_str());
curl_easy_setopt (curl, CURLOPT_HTTPHEADER, headers);
curl_easy_setopt (curl, CURLOPT_HTTPPOST, formpost);
CURLM *multi_handle = curl_multi_init();
curl_multi_add_handle (multi_handle, curl);
curl_multi_perform (multi_handle, &still_running);
do {
struct timeval timeout;
int rc; // select() return code
CURLMcode mc; // curl_multi_fdset() return code
fd_set fdread;
fd_set fdwrite;
fd_set fdexcep;
int maxfd = -1;
long curl_timeo = -1;
FD_ZERO (&fdread);
FD_ZERO (&fdwrite);
FD_ZERO (&fdexcep);
// set a suitable timeout to play around with
timeout.tv_sec = 1;
timeout.tv_usec = 0;
curl_multi_timeout (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
mc = curl_multi_fdset (multi_handle, &fdread, &fdwrite, &fdexcep, &maxfd);
if (mc != CURLM_OK)
{
clog << "curl_multi_fdset() failed" << curl_multi_strerror (mc) << endl;
return false;
}
/* On success the value of maxfd is guaranteed to be >= -1. We call
select(maxfd + 1, ...); specially in case of (maxfd == -1) there are
no fds ready yet so we call select(0, ...)to sleep 100ms,
the minimum suggested value */
if (maxfd == -1)
{
struct timeval wait = { 0, 100 * 1000 }; // 100ms
rc = select (0, NULL, NULL, NULL, &wait);
}
else
rc = select (maxfd+1, &fdread, &fdwrite, &fdexcep, &timeout);
switch (rc)
{
case -1:
/* select error */
break;
case 0:
default:
curl_multi_perform (multi_handle, &still_running);
break;
}
} while (still_running);
curl_multi_cleanup (multi_handle);
curl_formfree (formpost);
curl_slist_free_all (headers);
return true;
}
// Add FILE to files
void
http_client::add_file (std::string filename)
{
files.push_back (filename);
}
// Add MODULE to modules
void
http_client::add_module (std::string module)
{
modules.push_back (module);
}
// Add the server certificate to the client certificate database
bool
http_client::add_server_cert_to_client (string &tmpdir, bool init_db)
{
const char *certificate;
json_object *cert_obj;
// Get the certificate returned by the server
if (json_object_object_get_ex (root, "certificate", &cert_obj))
certificate = json_object_get_string(cert_obj);
else
return false;
string pem_tmp = tmpdir + "pemXXXXXX";
int fd = mkstemp ((char*)pem_tmp.c_str());
close(fd);
std::ofstream pem_out(pem_tmp);
pem_out << certificate;
pem_out.close();
// Add the certificate to the client nss certificate database
if (add_client_cert(pem_tmp, local_client_cert_db_path(), init_db) == SECSuccess)
{
remove_file_or_dir (pem_tmp.c_str());
return true;
}
return false;
}
// Ask the server to delete a URL.
bool
http_client::delete_op (const std::string & url)
{
if (curl)
curl_easy_reset (curl);
curl = curl_easy_init ();
curl_global_init (CURL_GLOBAL_ALL);
if (s.verbose > 2)
{
curl_easy_setopt (curl, CURLOPT_VERBOSE, 1L);
curl_easy_setopt (curl, CURLOPT_DEBUGFUNCTION, trace);
}
curl_easy_setopt (curl, CURLOPT_URL, url.c_str ());
curl_easy_setopt (curl, CURLOPT_NOSIGNAL, 1); //Prevent "longjmp causes uninitialized stack frame" bug
curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, "DELETE");
CURLcode res = curl_easy_perform (curl);
if (res != CURLE_OK)
{
clog << "curl_easy_perform() failed: " << curl_easy_strerror (res)
<< endl;
return false;
}
return true;
}
// Can a certificate having trust 'this_cert_trust' be handled by the corresponding host
bool
http_client::check_trust (enum cert_type this_cert_type, vector<compile_server_info> &specified_servers)
{
vector<compile_server_info> server_list;
string cert_db_path;
string cert_string;
if (this_cert_type == signer_trust)
{
cert_db_path = signing_cert_db_path ();
cert_string = "signing";
}
else if (this_cert_type == ssl_trust)
{
cert_db_path = local_client_cert_db_path ();
cert_string = "trusted";
}
get_server_info_from_db (s, server_list, cert_db_path);
vector<compile_server_info>::iterator i = specified_servers.begin ();
while (i != specified_servers.end ())
{
bool have_match = false;
for (vector<compile_server_info>::const_iterator j = server_list.begin ();
j != server_list.end ();
++j)
{
if (j->host_name == i->host_name
|| j->host_name == i->unresolved_host_name.substr(0,j->host_name.length()))
{
have_match = true;
break;
}
}
if (!have_match)
i = specified_servers.erase (i);
else
++i;
}
if (specified_servers.size() == 0)
{
clog << "No matching " << cert_string << " server; the " << cert_string << " servers are\n" << server_list << endl;
return false;
}
else
return true;
}
http_client_backend::http_client_backend (systemtap_session &s)
: client_backend(s), files_seen(false)
{
server_tmpdir = s.tmpdir;
}
int
http_client_backend::initialize ()
{
if (!http)
http = new http_client (s);
request_parameters.clear();
return 0;
}
// Symbolically link the given file or directory into the client's temp
// directory under the given subdirectory.
//
// We need to do this even for the http client/server so that we can
// fully handle systemtap's complexity. A tricky example of this
// complexity would be something like "stap -I tapset_dir script.stp",
// where "tapset_dir" is empty. You can transfer files with a POST,
// but you can't really indicate an empty directory.
//
// So, we'll handle this like the NSS client does - build up a
// directory of all the files we need to transfer over to the server
// and zip it up and send the one zip file.
int
http_client_backend::include_file_or_directory (const string &subdir,
const string &path,
const bool add_arg)
{
// Must predeclare these because we do use 'goto done' to
// exit from error situations.
vector<string> components;
string name;
int rc = 0;
// Canonicalize the given path and remove the leading /.
string rpath;
char *cpath = canonicalize_file_name (path.c_str ());
if (! cpath)
{
// It can not be canonicalized. Use the name relative to
// the current working directory and let the server deal with it.
char cwd[PATH_MAX];
if (getcwd (cwd, sizeof (cwd)) == NULL)
{
rpath = path;
rc = 1;
goto done;
}
rpath = string (cwd) + "/" + path;
}
else
{