~samwhited/xmpp

ref: c71a17569b03f07e0fc407f1da2094c1796cec90 xmpp/session.go -rw-r--r-- 7.7 KiB
c71a1756Sam Whited ibr2: Add API stability disclaimer to docs 4 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
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
// 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 xmpp

import (
	"context"
	"encoding/xml"
	"errors"
	"fmt"
	"io"
	"net"
	"reflect"
	"sync"

	"mellium.im/xmpp/internal"
	"mellium.im/xmpp/jid"
	"mellium.im/xmpp/streamerror"
)

// SessionState is a bitmask that represents the current state of an XMPP
// session. For a description of each bit, see the various SessionState typed
// constants.
type SessionState uint8

const (
	// Secure indicates that the underlying connection has been secured. For
	// instance, after STARTTLS has been performed or if a pre-secured connection
	// is being used such as websockets over HTTPS.
	Secure SessionState = 1 << iota

	// Authn indicates that the session has been authenticated (probably with
	// SASL).
	Authn

	// Ready indicates that the session is fully negotiated and that XMPP stanzas
	// may be sent and received.
	Ready

	// Received indicates that the session was initiated by a foreign entity.
	Received

	// OutputStreamClosed indicates that the output stream has been closed with a
	// stream end tag.  When set all write operations will return an error even if
	// the underlying TCP connection is still open.
	OutputStreamClosed

	// InputStreamClosed indicates that the input stream has been closed with a
	// stream end tag. When set all read operations will return an error.
	InputStreamClosed
)

// A Session represents an XMPP session comprising an input and an output XML
// stream.
type Session struct {
	config *Config

	// If the initial ReadWriter is a conn, save a reference to that as well so
	// that we can use it directly without type casting constantly.
	conn net.Conn
	rw   io.ReadWriter

	state SessionState

	// The actual origin of this conn (we don't want to mutate the config, so if
	// this origin exists and is different from the one in config, eg. because the
	// server did not assign us the resourcepart we requested, this is canonical).
	origin *jid.JID

	// The stream feature namespaces advertised for the current streams.
	features map[string]interface{}
	flock    sync.Mutex

	// The negotiated features (by namespace) for the current session.
	negotiated map[string]struct{}

	in struct {
		sync.Mutex
		stream
		d      *xml.Decoder
		ctx    context.Context
		cancel context.CancelFunc
	}
	out struct {
		sync.Mutex
		stream
		e *xml.Encoder
	}
}

// Send is used to marshal an element into XML and transmit it over the egress
// stream. If the interface is composed of a stanza (IQ, Message, or Presence)
// and the from or id attributes are empty, an appropriate value is inserted in
// the output XML.
func (s *Session) Send(v interface{}) error {
	v = enforceStanzaSemantics(v)
	return s.out.e.Encode(v)
}

func enforceStanzaSemantics(v interface{}) interface{} {
	// TODO: This is horrifying, and probably buggy. There has got to be a better
	//       way that I haven't thought of…

	var (
		stanza    interface{}
		fieldname string
	)
	switch copier := v.(type) {
	case interface {
		copyIQ() IQ
	}:
		iq := copier.copyIQ()
		if iq.ID == "" {
			iq.ID = internal.RandomID()
		}
		stanza = iq
		fieldname = "IQ"
	case interface {
		copyMessage() Message
	}:
		m := copier.copyMessage()
		if m.ID == "" {
			m.ID = internal.RandomID()
		}
		stanza = m
		fieldname = "Message"
	case interface {
		copyPresence() Presence
	}:
		p := copier.copyPresence()
		if p.ID == "" {
			p.ID = internal.RandomID()
		}
		stanza = p
		fieldname = "Presence"
	default:
		return v
	}

	val, err := getCopy(reflect.ValueOf(v))
	if err != nil {
		return nil
	}
	val.FieldByName(fieldname).Set(reflect.ValueOf(stanza))
	v = val.Interface()

	return v
}

func getCopy(val reflect.Value) (v reflect.Value, err error) {
	for val.Kind() == reflect.Interface || val.Kind() == reflect.Ptr {
		if val.IsNil() {
			return v, fmt.Errorf("Failed")
		}
		val = val.Elem()
	}
	return reflect.New(val.Type()).Elem(), nil
}

