Merge branch 'master' into phpng
[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 $offset = rand(0,2000);
58 foreach (range(8000+$offset, 9000+$offset) as $port) {
59 $comm = "exec nghttpd -d html $port http2.key http2.crt";
60 if (($proc = proc_open($comm, $spec, $pipes, __DIR__))) {
61 $stdin = $pipes[0];
62 $stdout = $pipes[1];
63 $stderr = $pipes[2];
64
65 usleep(50000);
66 $status = proc_get_status($proc);
67
68 if (!$status["running"]) {
69 continue;
70 }
71
72 try {
73 $cb($port, $stdin, $stdout, $stderr);
74 } catch (Exception $e) {
75 echo $e,"\n";
76 }
77
78 proc_terminate($proc);
79
80 fpassthru($stderr);
81 fpassthru($stdout);
82 return;
83 }
84 }
85
86 }
87
88 function proc($bin, $args, $cb) {
89 $spec = array(array("pipe","r"), array("pipe","w"), array("pipe","w"));
90 $comm = escapeshellcmd($bin) . " ". implode(" ", array_map("escapeshellarg", $args));
91 if (($proc = proc_open($comm, $spec, $pipes, __DIR__))) {
92 $stdin = $pipes[0];
93 $stdout = $pipes[1];
94 $stderr = $pipes[2];
95
96 do {
97 $port = trim(fgets($stderr));
98 $R = array($stderr); $W = array(); $E = array();
99 } while (is_numeric($port) && stream_select($R, $W, $E, 0, 10000));
100
101 if (is_numeric($port)) {
102 try {
103 $cb($port, $stdin, $stdout, $stderr);
104 } catch (Exception $e) {
105 echo $e,"\n";
106 }
107 }
108
109 proc_terminate($proc);
110
111 fpassthru($stderr);
112 fpassthru($stdout);
113 }
114 }