e3b7af6a956f4b3b58a5b2a159e0396008c0f977
[m6w6/ext-http] / tests / helper / server.inc
1 <?php
2
3 $php = getenv('TEST_PHP_EXECUTABLE');
4 if ($php) {
5 define('PHP_BIN', $php);
6 } else if (defined('PHP_BINARY')) {
7 define('PHP_BIN', PHP_BINARY);
8 } else {
9 // PHP-5.3
10 define("PHP_BIN", PHP_BINDIR.DIRECTORY_SEPARATOR."php");
11 }
12
13 function serve($cb) {
14 /* stream_socket_server() automatically sets SO_REUSEADDR,
15 * which is, well, bad if the tests are run in parallel
16 */
17 $offset = rand(0,2000);
18 foreach (range(8000+$offset, 9000+$offset) as $port) {
19 if (($server = @stream_socket_server("tcp://localhost:$port"))) {
20 fprintf(STDERR, "%s\n", $port);
21 do {
22 $R = array($server); $W = array(); $E = array();
23 $select = stream_select($R, $E, $E, 0, 10000);
24 if ($select && ($client = stream_socket_accept($server, 1))) {
25 if (getenv("PHP_HTTP_TEST_SSL")) {
26 stream_socket_enable_crypto($client, true, STREAM_CRYPTO_METHOD_SSLv23_SERVER);
27 }
28 try {
29 while (!feof($client)) {
30 $cb($client);
31 }
32 } catch (Exception $ex) {
33 /* ignore disconnect */
34 if ($ex->getMessage() !== "Empty message received from stream") {
35 fprintf(STDERR, "%s\n", $ex);
36 }
37 break;
38 }
39 }
40 } while ($select !== false);
41 return;
42 }
43 }
44 }
45
46 function server($handler, $cb) {
47 $args = explode(' ', getenv('TEST_PHP_ARGS'));
48 $args[] = __DIR__."/$handler";
49 foreach ($args as $k => $v) {
50 if (!$v) unset($args[$k]);
51 }
52 proc(PHP_BIN, $args, $cb);
53 }
54
55 function nghttpd($cb) {
56 $spec = array(array("pipe","r"), array("pipe","w"), array("pipe","w"));
57 foreach (range(8000+PHP_INT_SIZE, 9000) as $port) {
58 $comm = "exec nghttpd -d html $port http2.key http2.crt";
59 if (($proc = proc_open($comm, $spec, $pipes, __DIR__))) {
60 $stdin = $pipes[0];
61 $stdout = $pipes[1];
62 $stderr = $pipes[2];
63
64 usleep(50000);
65 $status = proc_get_status($proc);
66
67 if (!$status["running"]) {
68 continue;
69 }
70
71 try {
72 $cb($port, $stdin, $stdout, $stderr);
73 } catch (Exception $e) {
74 echo $e,"\n";
75 }
76
77 proc_terminate($proc);
78
79 fpassthru($stderr);
80 fpassthru($stdout);
81 return;
82 }
83 }
84
85 }
86
87 function proc($bin, $args, $cb) {
88 $spec = array(array("pipe","r"), array("pipe","w"), array("pipe","w"));
89 $comm = escapeshellcmd($bin) . " ". implode(" ", array_map("escapeshellarg", $args));
90 if (($proc = proc_open($comm, $spec, $pipes, __DIR__))) {
91 $stdin = $pipes[0];
92 $stdout = $pipes[1];
93 $stderr = $pipes[2];
94
95 do {
96 $port = trim(fgets($stderr));
97 $R = array($stderr); $W = array(); $E = array();
98 } while (is_numeric($port) && stream_select($R, $W, $E, 0, 10000));
99
100 if (is_numeric($port)) {
101 try {
102 $cb($port, $stdin, $stdout, $stderr);
103 } catch (Exception $e) {
104 echo $e,"\n";
105 }
106 }
107
108 proc_terminate($proc);
109
110 fpassthru($stderr);
111 fpassthru($stdout);
112 }
113 }