~samwhited/xmpp

ref: dcc6772f31033948a00a7dfb9232a120120be5b7 xmpp/mux/mux.go -rw-r--r-- 12.8 KiB
dcc6772fSam Whited all: add strict namespace checking to mux 26 days ago
                                                                                
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
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
// Copyright 2017 The Mellium Contributors.
// Use of this source code is governed by the BSD 2-clause
// license that can be found in the LICENSE file.

// Package mux contains a simple XMPP multiplexer.
//
// Aside from implementing its own muxer, this package contains handler
// interfaces designed to be standard across multiplexers.
// This lets you write, for example, a muxer that matches elements based on
// xpath expressions and take advantage of existing handlers.
package mux // import "mellium.im/xmpp/mux"

import (
	"encoding/xml"
	"fmt"
	"strings"

	"mellium.im/xmlstream"
	"mellium.im/xmpp"
	"mellium.im/xmpp/disco/info"
	"mellium.im/xmpp/disco/items"
	"mellium.im/xmpp/form"
	"mellium.im/xmpp/stanza"
)

const (
	iqStanza   = "iq"
	msgStanza  = "message"
	presStanza = "presence"
)

type pattern struct {
	Payload xml.Name
	Stanza  string
	Type    string
}

func (p pattern) String() string {
	return fmt.Sprintf("%s %s with payload {%s}%s", p.Type, p.Stanza, p.Payload.Space, p.Payload.Local)
}

// ServeMux is an XMPP stream multiplexer.
// It matches the start element token of each top level stream element against a
// list of registered patterns and calls the handler for the pattern that most
// closely matches the token.
//
// Patterns are XML names.
// If either the namespace or the localname is left off, any namespace or
// localname will be matched.
// Full XML names take precedence, followed by wildcard localnames, followed by
// wildcard namespaces.
type ServeMux struct {
	patterns         map[xml.Name]xmpp.Handler
	iqPatterns       map[pattern]IQHandler
	msgPatterns      map[pattern]MessageHandler
	presencePatterns map[pattern]PresenceHandler
	stanzaNS         string
}

// New allocates and returns a new ServeMux.
func New(stanzaNS string, opt ...Option) *ServeMux {
	m := &ServeMux{stanzaNS: stanzaNS}
	for _, o := range opt {
		o(m)
	}
	return m
}

// Handler returns the handler to use for a top level element with the provided
// XML name.
// If no exact match or wildcard handler exists, a default handler is returned
// (h is always non-nil) and ok will be false.
func (m *ServeMux) Handler(name xml.Name) (h xmpp.Handler, ok bool) {
	h = m.patterns[name]
	if h != nil {
		return h, true
	}

	n := name
	n.Space = ""
	h = m.patterns[n]
	if h != nil {
		return h, true
	}

	n = name
	n.Local = ""
	h = m.patterns[n]
	if h != nil {
		return h, true
	}

	if stanza.Is(name, m.stanzaNS) {
		switch name.Local {
		case iqStanza:
			return xmpp.HandlerFunc(m.iqRouter), true
		case msgStanza:
			return xmpp.HandlerFunc(m.msgRouter), true
		case presStanza:
			return xmpp.HandlerFunc(m.presenceRouter), true
		}
	}

	return nopHandler{}, false
}

// IQHandler returns the handler to use for an IQ payload with the given type
// and payload name.
// If no handler exists, a default handler is returned (h is always non-nil).
func (m *ServeMux) IQHandler(typ stanza.IQType, payload xml.Name) (h IQHandler, ok bool) {
	pattern := pattern{Stanza: iqStanza, Payload: payload, Type: string(typ)}
	h = m.iqPatterns[pattern]
	if h != nil {
		return h, true
	}

	pattern.Payload.Space = ""
	pattern.Payload.Local = payload.Local
	h = m.iqPatterns[pattern]
	if h != nil {
		return h, true
	}

	pattern.Payload.Space = payload.Space
	pattern.Payload.Local = ""
	h = m.iqPatterns[pattern]
	if h != nil {
		return h, true
	}

	pattern.Payload.Space = ""
	pattern.Payload.Local = ""
	h = m.iqPatterns[pattern]
	if h != nil {
		return h, true
	}

	return IQHandlerFunc(iqFallback), false
}

