summaryrefslogtreecommitdiff
path: root/src/Server.php
blob: 102c4fd7d0085c37f471407f3575965e76cab3f1 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
<?php

namespace GeminiFoundation;

class Server
{
  protected string $hostname;

  protected array $certificate = [
    'file' => null,
    'key' => null,
    'passphrase' => null,
  ];

  protected array $options = [];

  protected array $requestHandlers = [];

  /**
   * @param array $certificate
   * @param string $hostname
   * @param array $options
   */
  public function __construct(
    array $certificate,
    string $hostname = 'localhost',
    array $options = []
  )
  {
    $this->certificate = $certificate;
    $this->hostname = $hostname;

    $this->options = array_replace_recursive([
      'context' => [],
      'client_certificate_support_workaround' => false, # "support" until https://bugs.php.net/bug.php?id=80770
      'client_certificate_support_workaround_timeout' => 3,
    ], $options);
  }

  public function setCertificate(string $certificateFile, string $keyFile, string $passphrase = ''): static
  {
    $this->certificate = [
      'file' => $certificateFile,
      'key' => $keyFile,
      'passphrase' => $passphrase,
    ];

    return $this;
  }

  public function onRequest(RequestHandlerInterface|callable $callable): static
  {
    $this->requestHandlers[] = $callable;

    return $this;
  }

  public function listen(int $port = 1965): void
  {
    $contextOptions = array_replace_recursive([
      'ssl' => [
        'local_cert' => $this->certificate['file'],
        'local_pk' => $this->certificate['key'],
        'passphrase' => $this->certificate['passphrase'],

        'allow_self_signed' => true,
        'verify_peer' => false,
        'capture_peer_cert' => true,
      ],
    ], $this->options['context']);

    $context = stream_context_create(options: $contextOptions);

    $socket = stream_socket_server(
      address: "tls://{$this->hostname}:{$port}",
      context: $context
    );

    $connections = [];

    while (true) {
      if ($this->options['client_certificate_support_workaround']) {
        stream_context_set_option($socket, 'ssl', 'verify_peer', true);
      }

      echo "Listening for connections.\n";
      $connection = stream_socket_accept(
        socket: $socket,
        timeout: empty($connections) ? -1 : 0,
        peer_name: $peer
      );

      if ($connection) {
        $connections[$peer] = $connection;
      } else if ($this->options['client_certificate_support_workaround']) {
        echo "Enabling client certificate \"support\" workaround.\n";
        echo "Listening without verifying peer.\n";

        stream_context_set_option($socket, 'ssl', 'verify_peer', false);
        $connection = stream_socket_accept(
          socket: $socket,
          timeout: $this->options['client_certificate_support_workaround_timeout'],
          peer_name: $peer
        );

        if ($connection) {
          $connections[$peer] = $connection;
        }
      }

      if (count($connections) == 0) {
        continue;
      }

      $streams = stream_select(
        read: $connections,
        write: $write,
        except: $except,
        seconds: 5
      );

      if ($streams) {
        foreach ($connections as $peer => $connection) {
          if (feof($connection)) {
            fclose($connection);
            unset($connections[$peer]);
            continue;
          }

          $request = Request::fromResource($connection);
          $response = new Response();
          foreach ($this->requestHandlers as $requestHandler) {
            $response = $requestHandler($response, $request);
          }
          $response->send($connection);

          fclose($connection);
          unset($connections[$peer]);
        }
      }
    }
  }
}