livekit-protocol 0.8.3

Livekit protocol and utilities for the Rust SDK
Documentation
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
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
// Copyright 2023 LiveKit, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package livekit

import (
	"errors"
	fmt "fmt"
	"strconv"
	"strings"
)

// RFC 3261 compliant validation functions for SIP headers and messages

type allowedCharacters struct {
	ascii [128]bool
	utf8  bool
}

func NewAllowedCharacters() *allowedCharacters {
	return &allowedCharacters{}
}

func (a *allowedCharacters) AddUTF8() error {
	a.utf8 = true
	return nil
}

func (a *allowedCharacters) AddNumbers() error {
	for r := '0'; r <= '9'; r++ {
		a.ascii[r] = true
	}
	return nil
}

func (a *allowedCharacters) AddLowercaseASCII() error {
	for r := 'a'; r <= 'z'; r++ {
		a.ascii[r] = true
	}
	return nil
}

func (a *allowedCharacters) AddUppercaseASCII() error {
	for r := 'A'; r <= 'Z'; r++ {
		a.ascii[r] = true
	}
	return nil
}

func (a *allowedCharacters) AddPrintableLienarASCII() {
	// Anything between 0x20 and 0x7E
	for i := 0x20; i <= 0x7E; i++ {
		a.ascii[i] = true
	}
	a.ascii[0x09] = true // \t or HTAB
}

func (a *allowedCharacters) Add(chars string) error {
	for _, char := range chars {
		if int(char) >= len(a.ascii) {
			return fmt.Errorf("char %d out of range, consider explicilty adding utf8 characters", char)
		}
		a.ascii[char] = true
	}
	return nil
}

func (a *allowedCharacters) Remove(chars string) error {
	for _, char := range chars {
		if int(char) >= len(a.ascii) {
			return fmt.Errorf("char %d out of range, consider explicilty adding utf8 characters", char)
		}
		a.ascii[char] = false
	}
	return nil
}

func (a *allowedCharacters) Copy() *allowedCharacters {
	return &allowedCharacters{
		ascii: a.ascii,
		utf8:  a.utf8,
	}
}

func (a *allowedCharacters) Validate(target string) error {
	for _, char := range target {
		if int(char) >= len(a.ascii) {
			if a.utf8 {
				continue
			}
			return fmt.Errorf("char %d out of range, consider explicilty adding utf8 characters", char)
		}
		if !a.ascii[char] {
			return fmt.Errorf("char %d not allowed", char)
		}
	}
	return nil
}

var tokenCharacters *allowedCharacters
var displayNameCharacters *allowedCharacters
var headerValuesCharacters *allowedCharacters

func init() {
	// Per RFC 3261 Section 25.1
	//	SIP-message    =  Request / Response
	//	Request        =  Request-Line	*( message-header )	CRLF	[ message-body ]
	//	Response       =  Status-Line	*( message-header )	CRLF	[ message-body ]
	//	Request-Line   =  Method SP Request-URI SP SIP-Version CRLF
	//	Method         =  (CAPITAL ASCII)
	//	Request-URI    =  SIP-URI / SIPS-URI / absoluteURI
	//	SIP-Version    =  "SIP" "/" 1*DIGIT "." 1*DIGIT (CAPITAL ASCII, DIGITS, "/.")
	//	Status-Line    =  SIP-Version SP Status-Code SP Reason-Phrase CRLF
	//	Status-Code    =  (Alphanum + "-")
	//	Reason-Phrase  =  (Basically whatever...)
	//	extension-header =  header-name (token) ":" header-value (Basically whatever...)

	// URIs
	//	SIP-URI        =  "sip:" [ userinfo ] hostport uri-parameters [ headers ]
	//	SIPS-URI       =  "sips:" [ userinfo ] hostport uri-parameters [ headers ]

	// One specific header form we care about:
	//	name-addr      =  [ display-name ] LAQUOT addr-spec RAQUOT
	//	display-name   =  *(token LWS)/ quoted-string
	//	addr-spec      =  SIP-URI / SIPS-URI / absoluteURI

	tokenCharacters = NewAllowedCharacters()
	tokenCharacters.AddNumbers()
	tokenCharacters.AddLowercaseASCII()
	tokenCharacters.AddUppercaseASCII()
	tokenCharacters.Add("-.!%*_+`'~")

	displayNameCharacters = tokenCharacters.Copy()
	displayNameCharacters.Add(" \t")

	headerValuesCharacters = NewAllowedCharacters()
	headerValuesCharacters.AddPrintableLienarASCII()
	headerValuesCharacters.AddUTF8()
}

