~samwhited/xmpp

ref: a2ffaf710170d692a9289c2b428a4efa90c8e703 xmpp/internal/stream.go -rw-r--r-- 4.8 KiB
a2ffaf71Sam Whited all: update deps 3 years 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
// Copyright 2016 Sam Whited.
// Use of this source code is governed by the BSD 2-clause
// license that can be found in the LICENSE file.

package internal

import (
	"context"
	"encoding/xml"
	"fmt"
	"io"

	"mellium.im/xmpp/internal/ns"
	"mellium.im/xmpp/jid"
	"mellium.im/xmpp/stream"
)

const (
	// XMLHeader is an XML header like the one in encoding/xml but without a
	// newline at the end.
	XMLHeader = `<?xml version="1.0" encoding="UTF-8"?>`
)

// StreamInfo contains metadata extracted from a stream start token.
type StreamInfo struct {
	to      *jid.JID
	from    *jid.JID
	id      string
	version Version
	xmlns   string
	lang    string
}

// This MUST only return stream errors.
// TODO: Is the above true? Just make it return a StreamError?
func streamFromStartElement(s xml.StartElement) (StreamInfo, error) {
	streamData := StreamInfo{}
	for _, attr := range s.Attr {
		switch attr.Name {
		case xml.Name{Space: "", Local: "to"}:
			streamData.to = &jid.JID{}
			if err := streamData.to.UnmarshalXMLAttr(attr); err != nil {
				return streamData, stream.ImproperAddressing
			}
		case xml.Name{Space: "", Local: "from"}:
			streamData.from = &jid.JID{}
			if err := streamData.from.UnmarshalXMLAttr(attr); err != nil {
				return streamData, stream.ImproperAddressing
			}
		case xml.Name{Space: "", Local: "id"}:
			streamData.id = attr.Value
		case xml.Name{Space: "", Local: "version"}:
			(&streamData.version).UnmarshalXMLAttr(attr)
		case xml.Name{Space: "", Local: "xmlns"}:
			if attr.Value != "jabber:client" && attr.Value != "jabber:server" {
				return streamData, stream.InvalidNamespace
			}
			streamData.xmlns = attr.Value
		case xml.Name{Space: "xmlns", Local: "stream"}:
			if attr.Value != ns.Stream {
				return streamData, stream.InvalidNamespace
			}
		case xml.Name{Space: "xml", Local: "lang"}:
			streamData.lang = attr.Value
		}
	}
	return streamData, nil
}

// SendNewStream sends a new XML header followed by a stream start element on
// the given io.Writer. We don't use an xml.Encoder both because Go's standard
// library xml package really doesn't like the namespaced stream:stream
// attribute and because we can guarantee well-formedness of the XML with a
// print in this case and printing is much faster than encoding. Afterwards,
// clear the StreamRestartRequired bit and set the output stream information.
func SendNewStream(rw io.ReadWriter, s2s bool, version Version, lang string, location, origin, id string) (StreamInfo, error) {
	streamData := StreamInfo{}
	switch s2s {
	case true:
		streamData.xmlns = ns.Server
	case false:
		streamData.xmlns = ns.Client
	}

	streamData.id = id
	if id == "" {
		id = " "
	} else {
		id = ` id='` + id + `' `
	}

	_, err := fmt.Fprintf(rw,
		XMLHeader+`<stream:stream%sto='%s' from='%s' version='%s' xml:lang='`,
		id,
		location,
		origin,
		version,
	)
	if err != nil {
		return streamData, err
	}

	err = xml.EscapeText(rw, []byte(lang))
	if err != nil {
		return streamData, err
	}

	_, err = fmt.Fprintf(rw, `' xmlns='%s' xmlns:stream='http://etherx.jabber.org/streams'>`,
		streamData.xmlns,
	)
	if err != nil {
		return streamData, err
	}

	return streamData, nil
}

// ExpectNewStream reads a token from d and expects that it will be a new stream
// start token. If not, an error is returned. It then handles feature
// negotiation for the new stream.
// If an XML header is discovered instead, it is skipped.
func ExpectNewStream(ctx context.Context, d xml.TokenReader, recv bool) (streamData StreamInfo, err error) {
	var foundHeader bool

	for {
		select {
		case <-ctx.Done():
			return streamData, ctx.Err()
		default:
		}
		t, err := d.Token()
		if err != nil {
			return streamData, err
		}
		switch tok := t.(type) {
		case xml.StartElement:
			switch {
			case tok.Name.Local == "error" && tok.Name.Space == ns.Stream:
				se := stream.Error{}
				if err := xml.NewTokenDecoder(d).DecodeElement(&se, &tok); err != nil {
					return streamData, err
				}
				return streamData, se
			case tok.Name.Local != "stream":
				return streamData, stream.BadFormat
			case tok.Name.Space != ns.Stream:
				return streamData, stream.InvalidNamespace
			}

			streamData, err = streamFromStartElement(tok)
			switch {
			case err != nil:
				return streamData, err
			case streamData.version != DefaultVersion:
				return streamData, stream.UnsupportedVersion
			}

			if !recv && streamData.id == "" {
				// if we are the initiating entity and there is no stream ID…
				return streamData, stream.BadFormat
			}
			return streamData, nil
		case xml.ProcInst:
			// TODO: If version or encoding are declared, validate XML 1.0 and UTF-8
			if !foundHeader && tok.Target == "xml" {
				foundHeader = true
				continue
			}
			return streamData, stream.RestrictedXML
		case xml.EndElement:
			return streamData, stream.NotWellFormed
		default:
			return streamData, stream.RestrictedXML
		}
	}
}