This repository was archived by the owner on Jul 28, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlib.node.js
More file actions
97 lines (88 loc) · 2.28 KB
/
Copy pathlib.node.js
File metadata and controls
97 lines (88 loc) · 2.28 KB
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
'use strict'
const { AbortError, HTTPStatusError, TimeoutError } = require('./error.js')
const contentType = 'application/dns-message'
const endpoints = Object.values(require('./endpoints.json')).filter(function (endpoint) {
return !endpoint.filter && !endpoint.log
})
// https://tools.ietf.org/html/rfc8484
function toRFC8484 (buffer) {
return buffer.toString('base64')
.replace(/=/g, '')
.replace(/\+/g, '-')
.replace(/\//g, '_')
}
function request (protocol, host, port, path, method, packet, timeout, abortSignal, cb) {
let timer
const client = protocol === 'https:' ? require('https') : require('http')
let finish = (error, data) => {
finish = null
clearTimeout(timer)
if (abortSignal) {
abortSignal.removeEventListener('abort', onabort)
}
cb(error, data)
}
const pth = `${path}${method === 'GET' ? '?dns=' + toRFC8484(packet) : ''}`
const uri = `${protocol}//${host}:${port}${pth}`
const headers = {
Accept: contentType
}
if (method === 'POST') {
headers['Content-Type'] = contentType
headers['Content-Length'] = packet.byteLength
}
const req = client.request({
host: host,
port: port,
path: pth,
method: method,
headers: headers
}, onresponse)
if (abortSignal) {
abortSignal.addEventListener('abort', onabort)
}
req.on('error', finish)
if (method === 'POST') {
req.end(packet)
} else {
req.end()
}
resetTimeout()
function onabort () {
req.destroy(new AbortError())
}
function onresponse (res) {
if (res.statusCode !== 200) {
return res.destroy(new HTTPStatusError(uri, res.statusCode, method))
}
const result = []
res.on('error', onerror)
res.on('data', data => {
resetTimeout()
result.push(data)
})
res.on('end', onclose)
res.on('close', onclose)
function onclose () {
if (finish !== null) {
finish(null, Buffer.concat(result))
}
}
function onerror (error) {
if (finish !== null) {
finish(error || new Error('Unknown Error.'))
}
}
}
function resetTimeout () {
clearTimeout(timer)
timer = setTimeout(ontimeout, timeout)
}
function ontimeout () {
req.destroy(new TimeoutError(timeout))
}
}
module.exports = {
request: request,
endpoints: endpoints
}