// Required headers for SIP requests per RFC 3261 Section 8.1.1
var RequiredRequestHeaders = map[string]bool{
	"via":          true,
	"from":         true,
	"to":           true,
	"call-id":      true,
	"cseq":         true,
	"max-forwards": true,
}

// Required headers for SIP responses per RFC 3261 Section 8.2.1
var RequiredResponseHeaders = map[string]bool{
	"via":     true,
	"from":    true,
	"to":      true,
	"call-id": true,
	"cseq":    true,
}

// Crucial headers that can't be overridden by the user, and their shorthands
var ForbiddenSipHeaderNames = map[string]bool{
	"accept":           true,
	"accept-encoding":  true,
	"accept-language":  true,
	"allow":            true,
	"allow-events":     true, // rfc3903
	"call-id":          true,
	"contact":          true,
	"content-encoding": true,
	"content-length":   true,
	"content-type":     true,
	"cseq":             true,
	"event":            true, // rfc3903
	"expires":          true,
	"from":             true, // We might allow this in the future, but for now we're printing
	"max-forwards":     true,
	"record-route":     true,
	"refer-to":         true, // rfc3515
	"reply-to":         true,
	"k":                true, // Supported
	"l":                true, // Content-Length
	"m":                true, // Contact
	"o":                true, // Event; rfc3903
	"r":                true, // Refer-To; rfc3515
	"t":                true, // To
	"u":                true, // Allow-Events; rfc3903
	"v":                true, // Via
}

// Headers that will soon be forbidden
var deprecatedSipHeaderNames = map[string]string{
	"to":  "; use CreateSIPParticipantRequest.to_user_override instead",
	"via": "",
}

// Headers that must comply with name-addr specification per RFC 3261 Section 20.10
// name-addr = [display-name] <addr-spec>
// addr-spec = SIP-URI / SIPS-URI / absoluteURI
var nameAddrHeaders = map[string]bool{
	"from":                true,
	"to":                  true,
	"contact":             true,
	"route":               true,
	"record-route":        true,
	"reply-to":            true,
	"p-asserted-identity": true, // RFC 3325 Section 9.1
	"referred-by":         true, // RFC 3892 Section 3
}

// Deprecated: has no effect. Use ValidationResult method variants instead.
func SetSoftFailureReporter(reporter func(err error)) {}

// ValidateHeaderName validates a SIP header name per RFC 3261 Section 25.1
func ValidateHeaderName(name string, restrictNames bool) error {
	if name == "" {
		return errors.New("header name cannot be empty")
	}

	if len(name) > 255 {
		return errors.New("header name too long (max 255 characters)")
	}

	if err := tokenCharacters.Validate(name); err != nil {
		return fmt.Errorf("header name %s contains invalid characters: %w", name, err)
	}

	// Convert to lowercase for case-insensitive comparison
	if restrictNames {
		lowerName := strings.ToLower(name)
		if forbidden, exists := ForbiddenSipHeaderNames[lowerName]; exists && forbidden {
			return fmt.Errorf("header name %s not supported", name)
		}
	}

	return nil
}

// ValidateHeaderValue validates a SIP header value per RFC 3261 Section 25.1
func ValidateHeaderValue(name, value string) error {
	return ValidateHeaderValueResult(name, value).Error()
}

// ValidateHeaderValueResult
func ValidateHeaderValueResult(name, value string) ValidationResult {
	if value == "" {
		return ValidationResult{}
	}

	if len(value) > 1024 {
		return ValidationFailure(fmt.Errorf("header %s: value too long (max 1024 characters)", name))
	}

	// Basic character validation - printable ASCII. We're stricter than the spec here - no UTF-8 for now
	if err := headerValuesCharacters.Validate(value); err != nil {
		return ValidationFailure(fmt.Errorf("header %s: value: %w", name, err))
	}

	// Convert to lowercase for case-insensitive comparison
	var softErrs []error
	lowerName := strings.ToLower(name)
	if _, exists := nameAddrHeaders[lowerName]; exists {
		if err := validateNameAddrHeader(value); err != nil {
			softErrs = append(softErrs, fmt.Errorf("header %s: value: %w", name, err))
		}
	}
	return ValidationResult{nil, softErrs}
}

