-
Notifications
You must be signed in to change notification settings - Fork 0
/
server_all.py
1553 lines (1299 loc) · 49.6 KB
/
server_all.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
import os
import sys
import time
class Logger(object):
DEBUG = 0
INFO = 1
WARN = 2
ERROR = 3
rep = {DEBUG: "D", INFO: "I", WARN: "W", ERROR: "E"}
level = INFO
if "256color" in os.environ.get("TERM", ""):
GREY = "\033[90;20m"
YELLOW_BOLD = "\033[33;1m"
RED_BOLD = "\033[31;1m"
RESET = "\033[0m"
else:
GREY = YELLOW_BOLD = RED_BOLD = RESET = ""
@staticmethod
def set_level(level):
Logger.level = level
@staticmethod
def debug(text=""):
if Logger.level <= Logger.DEBUG:
sys.stderr.write(
(Logger.GREY + "%s [%s] %s\n" + Logger.RESET)
% (time.strftime("%Y-%m-%d %H:%M:%S"), Logger.rep[Logger.DEBUG], text)
)
@staticmethod
def info(text=""):
if Logger.level <= Logger.INFO:
sys.stderr.write(
("%s [%s] %s\n")
% (time.strftime("%Y-%m-%d %H:%M:%S"), Logger.rep[Logger.INFO], text)
)
@staticmethod
def warning(text=""):
if Logger.level <= Logger.WARN:
sys.stderr.write(
(Logger.YELLOW_BOLD + "%s [%s] %s\n" + Logger.RESET)
% (time.strftime("%Y-%m-%d %H:%M:%S"), Logger.rep[Logger.WARN], text)
)
@staticmethod
def error(text=""):
if Logger.level <= Logger.ERROR:
sys.stderr.write(
(Logger.RED_BOLD + "%s [%s] %s\n" + Logger.RESET)
% (time.strftime("%Y-%m-%d %H:%M:%S"), Logger.rep[Logger.ERROR], text)
)
from enum import IntEnum
import struct
import socket
import time
start_time = time.time()
NAT_PMP_VERSION = 0
# 自定义异常类
class NATPMPError(Exception):
"""NAT-PMP 基础异常类"""
pass
class UnsupportedVersionError(NATPMPError):
"""不支持的版本异常"""
pass
class UnsupportedOpcodeError(NATPMPError):
"""不支持的操作码异常"""
pass
class InsufficientDataError(NATPMPError):
"""数据包长度不足异常"""
pass
class MappingError(NATPMPError):
"""与端口映射相关的错误"""
pass
class NATPMPOpCode(IntEnum):
"""NAT-PMP 操作码基类"""
pass
class NATPMPClientOpCode(NATPMPOpCode):
GET_EXTERNAL_ADDRESS = 0 # 获取外部地址
MAP_UDP = 1 # 映射UDP
MAP_TCP = 2 # 映射TCP
class NATPMPServerOpCode(NATPMPOpCode):
RESPONSE_EXTERNAL_ADDRESS = 128 # 响应外部地址
RESPONSE_MAP_UDP = 129 # 响应映射UDP
RESPONSE_MAP_TCP = 130 # 响应映射TCP
class NATPMPErrorCode(IntEnum):
SUCCESS = 0 # 成功
UNSUPPORTED_VERSION = 1 # 不支持的版本
NOT_AUTHORIZED = 2 # 未授权
NETWORK_FAILURE = 3 # 网络错误
OUT_OF_RESOURCES = 4 # 资源不足
UNSUPPORTED_OPCODE = 5 # 不支持的操作码
class NATPMP_Packet:
"""NAT-PMP 数据包基类"""
def __init__(self, opcode: NATPMPOpCode, version: int = NAT_PMP_VERSION):
self.version = version
self.opcode = opcode
def pack(self) -> bytes:
"""打包数据包"""
return struct.pack("!BB", self.version, self.opcode)
@classmethod
def unpack(cls, data: bytes) -> "NATPMP_Packet":
"""解包数据包"""
if len(data) < 2: # 检查数据包长度
raise InsufficientDataError("Not enough data to unpack NATPMP_Packet")
version, opcode = struct.unpack("!BB", data[:2])
if version != NAT_PMP_VERSION:
raise UnsupportedVersionError("Unsupported version")
if opcode == NATPMPClientOpCode.GET_EXTERNAL_ADDRESS:
return RequestExternalAddressPacket()
elif opcode in (NATPMPClientOpCode.MAP_UDP, NATPMPClientOpCode.MAP_TCP):
return RequestMapPacket.unpack(data)
elif opcode in NATPMPServerOpCode.__members__.values():
return NATPMP_ServerPacket.unpack(data)
else:
raise UnsupportedOpcodeError("Unsupported opcode")
class RequestExternalAddressPacket(NATPMP_Packet):
"""获取外部地址请求数据包"""
def __init__(self):
super().__init__(NATPMPClientOpCode.GET_EXTERNAL_ADDRESS)
class RequestMapPacket(NATPMP_Packet):
"""端口映射请求数据包"""
def __init__(
self,
opcode: NATPMPClientOpCode,
internal_port: int,
external_port: int,
lifetime: int,
):
super().__init__(opcode)
self.internal_port = internal_port
self.external_port = external_port
self.lifetime = lifetime
def pack(self) -> bytes:
"""打包端口映射请求数据包"""
return super().pack() + struct.pack(
"!HHHI", 0, self.internal_port, self.external_port, self.lifetime
)
@classmethod
def unpack(cls, data: bytes) -> "RequestMapPacket":
"""解包端口映射请求数据包"""
if len(data) < 12: # 检查数据包长度
raise InsufficientDataError("Not enough data to unpack RequestMapPacket")
version, opcode, _, internal_port, external_port, lifetime = struct.unpack(
"!BBHHHI", data
)
if opcode in (NATPMPClientOpCode.MAP_UDP, NATPMPClientOpCode.MAP_TCP):
return cls(opcode, internal_port, external_port, lifetime)
else:
raise UnsupportedOpcodeError("Not a map request packet")
class NATPMP_ServerPacket(NATPMP_Packet):
"""NAT-PMP 服务器响应数据包"""
def __init__(
self,
opcode: NATPMPServerOpCode,
error: NATPMPErrorCode,
version: int = NAT_PMP_VERSION,
epoch_time: int = 0,
):
if opcode not in NATPMPServerOpCode.__members__.values() and opcode != 0:
raise UnsupportedOpcodeError("Unsupported server opcode")
super().__init__(opcode, version)
self.error = error
self.epoch_time = (
int(time.time() - start_time) if epoch_time == 0 else epoch_time
)
def pack(self) -> bytes:
"""打包服务器响应数据包"""
return super().pack() + struct.pack("!HI", self.error, self.epoch_time)
@classmethod
def unpack(cls, data: bytes) -> "NATPMP_ServerPacket":
"""解包服务器响应数据包"""
if len(data) < 8: # 检查数据包长度
raise InsufficientDataError("Not enough data to unpack NATPMP_ServerPacket")
version, opcode, error, seconds_since_epoch = struct.unpack("!BBHI", data[:8])
if opcode == NATPMPServerOpCode.RESPONSE_EXTERNAL_ADDRESS:
return ResponseExternalAddressPacket.unpack(data)
elif opcode in (
NATPMPServerOpCode.RESPONSE_MAP_UDP,
NATPMPServerOpCode.RESPONSE_MAP_TCP,
):
return ResponseMapPacket.unpack(data)
else:
raise UnsupportedOpcodeError("Not a server response packet")
class ResponseExternalAddressPacket(NATPMP_ServerPacket):
"""获取外部地址响应数据包"""
def __init__(
self,
error: NATPMPErrorCode,
external_ip: str,
version: int = NAT_PMP_VERSION,
epoch_time: int = 0,
):
super().__init__(
NATPMPServerOpCode.RESPONSE_EXTERNAL_ADDRESS, error, version, epoch_time
)
self.external_ip = external_ip
def pack(self) -> bytes:
"""打包外部地址响应数据包"""
return super().pack() + struct.pack("!4s", socket.inet_aton(self.external_ip))
@classmethod
def unpack(cls, data: bytes) -> "ResponseExternalAddressPacket":
"""解包外部地址响应数据包"""
if len(data) < 12: # 检查数据包长度
raise InsufficientDataError(
"Not enough data to unpack ResponseExternalAddressPacket"
)
version, opcode, error, seconds_since_epoch, external_ip_bytes = struct.unpack(
"!BBHI4s", data
)
external_ip = socket.inet_ntoa(external_ip_bytes)
return cls(error, external_ip, version, seconds_since_epoch)
class ResponseMapPacket(NATPMP_ServerPacket):
"""端口映射响应数据包"""
def __init__(
self,
opcode: NATPMPServerOpCode,
error: NATPMPErrorCode,
internal_port: int,
external_port: int,
lifetime: int,
version: int = NAT_PMP_VERSION,
epoch_time: int = 0,
):
super().__init__(opcode, error, version, epoch_time)
self.internal_port = internal_port
self.external_port = external_port
self.lifetime = lifetime
def pack(self) -> bytes:
"""打包端口映射响应数据包"""
return super().pack() + struct.pack(
"!HHI", self.internal_port, self.external_port, self.lifetime
)
@classmethod
def unpack(cls, data: bytes) -> "ResponseMapPacket":
"""解包端口映射响应数据包"""
if len(data) < 12: # 检查数据包长度
raise InsufficientDataError("Not enough data to unpack ResponseMapPacket")
(
version,
opcode,
error,
seconds_since_epoch,
internal_port,
external_port,
lifetime,
) = struct.unpack("!BBHIHHI", data)
return cls(
opcode,
error,
internal_port,
external_port,
lifetime,
version,
seconds_since_epoch,
)
import subprocess
import re
class FirewallRule:
def __init__(self, table_name: str, chain_name: str):
self.table_name = table_name
self.chain_name = chain_name
self.handle = None
self.rule_specifics = None # 用于存储规则特定部分
def enable(self):
"""启用规则,并添加到防火墙中"""
command = f"nft --handle --echo add rule {self.table_name} {self.chain_name} {self.rule_specifics}"
output = self._execute_command(command)
if output:
handle_match = re.search(r"handle (\d+)", output)
if handle_match:
self.handle = handle_match.group(1)
Logger.debug(f"已添加规则,句柄: {self.handle}")
else:
Logger.error(f"未能从输出中提取句柄: {output}")
def disable(self):
"""删除规则"""
if self.handle:
delete_command = f"nft delete rule {self.table_name} {self.chain_name} handle {self.handle}"
self._execute_command(delete_command)
Logger.debug(f"已删除规则,句柄: {self.handle}")
self.handle = None
def _execute_command(self, command):
"""执行系统命令,捕获输出和错误"""
try:
result = subprocess.run(
command,
shell=True,
check=True,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
)
return result.stdout.decode().strip()
except subprocess.CalledProcessError as e:
Logger.error(f"执行命令时出错: {command}\n错误信息: {e.stderr.decode()}")
return None
def __del__(self):
"""析构函数,删除规则"""
self.disable()
class UpnpForwardRule(FirewallRule):
def __init__(
self, protocol: str, internal_port: int, interface="eth0", enable=False
):
super().__init__("inet fw4", "upnp_forward")
self.protocol = protocol.lower() # 可以是 'tcp' 或 'udp'
self.internal_port = internal_port
self.interface = interface # 入站接口,默认为 'eth0'
# 设置规则特定部分
self.rule_specifics = (
f'iif "{self.interface}" {self.protocol} dport {self.internal_port} accept'
)
# 如果需要,启用规则
if enable:
self.enable()
class UpnpPreroutingRule(FirewallRule):
def __init__(
self,
protocol: str,
internal_ip: str,
internal_port: int,
relay_port: int,
interface="eth0",
enable=False,
):
super().__init__("inet fw4", "upnp_prerouting")
self.protocol = protocol.lower() # 可以是 'tcp' 或 'udp'
self.internal_ip = internal_ip
self.internal_port = internal_port
self.relay_port = relay_port
self.interface = interface
# 设置规则特定部分
self.rule_specifics = f'iif "{self.interface}" {self.protocol} dport {self.relay_port} dnat ip to {self.internal_ip}:{self.internal_port}'
# 如果需要,启用规则
if enable:
self.enable()
class InputRule(FirewallRule):
def __init__(self, protocol: str, port: int, interface="eth0", enable=False):
super().__init__("inet fw4", "input")
self.protocol = protocol.lower() # 可以是 'tcp' 或 'udp'
self.port = port
self.interface = interface # 入站接口,默认为 'eth0'
# 设置规则特定部分
self.rule_specifics = (
f'iif "{self.interface}" {self.protocol} dport {self.port} accept'
)
# 如果需要,启用规则
if enable:
self.enable()
#!/usr/bin/env python3
'''
Natter - https://github.com/MikeWang000000/Natter
Copyright (C) 2023 MikeWang000000
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
'''
import os
import re
import sys
import time
import errno
import atexit
import codecs
import random
import socket
import struct
import threading
__version__ = "2.1.1"
class NatterExit(object):
atexit.register(lambda : NatterExit._atexit[0]())
_atexit = [lambda : None]
@staticmethod
def set_atexit(func):
NatterExit._atexit[0] = func
class StunClient(object):
class ServerUnavailable(Exception):
pass
def __init__(self, source_host="0.0.0.0", source_port=0,
interface=None, udp=False):
stun_list = [
"fwa.lifesizecloud.com",
"global.turn.twilio.com",
"turn.cloudflare.com",
"stun.isp.net.au",
"stun.nextcloud.com",
"stun.freeswitch.org",
"stun.voip.blackberry.com",
"stunserver.stunprotocol.org",
"stun.sipnet.com",
"stun.radiojar.com",
"stun.sonetel.com",
"stun.telnyx.com"
]
if not udp:
stun_list = stun_list + [
"turn.cloud-rtc.com:80"
]
else:
stun_list = [
"stun.miwifi.com",
"stun.chat.bilibili.com",
"stun.hitv.com",
"stun.cdnbye.com",
"stun.douyucdn.cn:18000"
] + stun_list
stun_srv_list = []
for item in stun_list:
l = item.split(":", 2) + ["3478"]
stun_srv_list.append((l[0], int(l[1])),)
self.stun_server_list = stun_srv_list
self.source_host = source_host
self.source_port = source_port
self.interface = interface
self.udp = udp
def get_mapping(self):
first = self.stun_server_list[0]
while True:
try:
return self._get_mapping()
except StunClient.ServerUnavailable as ex:
Logger.warning("stun: STUN server %s is unavailable: %s" % (
addr_to_uri(self.stun_server_list[0], udp = self.udp), ex
))
self.stun_server_list.append(self.stun_server_list.pop(0))
if self.stun_server_list[0] == first:
Logger.error("stun: No STUN server is available right now")
# force sleep for 10 seconds, then try the next loop
time.sleep(10)
def _get_mapping(self):
# ref: https://www.rfc-editor.org/rfc/rfc5389
socket_type = socket.SOCK_DGRAM if self.udp else socket.SOCK_STREAM
stun_host, stun_port = self.stun_server_list[0]
sock = socket.socket(socket.AF_INET, socket_type)
socket_set_opt(
sock,
reuse = True,
bind_addr = (self.source_host, self.source_port),
interface = self.interface,
timeout = 3
)
try:
sock.connect((stun_host, stun_port))
inner_addr = sock.getsockname()
self.source_host, self.source_port = inner_addr
sock.send(struct.pack(
"!LLLLL", 0x00010000, 0x2112a442, 0x4e415452,
random.getrandbits(32), random.getrandbits(32)
))
buff = sock.recv(1500)
ip = port = 0
payload = buff[20:]
while payload:
attr_type, attr_len = struct.unpack("!HH", payload[:4])
if attr_type in [1, 32]:
_, _, port, ip = struct.unpack("!BBHL", payload[4:4+attr_len])
if attr_type == 32:
port ^= 0x2112
ip ^= 0x2112a442
break
payload = payload[4 + attr_len:]
else:
raise ValueError("Invalid STUN response")
outer_addr = socket.inet_ntop(socket.AF_INET, struct.pack("!L", ip)), port
Logger.debug("stun: Got address %s from %s, source %s" % (
addr_to_uri(outer_addr, udp=self.udp),
addr_to_uri((stun_host, stun_port), udp=self.udp),
addr_to_uri(inner_addr, udp=self.udp)
))
return inner_addr, outer_addr
except (OSError, ValueError, struct.error, socket.error) as ex:
raise StunClient.ServerUnavailable(ex)
finally:
sock.close()
class KeepAlive(object):
def __init__(self, host, port, source_host, source_port, interface=None, udp=False):
self.sock = None
self.host = host
self.port = port
self.source_host = source_host
self.source_port = source_port
self.interface = interface
self.udp = udp
self.reconn = False
def __del__(self):
if self.sock:
self.sock.close()
def _connect(self):
sock_type = socket.SOCK_DGRAM if self.udp else socket.SOCK_STREAM
sock = socket.socket(socket.AF_INET, sock_type)
socket_set_opt(
sock,
reuse = True,
bind_addr = (self.source_host, self.source_port),
interface = self.interface,
timeout = 3
)
sock.connect((self.host, self.port))
if not self.udp:
Logger.debug("keep-alive: Connected to host %s" % (
addr_to_uri((self.host, self.port), udp=self.udp)
))
if self.reconn:
Logger.info("keep-alive: connection restored")
self.reconn = False
self.sock = sock
def keep_alive(self):
if self.sock is None:
self._connect()
if self.udp:
self._keep_alive_udp()
else:
self._keep_alive_tcp()
Logger.debug("keep-alive: OK")
def reset(self):
if self.sock is not None:
self.sock.close()
self.sock = None
self.reconn = True
def _keep_alive_tcp(self):
# send a HTTP request
self.sock.sendall((
"HEAD /natter-keep-alive HTTP/1.1\r\n"
"Host: %s\r\n"
"User-Agent: curl/8.0.0 (Natter)\r\n"
"Accept: */*\r\n"
"Connection: keep-alive\r\n"
"\r\n" % self.host
).encode())
buff = b""
try:
while True:
buff = self.sock.recv(4096)
if not buff:
raise OSError("Keep-alive server closed connection")
except socket.timeout as ex:
if not buff:
raise ex
return
def _keep_alive_udp(self):
# send a DNS request
self.sock.send(
struct.pack(
"!HHHHHH", random.getrandbits(16), 0x0100, 0x0001, 0x0000, 0x0000, 0x0000
) + b"\x09keepalive\x06natter\x00" + struct.pack("!HH", 0x0001, 0x0001)
)
buff = b""
try:
while True:
buff = self.sock.recv(1500)
if not buff:
raise OSError("Keep-alive server closed connection")
except socket.timeout as ex:
if not buff:
raise ex
# fix: Keep-alive cause STUN socket timeout on Windows
if sys.platform == "win32":
self.reset()
return
class NatterExitException(Exception):
pass
class NatterRetryException(Exception):
pass
def socket_set_opt(sock, reuse=False, bind_addr=None, interface=None, timeout=-1):
if reuse:
if hasattr(socket, "SO_REUSEADDR"):
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
if hasattr(socket, "SO_REUSEPORT"):
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1)
if interface is not None:
if hasattr(socket, "SO_BINDTODEVICE"):
sock.setsockopt(
socket.SOL_SOCKET, socket.SO_BINDTODEVICE, interface.encode() + b"\0"
)
else:
raise RuntimeError("Binding to an interface is not supported on your platform.")
if bind_addr is not None:
sock.bind(bind_addr)
if timeout != -1:
sock.settimeout(timeout)
return sock
def start_daemon_thread(target, args=()):
th = threading.Thread(target=target, args=args)
th.daemon = True
th.start()
return th
def closed_socket_ex(ex):
if not hasattr(ex, "errno"):
return False
if hasattr(errno, "ECONNABORTED") and ex.errno == errno.ECONNABORTED:
return True
if hasattr(errno, "EBADFD") and ex.errno == errno.EBADFD:
return True
if hasattr(errno, "EBADF") and ex.errno == errno.EBADF:
return True
if hasattr(errno, "WSAEBADF") and ex.errno == errno.WSAEBADF:
return True
if hasattr(errno, "WSAEINTR") and ex.errno == errno.WSAEINTR:
return True
return False
def fix_codecs(codec_list = ["utf-8", "idna"]):
missing_codecs = []
for codec_name in codec_list:
try:
codecs.lookup(codec_name)
except LookupError:
missing_codecs.append(codec_name.lower())
def search_codec(name):
if name.lower() in missing_codecs:
return codecs.CodecInfo(codecs.ascii_encode, codecs.ascii_decode, name="ascii")
if missing_codecs:
codecs.register(search_codec)
def split_url(url):
m = re.match(
r"^http://([^\[\]:/]+)(?:\:([0-9]+))?(/\S*)?$", url
)
if not m:
raise ValueError("Unsupported URL: %s" % url)
hostname, port_str, path = m.groups()
port = 80
if port_str:
port = int(port_str)
if not path:
path = "/"
return hostname, port, path
def full_url(u, refurl):
if not u.startswith("/"):
return u
hostname, port, _ = split_url(refurl)
return "http://%s:%d" % (hostname, port) + u
def addr_to_str(addr):
return "%s:%d" % addr
def addr_to_uri(addr, udp=False):
if udp:
return "udp://%s:%d" % addr
else:
return "tcp://%s:%d" % addr
def validate_ip(s, err=True):
try:
socket.inet_aton(s)
return True
except (OSError, socket.error):
if err:
raise ValueError("Invalid IP address: %s" % s)
return False
def validate_port(s, err=True):
if str(s).isdigit() and int(s) in range(65536):
return True
if err:
raise ValueError("Invalid port number: %s" % s)
return False
def validate_addr_str(s, err=True):
l = str(s).split(":", 1)
if len(l) == 1:
return True
return validate_port(l[1], err)
def validate_positive(s, err=True):
if str(s).isdigit() and int(s) > 0:
return True
if err:
raise ValueError("Not a positive integer: %s" % s)
return False
def validate_filepath(s, err=True):
if os.path.isfile(s):
return True
if err:
raise ValueError("File not found: %s" % s)
return False
def ip_normalize(ipaddr):
return socket.inet_ntoa(socket.inet_aton(ipaddr))
from dataclasses import dataclass
from datetime import datetime, timedelta
from typing import Any, Tuple, Dict
from threading import Thread, Event, Lock
import socket
import http.client
import re
import os
global_thread_lock = Lock()
def is_valid_ip(ip):
# 使用提供的正则表达式检查IP地址的有效性
if not isinstance(ip, str):
return False
pattern = r"(?:(?:1[0-9][0-9]\.)|(?:2[0-4][0-9]\.)|(?:25[0-5]\.)|(?:[1-9][0-9]\.)|(?:[0-9]\.)){3}(?:(?:1[0-9][0-9])|(?:2[0-4][0-9])|(?:25[0-5])|(?:[1-9][0-9])|(?:[0-9]))"
return re.match(pattern, ip) is not None
def is_private_ip(ip):
# 定义局域网 IP 的正则表达式
private_ip_pattern = r"^(?:(?:10(?:(?:\.1[0-9][0-9])|(?:\.2[0-4][0-9])|(?:\.25[0-5])|(?:\.[1-9][0-9])|(?:\.[0-9])))|(?:172(?:\.(?:1[6-9])|(?:2[0-9])|(?:3[0-1])))|(?:192\.168))(?:(?:\.1[0-9][0-9])|(?:\.2[0-4][0-9])|(?:\.25[0-5])|(?:\.[1-9][0-9])|(?:\.[0-9])){2}$"
# 使用 re.match 来判断 ip 是否匹配
return re.match(private_ip_pattern, ip) is not None
def update_upnpd_config(file_path="/etc/config/upnpd"):
# 检查文件是否存在
if not os.path.exists(file_path):
return
# 读取文件内容
with open(file_path, "r") as file:
content = file.read()
# 使用 replace 方法更新选项
content = content.replace("option enabled '1'", "option enabled '0'")
content = content.replace("option enable_upnp '1'", "option enable_upnp '0'")
content = content.replace("option enable_natpmp '1'", "option enable_natpmp '0'")
content = content.replace("option use_stun '1'", "option use_stun '0'")
content = content.replace(
"option force_forwarding '1'", "option force_forwarding '0'"
)
# 写回修改后的内容
with open(file_path, "w") as file:
file.write(content)
os.system("/etc/init.d/miniupnpd restart")
Logger.debug(f"文件已更新: {file_path}")
# 定义缓存变量
cache = {"ip": None, "timestamp": 0}
def get_ip():
timeout = 0.5
cache_duration = 600 # 缓存有效期为 x 秒
# 检查缓存是否有效
current_time = time.time()
if is_valid_ip(cache["ip"]) and current_time - cache["timestamp"] < cache_duration:
return (200, cache["ip"])
# 创建 HTTP 连接,设置超时时间
conn = http.client.HTTPConnection("api.ipify.cn", timeout=timeout)
try:
# 发送 GET 请求
conn.request("GET", "/")
# 获取响应
response = conn.getresponse()
# 读取并解码响应内容
data = response.read().decode("utf-8")
# 检查响应状态码
if response.status == 200:
if is_valid_ip(data):
# 更新缓存
cache["ip"] = data
cache["timestamp"] = current_time
return (response.status, data) # 返回状态码和有效的 IP 地址
else:
return (400, "返回的内容不是有效的 IP 地址") # 状态码设置为 400
else:
return (response.status, f"请求失败,状态码: {response.status}")
except http.client.HTTPException as e:
return (500, f"HTTP 请求失败: {e}") # 处理HTTP异常
except Exception as e:
return (500, f"发生错误: {e}") # 处理其他异常
finally:
# 关闭连接
conn.close()
def new_socket_reuse(family, type):
sock = socket.socket(family, type)
if hasattr(socket, "SO_REUSEADDR"):
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
if hasattr(socket, "SO_REUSEPORT"):
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1)
return sock
def get_free_port(proto_type: str = "TCP") -> int:
# 创建一个新的套接字
sock = new_socket_reuse(
socket.AF_INET, socket.SOCK_STREAM if proto_type == "TCP" else socket.SOCK_DGRAM
)
sock.bind(("", 0)) # 绑定到任何地址的一个随机端口
ret = sock.getsockname()[1] # 获取绑定的端口
sock.close() # 关闭套接字
return ret
def keepalive_loop(
stun: StunClient,
keep_alive: KeepAlive,
udp_mode,
outer_addr,
stopEvent: Event,
interval=15,
):
need_recheck = False
cnt = 0
while True and not stopEvent.is_set():
# force recheck every 20th loop
cnt = (cnt + 1) % 20
if cnt == 0:
need_recheck = True
if need_recheck:
Logger.debug("Start recheck")
need_recheck = False
# then check through STUN
_, outer_addr_curr = stun.get_mapping()
if outer_addr_curr != outer_addr:
Logger.warning(f"STUN映射改变:{outer_addr} -> {outer_addr_curr}")
return
# end of recheck
ts = time.time()
try:
keep_alive.keep_alive()
except (OSError, socket.error) as ex:
if udp_mode:
Logger.debug("keep-alive: UDP response not received: %s" % ex)
else:
Logger.error("keep-alive: connection broken: %s" % ex)
keep_alive.reset()
need_recheck = True
sleep_sec = interval - (time.time() - ts)
while sleep_sec > 0 and not stopEvent.is_set():
time.sleep(1)
sleep_sec -= 1
class KeepAliveThread:
"""用于在对象销毁时自动停止线程"""
def __init__(
self,
stun: StunClient,
keep_alive: KeepAlive,
udp_mode,
outer_addr,
interval=15,
auto_start=True,
):
self.outer_addr = outer_addr
self.stopEvent = Event()
self.thread = Thread(
target=keepalive_loop,
args=(stun, keep_alive, udp_mode, outer_addr, self.stopEvent, interval),