-
Notifications
You must be signed in to change notification settings - Fork 112
Expand file tree
/
Copy pathinterface.cpp
More file actions
2514 lines (2161 loc) · 75 KB
/
interface.cpp
File metadata and controls
2514 lines (2161 loc) · 75 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
// Compiler for PHP (aka KPHP)
// Copyright (c) 2020 LLC «V Kontakte»
// Distributed under the GPL v3 License, see LICENSE.notice.txt
#include "runtime/interface.h"
#include <arpa/inet.h>
#include <cassert>
#include <clocale>
#include <csetjmp>
#include <csignal>
#include <fstream>
#include <functional>
#include <getopt.h>
#include <netdb.h>
#include <unistd.h>
#include "common/algorithms/string-algorithms.h"
#include "common/macos-ports.h"
#include "common/tl/constants/common.h"
#include "common/wrappers/overloaded.h"
#include "net/net-connections.h"
#include "runtime-common/stdlib/serialization/serialization-context.h"
#include "runtime-common/stdlib/server/url-functions.h"
#include "runtime-common/stdlib/string/string-context.h"
#include "runtime-common/stdlib/string/string-functions.h"
#include "runtime-common/stdlib/tracing/tracing-functions.h"
#include "runtime/array_functions.h"
#include "runtime/bcmath.h"
#include "runtime/confdata-functions.h"
#include "runtime/context/runtime-context.h"
#include "runtime/critical_section.h"
#include "runtime/curl.h"
#include "runtime/datetime/datetime_functions.h"
#include "runtime/datetime/timelib_wrapper.h"
#include "runtime/exception.h"
#include "runtime/files.h"
#include "runtime/instance-cache.h"
#include "runtime/job-workers/client-functions.h"
#include "runtime/job-workers/server-functions.h"
#include "runtime/kml.h"
#include "runtime/kphp-backtrace.h"
#include "runtime/kphp_tracing.h"
#include "runtime/math_functions.h"
#include "runtime/memcache.h"
#include "runtime/mysql.h"
#include "runtime/net_events.h"
#include "runtime/on_kphp_warning_callback.h"
#include "runtime/oom_handler.h"
#include "runtime/openssl.h"
#include "runtime/pdo/pdo.h"
#include "runtime/profiler.h"
#include "runtime/regexp.h"
#include "runtime/resumable.h"
#include "runtime/rpc.h"
#include "runtime/runtime-builtin-stats.h"
#include "runtime/streams.h"
#include "runtime/tcp.h"
#include "runtime/typed_rpc.h"
#include "runtime/udp.h"
#include "runtime/url.h"
#include "runtime/zlib.h"
#include "server/curl-adaptor.h"
#include "server/database-drivers/adaptor.h"
#include "server/database-drivers/mysql/mysql.h"
#include "server/database-drivers/pgsql/pgsql.h"
#include "server/job-workers/job-message.h"
#include "server/json-logger.h"
#include "server/numa-configuration.h"
#include "server/php-engine-vars.h"
#include "server/php-queries.h"
#include "server/php-query-data.h"
#include "server/php-runner.h"
#include "server/php-worker.h"
#include "server/server-config.h"
#include "server/shared-data-worker-cache.h"
#include "server/signal-handlers.h"
#include "server/workers-control.h"
static enum { QUERY_TYPE_NONE, QUERY_TYPE_CONSOLE, QUERY_TYPE_HTTP, QUERY_TYPE_RPC, QUERY_TYPE_JOB } query_type;
static bool is_head_query;
static const string HTTP_DATE("D, d M Y H:i:s \\G\\M\\T", 21);
static const int OB_MAX_BUFFERS = 50;
static int ob_cur_buffer;
static string_buffer oub[OB_MAX_BUFFERS];
string_buffer* coub;
constexpr int ob_system_level = 0;
static int http_need_gzip;
static bool is_utf8_enabled = false;
bool is_json_log_on_timeout_enabled = true;
bool is_demangled_stacktrace_logs_enabled = false;
static int ignore_level = 0;
mixed runtime_config;
mixed f$kphp_get_runtime_config() {
return runtime_config;
}
void f$ob_clean() {
coub->clean();
}
static inline void reset_gzip_header() {
if (ob_cur_buffer == 0) {
http_need_gzip &= ~4;
}
}
bool f$ob_end_clean() {
if (ob_cur_buffer == 0) {
return false;
}
coub = &oub[--ob_cur_buffer];
reset_gzip_header();
return true;
}
Optional<string> f$ob_get_clean() {
if (ob_cur_buffer == 0) {
return false;
}
string result = coub->str();
coub = &oub[--ob_cur_buffer];
reset_gzip_header();
return result;
}
string f$ob_get_contents() {
return coub->str();
}
void f$ob_start(const string& callback) {
if (ob_cur_buffer + 1 == OB_MAX_BUFFERS) {
php_warning("Maximum nested level of output buffering reached. Can't do ob_start(%s)", callback.c_str());
return;
}
if (!callback.empty()) {
if (ob_cur_buffer == 0 && callback == string("ob_gzhandler")) {
http_need_gzip |= 4;
} else {
php_critical_error("unsupported callback %s at buffering level %d", callback.c_str(), ob_cur_buffer + 1);
}
}
coub = &oub[++ob_cur_buffer];
coub->clean();
}
void f$ob_flush() {
if (ob_cur_buffer == 0) {
php_warning("ob_flush with no buffer opented");
return;
}
--ob_cur_buffer;
coub = &oub[ob_cur_buffer];
print(oub[ob_cur_buffer + 1]);
++ob_cur_buffer;
coub = &oub[ob_cur_buffer];
f$ob_clean();
}
bool f$ob_end_flush() {
if (ob_cur_buffer == 0) {
return false;
}
f$ob_flush();
return f$ob_end_clean();
}
Optional<string> f$ob_get_flush() {
if (ob_cur_buffer == 0) {
return false;
}
string result = coub->str();
f$ob_flush();
f$ob_end_clean();
return result;
}
Optional<int64_t> f$ob_get_length() {
if (ob_cur_buffer == 0) {
return false;
}
return coub->size();
}
int64_t f$ob_get_level() {
return ob_cur_buffer;
}
static int http_return_code;
static string http_status_line;
static char headers_storage[sizeof(array<string>)];
static array<string>* headers = reinterpret_cast<array<string>*>(headers_storage);
static long long header_last_query_num = -1;
static bool headers_custom_handler_invoked = false;
static bool headers_sent = false;
static headers_custom_handler_function_type headers_custom_handler_function;
static bool check_status_line_int(const char* str, int str_len, int* pos) {
if (*pos != str_len && str[*pos] == '0') {
(*pos)++;
return true;
}
for (int i = 0; i <= 9; i++) { // allow up to 9 digits total
if (*pos == str_len || str[*pos] < '0' || str[*pos] > '9') {
return i > 0;
}
(*pos)++;
}
return false;
}
static bool check_status_line(const char* str, int str_len) {
// skip check for beginning with "HTTP/"
int pos = 5;
if (!check_status_line_int(str, str_len, &pos)) {
return false;
}
if (pos == str_len || str[pos] != '.') {
return false;
}
pos++;
if (!check_status_line_int(str, str_len, &pos)) {
return false;
}
if (pos == str_len || str[pos] != ' ') {
return false;
}
pos++;
if (pos == str_len || str[pos] < '1' || str[pos] > '9') {
return false;
}
pos++;
if (pos == str_len || str[pos] < '0' || str[pos] > '9') {
return false;
}
pos++;
if (pos == str_len || str[pos] < '0' || str[pos] > '9') {
return false;
}
pos++;
if (pos == str_len || str[pos] != ' ') {
return false;
}
pos++;
while (pos != str_len) {
if ((0 <= str[pos] && str[pos] <= 31) || str[pos] == 127) {
return false;
}
pos++;
}
return true;
}
static void header(const char* str, int str_len, bool replace = true, int http_response_code = 0) {
if (dl::query_num != header_last_query_num) {
new (headers_storage) array<string>();
header_last_query_num = dl::query_num;
}
// status line
if (str_len >= 5 && !strncasecmp(str, "HTTP/", 5)) {
if (check_status_line(str, str_len)) {
http_status_line = string(str, str_len);
int pos = 5;
while (str[pos] != ' ') {
pos++;
}
sscanf(str + pos, "%d", &http_return_code);
} else {
php_critical_error("wrong status line '%s' specified in function header", str);
}
return;
}
// regular header
const char* p = strchr(str, ':');
if (p == nullptr) {
php_warning("Wrong header line specified: \"%s\"", str);
return;
}
string name = f$trim(string(str, static_cast<string::size_type>(p - str)));
if (strpbrk(name.c_str(), "()<>@,;:\\\"/[]?={}") != nullptr) {
php_warning("Wrong header name: \"%s\"", name.c_str());
return;
}
for (string::size_type i = 0; i < name.size(); i++) {
if (name[i] <= 32 || name[i] >= 127) {
php_warning("Wrong header name: \"%s\"", name.c_str());
return;
}
}
for (int i = (int)(p - str + 1); i < str_len; i++) {
if ((0 <= str[i] && str[i] <= 31) || str[i] == 127) {
php_warning("Wrong header value: \"%s\"", p + 1);
return;
}
}
string value = string(static_cast<string::size_type>(name.size() + (str_len - (p - str)) + 2), false);
memcpy(value.buffer(), name.c_str(), name.size());
memcpy(value.buffer() + name.size(), p, str_len - (p - str));
value[value.size() - 2] = '\r';
value[value.size() - 1] = '\n';
name = f$strtolower(name);
if (replace || !headers->has_key(name)) {
headers->set_value(name, value);
} else {
(*headers)[name].append(value);
}
if (str_len >= 9 && !strncasecmp(str, "Location:", 9) && http_response_code == 0) {
http_response_code = 302;
}
if (str_len && http_response_code > 0 && http_response_code != http_return_code) {
http_return_code = http_response_code;
http_status_line = string();
}
}
void f$header(const string& str, bool replace, int64_t http_response_code) {
header(str.c_str(), (int)str.size(), replace, static_cast<int32_t>(http_response_code));
}
array<string> f$headers_list() {
array<string> result;
if (dl::query_num != header_last_query_num) {
new (headers_storage) array<string>();
header_last_query_num = dl::query_num;
}
string delim("\r\n");
for (auto header = headers->cbegin(); header != headers->cend(); ++header) {
array<string> temp = f$explode(delim, header.get_value());
for (auto part = temp.cbegin(); part != temp.cend(); ++part) {
if (!part.get_value().empty()) {
result.push_back(part.get_value());
}
}
}
return result;
}
Optional<string>& get_dummy_headers_sent_filename() noexcept {
static Optional<string> filename;
return filename;
}
Optional<int64_t>& get_dummy_headers_sent_line() noexcept {
static Optional<int64_t> dummy_line;
return dummy_line;
}
bool f$headers_sent([[maybe_unused]] Optional<string>& filename, [[maybe_unused]] Optional<int64_t>& line) {
return headers_sent;
}
void f$send_http_103_early_hints(const array<string>& headers) {
string header("HTTP/1.1 103 Early Hints\r\n");
for (const auto& h : headers) {
header.append(h.get_value().c_str()).append("\r\n");
}
http_send_immediate_response(header.c_str(), header.size(), "\r\n", 2);
}
void f$setrawcookie(const string& name, const string& value, int64_t expire, const string& path, const string& domain, bool secure, bool http_only) {
string date = f$gmdate(HTTP_DATE, expire);
kphp_runtime_context.static_SB_spare.clean() << "Set-Cookie: " << name << '=';
if (value.empty()) {
kphp_runtime_context.static_SB_spare << "DELETED; expires=Thu, 01 Jan 1970 00:00:01 GMT";
} else {
kphp_runtime_context.static_SB_spare << value;
if (expire != 0) {
kphp_runtime_context.static_SB_spare << "; expires=" << date;
}
}
if (!path.empty()) {
kphp_runtime_context.static_SB_spare << "; path=" << path;
}
if (!domain.empty()) {
kphp_runtime_context.static_SB_spare << "; domain=" << domain;
}
if (secure) {
kphp_runtime_context.static_SB_spare << "; secure";
}
if (http_only) {
kphp_runtime_context.static_SB_spare << "; HttpOnly";
}
header(kphp_runtime_context.static_SB_spare.c_str(), (int)kphp_runtime_context.static_SB_spare.size(), false);
}
void f$setcookie(const string& name, const string& value, int64_t expire, const string& path, const string& domain, bool secure, bool http_only) {
f$setrawcookie(name, f$urlencode(value), expire, path, domain, secure, http_only);
}
int64_t f$ignore_user_abort(Optional<bool> enable) {
php_assert(php_worker.has_value() && php_worker->conn != nullptr);
if (enable.is_null()) {
return ignore_level;
} else if (enable.val()) {
php_worker->conn->ignored = true;
return ignore_level++;
} else {
int prev = ignore_level > 0 ? ignore_level-- : 0;
if (ignore_level == 0) {
php_worker->conn->ignored = false;
}
if (php_worker->conn->interrupted && !php_worker->conn->ignored) {
php_worker->conn->status = conn_error;
f$exit(1);
}
return prev;
}
}
static inline const char* http_get_error_msg_text(int* code) {
if (*code == 200) {
return "OK";
}
if (*code < 100 || *code > 999) {
*code = 500;
}
switch (*code) {
case 201:
return "Created";
case 202:
return "Accepted";
case 204:
return "No Content";
case 206:
return "Partial Content";
case 301:
return "Moved Permanently";
case 302:
return "Found";
case 303:
return "See Other";
case 304:
return "Not Modified";
case 307:
return "Temporary Redirect";
case 400:
return "Bad Request";
case 401:
return "Unauthorized";
case 403:
return "Forbidden";
case 404:
return "Not Found";
case 405:
return "Method Not Allowed";
case 406:
return "Not Acceptable";
case 408:
return "Request Timeout";
case 411:
return "Length Required";
case 413:
return "Request Entity Too Large";
case 414:
return "Request-URI Too Long";
case 418:
return "I'm a teapot";
case 480:
return "Temporarily Unavailable";
case 500:
return "Internal Server Error";
case 501:
return "Not Implemented";
case 502:
return "Bad Gateway";
case 503:
return "Service Unavailable";
}
return "Extension Code";
}
static void set_content_length_header(int content_length) {
kphp_runtime_context.static_SB_spare.clean() << "Content-Length: " << content_length;
header(kphp_runtime_context.static_SB_spare.c_str(), (int)kphp_runtime_context.static_SB_spare.size());
}
static const string_buffer* get_headers() { // can't use static_SB, returns pointer to kphp_runtime_context.static_SB_spare
string date = f$gmdate(HTTP_DATE);
kphp_runtime_context.static_SB_spare.clean() << "Date: " << date;
header(kphp_runtime_context.static_SB_spare.c_str(), (int)kphp_runtime_context.static_SB_spare.size());
php_assert(dl::query_num == header_last_query_num);
kphp_runtime_context.static_SB_spare.clean();
if (!http_status_line.empty()) {
kphp_runtime_context.static_SB_spare << http_status_line << "\r\n";
} else {
const char* message = http_get_error_msg_text(&http_return_code);
kphp_runtime_context.static_SB_spare << "HTTP/1.1 " << http_return_code << " " << message << "\r\n";
}
const array<string>* arr = headers;
for (array<string>::const_iterator p = arr->begin(); p != arr->end(); ++p) {
kphp_runtime_context.static_SB_spare << p.get_value();
}
kphp_runtime_context.static_SB_spare << "\r\n";
return &kphp_runtime_context.static_SB_spare;
}
constexpr uint32_t MAX_SHUTDOWN_FUNCTIONS = 256;
namespace {
int shutdown_functions_count = 0;
char shutdown_function_storage[MAX_SHUTDOWN_FUNCTIONS * sizeof(shutdown_function_type)];
shutdown_function_type* const shutdown_functions = reinterpret_cast<shutdown_function_type*>(shutdown_function_storage);
shutdown_functions_status shutdown_functions_status_value = shutdown_functions_status::not_executed;
jmp_buf timeout_exit;
bool finished = false;
} // namespace
static const string_buffer* compress_http_query_body(string_buffer* http_query_body) {
php_assert(http_query_body != nullptr);
if (is_head_query) {
http_query_body->clean();
return http_query_body;
} else {
if ((http_need_gzip & 5) == 5) {
header("Content-Encoding: gzip", 22, true);
return zlib_encode(http_query_body->c_str(), http_query_body->size(), 6, ZLIB_ENCODING_GZIP);
} else if ((http_need_gzip & 6) == 6) {
header("Content-Encoding: deflate", 25, true);
return zlib_encode(http_query_body->c_str(), http_query_body->size(), 6, ZLIB_ENCODING_DEFLATE);
} else {
return http_query_body;
}
}
}
static int ob_merge_buffers() {
php_assert(ob_cur_buffer >= 0);
int ob_first_not_empty = 0;
while (ob_first_not_empty < ob_cur_buffer && oub[ob_first_not_empty].size() == 0) {
ob_first_not_empty++;
}
for (int i = ob_first_not_empty + 1; i <= ob_cur_buffer; i++) {
oub[ob_first_not_empty].append(oub[i].c_str(), oub[i].size());
}
return ob_first_not_empty;
}
void f$flush() {
php_assert(ob_cur_buffer >= 0 && php_worker.has_value());
// Run custom headers handler before body processing
if (!headers_custom_handler_invoked && query_type == QUERY_TYPE_HTTP) {
headers_custom_handler_invoked = true;
if (headers_custom_handler_function) {
headers_custom_handler_function();
}
headers_sent = true;
}
string_buffer const* http_body = compress_http_query_body(&oub[ob_system_level]);
string_buffer const* http_headers = nullptr;
if (!php_worker->flushed_http_connection) {
http_headers = get_headers();
php_worker->flushed_http_connection = true;
}
http_send_immediate_response(http_headers ? http_headers->buffer() : nullptr, http_headers ? http_headers->size() : 0, http_body->buffer(),
http_body->size());
oub[ob_system_level].clean();
kphp_runtime_context.static_SB_spare.clean();
}
void f$fastcgi_finish_request(int64_t exit_code) {
// Run custom headers handler before body processing
if (!headers_custom_handler_invoked && query_type == QUERY_TYPE_HTTP) {
headers_custom_handler_invoked = true;
if (headers_custom_handler_function) {
headers_custom_handler_function();
}
headers_sent = true;
}
int ob_total_buffer = ob_merge_buffers();
if (php_worker.has_value() && php_worker->flushed_http_connection) {
string const raw_response = oub[ob_total_buffer].str();
http_set_result(nullptr, 0, raw_response.c_str(), raw_response.size(), static_cast<int32_t>(exit_code));
php_assert(0);
}
if (!run_once) {
exit_code = 0; // TODO: is it correct?
}
switch (query_type) {
case QUERY_TYPE_CONSOLE: {
// TODO console_set_result
fflush(stderr);
write_safe(1, oub[ob_total_buffer].buffer(), oub[ob_total_buffer].size(), {});
// TODO move to finish_script
free_runtime_environment(PhpScriptMutableGlobals::current().get_superglobals());
break;
}
case QUERY_TYPE_HTTP: {
const string_buffer* compressed = compress_http_query_body(&oub[ob_total_buffer]);
if (!is_head_query) {
set_content_length_header(compressed->size());
}
const string_buffer* headers = get_headers();
http_set_result(headers->buffer(), headers->size(), compressed->buffer(), compressed->size(), static_cast<int32_t>(exit_code));
break;
}
case QUERY_TYPE_RPC: {
rpc_set_result(oub[ob_total_buffer].buffer(), oub[ob_total_buffer].size(), static_cast<int32_t>(exit_code));
break;
}
case QUERY_TYPE_JOB: {
job_set_result(static_cast<int32_t>(exit_code));
break;
}
default:
php_assert(0);
exit(1);
}
ob_cur_buffer = 0;
coub = &oub[ob_cur_buffer];
coub->clean();
}
void run_shutdown_functions(ShutdownType shutdown_type) {
if (kphp_tracing::is_turned_on()) {
kphp_tracing::on_shutdown_functions_start(static_cast<int>(shutdown_type));
}
php_assert(dl::is_malloc_replaced() == false);
forcibly_stop_all_running_resumables();
ShutdownProfiler shutdown_profiler;
for (int i = 0; i < shutdown_functions_count; i++) {
shutdown_functions[i]();
}
// don't wrap this call into if(kphp_tracing::is_turned_on()), intentionally
kphp_tracing::on_php_script_finish_ok(f$get_net_time(), f$get_script_time());
}
shutdown_functions_status get_shutdown_functions_status() {
return shutdown_functions_status_value;
}
int get_shutdown_functions_count() {
return shutdown_functions_count;
}
void run_shutdown_functions_from_timeout() {
shutdown_functions_status_value = shutdown_functions_status::running_from_timeout;
// to safely run the shutdown handlers in the timeout context, we set
// a recovery point to be used from the user-called die/exit;
// without that, exit would lead to a finished state instead of the error state
// we were about to enter (since timeout is an error state)
reset_script_timeout();
if (setjmp(timeout_exit) == 0) {
run_shutdown_functions(ShutdownType::timeout);
}
}
void run_shutdown_functions_from_script(ShutdownType shutdown_type) {
shutdown_functions_status_value = shutdown_functions_status::running;
// when running shutdown functions from a normal (non-timeout) context,
// reset the timer to give shutdown functions a new span of time to avoid
// prematurely terminated shutdown functions for long running scripts;
// if shutdown functions can't finish with that time quota, they will
// be interrupted as usual
reset_script_timeout();
run_shutdown_functions(shutdown_type);
}
void register_shutdown_function_impl(shutdown_function_type&& f) {
if (shutdown_functions_count == MAX_SHUTDOWN_FUNCTIONS) {
php_warning("Too many shutdown functions registered, ignore next one\n");
return;
}
// this guard is to preserve correct state of 'shutdown_function_type' after construction
// it's matter because the destructor of 'shutdown_function_type' is called now
dl::CriticalSectionGuard critical_section;
// I really need this, because this memory can contain random trash, if previouse script failed
new (&shutdown_functions[shutdown_functions_count++]) shutdown_function_type{std::move(f)};
}
void register_header_handler_impl(headers_custom_handler_function_type&& f) {
dl::CriticalSectionGuard critical_section;
// Move assignment leads to lhs object invalidation and fires memory releasing mechanism
// But memory is already released by destructor after previous run
// Therefore we need to use placement new
new (&headers_custom_handler_function) headers_custom_handler_function_type{std::move(f)};
}
void finish(int64_t exit_code, bool from_exit) {
check_script_timeout();
if (!finished) {
finished = true;
forcibly_stop_profiler();
run_shutdown_functions_from_script(from_exit ? ShutdownType::exit : ShutdownType::normal);
}
f$fastcgi_finish_request(exit_code);
finish_script(static_cast<int32_t>(exit_code));
// unreachable
php_assert(0);
}
void f$exit(const mixed& v) {
if (shutdown_functions_status_value == shutdown_functions_status::running_from_timeout) {
longjmp(timeout_exit, 1);
}
if (v.is_string()) {
*coub << v;
finish(0, true);
} else {
finish(v.to_int(), true);
}
}
void f$die(const mixed& v) {
f$exit(v);
}
Optional<array<string>> f$gethostbynamel(const string& name) {
dl::enter_critical_section(); // OK
struct hostent* hp = gethostbyname(name.c_str());
if (hp == nullptr || hp->h_addr_list == nullptr) {
dl::leave_critical_section();
return false;
}
dl::leave_critical_section();
array<string> result;
for (int i = 0; hp->h_addr_list[i] != nullptr; i++) {
dl::enter_critical_section(); // OK
const char* ip = inet_ntoa(*(struct in_addr*)hp->h_addr_list[i]);
dl::leave_critical_section();
result.push_back(string(ip));
}
return result;
}
Optional<string> f$inet_pton(const string& address) {
int af, size;
if (strchr(address.c_str(), ':')) {
af = AF_INET6;
size = 16;
} else if (strchr(address.c_str(), '.')) {
af = AF_INET;
size = 4;
} else {
php_warning("Unrecognized address \"%s\"", address.c_str());
return false;
}
char buffer[17] = {0};
dl::enter_critical_section(); // OK
if (inet_pton(af, address.c_str(), buffer) <= 0) {
dl::leave_critical_section();
php_warning("Unrecognized address \"%s\"", address.c_str());
return false;
}
dl::leave_critical_section();
return string(buffer, size);
}
extern bool run_once;
void print(const char* s, size_t s_len) {
if (run_once && ob_cur_buffer == 0) {
dl::CriticalSectionGuard critical_section;
write(kstdout, s, s_len);
} else {
coub->append(s, s_len);
}
}
void print(const char* s) {
print(s, strlen(s));
}
void print(const string& s) {
print(s.c_str(), s.size());
}
void print(const string_buffer& sb) {
print(sb.buffer(), sb.size());
}
void dbg_echo(const char* s, size_t s_len) {
dl::CriticalSectionGuard critical_section;
write(kstderr, s, s_len);
}
void dbg_echo(const char* s) {
dbg_echo(s, strlen(s));
}
void dbg_echo(const string& s) {
dbg_echo(s.c_str(), s.size());
}
void dbg_echo(const string_buffer& sb) {
dbg_echo(sb.buffer(), sb.size());
}
bool f$get_magic_quotes_gpc() {
return false;
}
static string php_sapi_name() {
switch (query_type) {
case QUERY_TYPE_CONSOLE:
return string("cli");
case QUERY_TYPE_HTTP:
return string("Kitten PHP");
case QUERY_TYPE_RPC:
if (run_once) {
return string("cli");
} else {
return string("Kitten PHP");
}
case QUERY_TYPE_JOB:
return string("KPHP job");
default:
php_assert(0);
exit(1);
}
}
string f$php_sapi_name() {
return PhpScriptMutableGlobals::current().get_superglobals().v$d$PHP_SAPI;
}
static std::aligned_storage_t<sizeof(array<bool>), alignof(array<bool>)> uploaded_files_storage;
static array<bool>* uploaded_files = reinterpret_cast<array<bool>*>(&uploaded_files_storage);
static long long uploaded_files_last_query_num = -1;
static const int MAX_FILES = 100;
static string raw_post_data;
bool f$is_uploaded_file(const string& filename) {
return (dl::query_num == uploaded_files_last_query_num && uploaded_files->get_value(filename) == 1);
}
bool f$move_uploaded_file(const string& oldname, const string& newname) {
if (!f$is_uploaded_file(oldname)) {
return false;
}
dl::enter_critical_section(); // NOT OK: uploaded_files
if (f$rename(oldname, newname)) {
uploaded_files->unset(oldname);
dl::leave_critical_section();
return true;
}
dl::leave_critical_section();
return false;
}
class post_reader {
char* buf;
int post_len;
int buf_pos;
int buf_len;
const string boundary;
post_reader(const post_reader&); // DISABLE copy constructor
post_reader operator=(const post_reader&); // DISABLE copy assignment
public:
post_reader(const char* post, int post_len, const string& boundary)
: post_len(post_len),
buf_pos(0),
boundary(boundary) {
if (post == nullptr) {
buf = StringLibContext::get().static_buf.get();
buf_len = 0;
} else {
buf = (char*)post;
buf_len = post_len;
}
}
int operator[](int i) {
php_assert(i >= buf_pos);
php_assert(i <= post_len);
if (i >= post_len) {
return 0;
}
i -= buf_pos;
while (i >= buf_len) {
int left = post_len - buf_pos - buf_len;
int chunk_size = (int)boundary.size() + 65536 + 10;
// fprintf (stderr, "Load at pos %d. i = %d, buf_len = %d, left = %d, chunk_size = %d\n", i + buf_pos, i, buf_len, left, chunk_size);
if (buf_len > 0) {
int to_leave = chunk_size;
int to_erase = buf_len - to_leave;
php_assert(left > 0);
php_assert(to_erase >= to_leave);
memcpy(buf, buf + to_erase, to_leave);
buf_pos += to_erase;
i -= to_erase;
buf_len = to_leave + http_load_long_query(buf + to_leave, min(to_leave, left), min(StringLibContext::STATIC_BUFFER_LENGTH - to_leave, left));
} else {
buf_len = http_load_long_query(buf, min(2 * chunk_size, left), min(StringLibContext::STATIC_BUFFER_LENGTH, left));
}
}
return buf[i];
}
bool is_boundary(int i) {
php_assert(i >= buf_pos);
php_assert(i <= post_len);
if (i >= post_len) {
return true;
}
if (i > 0) {
if ((*this)[i] == '\r') {
i++;
}
if ((*this)[i] == '\n') {
i++;
} else {
return false;
}
}
if ((*this)[i] == '-' && (*this)[i + 1] == '-') {
i += 2;
} else {
return false;
}
if (i + (int)boundary.size() > post_len) {
return false;
}
if (i - buf_pos + (int)boundary.size() <= buf_len) {
return !memcmp(buf + i - buf_pos, boundary.c_str(), boundary.size());
}
for (int j = 0; j < (int)boundary.size(); j++) {
if ((*this)[i + j] != boundary[j]) {
return false;
}
}
return true;
}
int upload_file(const string& file_name, int& pos, int64_t max_file_size) {
php_assert(pos > 0 && buf_len > 0 && buf_pos <= pos && pos <= post_len);
if (pos == post_len) {