/
protocol.py
1311 lines (1205 loc) · 57.3 KB
/
protocol.py
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
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# This file is part of Xpra.
# Copyright (C) 2011-2022 Antoine Martin <antoine@xpra.org>
# Copyright (C) 2008, 2009, 2010 Nathaniel Smith <njs@pobox.com>
# Xpra is released under the terms of the GNU GPL v2, or, at your option, any
# later version. See the file COPYING for details.
# oh gods it's threads
# but it works on win32, for whatever that's worth.
import os
from time import monotonic
from socket import error as socket_error
from threading import Lock, RLock, Event
from queue import Queue
from xpra.os_util import memoryview_to_bytes, strtobytes, bytestostr, hexstr
from xpra.util import repr_ellipsized, ellipsizer, csv, envint, envbool, typedict
from xpra.make_thread import make_thread, start_thread
from xpra.net.common import (
ConnectionClosedException, may_log_packet,
MAX_PACKET_SIZE, FLUSH_HEADER,
)
from xpra.net.bytestreams import ABORT
from xpra.net import compression
from xpra.net.compression import (
decompress,
InvalidCompressionException, Compressed, LevelCompressed, Compressible, LargeStructure,
)
from xpra.net import packet_encoding
from xpra.net.socket_util import guess_packet_type
from xpra.net.packet_encoding import (
decode,
InvalidPacketEncodingException,
)
from xpra.net.header import unpack_header, pack_header, FLAGS_CIPHER, FLAGS_NOHEADER, FLAGS_FLUSH, HEADER_SIZE
from xpra.net.crypto import get_encryptor, get_decryptor, pad, INITIAL_PADDING
from xpra.log import Logger
log = Logger("network", "protocol")
cryptolog = Logger("network", "crypto")
USE_ALIASES = envbool("XPRA_USE_ALIASES", True)
READ_BUFFER_SIZE = envint("XPRA_READ_BUFFER_SIZE", 65536)
#merge header and packet if packet is smaller than:
PACKET_JOIN_SIZE = envint("XPRA_PACKET_JOIN_SIZE", READ_BUFFER_SIZE)
LARGE_PACKET_SIZE = envint("XPRA_LARGE_PACKET_SIZE", 4096)
LOG_RAW_PACKET_SIZE = envbool("XPRA_LOG_RAW_PACKET_SIZE", False)
#inline compressed data in packet if smaller than:
INLINE_SIZE = envint("XPRA_INLINE_SIZE", 32768)
FAKE_JITTER = envint("XPRA_FAKE_JITTER", 0)
MIN_COMPRESS_SIZE = envint("XPRA_MIN_COMPRESS_SIZE", 378)
SEND_INVALID_PACKET = envint("XPRA_SEND_INVALID_PACKET", 0)
SEND_INVALID_PACKET_DATA = strtobytes(os.environ.get("XPRA_SEND_INVALID_PACKET_DATA", b"ZZinvalid-packetZZ"))
def exit_queue():
queue = Queue()
for _ in range(10): #just 2 should be enough!
queue.put(None)
return queue
def force_flush_queue(q):
try:
#discard all elements in the old queue and push the None marker:
try:
while q.qsize()>0:
q.get(False)
except Exception:
log("force_flush_queue(%s)", q, exc_info=True)
q.put_nowait(None)
except Exception:
log("force_flush_queue(%s)", q, exc_info=True)
def find_xpra_header(data, index=0, max_data_size=2**16):
pos = data.find(b"P")
while pos>=0:
if len(data)<pos+8:
#not enough data to try to parse this potential header
return -1
pchar, pflags, compress, packet_index, data_size = unpack_header(data[pos:pos+8])
log("find_xpra_header candidate at index %i: %s", pos, (pchar, pflags, compress, packet_index, data_size))
if pchar==b"P" and packet_index==index and data_size<max_data_size:
#validate flags:
if compress==0 or (compress & 0xf)>0:
# pylint: disable=import-outside-toplevel
from xpra.net.header import FLAGS_RENCODE, FLAGS_RENCODEPLUS, FLAGS_YAML
encoder_flag = pflags & (FLAGS_RENCODE | FLAGS_YAML | FLAGS_RENCODEPLUS)
n_flags_set = sum(1 for flag in (FLAGS_RENCODE, FLAGS_YAML, FLAGS_RENCODEPLUS) if encoder_flag & flag)
if encoder_flag==0 or n_flags_set==1:
return pos
#skip to the next potential header:
pos = data.find(b"P", pos+1)
log("checking again from pos=%s", pos)
return -1
def verify_packet(packet):
""" look for None values which may have caused the packet to fail encoding """
if not isinstance(packet, list):
return False
if not packet:
raise ValueError(f"invalid packet: {packet} ({type(packet)})")
tree = [f"{packet[0]!r} packet"]
return do_verify_packet(tree, packet)
def do_verify_packet(tree, packet):
def err(msg):
log.error("%s in %s", msg, "->".join(tree))
def new_tree(append):
nt = tree[:]
nt.append(append)
return nt
if packet is None:
err("None value")
return False
r = True
if isinstance(packet, (list, tuple)):
for i, x in enumerate(packet):
if not do_verify_packet(new_tree(f"[{i}]"), x):
r = False
elif isinstance(packet, dict):
for k,v in packet.items():
if not do_verify_packet(new_tree(f"key for value={v!r}"), k):
r = False
if not do_verify_packet(new_tree(f"value for key={k!r}"), v):
r = False
elif isinstance(packet, (int, bool, str, bytes)):
pass
else:
err(f"unsupported type: {type(packet)}")
r = False
return r
CONNECTION_LOST = "connection-lost"
GIBBERISH = "gibberish"
INVALID = "invalid"
class Protocol:
"""
This class handles sending and receiving packets,
it will encode and compress them before sending,
and decompress and decode when receiving.
"""
TYPE = "xpra"
def __init__(self, scheduler, conn, process_packet_cb, get_packet_cb=None):
"""
You must call this constructor and source_has_more() from the main thread.
"""
assert scheduler is not None
assert conn is not None
self.start_time = monotonic()
self.timeout_add = scheduler.timeout_add
self.idle_add = scheduler.idle_add
self.source_remove = scheduler.source_remove
self.read_buffer_size = READ_BUFFER_SIZE
self.hangup_delay = 1000
self._conn = conn
if FAKE_JITTER>0: # pragma: no cover
# pylint: disable=import-outside-toplevel
from xpra.net.fake_jitter import FakeJitter
fj = FakeJitter(self.timeout_add, process_packet_cb, FAKE_JITTER)
self._process_packet_cb = fj.process_packet_cb
else:
self._process_packet_cb = process_packet_cb
self.make_chunk_header = self.make_xpra_header
self.make_frame_header = self.noframe_header
self._write_queue = Queue(1)
self._read_queue = Queue(20)
self._pre_read = None
self._process_read = self.read_queue_put
self._read_queue_put = self.read_queue_put
# Invariant: if .source is None, then _source_has_more == False
self._get_packet_cb = get_packet_cb
#counters:
self.input_stats = {}
self.input_packetcount = 0
self.input_raw_packetcount = 0
self.output_stats = {}
self.output_packetcount = 0
self.output_raw_packetcount = 0
#initial value which may get increased by client/server after handshake:
self.max_packet_size = MAX_PACKET_SIZE
self.abs_max_packet_size = 256*1024*1024
self.large_packets = ["hello", "window-metadata", "sound-data", "notify_show", "setting-change", "shell-reply"]
self.send_aliases = {}
self.send_flush_flag = False
self.receive_aliases = {}
self._log_stats = None #None here means auto-detect
self._closed = False
self.encoder = "none"
self._encoder = packet_encoding.get_encoder("none")
self.compressor = "none"
self._compress = compression.get_compressor("none")
self.compression_level = 0
self.cipher_in = None
self.cipher_in_name = None
self.cipher_in_block_size = 0
self.cipher_in_padding = INITIAL_PADDING
self.cipher_out = None
self.cipher_out_name = None
self.cipher_out_block_size = 0
self.cipher_out_padding = INITIAL_PADDING
self._threading_lock = RLock()
self._write_lock = Lock()
self._write_thread = None
self._read_thread = make_thread(self._read_thread_loop, "read", daemon=True)
self._read_parser_thread = None #started when needed
self._write_format_thread = None #started when needed
self._source_has_more = Event()
self.receive_pending = False
self.wait_for_header = False
STATE_FIELDS = ("max_packet_size", "large_packets", "send_aliases", "receive_aliases",
"cipher_in", "cipher_in_name", "cipher_in_block_size", "cipher_in_padding",
"cipher_out", "cipher_out_name", "cipher_out_block_size", "cipher_out_padding",
"compression_level", "encoder", "compressor")
def save_state(self):
state = {}
for x in Protocol.STATE_FIELDS:
state[x] = getattr(self, x)
return state
def restore_state(self, state):
assert state is not None
for x in Protocol.STATE_FIELDS:
assert x in state, f"field {x!r} is missing"
setattr(self, x, state[x])
#special handling for compressor / encoder which are named objects:
self.enable_compressor(self.compressor)
self.enable_encoder(self.encoder)
def is_closed(self) -> bool:
return self._closed
def is_sending_encrypted(self):
return self.cipher_out or self._conn.socktype in ("ssl", "wss", "ssh")
def wait_for_io_threads_exit(self, timeout=None):
io_threads = (self._read_thread, self._write_thread)
for t in io_threads:
if t and t.is_alive():
t.join(timeout)
exited = True
cinfo = self._conn or "cleared connection"
for t in io_threads:
if t and t.is_alive():
log.warn("Warning: %s thread of %s is still alive (timeout=%s)", t.name, cinfo, timeout)
exited = False
return exited
def set_packet_source(self, get_packet_cb):
self._get_packet_cb = get_packet_cb
def set_cipher_in(self, ciphername, iv, password, key_salt, key_hash, key_size, iterations, padding):
cryptolog("set_cipher_in%s", (ciphername, iv, password, key_salt, key_hash, key_size, iterations))
self.cipher_in, self.cipher_in_block_size = get_decryptor(ciphername,
iv, password,
key_salt,key_hash, key_size, iterations)
self.cipher_in_padding = padding
if self.cipher_in_name!=ciphername:
cryptolog.info("receiving data using %s encryption", ciphername)
self.cipher_in_name = ciphername
def set_cipher_out(self, ciphername, iv, password, key_salt, key_hash, key_size, iterations, padding):
cryptolog("set_cipher_out%s", (ciphername, iv, password, key_salt, key_hash, key_size, iterations, padding))
self.cipher_out, self.cipher_out_block_size = get_encryptor(ciphername,
iv, password,
key_salt, key_hash, key_size, iterations)
self.cipher_out_padding = padding
if self.cipher_out_name!=ciphername:
cryptolog.info("sending data using %s encryption", ciphername)
self.cipher_out_name = ciphername
def __repr__(self):
return f"Protocol({self._conn})"
def get_threads(self):
return tuple(x for x in (
self._write_thread,
self._read_thread,
self._read_parser_thread,
self._write_format_thread,
) if x is not None)
def parse_remote_caps(self, caps : typedict):
for k,v in caps.dictget("aliases", {}).items():
self.send_aliases[bytestostr(k)] = v
self.send_flush_flag = FLUSH_HEADER and caps.boolget("flush", False)
def get_info(self, alias_info=True) -> dict:
shm = self._source_has_more
info = {
"large_packets" : self.large_packets,
"compression_level" : self.compression_level,
"max_packet_size" : self.max_packet_size,
"aliases" : USE_ALIASES,
"flush" : self.send_flush_flag,
"has_more" : shm and shm.is_set(),
"receive-pending" : self.receive_pending,
}
c = self.compressor
if c:
info["compressor"] = c
e = self.encoder
if e:
info["encoder"] = e
if alias_info:
info["send_alias"] = self.send_aliases
info["receive_alias"] = self.receive_aliases
c = self._conn
if c:
try:
info.update(c.get_info())
except Exception:
log.error("error collecting connection information on %s", c, exc_info=True)
#add stats to connection info:
info.setdefault("input", {}).update({
"buffer-size" : self.read_buffer_size,
"hangup-delay" : self.hangup_delay,
"packetcount" : self.input_packetcount,
"raw_packetcount" : self.input_raw_packetcount,
"count" : self.input_stats,
"cipher" : {"": self.cipher_in_name or "",
"padding" : self.cipher_in_padding,
},
})
info.setdefault("output", {}).update({
"packet-join-size" : PACKET_JOIN_SIZE,
"large-packet-size" : LARGE_PACKET_SIZE,
"inline-size" : INLINE_SIZE,
"min-compress-size" : MIN_COMPRESS_SIZE,
"packetcount" : self.output_packetcount,
"raw_packetcount" : self.output_raw_packetcount,
"count" : self.output_stats,
"cipher" : {"": self.cipher_out_name or "",
"padding" : self.cipher_out_padding
},
})
for t in (self._write_thread, self._read_thread, self._read_parser_thread, self._write_format_thread):
if t:
info.setdefault("thread", {})[t.name] = t.is_alive()
return info
def start(self):
def start_network_read_thread():
if not self._closed:
self._read_thread.start()
self.idle_add(start_network_read_thread)
if SEND_INVALID_PACKET:
self.timeout_add(SEND_INVALID_PACKET*1000, self.raw_write, "invalid", SEND_INVALID_PACKET_DATA)
def send_disconnect(self, reasons, done_callback=None):
self.flush_then_close(["disconnect"]+list(reasons), done_callback=done_callback)
def send_now(self, packet):
if self._closed:
log("send_now(%s ...) connection is closed already, not sending", packet[0])
return
log("send_now(%s ...)", packet[0])
if self._get_packet_cb:
raise Exception(f"cannot use send_now when a packet source exists! (set to {self._get_packet_cb})")
tmp_queue = [packet]
def packet_cb():
self._get_packet_cb = None
if not tmp_queue:
raise Exception("packet callback used more than once!")
packet = tmp_queue.pop()
return (packet, )
self._get_packet_cb = packet_cb
self.source_has_more()
def source_has_more(self): #pylint: disable=method-hidden
shm = self._source_has_more
if not shm or self._closed:
return
#from now on, take the shortcut:
self.source_has_more = shm.set
shm.set()
#start the format thread:
if not self._write_format_thread and not self._closed:
with self._threading_lock:
assert not self._write_format_thread, "write format thread already started"
self._write_format_thread = start_thread(self.write_format_thread_loop, "format", daemon=True)
def write_format_thread_loop(self):
log("write_format_thread_loop starting")
try:
while not self._closed:
self._source_has_more.wait()
gpc = self._get_packet_cb
if self._closed or not gpc:
return
self._add_packet_to_queue(*gpc())
except Exception as e:
if self._closed:
return
self._internal_error("error in network packet write/format", e, exc_info=True)
def _add_packet_to_queue(self, packet,
start_send_cb=None, end_send_cb=None, fail_cb=None,
synchronous=True, has_more=False, wait_for_more=False):
if not has_more:
shm = self._source_has_more
if shm:
shm.clear()
if packet is None:
return
#log("add_packet_to_queue(%s ... %s, %s, %s)", packet[0], synchronous, has_more, wait_for_more)
packet_type = packet[0]
chunks = self.encode(packet)
with self._write_lock:
if self._closed:
return
try:
self._add_chunks_to_queue(packet_type, chunks,
start_send_cb, end_send_cb, fail_cb,
synchronous, has_more or wait_for_more)
except:
log.error("Error: failed to queue '%s' packet", packet[0])
log("add_chunks_to_queue%s", (chunks, start_send_cb, end_send_cb, fail_cb), exc_info=True)
raise
def _add_chunks_to_queue(self, packet_type, chunks,
start_send_cb=None, end_send_cb=None,
fail_cb=None, synchronous=True, more=False):
""" the write_lock must be held when calling this function """
items = []
for proto_flags,index,level,data in chunks:
payload_size = len(data)
actual_size = payload_size
if self.cipher_out:
proto_flags |= FLAGS_CIPHER
#note: since we are padding: l!=len(data)
if self.cipher_out_block_size==0:
padding_size = 0
else:
padding_size = self.cipher_out_block_size - (payload_size % self.cipher_out_block_size)
if padding_size==0:
padded = data
else:
# pad byte value is number of padding bytes added
padded = memoryview_to_bytes(data) + pad(self.cipher_out_padding, padding_size)
actual_size += padding_size
if len(padded)!=actual_size:
raise RuntimeError(f"expected padded size to be {actual_size}, but got {len(padded)}")
data = self.cipher_out.encrypt(padded)
if len(data)!=actual_size:
raise RuntimeError(f"expected encrypted size to be {actual_size}, but got {len(data)}")
cryptolog("sending %s bytes %s encrypted with %s bytes of padding",
payload_size, self.cipher_out_name, padding_size)
if proto_flags & FLAGS_NOHEADER:
assert not self.cipher_out
#for plain/text packets (ie: gibberish response)
log("sending %s bytes without header", payload_size)
items.append(data)
else:
#if the other end can use this flag, expose it:
if self.send_flush_flag and not more and index==0:
proto_flags |= FLAGS_FLUSH
#the xpra packet header:
#(WebSocketProtocol may also add a websocket header too)
header = self.make_chunk_header(packet_type, proto_flags, level, index, payload_size)
if actual_size<PACKET_JOIN_SIZE:
if not isinstance(data, bytes):
data = memoryview_to_bytes(data)
items.append(header+data)
else:
items.append(header)
items.append(data)
#WebSocket header may be added here:
frame_header = self.make_frame_header(packet_type, items) #pylint: disable=assignment-from-none
if frame_header:
item0 = items[0]
if len(item0)<PACKET_JOIN_SIZE:
if not isinstance(item0, bytes):
item0 = memoryview_to_bytes(item0)
items[0] = frame_header + item0
else:
items.insert(0, frame_header)
self.raw_write(packet_type, items, start_send_cb, end_send_cb, fail_cb, synchronous, more)
def make_xpra_header(self, _packet_type, proto_flags, level, index, payload_size) -> bytes:
return pack_header(proto_flags, level, index, payload_size)
def noframe_header(self, _packet_type, _items):
return None
def start_write_thread(self):
with self._threading_lock:
assert not self._write_thread, "write thread already started"
self._write_thread = start_thread(self._write_thread_loop, "write", daemon=True)
def raw_write(self, packet_type, items, start_cb=None, end_cb=None, fail_cb=None, synchronous=True, more=False):
""" Warning: this bypasses the compression and packet encoder! """
if self._write_thread is None:
log("raw_write for %s, starting write thread", packet_type)
self.start_write_thread()
self._write_queue.put((items, start_cb, end_cb, fail_cb, synchronous, more))
def enable_default_encoder(self):
opts = packet_encoding.get_enabled_encoders()
assert opts, "no packet encoders available!"
self.enable_encoder(opts[0])
def enable_encoder_from_caps(self, caps):
opts = packet_encoding.get_enabled_encoders(order=packet_encoding.PERFORMANCE_ORDER)
log(f"enable_encoder_from_caps(..) options={opts}")
for e in opts:
if caps.boolget(e, e=="bencode"):
self.enable_encoder(e)
return True
log(f"client does not support {e}")
log.error("no matching packet encoder found!")
return False
def enable_encoder(self, e):
self._encoder = packet_encoding.get_encoder(e)
self.encoder = e
log(f"enable_encoder({e}): {self._encoder}")
def enable_default_compressor(self):
opts = compression.get_enabled_compressors()
if opts:
self.enable_compressor(opts[0])
else:
self.enable_compressor("none")
def enable_compressor_from_caps(self, caps):
if self.compression_level==0:
self.enable_compressor("none")
return
opts = compression.get_enabled_compressors(order=compression.PERFORMANCE_ORDER)
compressors = caps.strtupleget("compressors")
log(f"enable_compressor_from_caps(..) options={opts}, compressors from caps={compressors}")
for c in opts: #ie: [zlib, lz4]
if c=="none":
continue
if c in compressors or caps.boolget(c):
self.enable_compressor(c)
return
log(f"client does not support {c}")
log.warn("Warning: compression disabled, no matching compressor found")
log.warn(f" capabilities: {csv(compressors)}")
log.warn(f" enabled compressors: {csv(opts)}")
self.enable_compressor("none")
def enable_compressor(self, compressor):
self._compress = compression.get_compressor(compressor)
self.compressor = compressor
log(f"enable_compressor({compressor}): {self._compress}")
def encode(self, packet_in):
"""
Given a packet (tuple or list of items), converts it for the wire.
This method returns all the binary packets to send, as an array of:
(index, compression_level and compression flags, binary_data)
The index, if positive indicates the item to populate in the packet
whose index is zero.
ie: ["blah", [large binary data], "hello", 200]
may get converted to:
[
(1, compression_level, [large binary data now zlib compressed]),
(0, 0, bencoded/rencoded(["blah", '', "hello", 200]))
]
"""
packets = []
packet = list(packet_in)
level = self.compression_level
size_check = LARGE_PACKET_SIZE
min_comp_size = MIN_COMPRESS_SIZE
for i in range(1, len(packet)):
item = packet[i]
if item is None:
raise TypeError(f"invalid None value in {packet[0]} packet at index {i}")
ti = type(item)
if ti in (int, bool, dict, list, tuple):
continue
try:
l = len(item)
except TypeError as e:
raise TypeError(f"invalid type {ti} in {packet[0]} packet at index {i}: {e}") from None
if issubclass(ti, Compressible):
#this is a marker used to tell us we should compress it now
#(used by the client for clipboard data)
item = item.compress()
packet[i] = item
ti = type(item)
#(it may now be a "Compressed" item and be processed further)
if ti==memoryview:
if self.encoder!="rencodeplus":
packet[i] = packet[i].tobytes()
continue
if issubclass(ti, LargeStructure):
packet[i] = item.data
continue
if issubclass(ti, Compressed):
#already compressed data (usually pixels, cursors, etc)
if not item.can_inline or l>INLINE_SIZE:
il = 0
if ti==LevelCompressed:
#unlike Compressed (usually pixels, decompressed in the paint thread),
#LevelCompressed is decompressed by the network layer
#so we must tell it how to do that and pass the level flag
il = item.level
packets.append((0, i, il, item.data))
packet[i] = b''
else:
#data is small enough, inline it:
packet[i] = item.data
if isinstance(item.data, memoryview) and self.encoder!="rencodeplus":
packet[i] = item.data.tobytes()
min_comp_size += l
size_check += l
elif ti==bytes and level>0 and l>LARGE_PACKET_SIZE:
log.warn("Warning: found a large uncompressed item")
log.warn(f" in packet {packet[0]!r} at position {i}: {len(item)} bytes")
#add new binary packet with large item:
cl, cdata = self._compress(item, level)
packets.append((0, i, cl, cdata))
#replace this item with an empty string placeholder:
packet[i] = ''
elif ti not in (str, bytes):
log.warn(f"Warning: unexpected data type {ti}")
log.warn(f" in {packet[0]!r} packet at position {i}: {repr_ellipsized(item)}")
#now the main packet (or what is left of it):
packet_type = packet[0]
self.output_stats[packet_type] = self.output_stats.get(packet_type, 0)+1
if USE_ALIASES:
alias = self.send_aliases.get(packet_type)
if alias:
#replace the packet type with the alias:
packet[0] = alias
else:
log("packet type send alias not found for '%s'", packet_type)
try:
main_packet, proto_flags = self._encoder(packet)
except Exception:
if self._closed:
return [], 0
log.error(f"Error: failed to encode packet: {packet}", exc_info=True)
#make the error a bit nicer to parse: undo aliases:
packet[0] = packet_type
verify_packet(packet)
raise
if len(main_packet)>size_check and bytestostr(packet_in[0]) not in self.large_packets:
log.warn("Warning: found large packet")
log.warn(f" {packet_type!r} packet is {len(main_packet)} bytes: ")
log.warn(" argument types: %s", csv(type(x) for x in packet[1:]))
log.warn(" sizes: %s", csv(len(strtobytes(x)) for x in packet[1:]))
log.warn(f" packet: {repr_ellipsized(packet)}")
#compress, but don't bother for small packets:
if level>0 and len(main_packet)>min_comp_size:
try:
cl, cdata = self._compress(main_packet, level)
except Exception as e:
log.error(f"Error compressing {packet_type} packet")
log.estr(e)
raise
packets.append((proto_flags, 0, cl, cdata))
else:
packets.append((proto_flags, 0, 0, main_packet))
may_log_packet(True, packet_type, packet)
return packets
def set_compression_level(self, level : int):
#this may be used next time encode() is called
if level<0 or level>10:
raise ValueError(f"invalid compression level: {level} (must be between 0 and 10")
self.compression_level = level
def _io_thread_loop(self, name, callback):
try:
log(f"io_thread_loop({name}, {callback}) loop starting")
while not self._closed and callback():
pass
log(f"io_thread_loop({name}, {callback}) loop ended, closed={self._closed}")
except ConnectionClosedException as e:
log(f"{self._conn} closed in {name} loop", exc_info=True)
if not self._closed:
#ConnectionClosedException means the warning has been logged already
self._connection_lost(str(e))
except (OSError, socket_error) as e:
if not self._closed:
self._internal_error(f"{name} connection {e} reset", exc_info=e.args[0] not in ABORT)
except Exception as e:
#can happen during close(), in which case we just ignore:
if not self._closed:
log.error(f"Error: {name} on {self._conn} failed: {type(e)}", exc_info=True)
self.close()
def _write_thread_loop(self):
self._io_thread_loop("write", self._write)
def _write(self):
items = self._write_queue.get()
# Used to signal that we should exit:
if items is None:
log("write thread: empty marker, exiting")
self.close()
return False
return self.write_items(*items)
def write_items(self, buf_data, start_cb=None, end_cb=None, fail_cb=None, synchronous=True, more=False):
conn = self._conn
if not conn:
return False
try:
if more or len(buf_data)>1:
conn.set_nodelay(False)
if len(buf_data)>1:
conn.set_cork(True)
except OSError:
log("write_items(..)", exc_info=True)
if not self._closed:
raise
if start_cb:
try:
start_cb(conn.output_bytecount)
except Exception:
if not self._closed:
log.error(f"Error on write start callback {start_cb}", exc_info=True)
self.write_buffers(buf_data, fail_cb, synchronous)
try:
if len(buf_data)>1:
conn.set_cork(False)
if not more:
conn.set_nodelay(True)
except OSError:
log("write_items(..)", exc_info=True)
if not self._closed:
raise
if end_cb:
try:
end_cb(self._conn.output_bytecount)
except Exception:
if not self._closed:
log.error(f"Error on write end callback {end_cb}", exc_info=True)
return True
def write_buffers(self, buf_data, _fail_cb, _synchronous):
con = self._conn
if not con:
return
for buf in buf_data:
while buf and not self._closed:
written = self.con_write(con, buf)
#example test code, for sending small chunks very slowly:
#written = con.write(buf[:1024])
#import time
#time.sleep(0.05)
if written:
buf = buf[written:]
self.output_raw_packetcount += 1
self.output_packetcount += 1
def con_write(self, con, buf):
return con.write(buf)
def _read_thread_loop(self):
self._io_thread_loop("read", self._read)
def _read(self):
buf = self.con_read()
#log("read thread: got data of size %s: %s", len(buf), repr_ellipsized(buf))
#add to the read queue (or whatever takes its place - see steal_connection)
self._process_read(buf)
if not buf:
log("read thread: eof")
#give time to the parse thread to call close itself
#so it has time to parse and process the last packet received
self.timeout_add(1000, self.close)
return False
self.input_raw_packetcount += 1
return True
def con_read(self):
if self._pre_read:
r = self._pre_read.pop(0)
log("con_read() using pre_read value: %r", ellipsizer(r))
return r
return self._conn.read(self.read_buffer_size)
def _internal_error(self, message="", exc=None, exc_info=False):
#log exception info with last log message
if self._closed:
return
ei = exc_info
if exc:
ei = None #log it separately below
log.error(f"Error: {message}", exc_info=ei)
if exc:
log.error(f" {exc}", exc_info=exc_info)
exc = None
self.idle_add(self._connection_lost, message)
def _connection_lost(self, message="", exc_info=False):
log(f"connection lost: {message}", exc_info=exc_info)
self.close(message)
return False
def invalid(self, msg, data):
self.idle_add(self._process_packet_cb, self, [INVALID, msg, data])
# Then hang up:
self.timeout_add(1000, self._connection_lost, msg)
def gibberish(self, msg, data):
self.idle_add(self._process_packet_cb, self, [GIBBERISH, msg, data])
# Then hang up:
self.timeout_add(self.hangup_delay, self._connection_lost, msg)
#delegates to invalid_header()
#(so this can more easily be intercepted and overriden)
def invalid_header(self, proto, data, msg="invalid packet header"):
self._invalid_header(proto, data, msg)
def _invalid_header(self, proto, data, msg="invalid packet header"):
log("invalid_header(%s, %s bytes: '%s', %s)",
proto, len(data or ""), msg, ellipsizer(data))
guess = guess_packet_type(data)
if guess:
err = f"{msg}: {guess}"
else:
err = "%s: 0x%s" % (msg, hexstr(data[:HEADER_SIZE]))
if len(data)>1:
err += " read buffer=%s (%i bytes)" % (repr_ellipsized(data), len(data))
self.gibberish(err, data)
def process_read(self, data):
self._read_queue_put(data)
def read_queue_put(self, data):
#start the parse thread if needed:
if not self._read_parser_thread and not self._closed:
if data is None:
log("empty marker in read queue, exiting")
self.idle_add(self.close)
return
self.start_read_parser_thread()
self._read_queue.put(data)
#from now on, take shortcut:
self._read_queue_put = self._read_queue.put
def start_read_parser_thread(self):
with self._threading_lock:
assert not self._read_parser_thread, "read parser thread already started"
self._read_parser_thread = start_thread(self._read_parse_thread_loop, "parse", daemon=True)
def _read_parse_thread_loop(self):
log("read_parse_thread_loop starting")
try:
self.do_read_parse_thread_loop()
except Exception as e:
if self._closed:
return
self._internal_error("error in network packet reading/parsing", e, exc_info=True)
def do_read_parse_thread_loop(self):
"""
Process the individual network packets placed in _read_queue.
Concatenate the raw packet data, then try to parse it.
Extract the individual packets from the potentially large buffer,
saving the rest of the buffer for later, and optionally decompress this data
and re-construct the one python-object-packet from potentially multiple packets (see packet_index).
The 8 bytes packet header gives us information on the packet index, packet size and compression.
The actual processing of the packet is done via the callback process_packet_cb,
this will be called from this parsing thread so any calls that need to be made
from the UI thread will need to use a callback (usually via 'idle_add')
"""
header = b""
read_buffers = []
payload_size = -1
padding_size = 0
packet_index = 0
compression_level = 0
raw_packets = {}
PACKET_HEADER_CHAR = ord("P")
while not self._closed:
#log("parse thread: %i items in read queue", self._read_queue.qsize())
buf = self._read_queue.get()
if not buf:
log("parse thread: empty marker, exiting")
self.idle_add(self.close)
return
read_buffers.append(buf)
if self.wait_for_header:
#we're waiting to see the first xpra packet header
#which may come after some random characters
#(ie: when connecting over ssh, the channel may contain some unexpected output)
#for this to work, we have to assume that the initial packet is smaller than 64KB:
joined = b"".join(read_buffers)
pos = find_xpra_header(joined)
if pos<0:
#wait some more:
read_buffers = [joined]
continue
#found it, so proceed:
read_buffers = [joined[pos:]]
self.wait_for_header = False
while read_buffers:
#have we read the header yet?
if payload_size<0:
#try to handle the first buffer:
buf = read_buffers[0]
if not header and buf[0]!=PACKET_HEADER_CHAR:
self.invalid_header(self, buf, "invalid packet header byte")
return
#how much to we need to slice off to complete the header:
read = min(len(buf), HEADER_SIZE-len(header))
header += memoryview_to_bytes(buf[:read])
if len(header)<HEADER_SIZE:
#need to process more buffers to get a full header:
read_buffers.pop(0)
continue
if len(buf)<=read:
#we only got the header:
assert len(buf)==read
read_buffers.pop(0)
continue
#got the full header and more, keep the rest of the packet:
read_buffers[0] = buf[read:]
#parse the header:
# format: struct.pack(b'cBBBL', ...) - HEADER_SIZE bytes
_, protocol_flags, compression_level, packet_index, data_size = unpack_header(header)
#sanity check size (will often fail if not an xpra client):
if data_size>self.abs_max_packet_size:
self.invalid_header(self, header, f"invalid size in packet header: {data_size}")
return
if protocol_flags & FLAGS_CIPHER:
if not self.cipher_in_name:
cryptolog.warn("Warning: received cipher block,")
cryptolog.warn(" but we don't have a cipher to decrypt it with,")
cryptolog.warn(" not an xpra client?")
self.invalid_header(self, header, "invalid encryption packet flag (no cipher configured)")
return
if self.cipher_in_block_size==0:
padding_size = 0
else:
padding_size = self.cipher_in_block_size - (data_size % self.cipher_in_block_size)
payload_size = data_size + padding_size
else:
#no cipher, no padding:
padding_size = 0
payload_size = data_size
if payload_size<=0:
raise ValueError(f"invalid payload size {payload_size} for header {header!r}")
if payload_size>self.max_packet_size:
#this packet is seemingly too big, but check again from the main UI thread
#this gives 'set_max_packet_size' a chance to run from "hello"
def check_packet_size(size_to_check, packet_header):
if self._closed:
return False
log("check_packet_size(%#x, %s) max=%#x",
size_to_check, hexstr(packet_header), self.max_packet_size)
if size_to_check>self.max_packet_size:
# pylint: disable=line-too-long
msg = f"packet size requested is {size_to_check} but maximum allowed is {self.max_packet_size}"
self.invalid(msg, packet_header)
return False
self.timeout_add(1000, check_packet_size, payload_size, header)
#how much data do we have?
bl = sum(len(v) for v in read_buffers)
if bl<payload_size:
# incomplete packet, wait for the rest to arrive
break
buf = read_buffers[0]
if len(buf)==payload_size:
#exact match, consume it all:
data = read_buffers.pop(0)
elif len(buf)>payload_size:
#keep rest of packet for later:
read_buffers[0] = buf[payload_size:]
data = buf[:payload_size]
else: