-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
swoole_http_client_coro.cc
2229 lines (2012 loc) · 74.1 KB
/
swoole_http_client_coro.cc
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
/*
+----------------------------------------------------------------------+
| Swoole |
+----------------------------------------------------------------------+
| This source file is subject to version 2.0 of the Apache license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| http://www.apache.org/licenses/LICENSE-2.0.html |
| If you did not receive a copy of the Apache2.0 license and are unable|
| to obtain it through the world-wide-web, please send a note to |
| [email protected] so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Author: Tianfeng Han <[email protected]> |
| Author: Twosee <[email protected]> |
| Author: Fang <[email protected]> |
| Author: Yuanyi Zhi <[email protected]> |
+----------------------------------------------------------------------+
*/
#include "php_swoole_cxx.h"
#include "coroutine_c_api.h"
#include "swoole_http_client.h"
#include "mime_types.h"
#include "base64.h"
#ifdef SW_HAVE_BROTLI
#include <brotli/decode.h>
#endif
using namespace swoole;
using swoole::coroutine::Socket;
extern void php_swoole_client_coro_socket_free(Socket *cli);
static int http_parser_on_header_field(swoole_http_parser *parser, const char *at, size_t length);
static int http_parser_on_header_value(swoole_http_parser *parser, const char *at, size_t length);
static int http_parser_on_headers_complete(swoole_http_parser *parser);
static int http_parser_on_body(swoole_http_parser *parser, const char *at, size_t length);
static int http_parser_on_message_complete(swoole_http_parser *parser);
static const swoole_http_parser_settings http_parser_settings =
{
NULL,
NULL,
NULL,
NULL,
NULL,
http_parser_on_header_field,
http_parser_on_header_value,
http_parser_on_headers_complete,
http_parser_on_body,
http_parser_on_message_complete
};
class http_client
{
public:
/* request info */
std::string host = "127.0.0.1";
uint16_t port = 80;
#ifdef SW_USE_OPENSSL
uint8_t ssl = false;
#endif
double connect_timeout = Socket::default_connect_timeout;
bool defer = false;
int8_t method = SW_HTTP_GET;
std::string path;
std::string basic_auth;
/* for response parser */
char *tmp_header_field_name = nullptr;
int tmp_header_field_name_len = 0;
swString *body = nullptr;
#ifdef SW_HAVE_COMPRESSION
enum http_compress_method compress_method = HTTP_COMPRESS_NONE;
bool compression_error = false;
#endif
/* options */
uint8_t reconnect_interval = 1;
uint8_t reconnected_count = 0;
bool keep_alive = true; // enable by default
bool websocket = false; // if upgrade successfully
bool chunked = false; // Transfer-Encoding: chunked
bool websocket_mask = true; // enable websocket mask
#ifdef SW_HAVE_ZLIB
bool websocket_compression = false; // allow to compress websocket messages
#endif
int download_file_fd = 0; // save http response to file
bool has_upload_files = false;
/* safety zval */
zval _zobject;
zval *zobject = &_zobject;
swString *tmp_write_buffer = nullptr;
http_client(zval* zobject, std::string host, zend_long port = 80, zend_bool ssl = false);
private:
#ifdef SW_HAVE_ZLIB
bool gzip_stream_active = false;
z_stream gzip_stream;
#endif
#ifdef SW_HAVE_BROTLI
BrotliDecoderState *brotli_decoder_state = nullptr;
#endif
bool connect();
bool keep_liveness();
bool send();
void reset();
public:
#ifdef SW_HAVE_COMPRESSION
bool decompress_response(const char *in, size_t in_len);
#endif
void apply_setting(zval *zset, const bool check_all = true);
void set_basic_auth(const std::string & username, const std::string & password);
bool exec(std::string path);
bool recv(double timeout = 0);
void recv(zval *zframe, double timeout = 0);
bool recv_http_response(double timeout = 0);
bool upgrade(std::string path);
bool push(zval *zdata, zend_long opcode = WEBSOCKET_OPCODE_TEXT, uint8_t flags = SW_WEBSOCKET_FLAG_FIN);
bool close(const bool should_be_reset = true);
void get_header_out(zval *return_value)
{
swString *buffer = nullptr;
if (socket == nullptr) {
if (tmp_write_buffer) {
buffer = tmp_write_buffer;
}
}
else {
buffer = socket->get_write_buffer();
}
if (buffer == nullptr)
{
RETURN_FALSE;
}
off_t offset = swoole_strnpos(buffer->str, buffer->length, ZEND_STRL("\r\n\r\n"));
if (offset <= 0)
{
RETURN_FALSE;
}
RETURN_STRINGL(buffer->str, offset);
}
void getsockname(zval *return_value)
{
swSocketAddress sa;
if (!socket || !socket->getsockname(&sa))
{
ZVAL_FALSE(return_value);
return;
}
array_init(return_value);
add_assoc_string(return_value, "host", (char *) swConnection_get_ip(socket->get_type(), &sa));
add_assoc_long(return_value, "port", swConnection_get_port(socket->get_type(), &sa));
}
void getpeername(zval *return_value)
{
swSocketAddress sa;
if (!socket || !socket->getpeername(&sa))
{
ZVAL_FALSE(return_value);
return;
}
array_init(return_value);
add_assoc_string(return_value, "host", (char *) swConnection_get_ip(socket->get_type(), &sa));
add_assoc_long(return_value, "port", swConnection_get_port(socket->get_type(), &sa));
}
~http_client();
private:
Socket* socket = nullptr;
swSocket_type socket_type = SW_SOCK_TCP;
swoole_http_parser parser = {};
bool wait = false;
};
static zend_class_entry *swoole_http_client_coro_ce;
static zend_object_handlers swoole_http_client_coro_handlers;
static zend_class_entry *swoole_http_client_coro_exception_ce;
static zend_object_handlers swoole_http_client_coro_exception_handlers;
typedef struct
{
http_client* phc;
zend_object std;
} http_client_coro;
ZEND_BEGIN_ARG_INFO_EX(arginfo_swoole_void, 0, 0, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO_EX(arginfo_swoole_http_client_coro_coro_construct, 0, 0, 1)
ZEND_ARG_INFO(0, host)
ZEND_ARG_INFO(0, port)
ZEND_ARG_INFO(0, ssl)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO_EX(arginfo_swoole_http_client_coro_set, 0, 0, 1)
ZEND_ARG_ARRAY_INFO(0, settings, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO_EX(arginfo_swoole_http_client_coro_setDefer, 0, 0, 0)
ZEND_ARG_INFO(0, defer)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO_EX(arginfo_swoole_http_client_coro_setMethod, 0, 0, 1)
ZEND_ARG_INFO(0, method)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO_EX(arginfo_swoole_http_client_coro_setHeaders, 0, 0, 1)
ZEND_ARG_ARRAY_INFO(0, headers, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO_EX(arginfo_swoole_http_client_coro_setBasicAuth, 0, 0, 2)
ZEND_ARG_INFO(0, username)
ZEND_ARG_INFO(0, password)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO_EX(arginfo_swoole_http_client_coro_setCookies, 0, 0, 1)
ZEND_ARG_ARRAY_INFO(0, cookies, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO_EX(arginfo_swoole_http_client_coro_setData, 0, 0, 1)
ZEND_ARG_INFO(0, data)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO_EX(arginfo_swoole_http_client_coro_addFile, 0, 0, 2)
ZEND_ARG_INFO(0, path)
ZEND_ARG_INFO(0, name)
ZEND_ARG_INFO(0, type)
ZEND_ARG_INFO(0, filename)
ZEND_ARG_INFO(0, offset)
ZEND_ARG_INFO(0, length)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO_EX(arginfo_swoole_http_client_coro_addData, 0, 0, 2)
ZEND_ARG_INFO(0, path)
ZEND_ARG_INFO(0, name)
ZEND_ARG_INFO(0, type)
ZEND_ARG_INFO(0, filename)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO_EX(arginfo_swoole_http_client_coro_execute, 0, 0, 1)
ZEND_ARG_INFO(0, path)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO_EX(arginfo_swoole_http_client_coro_get, 0, 0, 1)
ZEND_ARG_INFO(0, path)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO_EX(arginfo_swoole_http_client_coro_post, 0, 0, 2)
ZEND_ARG_INFO(0, path)
ZEND_ARG_INFO(0, data)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO_EX(arginfo_swoole_http_client_coro_download, 0, 0, 2)
ZEND_ARG_INFO(0, path)
ZEND_ARG_INFO(0, file)
ZEND_ARG_INFO(0, offset)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO_EX(arginfo_swoole_http_client_coro_upgrade, 0, 0, 1)
ZEND_ARG_INFO(0, path)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO_EX(arginfo_swoole_http_client_coro_push, 0, 0, 1)
ZEND_ARG_INFO(0, data)
ZEND_ARG_INFO(0, opcode)
ZEND_ARG_INFO(0, flags)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO_EX(arginfo_swoole_http_client_coro_recv, 0, 0, 0)
ZEND_ARG_INFO(0, timeout)
ZEND_END_ARG_INFO()
static PHP_METHOD(swoole_http_client_coro, __construct);
static PHP_METHOD(swoole_http_client_coro, __destruct);
static PHP_METHOD(swoole_http_client_coro, set);
static PHP_METHOD(swoole_http_client_coro, getDefer);
static PHP_METHOD(swoole_http_client_coro, setDefer);
static PHP_METHOD(swoole_http_client_coro, setMethod);
static PHP_METHOD(swoole_http_client_coro, setHeaders);
static PHP_METHOD(swoole_http_client_coro, setBasicAuth);
static PHP_METHOD(swoole_http_client_coro, setCookies);
static PHP_METHOD(swoole_http_client_coro, setData);
static PHP_METHOD(swoole_http_client_coro, addFile);
static PHP_METHOD(swoole_http_client_coro, addData);
static PHP_METHOD(swoole_http_client_coro, execute);
static PHP_METHOD(swoole_http_client_coro, get);
static PHP_METHOD(swoole_http_client_coro, post);
static PHP_METHOD(swoole_http_client_coro, download);
static PHP_METHOD(swoole_http_client_coro, getBody);
static PHP_METHOD(swoole_http_client_coro, getHeaders);
static PHP_METHOD(swoole_http_client_coro, getCookies);
static PHP_METHOD(swoole_http_client_coro, getStatusCode);
static PHP_METHOD(swoole_http_client_coro, getHeaderOut);
static PHP_METHOD(swoole_http_client_coro, upgrade);
static PHP_METHOD(swoole_http_client_coro, push);
static PHP_METHOD(swoole_http_client_coro, recv);
static PHP_METHOD(swoole_http_client_coro, close);
static const zend_function_entry swoole_http_client_coro_methods[] =
{
PHP_ME(swoole_http_client_coro, __construct, arginfo_swoole_http_client_coro_coro_construct, ZEND_ACC_PUBLIC)
PHP_ME(swoole_http_client_coro, __destruct, arginfo_swoole_void, ZEND_ACC_PUBLIC)
PHP_ME(swoole_http_client_coro, set, arginfo_swoole_http_client_coro_set, ZEND_ACC_PUBLIC)
PHP_ME(swoole_http_client_coro, getDefer, arginfo_swoole_void, ZEND_ACC_PUBLIC)
PHP_ME(swoole_http_client_coro, setDefer, arginfo_swoole_http_client_coro_setDefer, ZEND_ACC_PUBLIC)
PHP_ME(swoole_http_client_coro, setMethod, arginfo_swoole_http_client_coro_setMethod, ZEND_ACC_PUBLIC)
PHP_ME(swoole_http_client_coro, setHeaders, arginfo_swoole_http_client_coro_setHeaders, ZEND_ACC_PUBLIC)
PHP_ME(swoole_http_client_coro, setBasicAuth, arginfo_swoole_http_client_coro_setBasicAuth, ZEND_ACC_PUBLIC)
PHP_ME(swoole_http_client_coro, setCookies, arginfo_swoole_http_client_coro_setCookies, ZEND_ACC_PUBLIC)
PHP_ME(swoole_http_client_coro, setData, arginfo_swoole_http_client_coro_setData, ZEND_ACC_PUBLIC)
PHP_ME(swoole_http_client_coro, addFile, arginfo_swoole_http_client_coro_addFile, ZEND_ACC_PUBLIC)
PHP_ME(swoole_http_client_coro, addData, arginfo_swoole_http_client_coro_addData, ZEND_ACC_PUBLIC)
PHP_ME(swoole_http_client_coro, execute, arginfo_swoole_http_client_coro_execute, ZEND_ACC_PUBLIC)
PHP_ME(swoole_http_client_coro, get, arginfo_swoole_http_client_coro_get, ZEND_ACC_PUBLIC)
PHP_ME(swoole_http_client_coro, post, arginfo_swoole_http_client_coro_post, ZEND_ACC_PUBLIC)
PHP_ME(swoole_http_client_coro, download, arginfo_swoole_http_client_coro_download, ZEND_ACC_PUBLIC)
PHP_ME(swoole_http_client_coro, getBody, arginfo_swoole_void, ZEND_ACC_PUBLIC)
PHP_ME(swoole_http_client_coro, getHeaders, arginfo_swoole_void, ZEND_ACC_PUBLIC)
PHP_ME(swoole_http_client_coro, getCookies, arginfo_swoole_void, ZEND_ACC_PUBLIC)
PHP_ME(swoole_http_client_coro, getStatusCode, arginfo_swoole_void, ZEND_ACC_PUBLIC)
PHP_ME(swoole_http_client_coro, getHeaderOut, arginfo_swoole_void, ZEND_ACC_PUBLIC)
PHP_ME(swoole_http_client_coro, upgrade, arginfo_swoole_http_client_coro_upgrade, ZEND_ACC_PUBLIC)
PHP_ME(swoole_http_client_coro, push, arginfo_swoole_http_client_coro_push, ZEND_ACC_PUBLIC)
PHP_ME(swoole_http_client_coro, recv, arginfo_swoole_http_client_coro_recv, ZEND_ACC_PUBLIC)
PHP_ME(swoole_http_client_coro, close, arginfo_swoole_void, ZEND_ACC_PUBLIC)
PHP_FE_END
};
void http_parse_set_cookies(const char *at, size_t length, zval *zcookies, zval *zset_cookie_headers)
{
const char *p, *eof = at + length;
size_t key_len = 0, value_len = 0;
zval zvalue;
// key
p = (char *) memchr(at, '=', length);
if (p)
{
key_len = p - at;
p++; // point to value
}
else
{
p = at; // key is empty
}
// value
eof = (char*) memchr(p, ';', at + length - p);
if (!eof)
{
eof = at + length;
}
value_len = eof - p;
if (value_len != 0)
{
ZVAL_STRINGL(&zvalue, p, value_len);
Z_STRLEN(zvalue) = php_url_decode(Z_STRVAL(zvalue), value_len);
}
else
{
ZVAL_EMPTY_STRING(&zvalue);
}
if (key_len == 0)
{
add_next_index_zval(zcookies, &zvalue);
}
else
{
add_assoc_zval_ex(zcookies, at, key_len, &zvalue);
}
// set_cookie_headers
add_next_index_stringl(zset_cookie_headers, (char *) at, length);
}
static int http_parser_on_header_field(swoole_http_parser *parser, const char *at, size_t length)
{
http_client* http = (http_client*) parser->data;
http->tmp_header_field_name = (char *) at;
http->tmp_header_field_name_len = length;
return 0;
}
static int http_parser_on_header_value(swoole_http_parser *parser, const char *at, size_t length)
{
http_client* http = (http_client*) parser->data;
zval* zobject = (zval*) http->zobject;
zval *zheaders = sw_zend_read_and_convert_property_array(swoole_http_client_coro_ce, zobject, ZEND_STRL("headers"), 0);
char *header_name = zend_str_tolower_dup(http->tmp_header_field_name, http->tmp_header_field_name_len);
size_t header_len = http->tmp_header_field_name_len;
add_assoc_stringl_ex(zheaders, header_name, http->tmp_header_field_name_len, (char *) at, length);
if (parser->status_code == SW_HTTP_SWITCHING_PROTOCOLS && SW_STREQ(header_name, header_len, "upgrade"))
{
if (SW_STRCASEEQ(at, length, "websocket"))
{
http->websocket = true;
}
/* TODO: protocol error? */
}
#ifdef SW_HAVE_ZLIB
else if (http->websocket && http->websocket_compression && SW_STREQ(header_name, header_len, "sec-websocket-extensions"))
{
if (
SW_STRCASECT(at, length, "permessage-deflate") &&
SW_STRCASECT(at, length, "client_no_context_takeover") &&
SW_STRCASECT(at, length, "server_no_context_takeover")
)
{
http->websocket_compression = true;
}
}
#endif
else if (SW_STREQ(header_name, header_len, "set-cookie"))
{
zval *zcookies = sw_zend_read_and_convert_property_array(swoole_http_client_coro_ce, zobject, ZEND_STRL("cookies"), 0);
zval *zset_cookie_headers = sw_zend_read_and_convert_property_array(swoole_http_client_coro_ce, zobject, ZEND_STRL("set_cookie_headers"), 0);
http_parse_set_cookies(at, length, zcookies, zset_cookie_headers);
}
#ifdef SW_HAVE_COMPRESSION
else if (SW_STREQ(header_name, header_len, "content-encoding"))
{
if (0) { }
#ifdef SW_HAVE_BROTLI
else if (SW_STRCASECT(at, length, "br"))
{
http->compress_method = HTTP_COMPRESS_BR;
}
#endif
#ifdef SW_HAVE_ZLIB
else if (SW_STRCASECT(at, length, "gzip"))
{
http->compress_method = HTTP_COMPRESS_GZIP;
}
else if (SW_STRCASECT(at, length, "deflate"))
{
http->compress_method = HTTP_COMPRESS_DEFLATE;
}
#endif
}
#endif
else if (SW_STREQ(header_name, header_len, "transfer-encoding") && SW_STRCASECT(at, length, "chunked"))
{
http->chunked = true;
}
efree(header_name);
return 0;
}
static int http_parser_on_headers_complete(swoole_http_parser *parser)
{
http_client* http = (http_client*) parser->data;
if (http->method == SW_HTTP_HEAD || parser->status_code == SW_HTTP_NO_CONTENT)
{
return 1;
}
return 0;
}
static int http_parser_on_body(swoole_http_parser *parser, const char *at, size_t length)
{
http_client* http = (http_client*) parser->data;
#ifdef SW_HAVE_COMPRESSION
if (!http->compression_error && http->compress_method != HTTP_COMPRESS_NONE)
{
if (!http->decompress_response(at, length))
{
http->compression_error = true;
goto _append_raw;
}
}
else
#endif
{
#ifdef SW_HAVE_COMPRESSION
_append_raw:
#endif
if (swString_append_ptr(http->body, at, length) < 0)
{
return -1;
}
}
if (http->download_file_fd > 0 && http->body->length > 0)
{
if (swoole_coroutine_write(http->download_file_fd, SW_STRINGL(http->body)) != (ssize_t) http->body->length)
{
return -1;
}
swString_clear(http->body);
}
return 0;
}
static int http_parser_on_message_complete(swoole_http_parser *parser)
{
http_client* http = (http_client*) parser->data;
zval* zobject = (zval*) http->zobject;
if (parser->upgrade && !http->websocket)
{
// not support, continue.
parser->upgrade = 0;
return 0;
}
zend_update_property_long(swoole_http_client_coro_ce, zobject, ZEND_STRL("statusCode"), parser->status_code);
if (http->download_file_fd <= 0)
{
zend_update_property_stringl(swoole_http_client_coro_ce, zobject, ZEND_STRL("body"), SW_STRINGL(http->body));
}
if (parser->upgrade)
{
// return 1 will finish the parser and means yes we support it.
return 1;
}
else
{
return 0;
}
}
http_client::http_client(zval* zobject, std::string host, zend_long port, zend_bool ssl)
{
this->socket_type = Socket::convert_to_type(host);
this->host = host;
this->port = port;
#ifdef SW_USE_OPENSSL
this->ssl = ssl;
#endif
_zobject = *zobject;
// TODO: zend_read_property cache here (strong type properties)
}
#ifdef SW_HAVE_COMPRESSION
bool http_client::decompress_response(const char *in, size_t in_len)
{
if (in_len == 0)
{
return false;
}
size_t reserved_body_length = body->length;
switch(compress_method)
{
#ifdef SW_HAVE_ZLIB
case HTTP_COMPRESS_GZIP:
case HTTP_COMPRESS_DEFLATE:
{
int status;
int encoding = compress_method == HTTP_COMPRESS_GZIP ? SW_ZLIB_ENCODING_GZIP : SW_ZLIB_ENCODING_DEFLATE;
bool first_decompress = !gzip_stream_active;
size_t total_out;
if (!gzip_stream_active)
{
_retry:
memset(&gzip_stream, 0, sizeof(gzip_stream));
gzip_stream.zalloc = php_zlib_alloc;
gzip_stream.zfree = php_zlib_free;
// gzip_stream.total_out = 0;
status = inflateInit2(&gzip_stream, encoding);
if (status != Z_OK)
{
swWarn("inflateInit2() failed by %s", zError(status));
return false;
}
gzip_stream_active = true;
}
gzip_stream.next_in = (Bytef *) in;
gzip_stream.avail_in = in_len;
gzip_stream.total_in = 0;
while (1)
{
total_out = gzip_stream.total_out;
gzip_stream.avail_out = body->size - body->length;
gzip_stream.next_out = (Bytef *) (body->str + body->length);
SW_ASSERT(body->length <= body->size);
status = inflate(&gzip_stream, Z_SYNC_FLUSH);
if (status >= 0)
{
body->length += (gzip_stream.total_out - total_out);
if (body->length + (SW_BUFFER_SIZE_STD / 2) >= body->size)
{
if (swString_extend(body, body->size * 2) < 0)
{
status = Z_MEM_ERROR;
break;
}
}
}
if (status == Z_STREAM_END || (status == Z_OK && gzip_stream.avail_in == 0))
{
return true;
}
if (status != Z_OK)
{
break;
}
}
if (status == Z_DATA_ERROR && first_decompress)
{
first_decompress = false;
inflateEnd(&gzip_stream);
encoding = SW_ZLIB_ENCODING_RAW;
body->length = reserved_body_length;
goto _retry;
}
swWarn("http_client::decompress_response failed by %s", zError(status));
body->length = reserved_body_length;
return false;
}
#endif
#ifdef SW_HAVE_BROTLI
case HTTP_COMPRESS_BR:
{
if (!brotli_decoder_state) {
brotli_decoder_state = BrotliDecoderCreateInstance(php_brotli_alloc, php_brotli_free, NULL);
if (!brotli_decoder_state)
{
swWarn("BrotliDecoderCreateInstance() failed");
return false;
}
}
const char *next_in = in;
size_t available_in = in_len;
while (1) {
size_t available_out = body->size - body->length, reserved_available_out = available_out;
char * next_out = body->str + body->length;
size_t total_out;
BrotliDecoderResult result;
SW_ASSERT(body->length <= body->size);
result = BrotliDecoderDecompressStream(
brotli_decoder_state,
&available_in, (const uint8_t **) &next_in,
&available_out, (uint8_t **) &next_out,
&total_out
);
body->length += reserved_available_out - available_out;
if (result == BROTLI_DECODER_RESULT_SUCCESS || result == BROTLI_DECODER_RESULT_NEEDS_MORE_INPUT)
{
return true;
}
else if (result == BROTLI_DECODER_RESULT_NEEDS_MORE_OUTPUT)
{
if (swString_extend_align(body, body->size * 2) < 0)
{
swWarn("BrotliDecoderDecompressStream() failed, no memory is available");
break;
}
}
else
{
swWarn("BrotliDecoderDecompressStream() failed, %s", BrotliDecoderErrorString(BrotliDecoderGetErrorCode(brotli_decoder_state)));
break;
}
}
body->length = reserved_body_length;
return false;
}
#endif
default:
break;
}
swWarn("http_client::decompress_response unknown compress method [%d]", compress_method);
return false;
}
#endif
void http_client::apply_setting(zval *zset, const bool check_all)
{
if (!ZVAL_IS_ARRAY(zset) || php_swoole_array_length(zset) == 0)
{
return;
}
if (check_all)
{
zval *ztmp;
HashTable *vht = Z_ARRVAL_P(zset);
if (php_swoole_array_get_value(vht, "connect_timeout", ztmp) || php_swoole_array_get_value(vht, "timeout", ztmp) /* backward compatibility */)
{
connect_timeout = zval_get_double(ztmp);
}
if (php_swoole_array_get_value(vht, "reconnect", ztmp))
{
reconnect_interval = (uint8_t) SW_MIN(zval_get_long(ztmp), UINT8_MAX);
}
if (php_swoole_array_get_value(vht, "defer", ztmp))
{
defer = zval_is_true(ztmp);
}
if (php_swoole_array_get_value(vht, "keep_alive", ztmp))
{
keep_alive = zval_is_true(ztmp);
}
if (php_swoole_array_get_value(vht, "websocket_mask", ztmp))
{
websocket_mask = zval_is_true(ztmp);
}
#ifdef SW_HAVE_ZLIB
if (php_swoole_array_get_value(vht, "websocket_compression", ztmp))
{
websocket_compression = zval_is_true(ztmp);
}
#endif
}
if (socket)
{
php_swoole_client_set(socket, zset);
#ifdef SW_USE_OPENSSL
if (socket->http_proxy && !socket->open_ssl)
#else
if (socket->http_proxy)
#endif
{
socket->http_proxy->dont_handshake = 1;
}
}
}
void http_client::set_basic_auth(const std::string &username, const std::string &password)
{
std::string input = username + ":" + password;
size_t output_size = sizeof("Basic ") + BASE64_ENCODE_OUT_SIZE(input.size());
char *output = (char *) emalloc(output_size);
if (sw_likely(output))
{
size_t output_len = sprintf(output, "Basic ");
output_len += swBase64_encode((const unsigned char *) input.c_str(), input.size(), output + output_len);
basic_auth = std::string((const char *) output, output_len);
efree(output);
}
}
bool http_client::connect()
{
if (!socket)
{
if (!body)
{
body = swString_new(SW_HTTP_RESPONSE_INIT_SIZE);
if (!body)
{
zend_update_property_long(swoole_http_client_coro_ce, zobject, ZEND_STRL("errCode"), ENOMEM);
zend_update_property_string(swoole_http_client_coro_ce, zobject, ZEND_STRL("errMsg"), swoole_strerror(ENOMEM));
zend_update_property_long(swoole_http_client_coro_ce, zobject, ZEND_STRL("statusCode"), HTTP_CLIENT_ESTATUS_CONNECT_FAILED);
return false;
}
}
php_swoole_check_reactor();
socket = new Socket(socket_type);
if (UNEXPECTED(socket->get_fd() < 0))
{
php_swoole_sys_error(E_WARNING, "new Socket() failed");
zend_update_property_long(swoole_http_client_coro_ce, zobject, ZEND_STRL("errCode"), errno);
zend_update_property_string(swoole_http_client_coro_ce, zobject, ZEND_STRL("errMsg"), swoole_strerror(errno));
zend_update_property_long(swoole_http_client_coro_ce, zobject, ZEND_STRL("statusCode"), HTTP_CLIENT_ESTATUS_CONNECT_FAILED);
delete socket;
socket = nullptr;
return false;
}
#ifdef SW_USE_OPENSSL
socket->open_ssl = ssl;
#endif
// apply settings
apply_setting(sw_zend_read_property(swoole_http_client_coro_ce, zobject, ZEND_STRL("setting"), 0), false);
// connect
socket->set_timeout(connect_timeout, SW_TIMEOUT_CONNECT);
if (!socket->connect(host, port))
{
zend_update_property_long(swoole_http_client_coro_ce, zobject, ZEND_STRL("errCode"), socket->errCode);
zend_update_property_string(swoole_http_client_coro_ce, zobject, ZEND_STRL("errMsg"), socket->errMsg);
zend_update_property_long(swoole_http_client_coro_ce, zobject, ZEND_STRL("statusCode"), HTTP_CLIENT_ESTATUS_CONNECT_FAILED);
close();
return false;
}
reconnected_count = 0;
zend_update_property_bool(swoole_http_client_coro_ce, zobject, ZEND_STRL("connected"), 1);
}
return true;
}
bool http_client::keep_liveness()
{
if (!socket || !socket->check_liveness())
{
if (socket)
{
/* in progress */
socket->check_bound_co(SW_EVENT_RDWR);
zend_update_property_long(swoole_http_client_coro_ce, zobject, ZEND_STRL("errCode"), socket->errCode);
zend_update_property_string(swoole_http_client_coro_ce, zobject, ZEND_STRL("errMsg"), socket->errMsg);
zend_update_property_long(swoole_http_client_coro_ce, zobject, ZEND_STRL("statusCode"), HTTP_CLIENT_ESTATUS_SERVER_RESET);
close(false);
}
for (; reconnected_count < reconnect_interval; reconnected_count++)
{
if (connect())
{
return true;
}
}
return false;
}
return true;
}
bool http_client::send()
{
zval *zvalue = NULL;
uint32_t header_flag = 0x0;
zval *zmethod, *zheaders, *zbody, *zupload_files, *zcookies, *z_download_file;
if (path.length() == 0)
{
php_swoole_fatal_error(E_WARNING, "path is empty");
return false;
}
// when new request, clear all properties about the last response
{
zend_update_property_null(swoole_http_client_coro_ce, SW_Z8_OBJ_P(zobject), ZEND_STRL("headers"));
zend_update_property_null(swoole_http_client_coro_ce, SW_Z8_OBJ_P(zobject), ZEND_STRL("set_cookie_headers"));
zend_update_property_string(swoole_http_client_coro_ce, zobject, ZEND_STRL("body"), "");
}
if (!keep_liveness())
{
return false;
}
else
{
zend_update_property_long(swoole_http_client_coro_ce, zobject, ZEND_STRL("errCode"), 0);
zend_update_property_string(swoole_http_client_coro_ce, zobject, ZEND_STRL("errMsg"), "");
zend_update_property_long(swoole_http_client_coro_ce, zobject, ZEND_STRL("statusCode"), 0);
}
/* another coroutine is connecting */
socket->check_bound_co(SW_EVENT_WRITE);
//clear errno
SwooleG.error = 0;
//alloc buffer
swString *buffer = socket->get_write_buffer();
swString_clear(buffer);
// clear body
swString_clear(body);
zmethod = sw_zend_read_property_not_null(swoole_http_client_coro_ce, zobject, ZEND_STRL("requestMethod"), 0);
zheaders = sw_zend_read_property(swoole_http_client_coro_ce, zobject, ZEND_STRL("requestHeaders"), 0);
zbody = sw_zend_read_property_not_null(swoole_http_client_coro_ce, zobject, ZEND_STRL("requestBody"), 0);
zupload_files = sw_zend_read_property(swoole_http_client_coro_ce, zobject, ZEND_STRL("uploadFiles"), 0);
zcookies = sw_zend_read_property(swoole_http_client_coro_ce, zobject, ZEND_STRL("cookies"), 0);
z_download_file = sw_zend_read_property_not_null(swoole_http_client_coro_ce, zobject, ZEND_STRL("downloadFile"), 0);
// ============ host ============
zend::string str_host;
if ((ZVAL_IS_ARRAY(zheaders)) && ((zvalue = zend_hash_str_find(Z_ARRVAL_P(zheaders), ZEND_STRL("Host"))) || (zvalue = zend_hash_str_find(Z_ARRVAL_P(zheaders), ZEND_STRL("host")))))
{
str_host = zvalue;
}
// ============ download ============
if (z_download_file)
{
zend::string str_download_file(z_download_file);
char *download_file_name = str_download_file.val();
zval *z_download_offset = sw_zend_read_property(swoole_http_client_coro_ce, zobject, ZEND_STRL("downloadOffset"), 0);
off_t download_offset = zval_get_long(z_download_offset);
int fd = ::open(download_file_name, O_CREAT | O_WRONLY, 0664);
if (fd < 0)
{
swSysWarn("open(%s, O_CREAT | O_WRONLY) failed", download_file_name);
return false;
}
if (download_offset == 0)
{
if (ftruncate(fd, 0) < 0)
{
swSysWarn("ftruncate(%s) failed", download_file_name);
::close(fd);
return false;
}
}
else
{
if (lseek(fd, download_offset, SEEK_SET) < 0)
{
swSysWarn("fseek(%s, %jd) failed", download_file_name, (intmax_t) download_offset);
::close(fd);
return false;
}
}
download_file_fd = fd;
}
// ============ method ============
{
zend::string str_method;
const char *method;
size_t method_len;
if (zmethod)
{
str_method = zmethod;
method = str_method.val();
method_len = str_method.len();
}
else
{
method = zbody ? "POST" : "GET";
method_len = strlen(method);
}
this->method = swHttp_get_method(method, method_len);
swString_append_ptr(buffer, method, method_len);
swString_append_ptr(buffer, ZEND_STRL(" "));
}
// ============ path & proxy ============
#ifdef SW_USE_OPENSSL
if (socket->http_proxy && !socket->open_ssl)
#else
if (socket->http_proxy)
#endif
{
const static char *pre = "http://";
char *_host = (char *) host.c_str();
size_t _host_len = host.length();
if (str_host.get())
{
_host = str_host.val();
_host_len = str_host.len();
}
size_t proxy_uri_len = path.length() + _host_len + strlen(pre) + 10;
char *proxy_uri = (char*) emalloc(proxy_uri_len);
if (nullptr == memchr(_host, ':', _host_len)) {
proxy_uri_len = sw_snprintf(proxy_uri, proxy_uri_len, "%s%s:%u%s", pre, _host, port, path.c_str());
} else {
proxy_uri_len = sw_snprintf(proxy_uri, proxy_uri_len, "%s%s%s", pre, _host, path.c_str());
}
swString_append_ptr(buffer, proxy_uri, proxy_uri_len);
efree(proxy_uri);
}
else
{
swString_append_ptr(buffer, path.c_str(), path.length());
}
// ============ protocol ============
swString_append_ptr(buffer, ZEND_STRL(" HTTP/1.1\r\n"));
// ============ headers ============
char *key;
uint32_t keylen;
int keytype;
// As much as possible to ensure that Host is the first header.
// See: http://tools.ietf.org/html/rfc7230#section-5.4
if (str_host.get())
{
http_client_swString_append_headers(buffer, ZEND_STRL("Host"), str_host.val(), str_host.len());
}
else
{
// See: https://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.23
const std::string *_host;
std::string __host;
#ifndef SW_USE_OPENSSL
if (port != 80)
#else
if (!ssl ? port != 80 : port != 443)
#endif