// MessageHandler returns the handler to use for a message with the given type
// and payload.
// If no handler exists, a default handler is returned (h is always non-nil).
func (m *ServeMux) MessageHandler(typ stanza.MessageType, payload xml.Name) (h MessageHandler, ok bool) {
	pattern := pattern{Stanza: msgStanza, Payload: payload, Type: string(typ)}
	h = m.msgPatterns[pattern]
	if h != nil {
		return h, true
	}

	pattern.Payload.Space = ""
	pattern.Payload.Local = payload.Local
	h = m.msgPatterns[pattern]
	if h != nil {
		return h, true
	}

	pattern.Payload.Space = payload.Space
	pattern.Payload.Local = ""
	h = m.msgPatterns[pattern]
	if h != nil {
		return h, true
	}

	pattern.Payload.Space = ""
	pattern.Payload.Local = ""
	h = m.msgPatterns[pattern]
	if h != nil {
		return h, true
	}

	return nopHandler{}, false
}

// PresenceHandler returns the handler to use for a presence payload with the
// given type.
// If no handler exists, a default handler is returned (h is always non-nil).
func (m *ServeMux) PresenceHandler(typ stanza.PresenceType, payload xml.Name) (h PresenceHandler, ok bool) {
	pattern := pattern{Stanza: presStanza, Payload: payload, Type: string(typ)}
	h = m.presencePatterns[pattern]
	if h != nil {
		return h, true
	}

	pattern.Payload.Space = ""
	pattern.Payload.Local = payload.Local
	h = m.presencePatterns[pattern]
	if h != nil {
		return h, true
	}

	pattern.Payload.Space = payload.Space
	pattern.Payload.Local = ""
	h = m.presencePatterns[pattern]
	if h != nil {
		return h, true
	}

	pattern.Payload.Space = ""
	pattern.Payload.Local = ""
	h = m.presencePatterns[pattern]
	if h != nil {
		return h, true
	}

	return nopHandler{}, false
}

// HandleXMPP dispatches the request to the handler that most closely matches.
func (m *ServeMux) HandleXMPP(t xmlstream.TokenReadEncoder, start *xml.StartElement) error {
	h, _ := m.Handler(start.Name)
	return h.HandleXMPP(t, start)
}

// ForItems implements items.Iter for the mux by iterating over all child items.
func (m *ServeMux) ForItems(node string, f func(items.Item) error) error {
	for _, h := range m.patterns {
		if itemIter, ok := h.(items.Iter); ok {
			err := itemIter.ForItems(node, f)
			if err != nil {
				return err
			}
		}
	}
	for _, h := range m.iqPatterns {
		if itemIter, ok := h.(items.Iter); ok {
			err := itemIter.ForItems(node, f)
			if err != nil {
				return err
			}
		}
	}
	for _, h := range m.msgPatterns {
		if itemIter, ok := h.(items.Iter); ok {
			err := itemIter.ForItems(node, f)
			if err != nil {
				return err
			}
		}
	}
	for _, h := range m.presencePatterns {
		if itemIter, ok := h.(items.Iter); ok {
			err := itemIter.ForItems(node, f)
			if err != nil {
				return err
			}
		}
	}
	return nil
}

