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