honours TEST_PHP_EXECUTABLE and TEST_PHP_ARGS (set by "make test")
[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 foreach (range(8000, 9000) as $port) {
15 if (($server = @stream_socket_server("tcp://localhost:$port"))) {
16 fprintf(STDERR, "%s\n", $port);
17 do {
18 $R = array($server); $W = array(); $E = array();
19 $select = stream_select($R, $E, $E, 0, 10000);
20 if ($select && ($client = stream_socket_accept($server, 1))) {
21 if (getenv("PHP_HTTP_TEST_SSL")) {
22 stream_socket_enable_crypto($client, true, STREAM_CRYPTO_METHOD_SSLv23_SERVER);
23 }
24 try {
25 while (!feof($client)) {
26 $cb($client);
27 }
28 } catch (Exception $ex) {
29 /* ignore disconnect */
30 if ($ex->getMessage() !== "Empty message received from stream") {
31 fprintf(STDERR, "%s\n", $ex);
32 }
33 break;
34 }
35 }
36 } while ($select !== false);
37 return;
38 }
39 }
40 }
41
42 function server($handler, $cb) {
43 $args = explode(' ', getenv('TEST_PHP_ARGS'));
44 $args[] = __DIR__."/$handler";
45 foreach ($args as $k => $v) {
46 if (!$v) unset($args[$k]);
47 }
48 proc(PHP_BIN, $args, $cb);
49 }
50
51 function nghttpd($cb) {
52 $spec = array(array("pipe","r"), array("pipe","w"), array("pipe","w"));
53 foreach (range(8000, 9000) as $port) {
54 $comm = "exec nghttpd -d html $port http2.key http2.crt";
55 if (($proc = proc_open($comm, $spec, $pipes, __DIR__))) {
56 $stdin = $pipes[0];
57 $stdout = $pipes[1];
58 $stderr = $pipes[2];
59
60 usleep(50000);
61 $status = proc_get_status($proc);
62
63 if (!$status["running"]) {
64 continue;
65 }
66
67 try {
68 $cb($port, $stdin, $stdout, $stderr);
69 } catch (Exception $e) {
70 echo $e,"\n";
71 }
72
73 proc_terminate($proc);
74
75 fpassthru($stderr);
76 fpassthru($stdout);
77 return;
78 }
79 }
80
81 }
82
83 function proc($bin, $args, $cb) {
84 $spec = array(array("pipe","r"), array("pipe","w"), array("pipe","w"));
85 $comm = escapeshellcmd($bin) . " ". implode(" ", array_map("escapeshellarg", $args));
86 if (($proc = proc_open($comm, $spec, $pipes, __DIR__))) {
87 $stdin = $pipes[0];
88 $stdout = $pipes[1];
89 $stderr = $pipes[2];
90
91 do {
92 $port = trim(fgets($stderr));
93 $R = array($stderr); $W = array(); $E = array();
94 } while (is_numeric($port) && stream_select($R, $W, $E, 0, 10000));
95
96 if (is_numeric($port)) {
97 try {
98 $cb($port, $stdin, $stdout, $stderr);
99 } catch (Exception $e) {
100 echo $e,"\n";
101 }
102 }
103
104 proc_terminate($proc);
105
106 fpassthru($stderr);
107 fpassthru($stdout);
108 }
109 }