summaryrefslogtreecommitdiffstats
path: root/lib/request-parser.js
blob: 04c5cd601939f1d619f70f39fcc84ec5cca97ca6 (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
'use strict'

const {Transform} = require('stream')
const {MESSAGES} = require('./statuses')

// https://gemini.circumlunar.space/docs/spec-spec.txt, 1.2
// > Gemini requests are a single CRLF-terminated line with the
// > following structure: <URL><CR><LF>
// > <URL> is a UTF-8 encoded absolute URL, of maximum length
// > 1024 bytes. [...]

const CRLF = '\r\n'
const MAX_HEADER_SIZE = 1024 + CRLF.length

const createRequestParser = () => {
	let headerParsed = false
	let peek = Buffer.alloc(0)

	const invalid = () => {
		peek = null
		out.destroy(new Error('invalid Gemini request'))
	}

	const onData = (data) => {
		if (headerParsed) {
			out.push(data)
			return;
		}

		peek = Buffer.concat([peek, data], peek.length + data.length)
		if (
			data.indexOf(CRLF) < 0 &&
			peek.length < MAX_HEADER_SIZE
		) return; // keep peeking

		const iCRLF = peek.indexOf(CRLF)
		if (iCRLF < 0) return invalid()

		const url = peek.slice(0, iCRLF).toString('utf8')
		headerParsed = true
		out.emit('header', {url})

		const iBody = iCRLF + 2
		if (peek.length > (iBody + 1)) {
			// `data` contains the beginning of the body
			out.push(peek.slice(iBody))
		}
		peek = null // allow garbage collection
	}

	const out = new Transform({
		write: (chunk, _, cb) => {
			onData(chunk)
			cb()
		},
		writev: (chunks, cb) => {
			for (let i = 0; i < chunks.length; i++) {
				onData(chunks[i].chunk)
			}
			cb()
		},
	})
	return out
}

// const p = createRequestParser()
// p.on('error', console.error)
// p.on('header', h => console.log('header', h))
// p.on('data', d => console.log('data', d.toString('utf8')))
// const b = str => Buffer.from(str, 'utf8')
// p.write(b('gemini://examp'))
// p.write(b('le.org/foo?bar#baz\r\nhel'))
// p.end(b('lo server!'))

module.exports = createRequestParser