Debian Codegraph @

xmpp-vala/src/module/xep/0047_in_band_bytestreams.vala

raw
1 using Gee;
2 using Xmpp;
3 using Xmpp.Xep;
4
5 namespace Xmpp.Xep.InBandBytestreams {
6
7 private const string NS_URI = "http://jabber.org/protocol/ibb";
8 private const int SEQ_MODULUS = 65536;
9
10 public class Module : XmppStreamModule, Iq.Handler {
11 public static Xmpp.ModuleIdentity<Module> IDENTITY = new Xmpp.ModuleIdentity<Module>(NS_URI, "0047_in_band_bytestreams");
12
13 public override void attach(XmppStream stream) {
14 stream.add_flag(new Flag());
15 stream.get_module(Iq.Module.IDENTITY).register_for_namespace(NS_URI, this);
16 }
17 public override void detach(XmppStream stream) {
18 stream.get_module(Iq.Module.IDENTITY).unregister_from_namespace(NS_URI, this);
19 }
20
21 public async void on_iq_set(XmppStream stream, Iq.Stanza iq) {
22 // the iq module ensures that there's only one child node
23 StanzaNode? node = null;
24 node = (node != null) ? node : iq.stanza.get_subnode("open", NS_URI);
25 node = (node != null) ? node : iq.stanza.get_subnode("data", NS_URI);
26 node = (node != null) ? node : iq.stanza.get_subnode("close", NS_URI);
27 if (node == null) {
28 stream.get_module(Iq.Module.IDENTITY).send_iq(stream, new Iq.Stanza.error(iq, new ErrorStanza.bad_request("unknown IBB action")) { to=iq.from });
29 return;
30 }
31 string? sid = node.get_attribute("sid");
32 if (sid == null) {
33 stream.get_module(Iq.Module.IDENTITY).send_iq(stream, new Iq.Stanza.error(iq, new ErrorStanza.bad_request("missing sid")) { to=iq.from });
34 return;
35 }
36 Connection? conn = stream.get_flag(Flag.IDENTITY).get_connection(sid);
37 if (node.name == "open") {
38 if (conn == null) {
39 stream.get_module(Iq.Module.IDENTITY).send_iq(stream, new Iq.Stanza.error(iq, new ErrorStanza.not_acceptable("unexpected IBB connection")) { to=iq.from });
40 return;
41 }
42 if (conn.state != Connection.State.WAITING_FOR_CONNECT) {
43 stream.get_module(Iq.Module.IDENTITY).send_iq(stream, new Iq.Stanza.error(iq, new ErrorStanza.bad_request("IBB open for already open connection")) { to=iq.from });
44 return;
45 }
46 conn.handle_open(stream, node, iq);
47 } else {
48 if (conn == null || conn.state != Connection.State.CONNECTED) {
49 stream.get_module(Iq.Module.IDENTITY).send_iq(stream, new Iq.Stanza.error(iq, new ErrorStanza.item_not_found()) { to=iq.from });
50 return;
51 }
52 if (node.name == "close") {
53 conn.handle_close(stream, node, iq);
54 } else {
55 conn.handle_data(stream, node, iq);
56 }
57 }
58 }
59
60 public override string get_ns() { return NS_URI; }
61 public override string get_id() { return IDENTITY.id; }
62 }
63
64 public class Connection : IOStream {
65 public class Input : InputStream {
66 private weak Connection connection;
67 public Input(Connection connection) {
68 this.connection = connection;
69 }
70 public override ssize_t read(uint8[] buffer, Cancellable? cancellable = null) throws IOError {
71 throw new IOError.NOT_SUPPORTED("can't do non-async reads on in-band bytestreams");
72 }
73 public override async ssize_t read_async(uint8[]? buffer, int io_priority = GLib.Priority.DEFAULT, Cancellable? cancellable = null) throws IOError {
74 return yield connection.read_async(buffer, io_priority, cancellable);
75 }
76 public override bool close(Cancellable? cancellable = null) throws IOError {
77 throw new IOError.NOT_SUPPORTED("can't do non-async closes on in-band bytestreams");
78 }
79 public override async bool close_async(int io_priority = GLib.Priority.DEFAULT, Cancellable? cancellable = null) throws IOError {
80 return yield connection.close_read_async(io_priority, cancellable);
81 }
82 }
83 public class Output : OutputStream {
84 private weak Connection connection;
85 public Output(Connection connection) {
86 this.connection = connection;
87 }
88 public override ssize_t write(uint8[] buffer, Cancellable? cancellable = null) throws IOError {
89 throw new IOError.NOT_SUPPORTED("can't do non-async writes on in-band bytestreams");
90 }
91 public override async ssize_t write_async(uint8[]? buffer, int io_priority = GLib.Priority.DEFAULT, Cancellable? cancellable = null) throws IOError {
92 return yield connection.write_async(buffer, io_priority, cancellable);
93 }
94 public override bool close(Cancellable? cancellable = null) throws IOError {
95 throw new IOError.NOT_SUPPORTED("can't do non-async closes on in-band bytestreams");
96 }
97 public override async bool close_async(int io_priority = GLib.Priority.DEFAULT, Cancellable? cancellable = null) throws IOError {
98 return yield connection.close_write_async(io_priority, cancellable);
99 }
100 }
101
102 private Input input;
103 private Output output;
104 public override InputStream input_stream { get { return input; } }
105 public override OutputStream output_stream { get { return output; } }
106
107 public enum State {
108 WAITING_FOR_CONNECT,
109 CONNECTING,
110 CONNECTED,
111 DISCONNECTING,
112 DISCONNECTED,
113 ERROR,
114 }
115 public State state { get; private set; }
116 Jid receiver_full_jid;
117 public string sid { get; private set; }
118 int block_size;
119 int local_seq = 0;
120 int remote_ack = 0;
121 internal int remote_seq = 0;
122
123 bool input_closed = false;
124 bool output_closed = false;
125
126 // ERROR
127 string? error = null;
128
129 XmppStream stream;
130
131 int read_callback_priority;
132 Cancellable? read_callback_cancellable = null;
133 ulong read_callback_cancellable_id;
134 SourceFunc? read_callback = null;
135 int write_callback_priority;
136 SourceFunc? write_callback = null;
137 ulong write_callback_cancellable_id;
138 Cancellable? write_callback_cancellable = null;
139 // Need `Bytes` instead of `uint8[]` because the latter doesn't work in
140 // parameter position of `LinkedList`.
141 LinkedList<Bytes> received = new LinkedList<Bytes>();
142
143 private Connection(XmppStream stream, Jid receiver_full_jid, string sid, int block_size, bool initiate) {
144 this.stream = stream;
145 this.receiver_full_jid = receiver_full_jid;
146 this.sid = sid;
147 this.block_size = block_size;
148 this.state = initiate ? State.CONNECTING : State.WAITING_FOR_CONNECT;
149
150 input = new Input(this);
151 output = new Output(this);
152 }
153
154 public void set_read_callback(owned SourceFunc callback, Cancellable? cancellable, int io_priority) throws IOError {
155 if (read_callback != null) {
156 throw new IOError.PENDING("only one async read is permitted at a time on an in-band bytestream");
157 }
158 if (cancellable != null) {
159 read_callback_cancellable_id = cancellable.connect(trigger_read_callback);
160 }
161 read_callback = (owned)callback;
162 read_callback_cancellable = cancellable;
163 read_callback_priority = io_priority;
164 }
165 public void set_write_callback(owned SourceFunc callback, Cancellable? cancellable, int io_priority) throws IOError {
166 if (write_callback != null) {
167 throw new IOError.PENDING("only one async write is permitted at a time on an in-band bytestream");
168 }
169 if (cancellable != null) {
170 write_callback_cancellable_id = cancellable.connect(trigger_write_callback);
171 }
172 write_callback = (owned)callback;
173 write_callback_cancellable = cancellable;
174 write_callback_priority = io_priority;
175 }
176 public void trigger_read_callback() {
177 if (read_callback != null) {
178 Idle.add((owned) read_callback, read_callback_priority);
179 read_callback = null;
180 if (read_callback_cancellable != null) {
181 read_callback_cancellable.disconnect(read_callback_cancellable_id);
182 }
183 read_callback_cancellable = null;
184 }
185 }
186 public void trigger_write_callback() {
187 if (write_callback != null) {
188 Idle.add((owned) write_callback, write_callback_priority);
189 write_callback = null;
190 if (write_callback_cancellable != null) {
191 write_callback_cancellable.disconnect(write_callback_cancellable_id);
192 }
193 write_callback_cancellable = null;
194 }
195 }
196
197 public async ssize_t read_async(uint8[]? buffer, int io_priority = GLib.Priority.DEFAULT, Cancellable? cancellable = null) throws IOError {
198 while (true) {
199 if (cancellable != null) {
200 cancellable.set_error_if_cancelled();
201 }
202 if (input_closed) {
203 return 0;
204 }
205 Bytes? chunk = received.poll();
206 if (chunk != null) {
207 int read = int.min(buffer.length, chunk.length);
208 for (int i = 0; i < read; i++) {
209 buffer[i] = chunk[i];
210 }
211 if (buffer.length < chunk.length) {
212 received.offer_head(chunk[buffer.length:chunk.length]);
213 }
214 return read;
215 }
216 if (state == Connection.State.DISCONNECTED) {
217 return 0;
218 }
219 set_read_callback(read_async.callback, cancellable, io_priority);
220 yield;
221 }
222 }
223
224 public async ssize_t write_async(uint8[]? buffer, int io_priority = GLib.Priority.DEFAULT, Cancellable? cancellable = null) throws IOError {
225 while (state == State.WAITING_FOR_CONNECT || state == State.CONNECTING) {
226 if (cancellable != null) {
227 cancellable.set_error_if_cancelled();
228 }
229 set_write_callback(write_async.callback, cancellable, io_priority);
230 yield;
231 }
232 throw_if_closed();
233 assert(state == State.CONNECTED);
234 // TODO(hrxi): merging?
235 int seq = local_seq;
236 local_seq = (local_seq + 1) % SEQ_MODULUS;
237 if (buffer.length > block_size) {
238 buffer = buffer[0:block_size];
239 }
240 StanzaNode data = new StanzaNode.build("data", NS_URI)
241 .add_self_xmlns()
242 .put_attribute("sid", sid)
243 .put_attribute("seq", seq.to_string())
244 .put_node(new StanzaNode.text(Base64.encode(buffer)));
245 Iq.Stanza iq = new Iq.Stanza.set(data) { to=receiver_full_jid };
246 set_write_callback(write_async.callback, cancellable, io_priority);
247 stream.get_module(Iq.Module.IDENTITY).send_iq(stream, iq, (stream, iq) => {
248 if (iq.is_error()) {
249 set_error("sending failed");
250 } else if (remote_ack != seq) {
251 set_error("out of order acks");
252 } else {
253 remote_ack = (remote_ack + 1) % SEQ_MODULUS;
254 if (local_seq == remote_ack) {
255 trigger_write_callback();
256 }
257 }
258 });
259 yield;
260 if (cancellable != null) {
261 cancellable.set_error_if_cancelled();
262 }
263 throw_if_error();
264 return buffer.length;
265 }
266
267 public async bool close_read_async(int io_priority = GLib.Priority.DEFAULT, Cancellable? cancellable = null) throws IOError {
268 input_closed = true;
269 if (!output_closed) {
270 return true;
271 }
272 return yield close_async_impl(io_priority, cancellable);
273 }
274 public async bool close_write_async(int io_priority = GLib.Priority.DEFAULT, Cancellable? cancellable = null) throws IOError {
275 output_closed = true;
276 if (!input_closed) {
277 return true;
278 }
279 return yield close_async_impl(io_priority, cancellable);
280 }
281 delegate void OnClose(bool success);
282 private bool close_impl(Cancellable? cancellable, OnClose on_close) {
283 if (state == State.DISCONNECTING || state == State.DISCONNECTED || state == State.ERROR) {
284 on_close(true);
285 return true;
286 }
287 if (state == State.WAITING_FOR_CONNECT) {
288 state = State.DISCONNECTED;
289 stream.get_flag(Flag.IDENTITY).remove_connection(this);
290 trigger_read_callback();
291 on_close(true);
292 return true;
293 }
294 state = State.DISCONNECTING;
295 StanzaNode close = new StanzaNode.build("close", NS_URI)
296 .add_self_xmlns()
297 .put_attribute("sid", sid);
298 Iq.Stanza iq = new Iq.Stanza.set(close) { to=receiver_full_jid };
299 stream.get_module(Iq.Module.IDENTITY).send_iq(stream, iq, (stream, iq) => {
300 assert(state == State.DISCONNECTING);
301 if (iq.is_error()) {
302 set_error("disconnecting failed");
303 } else {
304 state = State.DISCONNECTED;
305 }
306 stream.get_flag(Flag.IDENTITY).remove_connection(this);
307 trigger_read_callback();
308 on_close(!iq.is_error());
309 });
310 return true;
311 }
312 private async bool close_async_impl(int io_priority = GLib.Priority.DEFAULT, Cancellable? cancellable = null) throws IOError {
313 SourceFunc callback = close_async_impl.callback;
314 close_impl(cancellable, () => { Idle.add((owned) callback); });
315 yield;
316 throw_if_error();
317 return true;
318 }
319
320 public static Connection create(XmppStream stream, Jid receiver_full_jid, string sid, int block_size, bool initiate) {
321 Connection conn = new Connection(stream, receiver_full_jid, sid, block_size, initiate);
322 if (initiate) {
323 StanzaNode open = new StanzaNode.build("open", NS_URI)
324 .add_self_xmlns()
325 .put_attribute("block-size", block_size.to_string())
326 .put_attribute("sid", sid);
327
328 Iq.Stanza iq = new Iq.Stanza.set(open) { to=receiver_full_jid };
329 stream.get_module(Iq.Module.IDENTITY).send_iq(stream, iq, (stream, iq) => {
330 if (conn.state != State.CONNECTING) {
331 assert(conn.state != State.CONNECTED);
332 return;
333 }
334 if (!iq.is_error()) {
335 conn.state = State.CONNECTED;
336 stream.get_flag(Flag.IDENTITY).add_connection(conn);
337 conn.trigger_write_callback();
338 } else {
339 conn.set_error("connection failed");
340 }
341 });
342 } else {
343 stream.get_flag(Flag.IDENTITY).add_connection(conn);
344 }
345 return conn;
346 }
347
348 void throw_if_error() throws IOError {
349 if (state == State.ERROR) {
350 throw new IOError.FAILED(error);
351 }
352 }
353
354 void throw_if_closed() throws IOError {
355 throw_if_error();
356 if (state == State.DISCONNECTING || state == State.DISCONNECTED) {
357 throw new IOError.CLOSED("can't read/write on a closed connection");
358 }
359 }
360
361 void set_error(string error) {
362 if (state != State.WAITING_FOR_CONNECT && state != State.DISCONNECTING && state != State.DISCONNECTED && state != State.ERROR) {
363 close_async.begin();
364 }
365 state = State.ERROR;
366 this.error = error;
367 stream.get_flag(Flag.IDENTITY).remove_connection(this);
368 }
369
370 public void handle_open(XmppStream stream, StanzaNode open, Iq.Stanza iq) {
371 assert(state == State.WAITING_FOR_CONNECT);
372 int block_size = open.get_attribute_int("block-size");
373 string? stanza = open.get_attribute("stanza");
374 if (block_size < 0 || (stanza != null && stanza != "iq" && stanza != "message")) {
375 set_error("invalid open");
376 stream.get_module(Iq.Module.IDENTITY).send_iq(stream, new Iq.Stanza.error(iq, new ErrorStanza.bad_request("missing block_size or invalid stanza")) { to=iq.from });
377 return;
378 }
379 if (stanza != null && stanza != "iq") {
380 set_error("invalid open");
381 stream.get_module(Iq.Module.IDENTITY).send_iq(stream, new Iq.Stanza.error(iq, new ErrorStanza.feature_not_implemented("cannot use message stanzas for IBB")) { to=iq.from });
382 return;
383 }
384 if (block_size > this.block_size) {
385 set_error("invalid open");
386 stream.get_module(Iq.Module.IDENTITY).send_iq(stream, new Iq.Stanza.error(iq, new ErrorStanza.build(ErrorStanza.TYPE_CANCEL, ErrorStanza.CONDITION_RESOURCE_CONSTRAINT, "opening a connection with a greater than negotiated/acceptable block size", null)) { to=iq.from });
387 return;
388 }
389 this.block_size = block_size;
390 state = State.CONNECTED;
391 stream.get_module(Iq.Module.IDENTITY).send_iq(stream, new Iq.Stanza.result(iq));
392 trigger_write_callback();
393 }
394 public void handle_data(XmppStream stream, StanzaNode data, Iq.Stanza iq) {
395 assert(state == State.CONNECTED);
396 if (input_closed) {
397 set_error("unexpected data");
398 stream.get_module(Iq.Module.IDENTITY).send_iq(stream, new Iq.Stanza.error(iq, new ErrorStanza.not_allowed("unexpected data")) { to=iq.from });
399 return;
400 }
401 int seq = data.get_attribute_int("seq");
402 // TODO(hrxi): return an error on malformed base64 (need to do this
403 // according to the xep)
404 uint8[] content = Base64.decode(data.get_string_content());
405 if (content.length > block_size) {
406 set_error("data longer than negotiated block size");
407 stream.get_module(Iq.Module.IDENTITY).send_iq(stream, new Iq.Stanza.error(iq, new ErrorStanza.bad_request("data longer than negotiated block size")) { to=iq.from });
408 return;
409 }
410 if (seq < 0 || seq != remote_seq) {
411 set_error("out of order data packets");
412 stream.get_module(Iq.Module.IDENTITY).send_iq(stream, new Iq.Stanza.error(iq, new ErrorStanza.build(ErrorStanza.TYPE_CANCEL, ErrorStanza.CONDITION_UNEXPECTED_REQUEST, "out of order data packets", null)) { to=iq.from });
413 return;
414 }
415 remote_seq = (remote_seq + 1) % SEQ_MODULUS;
416
417 stream.get_module(Iq.Module.IDENTITY).send_iq(stream, new Iq.Stanza.result(iq));
418 if (content.length != 0) {
419 received.offer(new Bytes.take(content));
420 trigger_read_callback();
421 }
422 }
423 public void handle_close(XmppStream stream, StanzaNode close, Iq.Stanza iq) {
424 assert(state == State.CONNECTED);
425 stream.get_module(Iq.Module.IDENTITY).send_iq(stream, new Iq.Stanza.result(iq));
426 stream.get_flag(Flag.IDENTITY).remove_connection(this);
427 input_closed = true;
428 output_closed = true;
429 state = State.DISCONNECTED;
430
431 trigger_read_callback();
432 }
433 }
434
435
436 public class Flag : XmppStreamFlag {
437 public static FlagIdentity<Flag> IDENTITY = new FlagIdentity<Flag>(NS_URI, "in_band_bytestreams");
438
439 private HashMap<string, Connection> active = new HashMap<string, Connection>();
440
441 public void add_connection(Connection conn) {
442 active[conn.sid] = conn;
443 }
444 public Connection? get_connection(string sid) {
445 return active.has_key(sid) ? active[sid] : null;
446 }
447 public void remove_connection(Connection conn) {
448 active.unset(conn.sid);
449 }
450
451 public override string get_ns() { return NS_URI; }
452 public override string get_id() { return IDENTITY.id; }
453 }
454
455 }