forked from wikimedia/mediawiki-php-luasandbox
-
Notifications
You must be signed in to change notification settings - Fork 0
/
luasandbox.c
2224 lines (1943 loc) · 63.2 KB
/
luasandbox.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include <lua.h>
#include <lauxlib.h>
#include <math.h>
#include <time.h>
#include <stdlib.h>
#include "php.h"
#include "php_ini.h"
#include "ext/standard/info.h"
#include "zend_exceptions.h"
#include "php_luasandbox.h"
#include "luasandbox_timer.h"
#if PHP_VERSION_ID < 70000
#include "ext/standard/php_smart_str.h"
#else
#include "zend_smart_str.h"
#endif
#include "luasandbox_version.h"
// Compatability for PHP <= 5.3.6
#ifndef ZEND_FE_END
#define ZEND_FE_END { NULL, NULL, NULL, 0, 0 }
#endif
// Compatability typedefs and defines to hide some PHP5/PHP7 differences
#if PHP_VERSION_ID < 70000
typedef zend_object_value object_constructor_ret_t;
typedef int str_param_len_t;
typedef long long_param_t;
typedef zval*** star_param_t;
#define compat_zend_register_internal_class_ex(ce, parent_ce) zend_register_internal_class_ex(ce, parent_ce, NULL TSRMLS_CC)
#define compat_add_assoc_string(assoc, key, val) add_assoc_string((assoc), (key), (val), 1)
#else
typedef zend_object* object_constructor_ret_t;
typedef size_t str_param_len_t;
typedef zend_long long_param_t;
typedef zval* star_param_t;
#define compat_zend_register_internal_class_ex(ce, parent_ce) zend_register_internal_class_ex(ce, parent_ce)
#define compat_add_assoc_string(assoc, key, val) add_assoc_string((assoc), (key), (val))
#endif
#define CHECK_VALID_STATE(state) \
if (!state) { \
php_error_docref(NULL TSRMLS_CC, E_WARNING, "invalid LuaSandbox state"); \
RETURN_FALSE; \
}
static PHP_GINIT_FUNCTION(luasandbox);
static PHP_GSHUTDOWN_FUNCTION(luasandbox);
static int luasandbox_post_deactivate();
static object_constructor_ret_t luasandbox_new(zend_class_entry *ce TSRMLS_DC);
static lua_State * luasandbox_newstate(php_luasandbox_obj * intern TSRMLS_DC);
static void luasandbox_free_storage(zend_object *object TSRMLS_DC);
static object_constructor_ret_t luasandboxfunction_new(zend_class_entry *ce TSRMLS_DC);
static void luasandboxfunction_free_storage(zend_object *object TSRMLS_DC);
static int luasandbox_panic(lua_State * L);
static lua_State * luasandbox_state_from_zval(zval * this_ptr TSRMLS_DC);
static void luasandbox_load_helper(int binary, INTERNAL_FUNCTION_PARAMETERS);
static int luasandbox_find_field(lua_State * L, int index,
char * spec, int specLength);
static void luasandbox_set_timespec(struct timespec * dest, double source);
static int luasandbox_function_init(zval * this_ptr, php_luasandboxfunction_obj ** pfunc,
lua_State ** pstate, php_luasandbox_obj ** psandbox TSRMLS_DC);
static void luasandbox_function_push(php_luasandboxfunction_obj * pfunc, lua_State * pstate);
static void luasandbox_call_helper(lua_State * L, zval * sandbox_zval,
php_luasandbox_obj * sandbox,
star_param_t args, int numArgs, zval * return_value TSRMLS_DC);
static void luasandbox_handle_error(php_luasandbox_obj * sandbox, int status TSRMLS_DC);
static int luasandbox_dump_writer(lua_State * L, const void * p, size_t sz, void * ud);
static zend_bool luasandbox_instanceof(
zend_class_entry *child_class, zend_class_entry *parent_class);
extern char luasandbox_timeout_message[];
/** For LuaSandbox::getProfilerFunctionReport() */
enum {
LUASANDBOX_SAMPLES,
LUASANDBOX_SECONDS,
LUASANDBOX_PERCENT
};
zend_class_entry *luasandbox_ce;
zend_class_entry *luasandboxerror_ce;
zend_class_entry *luasandboxruntimeerror_ce;
zend_class_entry *luasandboxfatalerror_ce;
zend_class_entry *luasandboxsyntaxerror_ce;
zend_class_entry *luasandboxmemoryerror_ce;
zend_class_entry *luasandboxerrorerror_ce;
zend_class_entry *luasandboxtimeouterror_ce;
zend_class_entry *luasandboxemergencytimeouterror_ce;
zend_class_entry *luasandboxfunction_ce;
ZEND_DECLARE_MODULE_GLOBALS(luasandbox);
#if PHP_VERSION_ID >= 70000
static zend_object_handlers luasandbox_object_handlers;
static zend_object_handlers luasandboxfunction_object_handlers;
#endif
/** {{{ arginfo */
ZEND_BEGIN_ARG_INFO(arginfo_luasandbox_getVersionInfo, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO_EX(arginfo_luasandbox_loadString, 0, 0, 1)
ZEND_ARG_INFO(0, code)
ZEND_ARG_INFO(0, chunkName)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO_EX(arginfo_luasandbox_loadBinary, 0, 0, 1)
ZEND_ARG_INFO(0, code)
ZEND_ARG_INFO(0, chunkName)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO(arginfo_luasandbox_setMemoryLimit, 0)
ZEND_ARG_INFO(0, limit)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO(arginfo_luasandbox_getMemoryUsage, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO(arginfo_luasandbox_getPeakMemoryUsage, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO(arginfo_luasandbox_setCPULimit, 0)
ZEND_ARG_INFO(0, limit)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO(arginfo_luasandbox_getCPUUsage, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO(arginfo_luasandbox_pauseUsageTimer, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO(arginfo_luasandbox_unpauseUsageTimer, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO_EX(arginfo_luasandbox_enableProfiler, 0, 0, 0)
ZEND_ARG_INFO(0, period)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO(arginfo_luasandbox_disableProfiler, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO_EX(arginfo_luasandbox_getProfilerFunctionReport, 0, 0, 0)
ZEND_ARG_INFO(0, units)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO_EX(arginfo_luasandbox_callFunction, 0, 0, 1)
ZEND_ARG_INFO(0, name)
#ifdef ZEND_ARG_VARIADIC_INFO
ZEND_ARG_VARIADIC_INFO(0, args)
#else
ZEND_ARG_INFO(0, ...)
#endif
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO(arginfo_luasandbox_wrapPhpFunction, 0)
ZEND_ARG_INFO(0, function)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO(arginfo_luasandbox_registerLibrary, 0)
ZEND_ARG_INFO(0, libname)
ZEND_ARG_INFO(0, functions)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO(arginfo_luasandboxfunction___construct, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO_EX(arginfo_luasandboxfunction_call, 0, 0, 0)
#ifdef ZEND_ARG_VARIADIC_INFO
ZEND_ARG_VARIADIC_INFO(0, args)
#else
ZEND_ARG_INFO(0, ...)
#endif
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO(arginfo_luasandboxfunction_dump, 0)
ZEND_END_ARG_INFO()
/* }}} */
/** {{{ function entries */
const zend_function_entry luasandbox_functions[] = {
ZEND_FE_END /* Must be the last line in luasandbox_functions[] */
};
const zend_function_entry luasandbox_methods[] = {
PHP_ME(LuaSandbox, getVersionInfo, arginfo_luasandbox_getVersionInfo, ZEND_ACC_PUBLIC|ZEND_ACC_STATIC)
PHP_ME(LuaSandbox, loadString, arginfo_luasandbox_loadString, 0)
PHP_ME(LuaSandbox, loadBinary, arginfo_luasandbox_loadBinary, 0)
PHP_ME(LuaSandbox, setMemoryLimit, arginfo_luasandbox_setMemoryLimit, 0)
PHP_ME(LuaSandbox, getMemoryUsage, arginfo_luasandbox_getMemoryUsage, 0)
PHP_ME(LuaSandbox, getPeakMemoryUsage, arginfo_luasandbox_getPeakMemoryUsage, 0)
PHP_ME(LuaSandbox, setCPULimit, arginfo_luasandbox_setCPULimit, 0)
PHP_ME(LuaSandbox, getCPUUsage, arginfo_luasandbox_getCPUUsage, 0)
PHP_ME(LuaSandbox, pauseUsageTimer, arginfo_luasandbox_pauseUsageTimer, 0)
PHP_ME(LuaSandbox, unpauseUsageTimer, arginfo_luasandbox_unpauseUsageTimer, 0)
PHP_ME(LuaSandbox, enableProfiler, arginfo_luasandbox_enableProfiler, 0)
PHP_ME(LuaSandbox, disableProfiler, arginfo_luasandbox_disableProfiler, 0)
#ifdef HHVM
// We need to wrap this method in ext_luasandbox.php for HHVM
PHP_ME(LuaSandbox, _internal_getProfilerFunctionReport, arginfo_luasandbox_getProfilerFunctionReport,
ZEND_ACC_PRIVATE | ZEND_ACC_FINAL)
#else
PHP_ME(LuaSandbox, getProfilerFunctionReport, arginfo_luasandbox_getProfilerFunctionReport, 0)
#endif
PHP_ME(LuaSandbox, callFunction, arginfo_luasandbox_callFunction, 0)
PHP_ME(LuaSandbox, wrapPhpFunction, arginfo_luasandbox_wrapPhpFunction, 0)
PHP_ME(LuaSandbox, registerLibrary, arginfo_luasandbox_registerLibrary, 0)
ZEND_FE_END
};
const zend_function_entry luasandboxfunction_methods[] = {
PHP_ME(LuaSandboxFunction, __construct, arginfo_luasandboxfunction___construct,
ZEND_ACC_PRIVATE | ZEND_ACC_FINAL)
PHP_ME(LuaSandboxFunction, call, arginfo_luasandboxfunction_call, 0)
PHP_ME(LuaSandboxFunction, dump, arginfo_luasandboxfunction_dump, 0)
ZEND_FE_END
};
const zend_function_entry luasandbox_empty_methods[] = {
ZEND_FE_END
};
/* }}} */
/* {{{ luasandbox_module_entry
*/
zend_module_entry luasandbox_module_entry = {
#if ZEND_MODULE_API_NO >= 20010901
STANDARD_MODULE_HEADER,
#endif
"luasandbox",
luasandbox_functions,
PHP_MINIT(luasandbox),
PHP_MSHUTDOWN(luasandbox),
NULL, /* RINIT */
PHP_RSHUTDOWN(luasandbox), /* RSHUTDOWN */
PHP_MINFO(luasandbox),
LUASANDBOX_VERSION,
PHP_MODULE_GLOBALS(luasandbox),
PHP_GINIT(luasandbox),
PHP_GSHUTDOWN(luasandbox),
luasandbox_post_deactivate,
STANDARD_MODULE_PROPERTIES_EX
};
/* }}} */
#ifdef COMPILE_DL_LUASANDBOX
ZEND_GET_MODULE(luasandbox)
#endif
/* {{{ PHP_MINIT_FUNCTION
*/
PHP_MINIT_FUNCTION(luasandbox)
{
/* If you have INI entries, uncomment these lines
REGISTER_INI_ENTRIES();
*/
zend_class_entry ce;
INIT_CLASS_ENTRY(ce, "LuaSandbox", luasandbox_methods);
luasandbox_ce = zend_register_internal_class(&ce TSRMLS_CC);
luasandbox_ce->create_object = luasandbox_new;
zend_declare_class_constant_long(luasandbox_ce,
"SAMPLES", sizeof("SAMPLES")-1, LUASANDBOX_SAMPLES TSRMLS_CC);
zend_declare_class_constant_long(luasandbox_ce,
"SECONDS", sizeof("SECONDS")-1, LUASANDBOX_SECONDS TSRMLS_CC);
zend_declare_class_constant_long(luasandbox_ce,
"PERCENT", sizeof("PERCENT")-1, LUASANDBOX_PERCENT TSRMLS_CC);
INIT_CLASS_ENTRY(ce, "LuaSandboxError", luasandbox_empty_methods);
luasandboxerror_ce = compat_zend_register_internal_class_ex(&ce, zend_exception_get_default(TSRMLS_C));
zend_declare_class_constant_long(luasandboxerror_ce,
"RUN", sizeof("RUN")-1, LUA_ERRRUN TSRMLS_CC);
zend_declare_class_constant_long(luasandboxerror_ce,
"SYNTAX", sizeof("SYNTAX")-1, LUA_ERRSYNTAX TSRMLS_CC);
zend_declare_class_constant_long(luasandboxerror_ce,
"MEM", sizeof("MEM")-1, LUA_ERRMEM TSRMLS_CC);
zend_declare_class_constant_long(luasandboxerror_ce,
"ERR", sizeof("ERR")-1, LUA_ERRERR TSRMLS_CC);
INIT_CLASS_ENTRY(ce, "LuaSandboxRuntimeError", luasandbox_empty_methods);
luasandboxruntimeerror_ce = compat_zend_register_internal_class_ex(&ce, luasandboxerror_ce);
INIT_CLASS_ENTRY(ce, "LuaSandboxFatalError", luasandbox_empty_methods);
luasandboxfatalerror_ce = compat_zend_register_internal_class_ex(&ce, luasandboxerror_ce);
INIT_CLASS_ENTRY(ce, "LuaSandboxSyntaxError", luasandbox_empty_methods);
luasandboxsyntaxerror_ce = compat_zend_register_internal_class_ex(&ce, luasandboxfatalerror_ce);
INIT_CLASS_ENTRY(ce, "LuaSandboxMemoryError", luasandbox_empty_methods);
luasandboxmemoryerror_ce = compat_zend_register_internal_class_ex(&ce, luasandboxfatalerror_ce);
INIT_CLASS_ENTRY(ce, "LuaSandboxErrorError", luasandbox_empty_methods);
luasandboxerrorerror_ce = compat_zend_register_internal_class_ex(&ce, luasandboxfatalerror_ce);
INIT_CLASS_ENTRY(ce, "LuaSandboxTimeoutError", luasandbox_empty_methods);
luasandboxtimeouterror_ce = compat_zend_register_internal_class_ex(&ce, luasandboxfatalerror_ce);
// Deprecated, for catch blocks only
INIT_CLASS_ENTRY(ce, "LuaSandboxEmergencyTimeoutError", luasandbox_empty_methods);
luasandboxemergencytimeouterror_ce = compat_zend_register_internal_class_ex(&ce, luasandboxfatalerror_ce);
INIT_CLASS_ENTRY(ce, "LuaSandboxFunction", luasandboxfunction_methods);
luasandboxfunction_ce = zend_register_internal_class(&ce TSRMLS_CC);
luasandboxfunction_ce->create_object = luasandboxfunction_new;
#if PHP_VERSION_ID >= 70000
memcpy(&luasandbox_object_handlers, zend_get_std_object_handlers(), sizeof(zend_object_handlers));
luasandbox_object_handlers.offset = XtOffsetOf(php_luasandbox_obj, std);
luasandbox_object_handlers.free_obj = (zend_object_free_obj_t)luasandbox_free_storage;
memcpy(&luasandboxfunction_object_handlers, zend_get_std_object_handlers(), sizeof(zend_object_handlers));
luasandboxfunction_object_handlers.offset = XtOffsetOf(php_luasandboxfunction_obj, std);
luasandboxfunction_object_handlers.free_obj = (zend_object_free_obj_t)luasandboxfunction_free_storage;
#endif
luasandbox_timer_minit(TSRMLS_C);
return SUCCESS;
}
/* }}} */
/** {{{ luasandbox_init_globals */
static PHP_GINIT_FUNCTION(luasandbox)
{
memset(luasandbox_globals, 0, sizeof(*luasandbox_globals));
}
/* }}} */
/** {{{ luasandbox_destroy_globals */
static PHP_GSHUTDOWN_FUNCTION(luasandbox)
{
}
/* }}} */
/* {{{ PHP_MSHUTDOWN_FUNCTION
*/
PHP_MSHUTDOWN_FUNCTION(luasandbox)
{
luasandbox_timer_mshutdown(TSRMLS_C);
return SUCCESS;
}
/* }}} */
/* {{{ PHP_RSHUTDOWN_FUNCTION */
PHP_RSHUTDOWN_FUNCTION(luasandbox)
{
#ifdef HHVM
// Under HHVM, free_storage handlers are not called on request shutdown
if (LUASANDBOX_G(active_count)) {
php_error(E_WARNING, "leaking %ld LuaSandbox object(s)",
LUASANDBOX_G(active_count));
LUASANDBOX_G(active_count) = 0;
}
#endif
return SUCCESS;
}
/* }}} */
static int luasandbox_post_deactivate() /* {{{ */
{
TSRMLS_FETCH();
luasandbox_lib_destroy_globals(TSRMLS_C);
return SUCCESS;
}
/* }}} */
/* {{{ PHP_MINFO_FUNCTION
*/
PHP_MINFO_FUNCTION(luasandbox)
{
php_info_print_table_start();
php_info_print_table_header(2, "luasandbox support", "enabled");
php_info_print_table_end();
}
/* }}} */
/** {{{ luasandbox_new
*
* "new" handler for the LuaSandbox class
*/
static object_constructor_ret_t luasandbox_new(zend_class_entry *ce TSRMLS_DC)
{
php_luasandbox_obj * sandbox;
// Create the internal object
#if PHP_VERSION_ID < 70000
sandbox = (php_luasandbox_obj*)ecalloc(1, sizeof(php_luasandbox_obj));
#elif PHP_VERSION_ID < 70300
sandbox = (php_luasandbox_obj*)ecalloc(1, sizeof(php_luasandbox_obj) + zend_object_properties_size(ce));
#else
sandbox = (php_luasandbox_obj*)zend_object_alloc(sizeof(php_luasandbox_obj), ce);
#endif
zend_object_std_init(&sandbox->std, ce TSRMLS_CC);
#if PHP_VERSION_ID > 50399
object_properties_init(&sandbox->std, ce);
#endif
sandbox->alloc.memory_limit = (size_t)-1;
sandbox->allow_pause = 1;
// Initialise the Lua state
sandbox->state = luasandbox_newstate(sandbox TSRMLS_CC);
// Initialise the timer
luasandbox_timer_create(&sandbox->timer, sandbox);
#if PHP_VERSION_ID < 70000
// Put the object into the store
zend_object_value retval;
retval.handle = zend_objects_store_put(
sandbox,
(zend_objects_store_dtor_t)zend_objects_destroy_object,
(zend_objects_free_object_storage_t)luasandbox_free_storage,
NULL TSRMLS_CC);
retval.handlers = zend_get_std_object_handlers();
LUASANDBOX_G(active_count)++;
return retval;
#else
sandbox->std.handlers = &luasandbox_object_handlers;
LUASANDBOX_G(active_count)++;
return &sandbox->std;
#endif
}
/* }}} */
/** {{{ luasandbox_newstate
*
* Create a new lua_State which is suitable for running sandboxed scripts in.
* Initialise libraries and any necessary registry entries.
*/
static lua_State * luasandbox_newstate(php_luasandbox_obj * intern TSRMLS_DC)
{
lua_State * L = luasandbox_alloc_new_state(&intern->alloc, intern);
if (L == NULL) {
php_error_docref(NULL TSRMLS_CC, E_ERROR,
"Attempt to allocate a new Lua state failed");
}
lua_atpanic(L, luasandbox_panic);
// Register the standard library
luasandbox_lib_register(L TSRMLS_CC);
// Set up the data conversion module
luasandbox_data_conversion_init(L);
// Create a table for storing chunks
lua_newtable(L);
lua_setfield(L, LUA_REGISTRYINDEX, "php_luasandbox_chunks");
// Register a pointer to the PHP object so that C functions can find it
lua_pushlightuserdata(L, (void*)intern);
lua_setfield(L, LUA_REGISTRYINDEX, "php_luasandbox_obj");
return L;
}
/* }}} */
/** {{{ luasandbox_free_storage
*
* "Free storage" handler for LuaSandbox objects.
*/
static void luasandbox_free_storage(zend_object *object TSRMLS_DC)
{
php_luasandbox_obj * sandbox = php_luasandbox_fetch_object(object);
luasandbox_timer_destroy(&sandbox->timer);
if (sandbox->state) {
luasandbox_alloc_delete_state(&sandbox->alloc, sandbox->state);
sandbox->state = NULL;
}
zend_object_std_dtor(&sandbox->std TSRMLS_CC);
#if PHP_VERSION_ID < 70000
efree(object);
#endif
LUASANDBOX_G(active_count)--;
}
/* }}} */
/** {{{ luasandboxfunction_new
*
* "new" handler for the LuaSandboxFunction class.
*/
static object_constructor_ret_t luasandboxfunction_new(zend_class_entry *ce TSRMLS_DC)
{
php_luasandboxfunction_obj * intern;
// Create the internal object
#if PHP_VERSION_ID < 70000
intern = (php_luasandboxfunction_obj*)ecalloc(1, sizeof(php_luasandboxfunction_obj));
#elif PHP_VERSION_ID < 70300
intern = (php_luasandboxfunction_obj*)ecalloc(1, sizeof(php_luasandboxfunction_obj) + zend_object_properties_size(ce));
#else
intern = (php_luasandboxfunction_obj*)zend_object_alloc(sizeof(php_luasandboxfunction_obj), ce);
#endif
zend_object_std_init(&intern->std, ce TSRMLS_CC);
#if PHP_VERSION_ID > 50399
object_properties_init(&intern->std, ce);
#endif
#if PHP_VERSION_ID < 70000
// Put the object into the store
zend_object_value retval;
retval.handle = zend_objects_store_put(
intern,
(zend_objects_store_dtor_t)zend_objects_destroy_object,
(zend_objects_free_object_storage_t)luasandboxfunction_free_storage,
NULL TSRMLS_CC);
retval.handlers = zend_get_std_object_handlers();
return retval;
#else
intern->std.handlers = &luasandboxfunction_object_handlers;
return &intern->std;
#endif
}
/* }}} */
/** {{{ luasandboxfunction_free_storage
*
* "Free storage" handler for LuaSandboxFunction objects. Deletes the chunk
* from the registry and decrements the reference counter for the parent
* LuaSandbox object.
*/
static void luasandboxfunction_free_storage(zend_object *object TSRMLS_DC)
{
php_luasandboxfunction_obj * func = php_luasandboxfunction_fetch_object(object);
if (LUASANDBOXFUNCTION_SANDBOX_IS_OK(func)) {
zval *zsandbox = LUASANDBOXFUNCTION_GET_SANDBOX_ZVALPTR(func);
php_luasandbox_obj * sandbox = GET_LUASANDBOX_OBJ(zsandbox);
if (sandbox && sandbox->state) {
lua_State * L = sandbox->state;
// Delete the chunk
if (func->index) {
lua_getfield(L, LUA_REGISTRYINDEX, "php_luasandbox_chunks");
lua_pushnil(L);
lua_rawseti(L, -2, func->index);
lua_pop(L, 1);
}
}
// Delete the parent reference
zval_ptr_dtor(&func->sandbox);
#if PHP_VERSION_ID < 70000
func->sandbox = NULL;
#else
ZVAL_UNDEF(&func->sandbox);
#endif
}
zend_object_std_dtor(&func->std TSRMLS_CC);
#if PHP_VERSION_ID < 70000
efree(object);
#endif
}
/* }}} */
/** {{{ luasandbox_panic
*
* The Lua panic function. It is necessary to raise an E_ERROR, and thus do a
* longjmp(), since if this function returns, Lua will call exit(), breaking
* the Apache child.
*
* Generally, a panic will happen if the Lua API is used incorrectly in an
* unprotected environment. Currently this means C code which is called from
* PHP, not directly or indirectly from lua_pcall(). Sandboxed Lua code is run
* under lua_pcall() so can't cause a panic.
*
* Note that sandboxed Lua code may be executed in an unprotected environment
* if C code accesses a variable with a metamethod defined by the sandboxed
* code. For this reason, the "raw" functions such as lua_rawget() should be
* used where this is a possibility.
*/
static int luasandbox_panic(lua_State * L)
{
TSRMLS_FETCH();
php_error_docref(NULL TSRMLS_CC, E_ERROR,
"PANIC: unprotected error in call to Lua API (%s)",
luasandbox_error_to_string(L, -1));
return 0;
}
/* }}} */
/** {{{ luasandbox_state_from_zval
*
* Get a lua state from a zval* containing a LuaSandbox object. If the zval*
* contains something else, bad things will happen.
*/
static lua_State * luasandbox_state_from_zval(zval * this_ptr TSRMLS_DC)
{
php_luasandbox_obj * intern = GET_LUASANDBOX_OBJ(this_ptr);
return intern->state;
}
/* }}} */
/** {{{ luasandbox_load_helper
*
* Common code for LuaSandbox::loadString() and LuaSandbox::loadBinary(). The
* "binary" parameter will be 1 for loadBinary() and 0 for loadString().
*
* For catching Lua errors that might be raised, we need a struct and a helper
* function too.
*/
struct luasandbox_load_helper_params {
php_luasandbox_obj * sandbox;
zval *zthis;
zval *return_value;
#if defined(ZTS) && PHP_VERSION_ID < 70000
void ***tsrm_ls;
#endif
char *code;
char *chunkName;
str_param_len_t codeLength;
};
static int luasandbox_load_helper_protected(lua_State* L) {
struct luasandbox_load_helper_params *p = (struct luasandbox_load_helper_params *)lua_touserdata(L, 1);
int status;
zval *return_value = p->return_value;
#if defined(ZTS) && PHP_VERSION_ID < 70000
void ***tsrm_ls = p->tsrm_ls;
#endif
// Parse the string into a function on the stack
status = luaL_loadbuffer(L, p->code, p->codeLength, p->chunkName);
// Handle any error from luaL_loadbuffer
if (status != 0) {
luasandbox_handle_error(p->sandbox, status TSRMLS_CC);
RETVAL_FALSE;
return 0;
}
// Make a zval out of it, and return false on error
if (!luasandbox_lua_to_zval(p->return_value, L, lua_gettop(L), p->zthis, NULL TSRMLS_CC) ||
Z_TYPE_P(p->return_value) == IS_NULL
) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "too many chunks loaded already");
RETVAL_FALSE;
}
// Balance the stack
lua_pop(L, 1);
return 0;
}
static void luasandbox_load_helper(int binary, INTERNAL_FUNCTION_PARAMETERS)
{
struct luasandbox_load_helper_params p;
str_param_len_t chunkNameLength;
lua_State * L;
int have_mark;
int was_paused;
int status;
p.sandbox = GET_LUASANDBOX_OBJ(getThis());
L = p.sandbox->state;
CHECK_VALID_STATE(L);
p.chunkName = NULL;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|s",
&p.code, &p.codeLength, &p.chunkName, &chunkNameLength) == FAILURE) {
RETURN_FALSE;
}
if (p.chunkName == NULL) {
p.chunkName = "";
} else {
// Check chunkName for nulls
if (strlen(p.chunkName) != chunkNameLength) {
php_error_docref(NULL TSRMLS_CC, E_WARNING,
"chunk name may not contain null characters");
RETURN_FALSE;
}
}
// Check to see if the code is binary (with precompiled data mark) if this
// was called as loadBinary(), and plain code (without mark) if this was
// called as loadString()
have_mark = (php_memnstr(p.code, LUA_SIGNATURE,
sizeof(LUA_SIGNATURE) - 1, p.code + p.codeLength) != NULL);
if (binary && !have_mark) {
php_error_docref(NULL TSRMLS_CC, E_WARNING,
"the string does not appear to be a valid binary chunk");
RETURN_FALSE;
} else if (!binary && have_mark) {
php_error_docref(NULL TSRMLS_CC, E_WARNING,
"cannot load code with a Lua binary chunk marker escape sequence in it");
RETURN_FALSE;
}
// Make sure this is counted against the Lua usage time limit
was_paused = luasandbox_timer_is_paused(&p.sandbox->timer);
luasandbox_timer_unpause(&p.sandbox->timer);
p.zthis = getThis();
#if defined(ZTS) && PHP_VERSION_ID < 70000
p.tsrm_ls = tsrm_ls;
#endif
p.return_value = return_value;
status = lua_cpcall(L, luasandbox_load_helper_protected, &p);
// If the timers were paused before, re-pause them now
if (was_paused) {
luasandbox_timer_pause(&p.sandbox->timer);
}
// Handle any error from Lua
if (status != 0) {
luasandbox_handle_error(p.sandbox, status TSRMLS_CC);
RETURN_FALSE;
}
}
/* }}} */
/** {{{ proto static array LuaSandbox::getVersionInfo()
*
* Return the versions of LuaSandbox and Lua, as an associative array.
*/
PHP_METHOD(LuaSandbox, getVersionInfo)
{
array_init_size(return_value, 2);
compat_add_assoc_string(return_value, "LuaSandbox", LUASANDBOX_VERSION);
compat_add_assoc_string(return_value, "Lua", LUA_RELEASE);
}
/* }}} */
/** {{{ proto LuaSandboxFunction LuaSandbox::loadString(string code, string chunkName = '')
*
* Load a string into the LuaSandbox object. Returns a LuaSandboxFunction object
* which can be called or dumped.
*
* Note that global functions and variables defined in the chunk will not be
* present in the Lua state until the chunk is executed. Function definitions
* in Lua are a kind of executable statement.
*/
PHP_METHOD(LuaSandbox, loadString)
{
luasandbox_load_helper(0, INTERNAL_FUNCTION_PARAM_PASSTHRU);
}
/* }}} */
/** {{{ proto LuaSandboxFunction LuaSandbox::loadBinary(string bin, string chunkName = '')
* Load a string containing a precompiled binary chunk from
* LuaSandboxFunction::dump() or the Lua compiler luac. Returns a
* LuaSandboxFunction object.
*/
PHP_METHOD(LuaSandbox, loadBinary)
{
luasandbox_load_helper(1, INTERNAL_FUNCTION_PARAM_PASSTHRU);
}
/* }}} */
/** {{{ luasandbox_handle_error
*
* Handles the error return situation from lua_pcall() and lua_load(), where a
* status is returned and an error message pushed to the stack. Throws a suitable
* exception.
*
* This method shouldn't raise any Lua errors. This is accomplished by
* judicious disabling of the memory limit and by using a pcall for one bit
* that is otherwise unsafe.
*/
static int luasandbox_safe_trace_to_zval(lua_State* L) {
zval *zsandbox = (zval *)lua_touserdata(L, 2);
zval *ztrace = (zval *)lua_touserdata(L, 3);
#if defined(ZTS) && PHP_VERSION_ID < 70000
void ***tsrm_ls = (void ***)lua_touserdata(L, 4);
#endif
luasandbox_lua_to_zval(ztrace, L, 1, zsandbox, NULL TSRMLS_CC);
return 0;
}
static void luasandbox_handle_error(php_luasandbox_obj * sandbox, int status TSRMLS_DC)
{
lua_State * L = sandbox->state;
const char * errorMsg;
zend_class_entry * ce;
zval *zex, *ztrace;
size_t old_memory_limit;
#if PHP_VERSION_ID < 70000
MAKE_STD_ZVAL(zex);
ALLOC_INIT_ZVAL(ztrace); // IS_NULL if lua_to_zval fails.
#else
zval zvex, zvtrace;
zex = &zvex;
ztrace = &zvtrace;
ZVAL_NULL(ztrace);
#endif
if (EG(exception)) {
lua_pop(L, 1);
return;
}
// Temporarily disable the memory limit while fetching the error string, so
// the fetch doesn't raise a memory error.
old_memory_limit = sandbox->alloc.memory_limit;
sandbox->alloc.memory_limit = (size_t)-1;
errorMsg = luasandbox_error_to_string(L, -1);
sandbox->alloc.memory_limit = old_memory_limit;
switch (status) {
case LUA_ERRRUN:
default:
if (luasandbox_is_fatal(L, -1)) {
if (!strcmp(errorMsg, luasandbox_timeout_message)) {
ce = luasandboxtimeouterror_ce;
} else {
ce = luasandboxfatalerror_ce;
}
} else {
ce = luasandboxruntimeerror_ce;
}
break;
case LUA_ERRSYNTAX:
ce = luasandboxsyntaxerror_ce;
break;
case LUA_ERRMEM:
ce = luasandboxmemoryerror_ce;
break;
case LUA_ERRERR:
ce = luasandboxerrorerror_ce;
break;
}
object_init_ex(zex, ce);
if (luasandbox_is_trace_error(L, -1)) {
// Here we can't just ignore the memory limit since
// luasandbox_lua_to_zval can throw non-memory errors. So make a pcall
// to do the conversion.
//
// But we can and should ignore the memory limit while pushing the
// parameters for the pcall onto the stack.
old_memory_limit = sandbox->alloc.memory_limit;
sandbox->alloc.memory_limit = (size_t)-1;
lua_pushcfunction(L, luasandbox_safe_trace_to_zval);
lua_rawgeti(L, -2, 3);
lua_pushlightuserdata(L, LUASANDBOX_GET_CURRENT_ZVAL_PTR(sandbox));
lua_pushlightuserdata(L, ztrace);
lua_pushlightuserdata(L,
#if defined(ZTS) && PHP_VERSION_ID < 70000
tsrm_ls
#else
NULL
#endif
);
sandbox->alloc.memory_limit = old_memory_limit;
if (lua_pcall(L, 4, 0, 0) == 0) {
// Put it in the exception object
zend_update_property(ce, zex, "luaTrace", sizeof("luaTrace")-1, ztrace TSRMLS_CC);
} else {
// lua_pcall pushed an error on the stack.
old_memory_limit = sandbox->alloc.memory_limit;
sandbox->alloc.memory_limit = (size_t)-1;
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Failed to generate Lua trace (%s)",
luasandbox_error_to_string(L, -1));
sandbox->alloc.memory_limit = old_memory_limit;
lua_pop(L, 1);
}
}
#if PHP_VERSION_ID < 70000
zval_ptr_dtor(&ztrace);
#else
zval_ptr_dtor(&zvtrace);
#endif
// Initialise standard properties
// We would get Zend to do this, but the code for it is wrapped inside some
// very inconvenient interfaces (so inconvenient that Zend itself
// duplicates this code in several places).
zend_update_property_string(ce, zex, "message", sizeof("message")-1, errorMsg TSRMLS_CC);
zend_update_property_long(ce, zex, "code", sizeof("code")-1, status TSRMLS_CC);
zend_throw_exception_object(zex TSRMLS_CC);
lua_pop(L, 1);
}
/* }}} */
/** {{{ proto void LuaSandbox::setMemoryLimit(int limit)
*
* Set the memory limit for the Lua state. If the memory limit is exceeded,
* the allocator will return NULL. When running protected code, this will
* result in a LuaSandboxError exception being thrown. If this occurs in
* unprotected code, say due to loading too many functions with loadString(),
* a panic will be triggered, leading to a PHP fatal error.
*/
PHP_METHOD(LuaSandbox, setMemoryLimit)
{
long_param_t limit;
php_luasandbox_obj * intern = GET_LUASANDBOX_OBJ(getThis());
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l",
&limit) == FAILURE)
{
RETURN_FALSE;
}
intern->alloc.memory_limit = limit;
}
/* }}} */
/** {{{ proto void LuaSandbox::setCPULimit(mixed limit)
*
* Set the limit of CPU time (user+system) for all LuaSandboxFunction::call()
* calls against this LuaSandbox instance. The limit is specified in seconds,
* or false to disable the limiter.
*
* When the time limit expires, a flag will be set which causes a
* LuaSandboxError exception to be thrown when the currently-running Lua
* statement finishes.
*
* Setting the time limit from a callback while Lua is running causes the timer
* to be reset, or started if it was not already running.
*/
PHP_METHOD(LuaSandbox, setCPULimit)
{
zval *zp_limit = NULL;
php_luasandbox_obj * sandbox = GET_LUASANDBOX_OBJ(getThis());
struct timespec limit = {0, 0};
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z/",
&zp_limit) == FAILURE)
{
RETURN_FALSE;
}
if (!zp_limit
#ifdef IS_BOOL
|| (Z_TYPE_P(zp_limit) == IS_BOOL && Z_BVAL_P(zp_limit) == 0)
#else
|| Z_TYPE_P(zp_limit) == IS_FALSE
#endif
) {
// No limit
sandbox->is_cpu_limited = 0;
} else {
convert_to_double(zp_limit);
luasandbox_set_timespec(&limit, Z_DVAL_P(zp_limit));
sandbox->is_cpu_limited = 1;
}
// Set the timer
luasandbox_timer_set_limit(&sandbox->timer, &limit);
}
/* }}} */
/** {{{ luasandbox_set_timespec
* Initialise a timespec structure with the time in seconds given by the source
* argument.
*/
static void luasandbox_set_timespec(struct timespec * dest, double source)
{
double fractional, integral;
if (source < 0) {
dest->tv_sec = dest->tv_nsec = 0;
return;
}
fractional = modf(source, &integral);
dest->tv_sec = (time_t)integral;
dest->tv_nsec = (long)(fractional * 1000000000.0);
if (dest->tv_nsec >= 1000000000L) {
dest->tv_nsec -= 1000000000L;
dest->tv_sec ++;
}
}
/* }}} */
/** {{{ proto float LuaSandbox::getCPUUsage()
*
* Get the amount of CPU used by this LuaSandbox instance, including any PHP
* functions called by Lua.
*/
PHP_METHOD(LuaSandbox, getCPUUsage)
{
struct timespec ts;
php_luasandbox_obj * sandbox = GET_LUASANDBOX_OBJ(getThis());
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "") == FAILURE) {
RETURN_FALSE;