// ForFeatures implements info.FeatureIter for the mux by iterating over all
// child features.
func (m *ServeMux) ForFeatures(node string, f func(info.Feature) error) error {
	for _, h := range m.patterns {
		if featureIter, ok := h.(info.FeatureIter); ok {
			err := featureIter.ForFeatures(node, f)
			if err != nil {
				return err
			}
		}
	}
	for _, h := range m.iqPatterns {
		if featureIter, ok := h.(info.FeatureIter); ok {
			err := featureIter.ForFeatures(node, f)
			if err != nil {
				return err
			}
		}
	}
	for _, h := range m.msgPatterns {
		if featureIter, ok := h.(info.FeatureIter); ok {
			err := featureIter.ForFeatures(node, f)
			if err != nil {
				return err
			}
		}
	}
	for _, h := range m.presencePatterns {
		if featureIter, ok := h.(info.FeatureIter); ok {
			err := featureIter.ForFeatures(node, f)
			if err != nil {
				return err
			}
		}
	}
	return nil
}

// ForIdentities implements info.IdentityIter for the mux by iterating over
// all child handlers.
func (m *ServeMux) ForIdentities(node string, f func(info.Identity) error) error {
	for _, h := range m.patterns {
		if identIter, ok := h.(info.IdentityIter); ok {
			err := identIter.ForIdentities(node, f)
			if err != nil {
				return err
			}
		}
	}
	for _, h := range m.iqPatterns {
		if identIter, ok := h.(info.IdentityIter); ok {
			err := identIter.ForIdentities(node, f)
			if err != nil {
				return err
			}
		}
	}
	for _, h := range m.msgPatterns {
		if identIter, ok := h.(info.IdentityIter); ok {
			err := identIter.ForIdentities(node, f)
			if err != nil {
				return err
			}
		}
	}
	for _, h := range m.presencePatterns {
		if identIter, ok := h.(info.IdentityIter); ok {
			err := identIter.ForIdentities(node, f)
			if err != nil {
				return err
			}
		}
	}
	return nil
}

// ForForms implements form.Iter for the mux by iterating over all child
// handlers.
func (m *ServeMux) ForForms(node string, f func(*form.Data) error) error {
	for _, h := range m.patterns {
		if formIter, ok := h.(form.Iter); ok {
			err := formIter.ForForms(node, f)
			if err != nil {
				return err
			}
		}
	}
	for _, h := range m.iqPatterns {
		if formIter, ok := h.(form.Iter); ok {
			err := formIter.ForForms(node, f)
			if err != nil {
				return err
			}
		}
	}
	for _, h := range m.msgPatterns {
		if formIter, ok := h.(form.Iter); ok {
			err := formIter.ForForms(node, f)
			if err != nil {
				return err
			}
		}
	}
	for _, h := range m.presencePatterns {
		if formIter, ok := h.(form.Iter); ok {
			err := formIter.ForForms(node, f)
			if err != nil {
				return err
			}
		}
	}
	return nil
}

type nopHandler struct{}

func (nopHandler) HandleXMPP(t xmlstream.TokenReadEncoder, start *xml.StartElement) error { return nil }
func (nopHandler) HandleMessage(msg stanza.Message, t xmlstream.TokenReadEncoder) error   { return nil }
func (nopHandler) HandlePresence(p stanza.Presence, t xmlstream.TokenReadEncoder) error   { return nil }

func (m *ServeMux) iqRouter(t xmlstream.TokenReadEncoder, start *xml.StartElement) error {
	iq, err := stanza.NewIQ(*start)
	if err != nil {
		return err
	}

	// Limit the stream to the inside of the IQ element, don't allow handlers to
	// advance to the end token since they don't have access to the IQ start
	// token.
	t = struct {
		xml.TokenReader
		xmlstream.Encoder
	}{
		Encoder:     t,
		TokenReader: xmlstream.Inner(t),
	}
	tok, err := t.Token()
	if err != nil {
		return err
	}
	payloadStart, _ := tok.(xml.StartElement)
	h, _ := m.IQHandler(iq.Type, payloadStart.Name)
	return h.HandleIQ(iq, t, &payloadStart)
}

type bufReader struct {
	r      xml.TokenReader
	buf    []xml.Token
	offset uint
}

