aboutsummaryrefslogtreecommitdiff
path: root/laurali/server.ts
blob: f8c641f8e2c5899e3ae0ad92383f062f91076d11 (plain) (blame)
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
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
// This file is part of Laurali <https://github.com/gemrest/laurali>.
// Copyright (C) 2022-2022 Fuwn <[email protected]>
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, version 3.
//
// This program is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
//
// Copyright (C) 2022-2022 Fuwn <[email protected]>
// SPDX-License-Identifier: GPL-3.0-only

import { ServerConfiguration } from "./configuration.ts";
import { Hook } from "./hooks.ts";

/** The base Laurali server to be extended upon */
export abstract class Server {
  /**
   * The internal `Deno.TlsListener` which listens for and accepts client
   * connections.
   */
  #listener: Deno.TlsListener;
  /** All registered route functions of the `Server` */
  // deno-lint-ignore no-explicit-any
  static #routes: Map<string, (ctx: Deno.TlsConn) => any> = new Map();
  /** All registered hook functions of the `Server` */
  static #hooks: Map<Hook, (ctx: Deno.TlsConn) => void> = new Map();
  /** The port of the `Server` */
  static #port: number;
  /** The hostname of the `Server` */
  static #hostname: string;

  /**
   * @param certFile The path to the public key file of the `Server`
   * @param keyFile The path to the private key file of the `Server`
   * @param config Extra configuration options of the `Server`
   */
  constructor(
    certFile: string,
    keyFile: string,
    config?: ServerConfiguration,
  ) {
    const port = config?.port || 1965;
    const hostname = config?.hostname || "0.0.0.0";

    Server.#port = port;
    Server.#hostname = hostname;

    this.#listener = Deno.listenTls({
      port,
      hostname,
      certFile,
      keyFile,
    });

    if (config?.proxy?.enable) {
      if (config.proxy.baseURL === undefined) {
        throw new Error("ProxyConfiguration is missing proxy baseURL");
      }

      this.#proxy(config.proxy.baseURL, config.proxy.hostname || hostname);
    }
  }

  async #proxy(baseURL: string, host: string) {
    const server = Deno.listen({ port: 8080 });

    for await (const c of server) {
      for await (const r of Deno.serveHttp(c)) {
        r.respondWith(Response.redirect(baseURL + host));
      }
    }
  }

  /** Add a route function to the `Server` */
  // deno-lint-ignore no-explicit-any
  addRoute(route: string, handler: () => any) {
    Server.#routes.set(route, handler);
  }
  /** Add a hook function to the `Server` */
  addHook(hook: Hook, handler: () => void) {
    Server.#hooks.set(hook, handler);
  }

  /** Get the `port` of the `Server` */
  static get port() {
    return Server.#port;
  }

  /** Get the `hostname` of the `Server` */
  static get hostname() {
    return Server.#hostname;
  }

  /** Called before a connection to a client has been responded to */
  protected onPreRoute?(ctx?: Deno.TlsConn): void;

  /** Called after a connection to a client has concluded */
  protected onPostRoute?(ctx?: Deno.TlsConn): void;

  /** Called before the `Server` starts listening for connections */
  protected onListen?(): void;

  /**
   * The response delivered to a client when the `Server` experiences any error
   * while evaluating the result of a route function, or if the `Server` cannot
   * find a route function for a given path.
   */
  protected onError?(): void;

  /** Start listening and responding to client connections */
  async listen() {
    // If the `Server` has an `onListen` hook, call it.
    if (this.onListen) this.onListen();

    // Listen for connections and handle them.
    for await (const r of this.#listener) {
      const b = new Uint8Array(1026);
      let n;

      try {
        n = await r.read(b);
      } catch (error) {
        console.log(error);
        r.close();

        continue;
      }

      const onPreRoute = Server.#hooks.get(Hook.ON_PRE_ROUTE);
      const onPostRoute = Server.#hooks.get(Hook.ON_POST_ROUTE);
      const onError = Server.#hooks.get(Hook.ON_ERROR);

      // Make sure that the client has sent a request.
      if (n === null) {
        console.log("could not read from client");
        r.close();

        continue;
      }

      const path = String.fromCharCode(...b.subarray(0, n)).replace(
        /\r\n$/,
        "",
      ).replace(/gemini:\/\//, "");

      // If the `Server` has an `onPreRoute` hook, call it.
      if (onPreRoute) onPreRoute(r);

      // Respond to index requests.
      if (path.endsWith("/") || path.endsWith("localhost")) {
        const route = Server.#routes.get("/");
        let response;

        if (route === undefined) {
          if (onError) {
            response = onError(r);
          } else {
            response = "The server (Laurali) could not find that route.";
          }
        } else {
          response = route(r);
        }

        await r.write(
          (new TextEncoder()).encode(
            `20 text/gemini\r\n${response}`,
          ),
        );
        r.close();
      } else { // Respond to another other request.
        const route = Server.#routes.get(path.replace("localhost", ""));
        let response;

        if (route === undefined) {
          if (onError) {
            response = onError(r);
          } else {
            response = "The server (Laurali) could not find that route.";
          }
        } else {
          response = route(r);
        }

        await r.write(
          (new TextEncoder()).encode(
            `20 text/gemini\r\n${response}`,
          ),
        );
        r.close();
      }

      // If the `Server` has an `onPostRoute` hook, call it.
      if (onPostRoute) onPostRoute(r);

      continue;
    }
  }
}