// findAngleBrackets efficiently finds angle brackets in a single scan
// Returns: start, end positions (-1 = missing), and error status
func findAngleBrackets(value string) (int, int, error) {
	start := -1
	end := -1

	// A leading quoted display name may contain angle brackets of its own.
	offset := len(value) - len(skipQuotedDisplayName(value))
	for i, r := range value[offset:] {
		i += offset
		switch r {
		case '<':
			if start != -1 {
				return -1, -1, errors.New("multiple opening brackets")
			}
			start = i
		case '>':
			if end != -1 {
				return -1, -1, errors.New("multiple closing brackets")
			}
			end = i
		}
	}

	// Check for mismatched brackets
	if (start == -1) != (end == -1) {
		return -1, -1, errors.New("mismatched angle brackets")
	}

	// Check that < comes before >
	if start > end {
		return -1, -1, errors.New("malformed angle brackets")
	}

	return start, end, nil
}

// validateNameAddrHeader validates headers that use name-addr format per RFC 3261 Section 20.10
func validateNameAddrHeader(value string) error {
	_, err := ParseSIPNameAddr(value)
	return err
}

// ParseSIPNameAddr validates a value in name-addr or addr-spec format, as found
// in From, To and Refer-To headers, and returns the user part of its URI. The
// user is empty when the URI has none.
func ParseSIPNameAddr(value string) (string, error) {
	// RFC 3261 Section 20.10 - name-addr format
	// name-addr = [display-name] <addr-spec>
	// addr-spec = SIP-URI / SIPS-URI / absoluteURI

	uri := value
	start, end, err := findAngleBrackets(value)
	if err != nil {
		return "", err
	}
	if start >= 0 || end >= 0 {
		uri = value[start+1 : end]
		if err := validateDisplayName(strings.TrimSpace(value[:start])); err != nil {
			return "", err
		}
	} else {
		// This is a bare URI, and should comply with addr-spec, no special characters
		if strings.ContainsAny(value, ",? ") {
			return "", errors.New("bare URI with special characters")
		}
	}
	return uriUser(uri)
}

// skipQuotedDisplayName returns the part of a name-addr after a leading quoted
// display name. An unterminated quote returns the value unchanged.
func skipQuotedDisplayName(s string) string {
	if !strings.HasPrefix(s, "\"") {
		return s
	}
	for i := 1; i < len(s); i++ {
		switch s[i] {
		case '\\':
			i++
		case '"':
			return s[i+1:]
		}
	}
	return s
}

// validateDisplayName validates a display name in name-addr format
func validateDisplayName(displayName string) error {
	if displayName == "" {
		return nil
	}

	// Check if display name is quoted
	if strings.HasPrefix(displayName, `"`) && strings.HasSuffix(displayName, `"`) {
		// Quoted display name - use strconv.Unquote to validate proper escaping
		_, err := strconv.Unquote(displayName)
		if err != nil {
			return fmt.Errorf("display name: %w", err)
		}
		return nil
	}

	// Unquoted display name - must not contain special characters
	if err := displayNameCharacters.Validate(displayName); err != nil {
		return fmt.Errorf("display name: %w", err)
	}

	return nil
}

// uriUser validates a URI that can appear in name-addr format and returns its
// user part: up to the "@" for sip and sips, the whole number for tel, without
// parameters or headers.
func uriUser(uri string) (string, error) {
	// Just do the basics, full validation should be done by sip service
	scheme, rest, _ := strings.Cut(uri, ":")
	var user string
	switch strings.ToLower(scheme) {
	case "sip", "sips":
		if u, _, found := strings.Cut(rest, "@"); found {
			user = u
		}
	case "tel":
		// Technically, it either needs to be sip/s: or scheme://...
		// Thus, tel: uri should not be supported here... but we allow it because of de-facto usage.
		user = rest
	default:
		return "", errors.New("uri: scheme not one of sip, sips, or tel")
	}

	// Just no spaces, proper validation should be done in sip service
	if strings.Contains(uri, " ") {
		return "", errors.New("uri: contains spaces")
	}

	user, _, _ = strings.Cut(user, ";")
	return user, nil
}