func (r *bufReader) Token() (xml.Token, error) {
	if r.offset < uint(len(r.buf)) {
		o := r.offset
		r.offset++
		return r.buf[o], nil
	}

	tok, err := r.r.Token()
	if tok != nil {
		tok = xml.CopyToken(tok)
		r.buf = append(r.buf, tok)
		r.offset++
	}
	return tok, err
}

// TODO: this is terrible error handling, figure out a better way to handle
// multiple errors that should be turned into a single stanza error.
type multiErr []error

func (e multiErr) Error() string {
	var buf strings.Builder
	for i, err := range e {
		if i == 0 {
			buf.WriteString(err.Error())
			continue
		}
		fmt.Fprintf(&buf, ", %s", err.Error())
	}
	return buf.String()
}

func (m *ServeMux) msgRouter(t xmlstream.TokenReadEncoder, start *xml.StartElement) error {
	msg, err := stanza.NewMessage(*start)
	if err != nil {
		return err
	}

	return forChildren(m, msg, t, start)
}

func (m *ServeMux) presenceRouter(t xmlstream.TokenReadEncoder, start *xml.StartElement) error {
	presence, err := stanza.NewPresence(*start)
	if err != nil {
		return err
	}

	return forChildren(m, presence, t, start)
}

func forChildren(m *ServeMux, stanzaVal interface{}, t xmlstream.TokenReadEncoder, start *xml.StartElement) error {
	r := &bufReader{
		r: t,
		// TODO: figure out a good buffer size
		buf:    make([]xml.Token, 0, 10),
		offset: 1,
	}
	r.buf = append(r.buf, *start)

	// TODO: figure out a good buffer size
	errs := make([]error, 0, 10)

	iterator := xmlstream.NewIter(r)
	/* #nosec */
	defer iterator.Close()

	for iterator.Next() {
		start, _ := iterator.Current()

		var err error
		switch s := stanzaVal.(type) {
		case stanza.Presence:
			br := &bufReader{r: t, buf: r.buf}
			h, _ := m.PresenceHandler(s.Type, start.Name)
			err = h.HandlePresence(s, struct {
				xml.TokenReader
				xmlstream.Encoder
			}{
				TokenReader: br,
				Encoder:     t,
			})
			r.buf = br.buf
		case stanza.Message:
			br := &bufReader{r: t, buf: r.buf}
			h, _ := m.MessageHandler(s.Type, start.Name)
			err = h.HandleMessage(s, struct {
				xml.TokenReader
				xmlstream.Encoder
			}{
				TokenReader: br,
				Encoder:     t,
			})
			r.buf = br.buf
		}
		if err != nil {
			errs = append(errs, err)
		}
	}
	if err := iterator.Err(); err != nil {
		return err
	}
	if len(errs) > 0 {
		return multiErr(errs)
	}
	// If the only tokens are the start and close tokens, trigger any wildcard
	// handlers.
	if len(r.buf) == 2 {
		r.offset = 0
		switch s := stanzaVal.(type) {
		case stanza.Presence:
			h, _ := m.PresenceHandler(s.Type, xml.Name{})
			return h.HandlePresence(s, struct {
				xml.TokenReader
				xmlstream.Encoder
			}{
				TokenReader: r,
				Encoder:     t,
			})
		case stanza.Message:
			h, _ := m.MessageHandler(s.Type, xml.Name{})
			return h.HandleMessage(s, struct {
				xml.TokenReader
				xmlstream.Encoder
			}{
				TokenReader: r,
				Encoder:     t,
			})
		}
	}
	return nil
}

func iqFallback(iq stanza.IQ, t xmlstream.TokenReadEncoder, start *xml.StartElement) error {
	if iq.Type == stanza.ErrorIQ {
		return nil
	}

	iq.To, iq.From = iq.From, iq.To
	iq.Type = "error"

	e := stanza.Error{
		Type:      stanza.Cancel,
		Condition: stanza.ServiceUnavailable,
	}
	_, err := xmlstream.Copy(t, iq.Wrap(e.TokenReader()))
	return err
}