forked from serverless-dns/serverless-dns
-
Notifications
You must be signed in to change notification settings - Fork 0
/
server-deno.ts
201 lines (165 loc) · 5.45 KB
/
server-deno.ts
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
/*
* Copyright (c) 2022 RethinkDNS and its authors.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
// env config at top, so if .env file variables are used, it is available to
// other modules.
import "./core/deno/config.ts";
import { handleRequest } from "./core/doh.js";
import { serve, serveTls } from "https://deno.land/std@0.123.0/http/server.ts";
import * as system from "./system.js";
import * as util from "./commons/util.js";
import * as bufutil from "./commons/bufutil.js";
import * as dnsutil from "./commons/dnsutil.js";
import * as envutil from "./commons/envutil.js";
let log: any = null;
((main) => {
system.sub("go", systemUp);
// ask prepare phase to commence
system.pub("prepare");
})();
function systemUp() {
const onDenoDeploy = envutil.onDenoDeploy() as boolean;
const dohConnOpts = { port: envutil.dohBackendPort() };
const dotConnOpts = { port: envutil.dotBackendPort() };
const tlsOpts = {
certFile: envutil.tlsCrtPath() as string,
keyFile: envutil.tlsKeyPath() as string,
};
// deno.land/manual@v1.18.0/runtime/http_server_apis_low_level
const httpOpts = {
alpnProtocols: ["h2", "http/1.1"],
};
log = util.logger("Deno");
if (!log) throw new Error("logger unavailable on system up");
startDoh();
startDotIfPossible();
async function startDoh() {
if (terminateTls()) {
serveTls(serveDoh, {
...dohConnOpts,
...tlsOpts,
...httpOpts,
});
} else {
serve(serveDoh, { ...dohConnOpts });
}
up("DoH", dohConnOpts);
}
async function startDotIfPossible() {
// No DoT on Deno Deploy which supports only http workloads
if (onDenoDeploy) return;
// doc.deno.land/deno/stable/~/Deno.listenTls
// doc.deno.land/deno/stable/~/Deno.listen
const dot = terminateTls()
? Deno.listenTls({ ...dotConnOpts, ...tlsOpts })
: Deno.listen({ ...dotConnOpts });
up("DoT (no blocklists)", dotConnOpts);
// deno.land/manual@v1.11.3/runtime/http_server_apis#handling-connections
for await (const conn of dot) {
log.d("DoT conn:", conn.remoteAddr);
// to not block the server and accept further conns, do not await
serveTcp(conn);
}
}
function up(p: string, opts: any) {
log.i("up", p, opts, "tls?", terminateTls());
}
function terminateTls() {
if (onDenoDeploy) return false;
if (util.emptyString(tlsOpts.keyFile)) return false;
if (util.emptyString(tlsOpts.certFile)) return false;
return true;
}
}
async function serveDoh(req: Request) {
try {
// doc.deno.land/deno/stable/~/Deno.RequestEvent
// deno.land/manual/runtime/http_server_apis#http-requests-and-responses
return handleRequest(mkFetchEvent(req));
} catch (e) {
// Client may close conn abruptly before a response could be sent
log.w("doh fail", e);
}
}
async function serveTcp(conn: Deno.Conn) {
// TODO: Sync this impl with serveTcp in server-node.js
const qlBuf = new Uint8Array(2);
while (true) {
let n = null;
try {
n = await conn.read(qlBuf);
} catch (e) {
log.w("err tcp query read", e);
break;
}
if (n == 0 || n == null) {
log.d("tcp socket clean shutdown");
break;
}
// TODO: use dnsutil.validateSize instead
if (n < 2) {
log.w("query too small");
break;
}
const ql = new DataView(qlBuf.buffer).getUint16(0);
log.d(`Read ${n} octets; q len = ${qlBuf} = ${ql}`);
const q = new Uint8Array(ql);
n = await conn.read(q);
log.d(`Read ${n} length q`);
if (n != ql) {
log.w(`query len mismatch: ${n} < ${ql}`);
break;
}
// TODO: Parallel processing
await handleTCPQuery(q, conn);
}
// TODO: expect client to close the connection; timeouts.
conn.close();
}
async function handleTCPQuery(q: Uint8Array, conn: Deno.Conn) {
try {
const r = await resolveQuery(q);
const rlBuf = bufutil.encodeUint8ArrayBE(r.byteLength, 2);
const n = await conn.write(new Uint8Array([...rlBuf, ...r]));
if (n != r.byteLength + 2) {
log.e(`res write incomplete: ${n} < ${r.byteLength + 2}`);
}
} catch (e) {
log.w("err tcp query resolve", e);
}
}
async function resolveQuery(q: Uint8Array) {
// TODO: Sync code with server-node.js:resolveQuery
const freq: Request = new Request("https://ignored.example.com", {
method: "POST",
headers: util.concatHeaders(util.dnsHeaders(), util.contentLengthHeader(q)),
body: q,
});
const r: Response = (await handleRequest(mkFetchEvent(freq))) as Response;
const ans: ArrayBuffer = await r.arrayBuffer();
if (!bufutil.emptyBuf(ans)) {
return new Uint8Array(ans);
} else {
return new Uint8Array(dnsutil.servfailQ(q));
}
}
function mkFetchEvent(r: Request, ...fns: Function[]) {
if (!r) throw new Error("missing request");
// deno.land/manual/runtime/http_server_apis#http-requests-and-responses
// a service-worker event, with properties: type and request; and methods:
// respondWith(Response), waitUntil(Promise), passThroughOnException(void)
return {
type: "fetch",
request: r,
respondWith: fns[0] || stub("event.respondWith"),
waitUntil: fns[1] || stub("event.waitUntil"),
passThroughOnException: fns[2] || stub("event.passThroughOnException"),
};
}
function stub(fid: String) {
return (...rest: any) => log.d(fid, "stub fn, args:", ...rest);
}