This repository has been archived by the owner on Jan 5, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 166
/
shm_console.php
executable file
·375 lines (307 loc) · 12 KB
/
shm_console.php
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
#!/usr/bin/php
<?php
/**
* A simple console that lets you view and interact with a shared memory address
* Use the shortcut $addresses array to store commonly-attached memory addresses
* @author Shane Harter
*/
// Memory addresses are generated by the daemon using the current path of the daemon and the name of the worker alias
// As long as those things stay the same the address will stay the same, so you can save them here as shortcuts.
$addresses = array(
'PrimeNumbers' => 1342185173,
'GetFactors' => 1191190231,
'LongPoll_API' => 1090519102,
);
declare(ticks = 5);
register_signal_handlers();
$index = array_keys($addresses);
$string = '';
foreach($index as $id => $key) {
$string .= sprintf('%s [-%s] %s%s%s', PHP_EOL, $id, $key, "\t", $addresses[$key]);
}
echo PHP_EOL, "PHP Simple Daemon - Shared Memory Console";
echo PHP_EOL, "Enter Shared Memory Address";
if ($string)
echo " or Select a Shortcut:", $string;
echo PHP_EOL;
echo PHP_EOL, "Hint: To determine the address used by a worker, send a `10` signal to your daemon. It will be a 10 digit number beside the worker's alias";
echo PHP_EOL;
echo PHP_EOL;
stream_set_blocking(STDIN, 0);
$address = false;
$input = '';
$macro_input = '';
$prompt = true;
$header_exists = true;
$flash = '';
$interrupt = false;
while(true) {
if ($interrupt && $macro_input) {
$macro_input = '';
$prompt = true;
$interrupt = false;
echo PHP_EOL; // If the interrupt was sent via ctrl-c it'll put a ^C in the terminal
}
if ($interrupt) {
break;
}
$flash = '';
// Every few iterations check to see if the header still exists (if not the memory block
// has probably been detached and released by the daemon) If the header didn't exist when the memory
// was attached just skip the check and let the user figure out if the memory is detached.
if (!$macro_input && $address && $header_exists && ($input || mt_rand(1,3) == 2) && !shm_has_var($shm, 1)) {
out("Shared Memory Block {$address} Has Been Released");
$prompt = true;
$address = false;
@shm_detach($shm);
$shm = null;
if (!$input)
echo PHP_EOL;
}
if ($input || $prompt)
if (!$address)
echo "ADDR > ";
else
echo "ID > ";
$prompt = false;
if ($macro_input) {
$input = $macro_input;
$macro_input = '';
} else {
$input = strtolower(fgets(STDIN));
}
$prompt = $input == "\n";
$input = trim($input);
try {
switch(true) {
case empty($input):
continue;
case $address && input('exit'):
@exec("rm -f /tmp/shm_{$address}_*");
exit;
case input('exit'):
exit;
case $address && input('help'):
$out = array();
$out[] = '';
$out[] = 'Available Commands:';
$out[] = 'exit';
$out[] = 'help Display this help';
$out[] = 'addr [integer] Display an ADDR prompt to enter a new Address, and optionally pass an Address to switch directly to';
$out[] = '[integer] A valid memory address';
$out[] = 'scan Scan the shared memory block for items currently in-memory';
$out[] = 'watch Watch the shared memory block and log all Additions, Removals and Updates - Use [Enter] to break a Watch.';
$out[] = 'rewatch Pick-up a previous Watch where you left-off';
$out[] = '';
out(implode(PHP_EOL, $out));
continue;
case input('help'):
$out = array();
$out[] = '';
$out[] = 'Available Commands:';
$out[] = 'exit';
$out[] = 'help Display this help';
$out[] = '[integer] A valid memory address';
$out[] = '';
$out[] = 'Shortcuts:';
$out[] = $string;
$out[] = '';
$out[] = 'Shortcuts come from the $addresses array. Add your own shortcuts to make life easier.';
$out[] = '';
out(implode(PHP_EOL, $out));
continue;
case input('addr'):
if ($address) {
out("Releasing Address...");
$address = false;
@shm_detach($shm);
}
macro(1, $input);
continue;
case $address && input('scan'):
$out = '';
for ($i=0; $i<100000; $i++)
if(shm_has_var($shm, $i))
$out .= " $i";
out("Keys In Use:");
if ($out)
out($out);
else
out("None");
continue;
case $address && input('watch'):
// Watch resets the registry (which is used to compare the snapshot to)
// You can interrupt a Watch by pressing enter and then re-enter it by using rewatch
// Important to note that the iterative polling technique used here only works acceptably well because
// we know the characteristics of the way the Mediator uses shared memory: Numeric, monotonically increasing keys
out("\nWatching Shared Memory..");
out("Note: The `watch` command uses polling to determine changes. Changes made in between polling iterations will not be logged.\n");
$registry = array();
$max = 1;
case $address && input('rewatch'):
$snapshot = array();
$statuses = array();
// Build a Snapshot
for ($i=0; $i<$max+1000; $i++) {
if(shm_has_var($shm, $i)) {
$x = shm_get_var($shm, $i);
if (is_object($x) && isset($x->status))
$statuses[$i] = $x->status;
$snapshot[$i] = md5(print_r($x, true));
if ($i > $max)
$max = $i;
$x = null;
}
}
// Compare to Array
$removed = array_diff_key($registry, $snapshot);
foreach(array_keys($removed) as $item)
out("Item {$item} Removed");
$added = array_diff_key($snapshot, $registry);
foreach(array_keys($added) as $item)
if (isset($statuses[$item]))
out ("Item {$item} Added at Status " . $statuses[$item]);
else
out ("Item {$item} Added");
foreach(array_diff_key($registry, $removed) as $item => $hash)
if ($hash != $snapshot[$item])
if (isset($statuses[$item]))
out ("Item {$item} Updated at Status " . $statuses[$item]);
else
out ("Item {$item} Updated");
$registry = $snapshot;
macro(3);
continue;
case $address && is_numeric($input) && $input > 0:
out("Shared Memory Contents:");
if (!shm_has_var($shm, $input)) {
out("Null");
continue;
}
$contents = print_r(shm_get_var($shm, $input), true);
$sizeof = strlen($contents);
$cutoff = 1024 * 1.5;
if ($sizeof > $cutoff) {
$filename = "/tmp/shm_{$address}_{$input}";
$sizeof = number_format($sizeof, 0);
if (file_put_contents($filename, $contents)) {
out("Contents too big for console; Redirected {$sizeof} bytes to {$filename}");
out("Note: The file(s) will be removed when you `exit` this console");
continue;
}
out("Contents too big for console but output redirection to '{$filename}' failed.");
out("Displaying the first 1024 bytes (of {$sizeof} bytes total)");
}
out(substr($contents, 0, $cutoff));
continue;
case !$address && $input <= 0 && isset($index[abs($input)]):
$key = $index[abs($input)];
macro(2, $addresses[$key]);
out("Setting Address From Shortcut: " . $key);
continue;
case !$address && is_numeric($input) && $input > 0:
$address = $input;
$shm = shm_attach($input);
$header_exists = true;
out("Address {$input} Attached");
// If no header is written the memory can still be attached but warn them just in case they typo'd or something
if (!shm_has_var($shm, 1)) {
$header_exists = false;
out("Note: This shared memory address appears uninitilized: No header has been written.");
}
continue;
case $address:
throw new Exception("Invalid Key");
default:
throw new Exception('Invalid Input: Valid Address or Shortcut Required');
}
}
catch(Exception $e)
{
echo $e->getMessage(), PHP_EOL, PHP_EOL;
}
usleep(20 * 1000);
}
echo PHP_EOL;
function out($out)
{
global $flash;
if ($flash) {
echo $flash, PHP_EOL;
$flash = '';
}
echo $out, PHP_EOL;
}
function macro($id) {
global $input, $macro_input, $prompt, $addresss;
if ($macro_input)
$macro_input = '';
switch($id){
case 1:
// Macro 1 reads an optional Address from a address-reset command.
// Example: ID > addr 12345 The current address will be released and this macro will pull 12345 out and set
// it as the new address.
$arg = @func_get_arg(1);
if (!$arg || strlen(trim($arg)) < 4)
return;
$macro_input = trim(str_replace('addr', '', $arg));
break;
case 2:
// Macro 2 takes a saved address from the addresses array and reads it into $input
$arg = @func_get_arg(1);
if (!$arg || !is_numeric($arg))
return;
$macro_input = $arg;
break;
case 3:
usleep(30 * 1000);
if (fgets(STDIN) == "\n")
return;
$macro_input = 'rewatch';
break;
}
if ($macro_input)
$input = '';
}
function input($command, $in = null, Array $candidates = array('scan', 'addr', 'watch', 'rewatch', 'help', 'exit')) {
global $input, $flash;
if (empty($in))
$in = $input;
if (empty($in))
return null;
$in = substr($in, 0, strlen($command));
$matches = array();
foreach ($candidates as $candidate)
if ($in == substr($candidate, 0, strlen($in)))
$matches[] = $candidate;
if (count($matches) > 1)
out("Ambiguous Command. Matches: " . implode(', ', $matches));
if (count($matches) && $matches[0] == $command) {
if ($in != $matches[0])
$flash = $matches[0];
return true;
}
return false;
}
function register_signal_handlers() {
$signals = array(
SIGTERM, SIGINT, SIGHUP
);
foreach(array_unique($signals) as $signal) {
pcntl_signal($signal, 'signal');
}
}
function signal($signal) {
global $address, $shm, $interrupt;
switch($signal) {
case SIGINT:
case SIGTERM:
$interrupt = true;
break;
case SIGHUP:
if ($address) {
$shm = shm_attach($address);
}
break;
}
}