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

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

// https://gemini.circumlunar.space/docs/spec-spec.txt, 1.3.1
// > Gemini response headers look like this:
// > <STATUS><whitespace><META><CR><LF>
// > <STATUS> is a two-digit numeric status code [...].
// > <whitespace> is any non-zero number of consecutive spaces or tabs.
// > <META> is a UTF-8 encoded string of maximum length 1024, whose meaning is
// > <STATUS> dependent.

const CRLF = '\r\n'
const MAX_HEADER_SIZE = 2048 // cutoff

const createParser = () => {
	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 statusCodeAndSpace = peek.slice(0, 3).toString('utf8')
		if (!/\d{2} /.test(statusCodeAndSpace)) return invalid()
		const iCRLF = peek.indexOf(CRLF)
		if (iCRLF < 0) return invalid()

		let statusCode = parseInt(statusCodeAndSpace)
		let statusMsg = MESSAGES[statusCode]
		if (!statusMsg) {
			statusCode = Math.floor(statusCode / 10) * 10
			statusMsg = MESSAGES[statusCode]
			if (!statusMsg) return invalid()
		}

		const meta = peek.slice(3, iCRLF).toString('utf8').trim()

		headerParsed = true
		out.emit('header', {
			type: (
				statusCode >= 10 && statusCode < 20
				? 'request' : 'response'
			),
			statusCode, statusMsg,
			meta,
		})

		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 = createParser()
// 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('12 gemini://examp'))
// p.write(b('le.org/foo?bar#baz\r\nhel'))
// p.end(b('lo server!'))

module.exports = {
	MESSAGES,
	createParser,
}