26f0c5041c0faff35b2aa512f360f97b673ba902
[m6w6/ext-http] / tests / helper / server.inc
1 <?php
2
3 function serve(callable $cb) {
4 foreach (range(8000, 9000) as $port) {
5 if (($server = @stream_socket_server("tcp://localhost:$port"))) {
6 fprintf(STDERR, "%s\n", $port);
7 do {
8 $R = [$server]; $W = []; $E = [];
9 $select = stream_select($R, $E, $E, 0, 10000);
10 if ($select && ($client = stream_socket_accept($server, 1))) {
11 if (getenv("PHP_HTTP_TEST_SSL")) {
12 stream_socket_enable_crypto($client, true, STREAM_CRYPTO_METHOD_SSLv23_SERVER);
13 }
14 while (!feof($client)) {
15 $cb($client);
16 }
17 }
18 } while ($select !== false);
19 return;
20 }
21 }
22 }
23
24 function server($handler, callable $cb) {
25 proc(PHP_BINARY, [__DIR__."/$handler"], $cb);
26 }
27
28 function nghttpd(callable $cb) {
29 $spec = [["pipe","r"], ["pipe","w"], ["pipe","w"]];
30 foreach (range(8000, 9000) as $port) {
31 $comm = "exec nghttpd -d html $port http2.key http2.crt";
32 if (($proc = proc_open($comm, $spec, $pipes, __DIR__))) {
33 $stdin = $pipes[0];
34 $stdout = $pipes[1];
35 $stderr = $pipes[2];
36
37 usleep(50000);
38 $status = proc_get_status($proc);
39
40 if (!$status["running"]) {
41 continue;
42 }
43
44 try {
45 $cb($port, $stdin, $stdout, $stderr);
46 } catch (Exception $e) {
47 echo $e,"\n";
48 }
49
50 proc_terminate($proc);
51
52 fpassthru($stderr);
53 fpassthru($stdout);
54 return;
55 }
56 }
57
58 }
59
60 function proc($bin, $args, callable $cb) {
61 $spec = [["pipe","r"], ["pipe","w"], ["pipe","w"]];
62 $comm = escapeshellcmd($bin) . " ". implode(" ", array_map("escapeshellarg", $args));
63 if (($proc = proc_open($comm, $spec, $pipes, __DIR__))) {
64 $stdin = $pipes[0];
65 $stdout = $pipes[1];
66 $stderr = $pipes[2];
67
68 do {
69 $port = trim(fgets($stderr));
70 $R = [$stderr]; $W = []; $E = [];
71 } while (is_numeric($port) && stream_select($R, $W, $E, 0, 10000));
72
73 if (is_numeric($port)) {
74 try {
75 $cb($port, $stdin, $stdout, $stderr);
76 } catch (Exception $e) {
77 echo $e,"\n";
78 }
79 }
80
81 proc_terminate($proc);
82
83 fpassthru($stderr);
84 fpassthru($stdout);
85 }
86 }