-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathprotocol-debugger.py
More file actions
executable file
·865 lines (689 loc) · 23.3 KB
/
protocol-debugger.py
File metadata and controls
executable file
·865 lines (689 loc) · 23.3 KB
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
#!/usr/bin/env python3
# Deskflow -- mouse and keyboard sharing utility
# SPDX-License-Identifier: GPL-2.0-only WITH LicenseRef-OpenSSL-Exception
# SPDX-FileCopyrightText: 2025 Red Hat
# This is a protocol debugger working as a MITM process. Typically you would
# run it on the same host as the Deskflow server, then connect a client to it
# on the default port (24801). All messages between server and client are logged.
import argparse
import binascii
import logging
import os
import select
import socket
import struct
import sys
from dataclasses import dataclass, field, fields, Field
from typing import Optional, Self, Tuple
default_log_format = "%(asctime)s - %(name)-15s - %(levelname).1s - %(message)s"
# Create loggers for client and server
logger = logging.getLogger("deskflow")
clogger = logging.getLogger("server ← client")
slogger = logging.getLogger("server → client")
use_color = not os.getenv("NO_COLORS") and (
os.getenv("FORCE_COLORS") or sys.stdout.isatty()
)
if use_color:
try:
import colorlog
# Create separate handlers with different colors for each logger
deskflow_handler = colorlog.StreamHandler()
deskflow_handler.setFormatter(
colorlog.ColoredFormatter(
"%(green)s%(asctime)s - %(name)-15s - %(levelname).1s - %(message)s%(reset)s",
datefmt="%H:%M:%S",
)
)
client_handler = colorlog.StreamHandler()
client_handler.setFormatter(
colorlog.ColoredFormatter(
"%(blue)s%(asctime)s - %(name)-15s - %(levelname).1s - %(message)s%(reset)s",
datefmt="%H:%M:%S",
)
)
server_handler = colorlog.StreamHandler()
server_handler.setFormatter(
colorlog.ColoredFormatter(
"%(purple)s%(asctime)s - %(name)-15s - %(levelname).1s - %(message)s%(reset)s",
datefmt="%H:%M:%S",
)
)
logger.addHandler(deskflow_handler)
clogger.addHandler(client_handler)
slogger.addHandler(server_handler)
# Remove the default handler that might have been added
logger.propagate = False
clogger.propagate = False
slogger.propagate = False
except ImportError:
use_color = False
if not use_color:
# Configure logging
logging.basicConfig(
level=logging.DEBUG,
format=default_log_format,
datefmt="%H:%M:%S",
)
# Protocol constants
DEFAULT_PORT = 24800
BUFFER_SIZE = 4096 # 4KB buffer for reading
show_keycodes = False
class HexInt(int):
"""Pseudo-class that we can easily detect and change the print to hex"""
pass
@dataclass
class ProtocolMessage:
"""Base class for all protocol messages."""
# Note that the format string is for human verification
# only, it is not used for parsing. This hopefully
# exposes any oddities in the protocol where the parsing
# string mismatches what one would expect.
format_string: str = None # type: ignore
code: str = None # type: ignore
@property
def is_obfuscated(self) -> bool:
return False
@classmethod
def from_bytes(cls, data: bytes) -> Self:
return cls()
def __str__(self) -> str:
exclude = ["format_string", "code"]
datafields = [
f
for f in fields(self)
if not f.name.startswith("_") and f.name not in exclude
]
def stringify(f: Field) -> str:
value = getattr(self, f.name)
if isinstance(value, HexInt):
return f"{f.name}=0x{value:04x}"
else:
return f"{f.name}={value}"
data = ", ".join(map(stringify, datafields))
return f"{self.code} {data}{' (obfuscated)' if self.is_obfuscated else ''}"
# Hello messages don't have a common prefix so for convenience
# we just implement them as separate classes
@dataclass
class _MessageHello(ProtocolMessage):
major: int = 0
minor: int = 0
@classmethod
def from_bytes(cls, data: bytes) -> Self:
versions = data[len(cls.code) :]
return cls(
major=int.from_bytes(versions[0:2], byteorder="big"),
minor=int.from_bytes(versions[2:4], byteorder="big"),
)
@dataclass
class MessageHelloBarrier(_MessageHello):
code: str = "Barrier"
@dataclass
class MessageHelloSynergy(_MessageHello):
code: str = "Synergy"
@dataclass
class MessageCNOP(ProtocolMessage):
code: str = "CNOP"
format_string: str = "CNOP"
@dataclass
class MessageCBYE(ProtocolMessage):
code: str = "CBYE"
format_string: str = ""
@dataclass
class MessageCINN(ProtocolMessage):
code: str = "CINN"
format_string: str = "CINN%2i%2i%4i%2i"
x: int = 0
y: int = 0
sequence: int = 0
mask: HexInt = HexInt(0)
@classmethod
def from_bytes(cls, data: bytes) -> Self:
data = data[len(cls.code) :]
return cls(
x=int.from_bytes(data[0:2], byteorder="big"),
y=int.from_bytes(data[2:4], byteorder="big"),
sequence=int.from_bytes(data[4:8], byteorder="big"),
mask=HexInt.from_bytes(data[8:10], byteorder="big"),
)
@dataclass
class MessageCOUT(ProtocolMessage):
code: str = "COUT"
format_string: str = "COUT"
@dataclass
class MessageCCLP(ProtocolMessage):
code: str = "CCLP"
format_string: str = "CCLP%1i%4i"
id: int = 0
sequence: int = 0
@classmethod
def from_bytes(cls, data: bytes) -> Self:
data = data[len(cls.code) :]
return cls(
id=int.from_bytes(data[0:1], byteorder="big"),
sequence=int.from_bytes(data[1:5], byteorder="big"),
)
@dataclass
class MessageCSEC(ProtocolMessage):
code: str = "CSEC"
format_string: str = "CSEC%1i"
state: int = 0
@classmethod
def from_bytes(cls, data: bytes) -> Self:
data = data[len(cls.code) :]
return cls(
state=int.from_bytes(data[0:1], byteorder="big"),
)
@dataclass
class MessageCROP(ProtocolMessage):
code: str = "CROP"
format_string: str = "CROP"
@dataclass
class MessageCIAK(ProtocolMessage):
code: str = "CIAK"
format_string: str = "CIAK"
@dataclass
class MessageCALV(ProtocolMessage):
code: str = "CALV"
format_string: str = "CALV"
@dataclass
class MessageDKDL(ProtocolMessage):
code: str = "DKDL"
format_string: str = "DKDL%2i%2i%2i%s"
keyid: HexInt = HexInt(0)
mask: HexInt = HexInt(0)
button: HexInt = HexInt(0)
lang: str = ""
@property
def is_obfuscated(self) -> bool:
return not show_keycodes
@classmethod
def from_bytes(cls, data: bytes) -> Self:
data = data[len(cls.code) :]
if show_keycodes:
keyid = HexInt.from_bytes(data[0:2], byteorder="big")
button = HexInt.from_bytes(data[4:6], byteorder="big")
else:
keyid = HexInt(97)
button = HexInt(38)
return cls(
keyid=keyid,
mask=HexInt.from_bytes(data[2:4], byteorder="big"),
button=button,
lang=data[6:].decode("utf-8", errors="replace"),
)
@dataclass
class MessageDKDN(ProtocolMessage):
code: str = "DKDN"
format_string: str = "DKDN%2i%2i%2i"
keyid: HexInt = HexInt(0)
mask: HexInt = HexInt(0)
button: HexInt = HexInt(0)
@property
def is_obfuscated(self) -> bool:
return not show_keycodes
@classmethod
def from_bytes(cls, data: bytes) -> Self:
data = data[len(cls.code) :]
if show_keycodes:
keyid = HexInt.from_bytes(data[0:2], byteorder="big")
button = HexInt.from_bytes(data[4:6], byteorder="big")
else:
keyid = HexInt(97)
button = HexInt(38)
return cls(
keyid=keyid,
mask=HexInt.from_bytes(data[2:4], byteorder="big"),
button=button,
)
@dataclass
class MessageDKRP(ProtocolMessage):
code: str = "DKRP"
format_string: str = "DKRP%2i%2i%2i%2i%s"
keyid: HexInt = HexInt(0)
mask: HexInt = HexInt(0)
button: HexInt = HexInt(0)
count: int = 0
lang: str = ""
@property
def is_obfuscated(self) -> bool:
return not show_keycodes
@classmethod
def from_bytes(cls, data: bytes) -> Self:
data = data[len(cls.code) :]
if show_keycodes:
keyid = HexInt.from_bytes(data[0:2], byteorder="big")
button = HexInt.from_bytes(data[4:6], byteorder="big")
else:
keyid = HexInt(97)
button = HexInt(38)
return cls(
keyid=keyid,
mask=HexInt.from_bytes(data[2:4], byteorder="big"),
button=button,
count=int.from_bytes(data[6:8], byteorder="big"),
lang=data[8:].decode("utf-8", errors="replace"),
)
@dataclass
class MessageDKUP(ProtocolMessage):
code: str = "DKUP"
format_string: str = "DKUP%2i%2i%2i"
keyid: HexInt = HexInt(0)
mask: HexInt = HexInt(0)
button: HexInt = HexInt(0)
@property
def is_obfuscated(self) -> bool:
return not show_keycodes
@classmethod
def from_bytes(cls, data: bytes) -> Self:
data = data[len(cls.code) :]
if show_keycodes:
keyid = HexInt.from_bytes(data[0:2], byteorder="big")
button = HexInt.from_bytes(data[2:4], byteorder="big")
else:
keyid = HexInt(97)
button = HexInt(38)
return cls(
keyid=keyid,
mask=HexInt.from_bytes(data[2:4], byteorder="big"),
button=button,
)
@dataclass
class MessageDMDN(ProtocolMessage):
code: str = "DMDN"
format_string: str = "DMDN%1i"
button: HexInt = HexInt(0)
@classmethod
def from_bytes(cls, data: bytes) -> Self:
data = data[len(cls.code) :]
return cls(
button=HexInt.from_bytes(data[0:1], byteorder="big"),
)
@dataclass
class MessageDMUP(ProtocolMessage):
code: str = "DMUP"
format_string: str = "DMUP%1i"
button: HexInt = HexInt(0)
@classmethod
def from_bytes(cls, data: bytes) -> Self:
data = data[len(cls.code) :]
return cls(
button=HexInt.from_bytes(data[0:1], byteorder="big"),
)
@dataclass
class MessageDMMV(ProtocolMessage):
code: str = "DMMV"
format_string: str = "DMMV%2i%2i"
x: int = 0
y: int = 0
@classmethod
def from_bytes(cls, data: bytes) -> Self:
data = data[len(cls.code) :]
return cls(
x=int.from_bytes(data[0:2], byteorder="big"),
y=int.from_bytes(data[2:4], byteorder="big"),
)
@dataclass
class MessageDMRM(ProtocolMessage):
code: str = "DMRM"
format_string: str = "DMRM%2i%2i"
x: int = 0
y: int = 0
@classmethod
def from_bytes(cls, data: bytes) -> Self:
data = data[len(cls.code) :]
return cls(
x=int.from_bytes(data[0:2], byteorder="big"),
y=int.from_bytes(data[2:4], byteorder="big"),
)
@dataclass
class MessageDMWM(ProtocolMessage):
code: str = "DMWM"
format_string: str = "DMWM%2i%2i"
xdelta: int = 0
ydelta: int = 0
@classmethod
def from_bytes(cls, data: bytes) -> Self:
data = data[len(cls.code) :]
return cls(
xdelta=int.from_bytes(data[0:2], byteorder="big"),
ydelta=int.from_bytes(data[2:4], byteorder="big"),
)
@dataclass
class MessageDCLP(ProtocolMessage):
code: str = "DCLP"
format_string: str = "DCLP%1i%4i%1i%s"
id: int = 0
sequence: int = 0
mark: int = 0
data: str = ""
@classmethod
def from_bytes(cls, data: bytes) -> Self:
data = data[len(cls.code) :]
return cls(
id=int.from_bytes(data[0:1], byteorder="big"),
sequence=int.from_bytes(data[1:5], byteorder="big"),
mark=int.from_bytes(data[5:6], byteorder="big"),
data=data[6:].decode("utf-8", errors="replace"),
)
@dataclass
class MessageDINF(ProtocolMessage):
code: str = "DINF"
format_string: str = "DINF%2i%2i%2i%2i%2i%2i%2i"
x: int = 0
y: int = 0
w: int = 0
h: int = 0
mx: int = 0
my: int = 0
size: int = 0
@classmethod
def from_bytes(cls, data: bytes) -> Self:
data = data[len(cls.code) :]
return cls(
x=int.from_bytes(data[0:2], byteorder="big"),
y=int.from_bytes(data[2:4], byteorder="big"),
w=int.from_bytes(data[4:6], byteorder="big"),
h=int.from_bytes(data[6:8], byteorder="big"),
mx=int.from_bytes(data[8:10], byteorder="big"),
my=int.from_bytes(data[10:12], byteorder="big"),
size=int.from_bytes(data[12:14], byteorder="big"),
)
@dataclass
class MessageDSOP(ProtocolMessage):
code: str = "DSOP"
format_string: str = "DSOP%4I"
options: int = 0
@classmethod
def from_bytes(cls, data: bytes) -> Self:
data = data[len(cls.code) :]
return cls(
options=int.from_bytes(data[0:4], byteorder="big"),
)
@dataclass
class MessageDFTR(ProtocolMessage):
code: str = "DFTR"
format_string: str = "DFTR%1i%s"
mark: int = 0
data: str = ""
@classmethod
def from_bytes(cls, data: bytes) -> Self:
data = data[len(cls.code) :]
return cls(
mark=int.from_bytes(data[0:1], byteorder="big"),
data=data[1:].decode("utf-8", errors="replace"),
)
@dataclass
class MessageDDRG(ProtocolMessage):
code: str = "DDRG"
format_string: str = "DDRG%2i%s"
size: int = 0
data: str = ""
@classmethod
def from_bytes(cls, data: bytes) -> Self:
data = data[len(cls.code) :]
return cls(
size=int.from_bytes(data[0:2], byteorder="big"),
data=data[2:].decode("utf-8", errors="replace"),
)
@dataclass
class MessageSECN(ProtocolMessage):
code: str = "SECN"
format_string: str = "SECN%s"
data: str = ""
@classmethod
def from_bytes(cls, data: bytes) -> Self:
data = data[len(cls.code) :]
return cls(
data=data.decode("utf-8", errors="replace"),
)
@dataclass
class MessageLSYN(ProtocolMessage):
code: str = "LSYN"
format_string: str = "LSYN%s"
data: str = ""
@classmethod
def from_bytes(cls, data: bytes) -> Self:
data = data[len(cls.code) :]
return cls(
data=data.decode("utf-8", errors="replace"),
)
@dataclass
class MessageQINF(ProtocolMessage):
code: str = "QINF"
format_string: str = "QINF"
@dataclass
class MessageEICV(ProtocolMessage):
code: str = "EICV"
format_string: str = "EICV%2i%2i"
major_remote: int = 0
minor_remote: int = 0
@classmethod
def from_bytes(cls, data: bytes) -> Self:
data = data[len(cls.code) :]
return cls(
major_remote=int.from_bytes(data[0:2], byteorder="big"),
minor_remote=int.from_bytes(data[2:4], byteorder="big"),
)
@dataclass
class MessageEBSY(ProtocolMessage):
code: str = "EBSY"
format_string: str = "EBSY"
@dataclass
class MessageEUNK(ProtocolMessage):
code: str = "EUNK"
format_string: str = "EUNK"
@dataclass
class MessageEBAD(ProtocolMessage):
code: str = "EBAD"
format_string: str = "EBAD"
def find_local_classes(prefix) -> list[type[ProtocolMessage]]:
import inspect
current_module = sys.modules[__name__]
return [
c
for _, c in inspect.getmembers(
current_module,
lambda x: inspect.isclass(x)
and x.__module__ == __name__
and x.__name__.startswith(prefix),
)
]
MESSAGES = {m.code: m for m in find_local_classes("Message")}
@dataclass
class Message:
"""A protocol message with its length prefix removed."""
length: int
data: bytes
@property
def hex(self) -> str:
return binascii.hexlify(self.data, sep=" ").decode("ascii")
@property
def textify(self) -> str:
return "".join(chr(x) for x in self.data)
def __str__(self) -> str:
return f"Message(length={self.length}, hex={self.hex}, text={self.textify})"
def as_protocol_message(self) -> Optional[ProtocolMessage]:
try:
data = self.data
for code, msg_type in MESSAGES.items():
if data.startswith(code.encode("ascii")):
return msg_type.from_bytes(data)
return None
except (UnicodeDecodeError, IndexError, KeyError, struct.error) as e:
logging.debug(f"Failed to parse message: {e}")
return None
@dataclass
class Connection:
"""Represents a socket connection with its associated logger."""
socket: socket.socket
logger: logging.Logger
peer_addr: Tuple[str, int]
buffer: bytearray = field(
default_factory=bytearray
) # Buffer for incomplete messages
@dataclass
class HostPort:
"""Represents a host and port combination."""
host: str
port: int
@classmethod
def from_string(cls, addr: str) -> Self:
if ":" in addr:
host, port = addr.rsplit(":", 1)
return cls(host, int(port))
return cls(addr, DEFAULT_PORT)
def next_message(buffer: bytearray) -> Optional[Message]:
"""Process the buffer and return a complete message if available."""
if len(buffer) < 4:
return None
length = int.from_bytes(buffer[:4], byteorder="big")
total_size = length + 4 # Include the length prefix
if len(buffer) < total_size:
return None
msg = Message(length, buffer[4:total_size])
del buffer[:total_size]
return msg
def handle_connection(source: Connection, dest: Connection, filters: list[str]) -> None:
"""Handle data transfer between source and destination connections."""
try:
data = source.socket.recv(BUFFER_SIZE)
if not data:
raise socket.error("Connection closed")
# Add received data to the buffer
source.buffer.extend(data)
source.logger.debug(
f"Received {len(data)} bytes: {binascii.hexlify(data, sep=' ')} {''.join(chr(x) for x in data)}"
)
while msg := next_message(source.buffer):
source.logger.debug(msg)
# Try to identify and parse the protocol message
protocol_message = msg.as_protocol_message()
if protocol_message:
if not filters or protocol_message.code not in filters:
source.logger.info(protocol_message)
else:
source.logger.warning(f"Unknown message: {msg}")
# Forward the complete message including its length prefix
dest.socket.sendall(len(msg.data).to_bytes(4, byteorder="big") + msg.data)
except socket.error as e:
if not isinstance(e, BlockingIOError):
source.logger.error(f"Socket error: {e}")
raise
def main():
parser = argparse.ArgumentParser(
description="Deskflow protocol debugger",
formatter_class=argparse.RawDescriptionHelpFormatter,
epilog="""
Examples:
# Use all defaults (listen on 24801, connect to localhost:24800)
%(prog)s
# Connect to a specific host (listen on 24801)
%(prog)s otherhost
# Connect to a specific host:port (listen on 24801)
%(prog)s otherhost:12345
# Listen on a different port
%(prog)s --port 12345 otherhost
The debugger acts as a MITM proxy, logging all protocol messages that pass through it.
It listens for incoming connections and forwards them to the specified remote host.""",
)
parser.add_argument(
"remote",
nargs="?",
default="localhost",
help="Deskflow server host:port to connect to (defaults to localhost:24800)",
)
parser.add_argument(
"--port",
type=int,
default=24801,
help="Port to listen on for incoming deskflow client connections (default: 24801)",
)
parser.add_argument(
"--verbose",
"-v",
action="store_true",
help="Enable verbose logging",
)
parser.add_argument(
"--show-keycodes",
action="store_true",
default=False,
help="Show keycodes in the logging output (by default all keys are shown as A)",
)
parser.add_argument(
"--filter",
type=str,
default="CALV,CNOP",
help="A comma-separated list of protocol codes to ignore (default: CALV,CNOP)",
)
args = parser.parse_args()
global show_keycodes
show_keycodes = args.show_keycodes
# Configure logging based on verbosity
log_level = logging.DEBUG if args.verbose else logging.INFO
logger.setLevel(log_level)
clogger.setLevel(log_level)
slogger.setLevel(log_level)
filters = [ff for ff in (f.strip() for f in args.filter.split(",")) if ff]
logger.info(f"Filtering message codes: {filters}")
# Parse remote address
remote = HostPort.from_string(args.remote)
# Create server socket
server_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
server_sock.bind(("", args.port))
server_sock.listen(1)
logger.info(
f"Listening on port {args.port}, connecting to {remote.host}:{remote.port}"
)
while True:
try:
# Accept client connection
client_sock, client_addr = server_sock.accept()
logger.info(f"Client connected from {client_addr[0]}:{client_addr[1]}")
# Connect to remote server
remote_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
remote_sock.connect((remote.host, remote.port))
logger.info(f"Connected to remote {remote.host}:{remote.port}")
# Create connection objects
client_conn = Connection(client_sock, clogger, client_addr)
remote_conn = Connection(remote_sock, slogger, (remote.host, remote.port))
# Set up polling
poller = select.poll()
poller.register(client_sock, select.POLLIN)
poller.register(remote_sock, select.POLLIN)
# Main event loop
while True:
try:
# Wait for events with a 1-second timeout
events = poller.poll(1000) # timeout in milliseconds
for fd, event in events:
if event & select.POLLIN:
if fd == client_sock.fileno():
handle_connection(client_conn, remote_conn, filters)
elif fd == remote_sock.fileno():
handle_connection(remote_conn, client_conn, filters)
if event & (select.POLLHUP | select.POLLERR):
raise socket.error("Connection closed")
except BlockingIOError:
continue
except socket.error as e:
logger.error(f"Socket error: {e}")
break
except KeyboardInterrupt:
logger.info("Shutting down on request")
break
except Exception as e:
logger.warning(f"Error: {e}")
continue
finally:
try:
poller.unregister(client_sock)
poller.unregister(remote_sock)
client_sock.close()
remote_sock.close()
except Exception:
pass
server_sock.close()
if __name__ == "__main__":
main()