summaryrefslogtreecommitdiff
path: root/src/sp_harden_rand.c
diff options
context:
space:
mode:
authorSebastien Blot2017-09-20 10:11:01 +0200
committerSebastien Blot2017-09-20 10:11:01 +0200
commit868f96c759b6650d88ff9f4fbc5c048302134248 (patch)
treec0de0af318bf77a8959164ef11aeeeb2b7bab294 /src/sp_harden_rand.c
Initial import
Diffstat (limited to 'src/sp_harden_rand.c')
-rw-r--r--src/sp_harden_rand.c77
1 files changed, 77 insertions, 0 deletions
diff --git a/src/sp_harden_rand.c b/src/sp_harden_rand.c
new file mode 100644
index 0000000..e0e35ff
--- /dev/null
+++ b/src/sp_harden_rand.c
@@ -0,0 +1,77 @@
1#include "php_snuffleupagus.h"
2
3extern ZEND_API zend_class_entry *zend_ce_error;
4
5ZEND_DECLARE_MODULE_GLOBALS(snuffleupagus)
6
7/* This function is needed because `rand` and `mt_rand` parameters
8 * are optional, while the ones from `random_int` aren't. */
9static void random_int_wrapper(INTERNAL_FUNCTION_PARAMETERS) {
10 zend_long min, max, result;
11
12 switch (EX_NUM_ARGS()) {
13 case 0:
14 min = 0;
15 max = PHP_MT_RAND_MAX;
16 break;
17 case 1:
18 ZEND_PARSE_PARAMETERS_START_EX(ZEND_PARSE_PARAMS_QUIET, 1, 1);
19 Z_PARAM_LONG(min);
20 ZEND_PARSE_PARAMETERS_END();
21 max = PHP_MT_RAND_MAX;
22 break;
23 case 2:
24 default:
25 ZEND_PARSE_PARAMETERS_START_EX(ZEND_PARSE_PARAMS_QUIET, 0, 2);
26 Z_PARAM_LONG(min);
27 Z_PARAM_LONG(max);
28 ZEND_PARSE_PARAMETERS_END();
29 }
30
31 if (min > max) {
32 if (php_random_int_throw(max, min, &result) == FAILURE) {
33 return;
34 }
35 } else {
36 if (php_random_int_throw(min, max, &result) == FAILURE) {
37 return;
38 }
39 }
40
41 RETURN_LONG(result);
42}
43
44PHP_FUNCTION(sp_rand) {
45 void (*orig_handler)(INTERNAL_FUNCTION_PARAMETERS);
46
47 if ((orig_handler = zend_hash_str_find_ptr(SNUFFLEUPAGUS_G(sp_internal_functions_hook), "rand",
48 strlen("rand")))) {
49 /* call the original `rand` function,
50 * since we might no be the only ones to hook it*/
51 orig_handler(INTERNAL_FUNCTION_PARAM_PASSTHRU);
52 }
53
54 random_int_wrapper(INTERNAL_FUNCTION_PARAM_PASSTHRU);
55}
56
57PHP_FUNCTION(sp_mt_rand) {
58 void (*orig_handler)(INTERNAL_FUNCTION_PARAMETERS);
59
60 if ((orig_handler = zend_hash_str_find_ptr(SNUFFLEUPAGUS_G(sp_internal_functions_hook),
61 "mt_rand", strlen("mt_rand")))) {
62 /* call the original `mt_rand` function,
63 * since we might no be the only ones to hook it*/
64 orig_handler(INTERNAL_FUNCTION_PARAM_PASSTHRU);
65 }
66
67 random_int_wrapper(INTERNAL_FUNCTION_PARAM_PASSTHRU);
68}
69
70int hook_rand() {
71 TSRMLS_FETCH();
72
73 HOOK_FUNCTION("rand", sp_internal_functions_hook, PHP_FN(sp_rand), false);
74 HOOK_FUNCTION("mt_rand", sp_internal_functions_hook, PHP_FN(sp_mt_rand), false);
75
76 return SUCCESS;
77}