summaryrefslogtreecommitdiffstats
path: root/header.go
blob: cb16db5cac2cc584ff9f5217b0749ef653b2c931 (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
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
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
package cnp

import (
	"bufio"
	"bytes"
	"io"
	"sort"
	"strconv"
)

const (
	// IntentOK represents the "ok" response intent.
	IntentOK = "ok"
	// IntentNotModified represents the "not_modified" response intent.
	IntentNotModified = "not_modified"
	// IntentError represents the "error" response intent.
	IntentError = "error"
	// IntentRedirect represents the "redirect" response intent.
	IntentRedirect = "redirect"
)

// Header represents a CNP message header
type Header struct {
	// VersionMajor is the major CNP version given in the header.
	VersionMajor int
	// VersionMinor is the minor CNP version given in the header.
	VersionMinor int
	// Intent is the intent string of the message.
	Intent string
	// Parameters is a decoded map of the message parameters.
	Parameters Parameters
}

// NewHeader creates a new CNP header from an intent and optional parameter
// map.
func NewHeader(intent string, params Parameters) Header {
	if params == nil {
		params = make(Parameters)
	}
	return Header{
		VersionMajor: VersionMajor,
		VersionMinor: VersionMinor,
		Intent:       intent,
		Parameters:   params,
	}
}

// ParseHeader parses a CNP header from a bytestring.
// The line parameter must be a single line that ends with a line feed.
func ParseHeader(line []byte) (h Header, err error) {
	if bytes.IndexByte(line, '\x00') >= 0 {
		err = ErrorSyntax{"invalid header: NUL byte"}
		return
	}

	if !bytes.HasPrefix(line, []byte("cnp/")) {
		err = ErrorSyntax{"invalid header: no version string"}
		return
	}
	line = line[len("cnp/"):]

	var o int

	h.VersionMajor, o, err = parseHeaderNumber(line)
	if err != nil {
		return
	}
	line = line[o:]

	if len(line) == 0 || line[0] != '.' {
		err = ErrorSyntax{"invalid header: invalid version number tuple"}
		return
	}
	line = line[1:]
	h.VersionMinor, o, err = parseHeaderNumber(line)
	if err != nil {
		return
	}
	line = line[o:]

	if len(line) == 0 || line[0] != ' ' {
		err = ErrorSyntax{"invalid header: expected a space"}
		return
	}
	line = line[1:]

	h.Intent, o, err = parseHeaderIntent(line)
	if err != nil {
		return
	}
	line = line[o:]

	h.Parameters, o, err = parseHeaderParameters(line)
	if err != nil {
		return
	}
	line = line[o:]

	if len(line) != 1 || line[0] != '\n' {
		err = ErrorSyntax{"invalid header: expected line feed and end"}
		return
	}

	return
}

func parseHeaderNumber(line []byte) (n int, length int, err error) {
	i := 0
	for ; i < len(line); i++ {
		b := line[i]
		if '0' <= b && b <= '9' {
		} else {
			break
		}
	}
	n, err = strconv.Atoi(string(line[:i]))
	if err != nil || (i > 1 && line[0] == '0') {
		err = ErrorSyntax{"invalid header: invalid version number format"}
		return
	}
	length = i
	return
}

func parseHeaderIntent(line []byte) (intent string, length int, err error) {
	p := bytes.IndexAny(line, " \n=\x00")
	if p < 0 {
		p = len(line) - 1
	}
	if p == 0 {
		err = ErrorSyntax{"invalid header: empty intent"}
		return
	}
	intent, err = Unescape(line[:p])
	length = p
	return
}

func parseHeaderParameters(line []byte) (params Parameters, length int, err error) {
	params = make(Parameters)

	for len(line) > 1 {
		if line[0] == '\n' {
			break
		} else if line[0] != ' ' {
			err = ErrorSyntax{"invalid header: expected a space"}
			return
		}
		line = line[1:]
		length++

		var k, v string
		var o int
		k, v, o, err = parseHeaderParameter(line)
		if err != nil {
			return
		}
		if _, ok := params[k]; ok {
			err = ErrorSyntax{"invalid header: duplicate parameter"}
			return
		}
		params[k] = v
		line = line[o:]
		length += o
	}

	return
}

func parseHeaderParameter(line []byte) (key, value string, length int, err error) {
	var o int
	key, o, err = parseHeaderParamString(line)
	if err != nil {
		return
	}
	line = line[o:]
	length += o

	if len(line) == 0 || line[0] != '=' {
		err = ErrorSyntax{"invalid header: expected an equals sign"}
		return
	}
	line = line[1:]
	length++

	value, o, err = parseHeaderParamString(line)
	if err != nil {
		return
	}
	length += o

	return
}

func parseHeaderParamString(line []byte) (s string, length int, err error) {
	for ; length < len(line); length++ {
		b := line[length]
		if b == '\n' || b == ' ' || b == '=' {
			break
		}
	}
	s, err = Unescape(line[:length])
	return
}

// Version returns the message's CNP version as a "cnp/X.Y" string.
func (h Header) Version() string {
	return "cnp/" + strconv.Itoa(h.VersionMajor) + "." + strconv.Itoa(h.VersionMinor)
}

// Write writes the CNP message header line in the wire format.
// The written line ends with a line feed.
func (h Header) Write(w io.Writer) (err error) {
	bw := bufio.NewWriter(w)
	_, err = bw.WriteString(h.Version())
	if err != nil {
		return
	}
	err = bw.WriteByte(' ')
	if err != nil {
		return
	}
	_, err = bw.Write(Escape(h.Intent))
	if err != nil {
		return
	}
	err = h.Parameters.Write(bw)
	if err != nil {
		return
	}
	err = bw.WriteByte('\n')
	if err != nil {
		return
	}
	return bw.Flush()
}

func (h Header) String() string {
	var buf bytes.Buffer
	_ = h.Write(&buf)
	return buf.String()
}

// Parameters represents CNP message parameter key=value pairs.
type Parameters map[string]string

// Write writes the parameters encoded for inclusion in the wire format.
// Includes a leading space if p is nonempty.
func (p Parameters) Write(w io.Writer) (err error) {
	bw := bufio.NewWriter(w)
	keys := []string{}
	for k := range p {
		keys = append(keys, k)
	}
	sort.Strings(keys)
	for _, k := range keys {
		err = bw.WriteByte(' ')
		if err != nil {
			return
		}
		_, err = bw.Write(Escape(k))
		if err != nil {
			return
		}
		err = bw.WriteByte('=')
		if err != nil {
			return
		}
		_, err = bw.Write(Escape(p[k]))
		if err != nil {
			return
		}
	}
	return
}

// Escape CNP-escapes the bytestring s.
func Escape(s string) []byte {
	el := escapeLength(s)
	if el == len(s) {
		return []byte(s)
	}
	data := make([]byte, el)
	bi := 0
	for i := 0; i < len(s); i++ {
		switch s[i] {
		case '\x00':
			data[bi] = '\\'
			data[bi+1] = '0'
			bi += 2

		case '\n':
			data[bi] = '\\'
			data[bi+1] = 'n'
			bi += 2

		case ' ':
			data[bi] = '\\'
			data[bi+1] = '_'
			bi += 2

		case '=':
			data[bi] = '\\'
			data[bi+1] = '-'
			bi += 2

		case '\\':
			data[bi] = '\\'
			data[bi+1] = '\\'
			bi += 2

		default:
			data[bi] = s[i]
			bi++
		}
	}
	return data
}

func escapeLength(s string) (l int) {
	for i := 0; i < len(s); i++ {
		switch s[i] {
		case '\x00', '\n', ' ', '=', '\\':
			l += 2
		default:
			l++
		}
	}
	return
}

// Unescape unescapes data from wire format into a bytestring.
func Unescape(data []byte) (string, error) {
	buf := make([]byte, len(data))
	bi := 0

	for i := 0; i < len(data); i++ {
		switch data[i] {
		case '\\':
			i++
			if i >= len(data) {
				return string(buf[:bi]), ErrorSyntax{"invalid escape sequence: unexpected end of string"}
			}
			switch data[i] {
			case '0':
				buf[bi] = '\x00'
			case 'n':
				buf[bi] = '\n'
			case '_':
				buf[bi] = ' '
			case '-':
				buf[bi] = '='
			case '\\':
				buf[bi] = '\\'
			default:
				return string(buf[:bi]), ErrorSyntax{"invalid escape sequence: undefined sequence"}
			}
		default:
			buf[bi] = data[i]
		}
		bi++
	}

	return string(buf[:bi]), nil
}