forked from MattNapsAlot/webstor
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwsconn.cpp
More file actions
3586 lines (2827 loc) · 103 KB
/
wsconn.cpp
File metadata and controls
3586 lines (2827 loc) · 103 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2011-2012, OblakSoft LLC.
//
// Licensed 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.
//
//
// Authors: Maxim Mazeev <mazeev@hotmail.com>
// Artem Livshits <artem.livshits@gmail.com>
//////////////////////////////////////////////////////////////////////////////
// WebStor connection.
//////////////////////////////////////////////////////////////////////////////
#include "wsconn.h"
#include "sysutils.h"
#define NOMINMAX
#include <curl/curl.h>
#include <libxml/parser.h>
#include <openssl/err.h>
#include <openssl/hmac.h>
#include <openssl/ssl.h>
#include <algorithm>
#include <memory>
namespace webstor
{
using namespace internal;
//////////////////////////////////////////////////////////////////////////////
// WebStor errors.
const static char errUnexpected[] = "Unexpected error." ;
const static char errCurl[] = "%s.";
const static char errHTTP[] = "%s.";
const static char errHTTPResourceNotFound[] = "HTTP resource not found: %s.";
const static char errParser[] = "Cannot parse the response.";
const static char errWsDetail[] = "%s (Code='%s', RequestId='%s').";
const static char errOpSummary[] = "The '%s' operation for '%s' failed. %s";
const static char errTooManyConnetions[] = "Too many connections passed to waitAny method.";
//////////////////////////////////////////////////////////////////////////////
// WebStor statics.
static const char s_defaultS3Host[] = "s3.amazonaws.com";
static const char s_defaultGcsHost[] = "commondatastorage.googleapis.com";
static const char s_defaultWalrusPort[] = "8773";
static const char s_CACertIgnore[] = "none";
static const char s_contentTypeBinary[] = "application/octet-stream";
static const char s_contentTypeXml[] = "application/xml";
// Default timeouts.
// We need default timeouts, otherwise WsConnection may stuck forever if cable is unplugged or
// anything else happens stopping any activity on socket(s).
static const UInt32 s_defaultTimeout = 120 * 1000; // 2 mins
static const UInt32 s_defaultConnectTimeout = 30 * 1000; // 30 secs
// Enable TCP KeepAlive to let TCP stack send keepalive probes
// when transfer is idle. This allows detecting connection issues faster.
static const TcpKeepAliveParams s_tcpKeepAliveProbes =
{
// The following parameters should allow detecting connection issues within 20 secs:
// probeStartTime + probeIntervalTime * probeCount
5 * 1000, // 5 sec, how long to stay in idle before sending keepalive probe, in milliseconds
5 * 1000, // 5 sec, delay between TCP keepalive probes, in milliseconds
3 // 3, the number of unacknowledged probes to send before considering the connection dead
// The latter is not supported on Windows. See webstor::internal::setTcpKeepAlive(..).
};
// Maximum socket send/receive buffer size.
// This gives us: throughput = window_size / RTT = 1MB / 100 ms = 10 MB/s on one connection
// Note: On Linux, the kernel doubles this value for internal bookkeeping overhead.
// Note: the OS may limit the buffer size according to the system-wide settings. To
// take advantage of high-bandwidth & high-latency network, the receive buffer size
// must be large enough to support large TCP window sizes. The default max value on
// Linux (as of 2012/09/15) is 128 KB, which is too small. The value is controlled
// by /proc/sys/net/core/rmem_max which should be set to at least 2 MB.
static const UInt32 s_socketBufferSize = 1024 * 1024; // 1MB
//////////////////////////////////////////////////////////////////////////////
// String conversion functions.
#ifdef _WIN32
static inline Int64 atoll( const char *s ) { return _atoi64(s); }
#endif
static const char *uitoa( unsigned int val, char *buf )
{
char *p = buf;
do
{
*p++ = '0' + val % 10;
val /= 10;
} while( val > 0 );
*p = '\0';
p--;
// Swap.
for( char *p1 = buf; p1 < p; ++p1, --p )
{
char tmp = *p;
*p = *p1;
*p1 = tmp;
}
return buf;
}
//////////////////////////////////////////////////////////////////////////////
// Default SSL certificates.
static const char
**getDefaultCACerts()
{
// AWS SSL Server Certificates have been issued by several CAs
// depending on AWS region. E.g. standard US is issued by
// "VeriSign Class 3 Secure Server CA - G2".
// This and other certificates are hardcoded here.
// The certificate chain used by AWS can be verified using the following
// command:
// openssl s_client -connect <region-specific-url>:443,
// example:
// openssl s_client -connect s3.amazonaws.com:443
static const char *s_certs[] =
{
// Verisign Class 3 Public Primary Certification Authority - G2.
// * US Standard (s3.amazonaws.com:443)
"-----BEGIN CERTIFICATE-----\n"
"MIIDAjCCAmsCEH3Z/gfPqB63EHln+6eJNMYwDQYJKoZIhvcNAQEFBQAwgcExCzAJBgNVBAYTAlVT\n"
"MRcwFQYDVQQKEw5WZXJpU2lnbiwgSW5jLjE8MDoGA1UECxMzQ2xhc3MgMyBQdWJsaWMgUHJpbWFy\n"
"eSBDZXJ0aWZpY2F0aW9uIEF1dGhvcml0eSAtIEcyMTowOAYDVQQLEzEoYykgMTk5OCBWZXJpU2ln\n"
"biwgSW5jLiAtIEZvciBhdXRob3JpemVkIHVzZSBvbmx5MR8wHQYDVQQLExZWZXJpU2lnbiBUcnVz\n"
"dCBOZXR3b3JrMB4XDTk4MDUxODAwMDAwMFoXDTI4MDgwMTIzNTk1OVowgcExCzAJBgNVBAYTAlVT\n"
"MRcwFQYDVQQKEw5WZXJpU2lnbiwgSW5jLjE8MDoGA1UECxMzQ2xhc3MgMyBQdWJsaWMgUHJpbWFy\n"
"eSBDZXJ0aWZpY2F0aW9uIEF1dGhvcml0eSAtIEcyMTowOAYDVQQLEzEoYykgMTk5OCBWZXJpU2ln\n"
"biwgSW5jLiAtIEZvciBhdXRob3JpemVkIHVzZSBvbmx5MR8wHQYDVQQLExZWZXJpU2lnbiBUcnVz\n"
"dCBOZXR3b3JrMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDMXtERXVxp0KvTuWpMmR9ZmDCO\n"
"FoUgRm1HP9SFIIThbbP4pO0M8RcPO/mn+SXXwc+EY/J8Y8+iR/LGWzOOZEAEaMGAuWQcRXfH2G71\n"
"lSk8UOg013gfqLptQ5GVj0VXXn7F+8qkBOvqlzdUMG+7AUcyM83cV5tkaWH4mx0ciU9cZwIDAQAB\n"
"MA0GCSqGSIb3DQEBBQUAA4GBAFFNzb5cy5gZnBWyATl4Lk0PZ3BwmcYQWpSkU01UbSuvDV1Ai2TT\n"
"1+7eVmGSX6bEHRBhNtMsJzzoKQm5EWR0zLVznxxIqbxhAe7iF6YM40AIOw7n60RzKprxaZLvcRTD\n"
"Oaxxp5EJb+RxBrO6WVcmeQD2+A2iMzAo1KpYoJ2daZH9\n"
"-----END CERTIFICATE-----\n",
// Entrust.net Secure Server CA
// * US West-1 N. California (s3-us-west-2.amazonaws.com)
// * US West-2 Oregon (s3-us-west-1.amazonaws.com)
"-----BEGIN CERTIFICATE-----\n"
"MIIE2DCCBEGgAwIBAgIEN0rSQzANBgkqhkiG9w0BAQUFADCBwzELMAkGA1UEBhMCVVMxFDASBgNV\n"
"BAoTC0VudHJ1c3QubmV0MTswOQYDVQQLEzJ3d3cuZW50cnVzdC5uZXQvQ1BTIGluY29ycC4gYnkg\n"
"cmVmLiAobGltaXRzIGxpYWIuKTElMCMGA1UECxMcKGMpIDE5OTkgRW50cnVzdC5uZXQgTGltaXRl\n"
"ZDE6MDgGA1UEAxMxRW50cnVzdC5uZXQgU2VjdXJlIFNlcnZlciBDZXJ0aWZpY2F0aW9uIEF1dGhv\n"
"cml0eTAeFw05OTA1MjUxNjA5NDBaFw0xOTA1MjUxNjM5NDBaMIHDMQswCQYDVQQGEwJVUzEUMBIG\n"
"A1UEChMLRW50cnVzdC5uZXQxOzA5BgNVBAsTMnd3dy5lbnRydXN0Lm5ldC9DUFMgaW5jb3JwLiBi\n"
"eSByZWYuIChsaW1pdHMgbGlhYi4pMSUwIwYDVQQLExwoYykgMTk5OSBFbnRydXN0Lm5ldCBMaW1p\n"
"dGVkMTowOAYDVQQDEzFFbnRydXN0Lm5ldCBTZWN1cmUgU2VydmVyIENlcnRpZmljYXRpb24gQXV0\n"
"aG9yaXR5MIGdMA0GCSqGSIb3DQEBAQUAA4GLADCBhwKBgQDNKIM0VBuJ8w+vN5Ex/68xYMmo6LIQ\n"
"aO2f55M28Qpku0f1BBc/I0dNxScZgSYMVHINiC3ZH5oSn7yzcdOAGT9HZnuMNSjSuQrfJNqc1lB5\n"
"gXpa0zf3wkrYKZImZNHkmGw6AIr1NJtl+O3jEP/9uElY3KDegjlrgbEWGWG5VLbmQwIBA6OCAdcw\n"
"ggHTMBEGCWCGSAGG+EIBAQQEAwIABzCCARkGA1UdHwSCARAwggEMMIHeoIHboIHYpIHVMIHSMQsw\n"
"CQYDVQQGEwJVUzEUMBIGA1UEChMLRW50cnVzdC5uZXQxOzA5BgNVBAsTMnd3dy5lbnRydXN0Lm5l\n"
"dC9DUFMgaW5jb3JwLiBieSByZWYuIChsaW1pdHMgbGlhYi4pMSUwIwYDVQQLExwoYykgMTk5OSBF\n"
"bnRydXN0Lm5ldCBMaW1pdGVkMTowOAYDVQQDEzFFbnRydXN0Lm5ldCBTZWN1cmUgU2VydmVyIENl\n"
"cnRpZmljYXRpb24gQXV0aG9yaXR5MQ0wCwYDVQQDEwRDUkwxMCmgJ6AlhiNodHRwOi8vd3d3LmVu\n"
"dHJ1c3QubmV0L0NSTC9uZXQxLmNybDArBgNVHRAEJDAigA8xOTk5MDUyNTE2MDk0MFqBDzIwMTkw\n"
"NTI1MTYwOTQwWjALBgNVHQ8EBAMCAQYwHwYDVR0jBBgwFoAU8BdiE1U9s/8KAGv7UISX8+1i0Bow\n"
"HQYDVR0OBBYEFPAXYhNVPbP/CgBr+1CEl/PtYtAaMAwGA1UdEwQFMAMBAf8wGQYJKoZIhvZ9B0EA\n"
"BAwwChsEVjQuMAMCBJAwDQYJKoZIhvcNAQEFBQADgYEAkNwwAvpkdMKnCqV8IY00F6j7Rw7/JXyN\n"
"Ewr75Ji174z4xRAN95K+8cPV1ZVqBLssziY2ZcgxxufuP+NXdYR6Ee9GTxj005i7qIcyunL2POI9\n"
"n9cd2cNgQ4xYDiKWL2KjLB+6rQXvqzJ4h6BUcxm1XAX5Uj5tLUUL9wqT6u0G+bI=\n"
"-----END CERTIFICATE-----\n",
// DigiCert High Assurance EV Root CA
// * EU Ireland (s3-eu-west-1.amazonaws.com)
// * Asia Pacific Singapore (s3-ap-southeast-1.amazonaws.com)
// * Asia Pacific Tokyo (s3-ap-northeast-1.amazonaws.com)
// * South America (Sao Paulo) Region (s3-sa-east-1.amazonaws.com)
"-----BEGIN CERTIFICATE-----\n"
"MIIDxTCCAq2gAwIBAgIQAqxcJmoLQJuPC3nyrkYldzANBgkqhkiG9w0BAQUFADBsMQswCQYDVQQG\n"
"EwJVUzEVMBMGA1UEChMMRGlnaUNlcnQgSW5jMRkwFwYDVQQLExB3d3cuZGlnaWNlcnQuY29tMSsw\n"
"KQYDVQQDEyJEaWdpQ2VydCBIaWdoIEFzc3VyYW5jZSBFViBSb290IENBMB4XDTA2MTExMDAwMDAw\n"
"MFoXDTMxMTExMDAwMDAwMFowbDELMAkGA1UEBhMCVVMxFTATBgNVBAoTDERpZ2lDZXJ0IEluYzEZ\n"
"MBcGA1UECxMQd3d3LmRpZ2ljZXJ0LmNvbTErMCkGA1UEAxMiRGlnaUNlcnQgSGlnaCBBc3N1cmFu\n"
"Y2UgRVYgUm9vdCBDQTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAMbM5XPm+9S75S0t\n"
"Mqbf5YE/yc0lSbZxKsPVlDRnogocsF9ppkCxxLeyj9CYpKlBWTrT3JTWPNt0OKRKzE0lgvdKpVMS\n"
"OO7zSW1xkX5jtqumX8OkhPhPYlG++MXs2ziS4wblCJEMxChBVfvLWokVfnHoNb9Ncgk9vjo4UFt3\n"
"MRuNs8ckRZqnrG0AFFoEt7oT61EKmEFBIk5lYYeBQVCmeVyJ3hlKV9Uu5l0cUyx+mM0aBhakaHPQ\n"
"NAQTXKFx01p8VdteZOE3hzBWBOURtCmAEvF5OYiiAhF8J2a3iLd48soKqDirCmTCv2ZdlYTBoSUe\n"
"h10aUAsgEsxBu24LUTi4S8sCAwEAAaNjMGEwDgYDVR0PAQH/BAQDAgGGMA8GA1UdEwEB/wQFMAMB\n"
"Af8wHQYDVR0OBBYEFLE+w2kD+L9HAdSYJhoIAu9jZCvDMB8GA1UdIwQYMBaAFLE+w2kD+L9HAdSY\n"
"JhoIAu9jZCvDMA0GCSqGSIb3DQEBBQUAA4IBAQAcGgaX3NecnzyIZgYIVyHbIUf4KmeqvxgydkAQ\n"
"V8GK83rZEWWONfqe/EW1ntlMMUu4kehDLI6zeM7b41N5cdblIZQB2lWHmiRk9opmzN6cN82oNLFp\n"
"myPInngiK3BD41VHMWEZ71jFhS9OMPagMRYjyOfiZRYzy78aG6A9+MpeizGLYAiJLQwGXFK3xPkK\n"
"mNEVX58Svnw2Yzi9RKR/5CYrCsSXaQ3pjOLAEFe4yHYSkVXySGnYvCoCWw9E1CAx2/S6cCZdkGCe\n"
"vEsXCS+0yx5DaMkHJ8HSXPfqIbloEpw8nL+e/IBcm2PN7EeqJSdnoDfzAIJ9VNep+OkuE6N36B9K\n"
"-----END CERTIFICATE-----",
// Equifax Secure CA
// * Google Cloud Storage (commondatastorage.googleapis.com)
"-----BEGIN CERTIFICATE-----\n"
"MIIDIDCCAomgAwIBAgIENd70zzANBgkqhkiG9w0BAQUFADBOMQswCQYDVQQGEwJVUzEQMA4GA1UE\n"
"ChMHRXF1aWZheDEtMCsGA1UECxMkRXF1aWZheCBTZWN1cmUgQ2VydGlmaWNhdGUgQXV0aG9yaXR5\n"
"MB4XDTk4MDgyMjE2NDE1MVoXDTE4MDgyMjE2NDE1MVowTjELMAkGA1UEBhMCVVMxEDAOBgNVBAoT\n"
"B0VxdWlmYXgxLTArBgNVBAsTJEVxdWlmYXggU2VjdXJlIENlcnRpZmljYXRlIEF1dGhvcml0eTCB\n"
"nzANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEAwV2xWGcIYu6gmi0fCG2RFGiYCh7+2gRvE4RiIcPR\n"
"fM6fBeC4AfBONOziipUEZKzxa1NfBbPLZ4C/QgKO/t0BCezhABRP/PvwDN1Dulsr4R+AcJkVV5MW\n"
"8Q+XarfCaCMczE1ZMKxRHjuvK9buY0V7xdlfUNLjUA86iOe/FP3gx7kCAwEAAaOCAQkwggEFMHAG\n"
"A1UdHwRpMGcwZaBjoGGkXzBdMQswCQYDVQQGEwJVUzEQMA4GA1UEChMHRXF1aWZheDEtMCsGA1UE\n"
"CxMkRXF1aWZheCBTZWN1cmUgQ2VydGlmaWNhdGUgQXV0aG9yaXR5MQ0wCwYDVQQDEwRDUkwxMBoG\n"
"A1UdEAQTMBGBDzIwMTgwODIyMTY0MTUxWjALBgNVHQ8EBAMCAQYwHwYDVR0jBBgwFoAUSOZo+SvS\n"
"spXXR9gjIBBPM5iQn9QwHQYDVR0OBBYEFEjmaPkr0rKV10fYIyAQTzOYkJ/UMAwGA1UdEwQFMAMB\n"
"Af8wGgYJKoZIhvZ9B0EABA0wCxsFVjMuMGMDAgbAMA0GCSqGSIb3DQEBBQUAA4GBAFjOKer89961\n"
"zgK5F7WF0bnj4JXMJTENAKaSbn+2kmOeUJXRmm/kEd5jhW6Y7qj/WsjTVbJmcVfewCHrPSqnI0kB\n"
"BIZCe/zuf6IWUrVnZ9NA2zsmWLIodz2uFHdh1voqZiegDfqnc1zqcPGUIWVEX/r87yloqaKHee95\n"
"70+sB3c4\n"
"-----END CERTIFICATE-----\n",
NULL
};
return s_certs;
}
struct BIODeleter
{
static void free( BIO *bio ){ dbgAssert( bio ); BIO_free_all( bio ); }
};
struct X509Deleter
{
static void free( X509 *cert ){ dbgAssert( cert ); X509_free( cert ); }
};
static CURLcode
addDefaultCACerts( CURL * curl, void * sslctx, void * parm ) // nofail
{
// Get X509 certificate store.
X509_STORE* store = SSL_CTX_get_cert_store( reinterpret_cast< SSL_CTX * >( sslctx ) );
for ( const char **p = getDefaultCACerts(); *p != NULL; ++p )
{
// Construct a BIO.
BIO* bio = BIO_new_mem_buf( ( void *)( *p ), -1 );
if( !bio )
{
return CURLE_OUT_OF_MEMORY;
}
auto_scope< BIO *, BIODeleter > scoped_bio( bio );
// Extract a certificate.
X509* cert = PEM_read_bio_X509( bio, NULL, 0, NULL );
if( !cert )
{
dbgPanicSz( "UNEXPECTED: Cannot read the default root certificate!!!" );
continue;
}
auto_scope< X509 *, X509Deleter > scoped_cert( cert );
// Add it to the store.
bool isAdded = X509_STORE_add_cert( store, cert );
unsigned long err = ERR_get_error();
if( !isAdded &&
!( ERR_GET_LIB( err ) == ERR_LIB_X509 &&
ERR_GET_REASON( err ) == X509_R_CERT_ALREADY_IN_HASH_TABLE ) )
{
dbgPanicSz( "UNEXPECTED: Cannot add the default root certificate!!!" );
continue;
}
}
return CURLE_OK;
}
//////////////////////////////////////////////////////////////////////////////
// Common utils.
static void
append64Encoded( std::string *encoded, const void *data, size_t size )
{
dbgAssert( implies( size, data ) );
dbgAssert( encoded );
if( !size )
{
return;
}
BIO* bio = BIO_new( BIO_s_mem() );
if( !bio )
{
throw std::bad_alloc();
}
auto_scope< BIO *, BIODeleter > scoped_bio( bio );
BIO* base64 = BIO_new( BIO_f_base64() );
if( !base64 )
{
throw std::bad_alloc();
}
BIO_set_flags( base64, BIO_FLAGS_BASE64_NO_NL );
dbgVerify( bio = BIO_push( base64, bio ) ); // scoped_bio will take care of freeing both bios (bio and base64).
dbgVerify( BIO_write( bio, data, size ) > 0 );
dbgVerify( BIO_flush( bio ) > 0 );
const char *tmp = NULL;
size_t length = BIO_get_mem_data( bio, &tmp );
dbgAssert( tmp && length );
encoded->append( tmp, length );
}
struct CurlStringDeleter
{
static void free( char *value ){ dbgAssert( value ); curl_free( value ); }
};
static void
appendEscapedUrl( std::string *escapedUrl, const char *value )
{
dbgAssert( value );
dbgAssert( escapedUrl );
char *escapedValue = curl_escape( value, 0 /* auto detect length */ );
if( !escapedValue )
{
// This can be either OOM or unsupported character. We control what
// strings we escape (except for weblob extensions but that should be
// an extreme case) so if we are here it's most likely OOM.
throw std::bad_alloc();
}
auto_scope< char *, CurlStringDeleter > scoped( escapedValue );
escapedUrl->append( escapedValue );
}
#define curl_easy_setopt_checked( handle, option, ... ) dbgVerify( curl_easy_setopt( handle, option, __VA_ARGS__ ) == CURLE_OK )
//////////////////////////////////////////////////////////////////////////////
// Helper methods to deal with the query part of url.
static void
appendQueryPart( std::string *url, const char *key, const char *value, bool *pfirst = 0 /* in / out */ )
{
dbgAssert( url );
dbgAssert( key );
if( !value )
return;
// Append "?[key]=[value]" or "&[key]=[value]" to the URL.
// The value is escaped, the key is supposed to not require
// escaping.
url->append( 1, pfirst && *pfirst ? '?' : '&' );
url->append( key );
url->append( 1, '=' );
appendEscapedUrl( url, value );
if( pfirst )
*pfirst = false;
}
//////////////////////////////////////////////////////////////////////////////
// Helper methods for signing.
static const char s_aclHeaderKey[] = "x-amz-acl";
static const char s_aclHeaderValue[] = "public-read";
static const char s_encryptHeaderKey[] = "x-amz-server-side-encryption";
static const char s_encryptHeaderValue[] = "AES256";
static const char s_tokenHeaderKey[] = "x-amz-security-token";
static inline void
appendSigHeader( const char *key, const char *value, std::string *ptoSign )
{
dbgAssert( ptoSign );
// Some headers include key and some headers contains only value.
if( key )
{
ptoSign->append( key );
ptoSign->append( 1, ':' );
}
ptoSign->append( value ? value : "" );
ptoSign->append( 1, '\n' );
}
static void
calcSignature( const std::string &accKey, const std::string &secKey,
const char *contentMd5, const char *contentType, const char *date, bool makePublic, bool srvEncrypt,
const char *action, const char *bucketName, const char *key, WsStorType storType,
std::string *signature, std::string sessionToken )
{
dbgAssert( action );
dbgAssert( signature );
// Construct a string to sign.
std::string toSign;
toSign.reserve( 1024 );
toSign.append( action );
toSign.append( 1, '\n' );
// Add headers.
appendSigHeader( 0, contentMd5, &toSign );
appendSigHeader( 0, contentType, &toSign );
appendSigHeader( 0, date, &toSign );
if( makePublic )
appendSigHeader( s_aclHeaderKey, s_aclHeaderValue, &toSign );
if( sessionToken.compare("") != 0 )
appendSigHeader( s_tokenHeaderKey, sessionToken.c_str(), &toSign );
if( srvEncrypt )
appendSigHeader( s_encryptHeaderKey, s_encryptHeaderValue, &toSign );
// Add URL.
if( storType == WST_WALRUS )
toSign.append( STRING_WITH_LEN( "/services/Walrus" ) );
if( bucketName )
{
toSign.append( 1, '/' );
toSign.append( bucketName );
}
if( key )
{
toSign.append( 1, '/' );
toSign.append( key );
}
// Compute signature.
unsigned char hash[ 1024 ];
unsigned int hashSize;
HMAC( EVP_sha1(), secKey.c_str(), secKey.size(),
reinterpret_cast< const unsigned char* >( toSign.c_str() ), toSign.size(),
hash, &hashSize );
signature->append( STRING_WITH_LEN( " AWS " ) );
signature->append( accKey );
signature->append( 1, ':' );
append64Encoded( signature, hash, hashSize );
}
//////////////////////////////////////////////////////////////////////////////
// Helper methods to deal with headers.
struct CurlListDeleter
{
static void free( curl_slist *curlList ){ dbgAssert( curlList ); curl_slist_free_all( curlList ); }
};
typedef auto_scope< curl_slist *, CurlListDeleter > ScopedCurlList;
static void
appendRequestHeader( const char *key, const char *value, ScopedCurlList *plist )
{
dbgAssert( key );
dbgAssert( plist );
if( !value )
return;
std::string header;
header.reserve( 128 );
// Header is a "key: value" string.
header.append( key );
header.append( STRING_WITH_LEN( ": " ) );
header.append( value );
// Create a new list head and dupe the string.
curl_slist *const newlist = curl_slist_append( *plist, header.c_str() );
if( !newlist )
throw std::bad_alloc();
// Now the newlist is the new list.
plist->release();
*plist->unsafeAddress() = newlist;
}
static void
setRequestHeaders( const std::string &accKey, const std::string &secKey,
const char *contentMd5, const char *contentType, bool makePublic, bool srvEncrypt,
const char *action, const char *bucketName, const char *key, WsStorType storType,
ScopedCurlList *plist, const std::string sessionToken )
{
dbgAssert( plist );
// Get current time.
//$ FUTURE: have more elaborate logic here to get the time, as
// the auth will fail if time is too skewed, so we should detect
// time skewed errors and take the time value from the cloud.
time_t local;
time ( &local );
tm gmtTime;
#ifdef _WIN32
gmtime_s( &gmtTime, &local );
#else
gmtime_r( &local, &gmtTime );
#endif
char date[ 64 ];
dbgVerify( strftime( date, sizeof( date ),
"%a, %d %b %Y %H:%M:%S GMT",
&gmtTime ) < sizeof( date ) );
// Calculate auth signature.
std::string signature;
calcSignature( accKey, secKey,
contentMd5, contentType, date, makePublic, srvEncrypt,
action, bucketName, key, storType,
&signature, sessionToken );
// Set request headers.
// Header notes:
//
// Add empty Accept header otherwise curl will add Accept: */*
//
// We want to make sure that connection is kept alive between requests,
// so set Keep-Alive explicitly.
//
// Note 1:
// Unfortunately this may cause a hang in old proxies that don't understand
// Keep-Alive header and wait for the connection close.
// On the other hand, if this header is missing, AWS closes the connection.
// Let's choose perf and enable keep-alive. If we run into issues with
// legacy proxies, we can make this parameter configurable.
//
// Note 2:
// Walrus keeps connection open for GET requests but closes for PUT requests
// (and potentially for others) ignoring "Connection: " header,
// "Keep-Alive" has only a limited effect on Walrus connections.
//
// Note 3:
// If you capture traffic with Fiddler, you may see 2 headers "Connection: Keep-Alive".
// One of them is ours and the other is "Proxy-Connection: Keep-Alive" header
// converted to "Connection:" by Fiddler.
// Without Fiddler, there should be exactly one "Connection: Keep-Alive".
// Having 2 with Fiddler seems fine as well.
appendRequestHeader( "Content-MD5", contentMd5, plist );
appendRequestHeader( "Content-Type", contentType, plist );
appendRequestHeader( "Date", date, plist );
if( makePublic )
appendRequestHeader( s_aclHeaderKey, s_aclHeaderValue, plist );
if( sessionToken.compare("") != 0 )
appendRequestHeader( s_tokenHeaderKey, sessionToken.c_str(), plist );
if( srvEncrypt )
appendRequestHeader( s_encryptHeaderKey, s_encryptHeaderValue, plist );
appendRequestHeader( "Accept", "", plist );
appendRequestHeader( "Authorization", signature.c_str(), plist );
appendRequestHeader( "Connection", "Keep-Alive", plist );
appendRequestHeader( "Expect", "", plist );
appendRequestHeader( "Transfer-Encoding", "", plist );
}
//////////////////////////////////////////////////////////////////////////////
// Response loader to a given buffer.
struct WsGetResponseBufferLoader : public WsGetResponseLoader
{
WsGetResponseBufferLoader( void *buffer, size_t size );
size_t onLoad( const void *chunkData, size_t chunkSize, size_t totalSizeHint ) ;
void *p;
size_t left;
};
WsGetResponseBufferLoader::WsGetResponseBufferLoader( void *buffer, size_t size )
: p( buffer )
, left( size )
{
dbgAssert( implies( size, buffer ) );
}
size_t
WsGetResponseBufferLoader::onLoad( const void *chunkData, size_t chunkSize, size_t totalSizeHint )
{
if( !left )
{
return false;
}
size_t toCopy = std::min( chunkSize, left );
memcpy( p, chunkData, toCopy );
p = static_cast< unsigned char* >( p ) + toCopy;
left -= toCopy;
LOG_TRACE( "onLoad: loader=0x%llx, left=%llu, size=%llu", ( UInt64 )this, left, totalSizeHint );
return toCopy;
}
//////////////////////////////////////////////////////////////////////////////
// Request uploader from a given buffer.
struct WsPutRequestBufferUploader : public WsPutRequestUploader
{
WsPutRequestBufferUploader( const void *_buffer, size_t _size );
void setUpload( const void *_buffer, size_t _size );
virtual size_t onUpload( void *chunkBuf, size_t chunkSize );
const void * buffer;
size_t size;
size_t offset;
};
WsPutRequestBufferUploader::WsPutRequestBufferUploader( const void *_buffer, size_t _size )
: buffer( _buffer )
, size( _size )
, offset( 0 )
{
}
void
WsPutRequestBufferUploader::setUpload( const void *_buffer, size_t _size )
{
dbgAssert( implies( size, buffer ) );
buffer = _buffer;
size = _size;
offset = 0;
}
size_t
WsPutRequestBufferUploader::onUpload( void *chunkBuf, size_t chunkSize )
{
if( !size )
{
return 0;
}
dbgAssert( size >= offset );
size_t toCopy = std::min( size - offset, chunkSize );
memcpy( chunkBuf, static_cast< const char *>( buffer ) + offset, toCopy );
offset += toCopy;
LOG_TRACE( "onUpload: uploader=0x%llx, offset=%llu, size=%llu", ( UInt64 )this, offset, size );
return toCopy;
}
//////////////////////////////////////////////////////////////////////////////
// Response handling.
enum WS_RESPONSE_STATUS
{
WS_RESPONSE_STATUS_UNEXPECTED = -1,
WS_RESPONSE_STATUS_SUCCESS,
WS_RESPONSE_STATUS_FAILURE_WITH_DETAILS,
WS_RESPONSE_STATUS_HTTP_FAILURE,
WS_RESPONSE_STATUS_HTTP_RESOURSE_NOT_FOUND,
WS_RESPONSE_STATUS_HTTP_OR_WS_FAILURE,
};
struct WsResponseDetails
{
WsResponseDetails();
WS_RESPONSE_STATUS status;
std::string url;
std::string name;
// Common headers.
std::string httpStatus;
std::string httpDate;
size_t httpContentLength;
std::string httpContentType;
std::string amazonId;
std::string requestId;
std::string etag;
// Common xml body elements.
std::string errorCode;
std::string errorMessage;
std::string hostId;
bool isTruncated;
std::string uploadId;
// Length of the loaded content (in case of Get response)
size_t loadedContentLength;
};
WsResponseDetails::WsResponseDetails()
: status( WS_RESPONSE_STATUS_UNEXPECTED )
, httpContentLength( -1 )
, isTruncated( false )
, loadedContentLength( 0 )
{}
//////////////////////////////////////////////////////////////////////////////
// WebStor exception.
class WsException : public std::exception
{
public:
WsException( const char *fmt, ... );
virtual ~WsException() throw() {}
virtual const char * what() const throw();
protected:
std::vector< char > m_msg;
};
//////////////////////////////////////////////////////////////////////////////
// Base request handling.
class Request
{
public:
Request();
virtual ~Request();
void prepare( CURL *curl, char *errorBuffer, size_t errorBufferSize );
// Error support.
void saveError();
void raiseIfError();
void saveIfCurlError( CURLcode curlCode );
void saveBadAllocError() { m_is_bad_alloc = true; }
bool hasError() { return m_is_bad_alloc || m_error.get(); }
private:
Request( const Request& );
Request& operator=( const Request& );
protected:
virtual void onPrepare( CURL *curl ) { }
// A reference to the curl handle and error buffer, Request doesn't own them!
CURL *m_curl;
char *m_curlErrorDetails;
size_t m_curlErrorDetailsSize;
// Saved error. We need this to ensure 'nofail' behavior in callbacks that cannot throw
// and to marshal the error between threads in async case.
std::auto_ptr< WsException > m_error;
bool m_is_bad_alloc;
};
Request::Request()
: m_curl( NULL )
, m_is_bad_alloc( false )
{
}
Request::~Request()
{
}
void
Request::prepare( CURL *curl, char *errorBuffer, size_t errorBufferSize )
{
dbgAssert( curl );
dbgAssert( !m_curl );
dbgAssert( errorBuffer && errorBufferSize );
m_curl = curl;
m_curlErrorDetails = errorBuffer;
m_curlErrorDetailsSize = errorBufferSize;
// Clear the details.
memset( m_curlErrorDetails, 0, m_curlErrorDetailsSize );
onPrepare( curl );
}
void
Request::saveIfCurlError( CURLcode curlCode )
{
if( curlCode == CURLE_OUT_OF_MEMORY )
{
saveBadAllocError();
return;
}
// Ignore CURLE_WRITE_ERROR, when m_error is not set (see the check below), we should
// treat CURLE_WRITE_ERROR as success. The error is returned only when our handleXXX methods
// processed a part of the response and don't care about the rest.
if( curlCode != CURLE_OK && curlCode != CURLE_WRITE_ERROR )
{
// Check if we have any details about this error.
dbgAssert( m_curlErrorDetails );
if( *m_curlErrorDetails )
{
// Null terminate the errDetails.
m_curlErrorDetails[ m_curlErrorDetailsSize - 1 ] = '\0'; // null terminate.
m_error.reset( new WsException( errCurl, m_curlErrorDetails ) );
}
else
{
m_error.reset( new WsException( errCurl, curl_easy_strerror( curlCode ) ) );
}
}
}
void
Request::raiseIfError()
{
if( m_is_bad_alloc )
{
throw std::bad_alloc();
}
if( m_error.get() )
{
throw *m_error;
}
}
void
Request::saveError()
{
// This function must be called from inside of a catch( ... ).
try
{
try
{
throw;
}
catch( const std::bad_alloc & )
{
saveBadAllocError();
}
catch( const std::exception &e )
{
m_error.reset( new WsException( e.what() ) );
}
catch( ... )
{
m_error.reset( new WsException( errUnexpected ) );
}
}
catch( const std::bad_alloc & )
{
saveBadAllocError();
}
}
//////////////////////////////////////////////////////////////////////////////
// WebStor response Xml nodes.
// Values are sorted and order between enums and strings must match.
enum WS_RESPONSE_NODE
{
WS_RESPONSE_NODE_BUCKET,
WS_RESPONSE_NODE_CODE,
WS_RESPONSE_NODE_COMMON_PREFIXES,
WS_RESPONSE_NODE_CONTENTS,
WS_RESPONSE_NODE_CREATION_DATE,
WS_RESPONSE_NODE_ETAG,
WS_RESPONSE_NODE_ERROR,
WS_RESPONSE_NODE_HOST_ID,
WS_RESPONSE_NODE_IS_TRUNCATED,
WS_RESPONSE_NODE_KEY,
WS_RESPONSE_NODE_LAST_MODIFIED,
WS_RESPONSE_NODE_MESSAGE,
WS_RESPONSE_NODE_NAME,
WS_RESPONSE_NODE_NEXT_MARKER,
WS_RESPONSE_NODE_PREFIX,
WS_RESPONSE_NODE_REQUEST_ID,
WS_RESPONSE_NODE_SIZE,
WS_RESPONSE_NODE_UPLOAD,
WS_RESPONSE_NODE_UPLOAD_ID,
WS_RESPONSE_NODE_LAST
};
static StringWithLen s_wsResponseNodeStrings[] =
{
{ STRING_WITH_LEN( "Bucket" ) },
{ STRING_WITH_LEN( "Code" ) },
{ STRING_WITH_LEN( "CommonPrefixes" ) },
{ STRING_WITH_LEN( "Contents" ) },
{ STRING_WITH_LEN( "CreationDate" ) },
{ STRING_WITH_LEN( "ETag" ) },
{ STRING_WITH_LEN( "Error" ) },
{ STRING_WITH_LEN( "HostId" ) },
{ STRING_WITH_LEN( "IsTruncated" ) },
{ STRING_WITH_LEN( "Key" ) },
{ STRING_WITH_LEN( "LastModified" ) },
{ STRING_WITH_LEN( "Message" ) },
{ STRING_WITH_LEN( "Name" ) },
{ STRING_WITH_LEN( "NextMarker" ) },
{ STRING_WITH_LEN( "Prefix" ) },
{ STRING_WITH_LEN( "RequestId" ) },
{ STRING_WITH_LEN( "Size" ) },
{ STRING_WITH_LEN( "Upload" ) },
{ STRING_WITH_LEN( "UploadId" ) },
};
CASSERT( dimensionOf( s_wsResponseNodeStrings ) == WS_RESPONSE_NODE_LAST );
//////////////////////////////////////////////////////////////////////////////
// WebStor operation request handling.
class WsRequest : public Request
{
public:
WsRequest( const char *name = NULL );
virtual ~WsRequest();
// Sync execution.
WsResponseDetails &execute();
// Complete request.
WsResponseDetails &complete( CURLcode curlCode );
// Misc properties.
const char* url() { return m_responseDetails.url.c_str(); }
void setUrl( const char *url );
const char * name() { return m_responseDetails.name.c_str(); }