// Feature checks if a feature with the given namespace was advertised
// by the server for the current stream. If it was data will be the canonical
// representation of the feature as returned by the feature's Parse function.
func (s *Session) Feature(namespace string) (data interface{}, ok bool) {
	s.flock.Lock()
	defer s.flock.Unlock()

	// TODO: Make the features struct actually store the parsed representation.
	data, ok = s.features[namespace]
	return
}

// NewSession attempts to use an existing connection (or any io.ReadWriteCloser) to
// negotiate an XMPP session based on the given config. If the provided context
// is canceled before stream negotiation is complete an error is returned. After
// stream negotiation if the context is canceled it has no effect.
func NewSession(ctx context.Context, config *Config, rw io.ReadWriter) (*Session, error) {
	s := &Session{
		config: config,
		rw:     rw,
	}
	s.in.ctx, s.in.cancel = context.WithCancel(context.Background())

	if conn, ok := rw.(net.Conn); ok {
		s.conn = conn
	}

	err := s.negotiateStreams(ctx, rw)
	if err != nil {
		return nil, err
	}
	if config.Handler != nil {
		go s.handleInputStream()
	}
	return s, err
}

func (s *Session) handleInputStream() {
	for {
		select {
		case <-s.in.ctx.Done():
			return
		default:
		}
		// TODO: This needs to be cancelable somehow.
		tok, err := s.Decoder().Token()
		if err != nil {
			select {
			case <-s.in.ctx.Done():
				return
			default:
				// TODO: We need a way to figure out if this was an XML error or an error
				// with the underlying connection.
				s.Encoder().Encode(streamerror.BadFormat)
			}
		}
		switch t := tok.(type) {
		case xml.StartElement:
			s.config.Handler.HandleXMPP(s, &t)
		default:
			select {
			case <-s.in.ctx.Done():
				return
			default:
				// TODO: We need a way to figure out if this was an XML error or an error
				// with the underlying connection.
				s.Encoder().Encode(streamerror.BadFormat)
			}
		}
	}
}

// Conn returns the Session's backing net.Conn or other ReadWriter.
func (s *Session) Conn() io.ReadWriter {
	return s.rw
}

// Decoder returns the XML decoder that was used to negotiate the latest stream.
func (s *Session) Decoder() *xml.Decoder {
	return s.in.d
}

// Encoder returns the XML encoder that was used to negotiate the latest stream.
func (s *Session) Encoder() *xml.Encoder {
	return s.out.e
}

// Config returns the connections config.
func (s *Session) Config() *Config {
	return s.config
}

func (s *Session) read(b []byte) (n int, err error) {
	s.in.Lock()
	defer s.in.Unlock()

	if s.state&InputStreamClosed == InputStreamClosed {
		return 0, errors.New("XML input stream is closed")
	}

	n, err = s.rw.Read(b)
	return
}

func (s *Session) write(b []byte) (n int, err error) {
	s.out.Lock()
	defer s.out.Unlock()

	if s.state&OutputStreamClosed == OutputStreamClosed {
		return 0, errors.New("XML output stream is closed")
	}

	n, err = s.rw.Write(b)
	return
}

// Close ends the output stream and blocks until the remote client closes the
// input stream.
func (s *Session) Close() (err error) {
	// TODO: Block until input stream is closed?
	_, err = s.write([]byte(`</stream:stream>`))
	return
}

// State returns the current state of the session. For more information, see the
// SessionState type.
func (s *Session) State() SessionState {
	return s.state
}

// LocalAddr returns the Origin address for initiated connections, or the
// Location for received connections.
func (s *Session) LocalAddr() *jid.JID {
	if (s.state & Received) == Received {
		return s.config.Location
	}
	if s.origin != nil {
		return s.origin
	}
	return s.config.Origin
}

// RemoteAddr returns the Location address for initiated connections, or the
// Origin address for received connections.
func (s *Session) RemoteAddr() *jid.JID {
	if (s.state & Received) == Received {
		return s.config.Origin
	}
	return s.config.Location
}