This repository has been archived by the owner on Jun 14, 2018. It is now read-only.
forked from genotrance/px
-
Notifications
You must be signed in to change notification settings - Fork 0
/
px.py
947 lines (780 loc) · 27.7 KB
/
px.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
from __future__ import print_function
import base64
import ctypes
import ctypes.wintypes
import multiprocessing
import os
import select
import signal
import socket
import sys
import threading
import time
import traceback
import datetime
# Dependencies
try:
import concurrent.futures
except ImportError:
print("Requires modules futures")
sys.exit()
try:
import netaddr
except ImportError:
print("Requires modules netaddr")
sys.exit()
try:
import psutil
except ImportError:
print("Requires modules psutil")
sys.exit()
# Default to winkerberos for SSPI
# Try pywin32 SSPI if winkerberos missing
# - pywin32 known to fail in Python 3.6+ : https://github.com/genotrance/px/issues/9
try:
import winkerberos
except ImportError:
if sys.version_info[0] > 2:
if sys.version_info[1] > 5:
print("Requires Python module winkerberos")
sys.exit()
# Less than 3.6, can use pywin32
try:
import pywintypes
import sspi
except ImportError:
print("Requires Python module pywin32 or winkerberos")
sys.exit()
# Python 2.x vs 3.x support
try:
import configparser
import http.server as httpserver
import socketserver
import urllib.parse as urlparse
import winreg
except ImportError:
import ConfigParser as configparser
import SimpleHTTPServer as httpserver
import SocketServer as socketserver
import urlparse
import _winreg as winreg
DEBUG = False
EXIT = False
LISTEN = '127.0.0.1'
LOGGER = None
NOPROXY = netaddr.IPSet([])
ALLOW = None
GATEWAY_IPADDRESSES = None
ALLOWLOCAL=False
ALLOWLOCAL_NEXTREFRESH = None
NTLM_PROXY = None
PORT = 3128
STDOUT = None
MAX_IDLE = 30
MAX_DISCONNECT = 3
MAX_LINE = 65536 + 1
MAX_THREADS = 40
MAX_WORKERS = 2
MAX_ALLOWLOCAL_TTL = 5
INI = "px.ini"
class Log(object):
def __init__(self, name, mode):
self.file = open(name, mode)
self.stdout = sys.stdout
self.stderr = sys.stderr
sys.stdout = self
sys.stderr = self
def close(self):
sys.stdout = self.stdout
sys.stderr = self.stderr
self.file.close()
def write(self, data):
try:
self.file.write(data)
except:
pass
self.file.flush()
self.stdout.write(data)
def flush(self):
self.file.flush()
def dprint(*objs):
if DEBUG:
print(multiprocessing.current_process().name + ": " + threading.current_thread().name + ": " + str(int(time.time())) + ": " + sys._getframe(1).f_code.co_name + ": ", end="")
print(*objs)
def reopen_stdout():
global STDOUT
clrstr = "\r" + " " * 80 + "\r"
if LOGGER == None:
STDOUT = sys.stdout
sys.stdout = open("CONOUT$", "w")
sys.stdout.write(clrstr)
else:
STDOUT = LOGGER.stdout
LOGGER.stdout = open("CONOUT$", "w")
LOGGER.stdout.write(clrstr)
def restore_stdout():
if LOGGER == None:
sys.stdout.close()
sys.stdout = STDOUT
else:
LOGGER.stdout.close()
LOGGER.stdout = STDOUT
###
# NTLM support
class NtlmMessageGenerator:
def __init__(self):
if "winkerberos" in sys.modules:
status, self.ctx = winkerberos.authGSSClientInit("NTLM", gssflags=0, mech_oid=winkerberos.GSS_MECH_OID_SPNEGO)
self.get_response = self.get_response_wkb
else:
self.sspi_client = sspi.ClientAuth("NTLM", os.environ.get("USERNAME"), scflags=0)
self.get_response = self.get_response_sspi
def get_response_sspi(self, challenge=None):
dprint("pywin32 SSPI")
if challenge:
try:
challenge = base64.decodebytes(challenge.encode("utf-8"))
except AttributeError:
challenge = base64.decodestring(challenge)
output_buffer = None
try:
error_msg, output_buffer = self.sspi_client.authorize(challenge)
except pywintypes.error:
traceback.print_exc(file=sys.stdout)
return None
response_msg = output_buffer[0].Buffer
try:
response_msg = base64.encodebytes(response_msg.encode("utf-8"))
except AttributeError:
response_msg = base64.encodestring(response_msg)
response_msg = response_msg.decode("utf-8").replace('\012', '')
return response_msg
def get_response_wkb(self, challenge=""):
dprint("winkerberos SSPI")
try:
winkerberos.authGSSClientStep(self.ctx, challenge)
auth_req = winkerberos.authGSSClientResponse(self.ctx)
except winkerberos.GSSError:
traceback.print_exc(file=sys.stdout)
return None
return auth_req
###
# Proxy handler
class Proxy(httpserver.SimpleHTTPRequestHandler):
protocol_version = "HTTP/1.1"
def handle_one_request(self):
try:
httpserver.SimpleHTTPRequestHandler.handle_one_request(self)
except socket.error:
if not hasattr(self, "_host_disconnected"):
self._host_disconnected = 1
dprint("Host disconnected")
elif self._host_disconnected < MAX_DISCONNECT:
self._host_disconnected += 1
dprint("Host disconnected: %d" % self._host_disconnected)
else:
dprint("Closed connection to avoid infinite loop")
self.close_connection = True
def address_string(self):
host, port = self.client_address[:2]
#return socket.getfqdn(host)
return host
def do_socket(self, xheaders=[], destination=None):
dprint("Entering")
if not destination:
destination = NTLM_PROXY
if not hasattr(self, "client_socket") or self.client_socket is None:
dprint("New connection")
self.client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
self.client_socket.connect(destination)
except:
traceback.print_exc(file=sys.stdout)
return 503, None, None
# No chit chat on SSL
if destination != NTLM_PROXY and self.command == "CONNECT":
return 200, None, None
cl = None
chk = False
expect = False
keepalive = False
cmdstr = ("%s %s %s\r\n" % (self.command, self.path, self.request_version)).encode("utf-8")
self.client_socket.send(cmdstr)
dprint(cmdstr)
for header in self.headers:
h = ("%s: %s\r\n" % (header, self.headers[header])).encode("utf-8")
self.client_socket.send(h)
dprint("Sending %s" % h)
if header.lower() == "content-length":
cl = int(self.headers[header])
elif header.lower() == "expect" and self.headers[header].lower() == "100-continue":
expect = True
elif header.lower() == "proxy-connection":
keepalive = True
elif header.lower() == "transfer-encoding" and self.headers[header].lower() == "chunked":
dprint("CHUNKED data")
chk = True
if not keepalive and self.request_version.lower() == "http/1.0":
xheaders["Proxy-Connection"] = "keep-alive"
for header in xheaders:
h = ("%s: %s\r\n" % (header, xheaders[header])).encode("utf-8")
self.client_socket.send(h)
dprint("Sending extra %s" % h)
self.client_socket.send(b"\r\n")
if self.command in ["POST", "PUT", "PATCH"]:
if not hasattr(self, "body"):
dprint("Getting body for POST/PUT/PATCH")
if cl != None:
self.body = self.rfile.read(cl)
else:
self.body = self.rfile.read()
dprint("Sending body for POST/PUT/PATCH: %d = %d" % (cl or -1, len(self.body)))
self.client_socket.send(self.body)
self.client_fp = self.client_socket.makefile("rb")
resp = 503
nobody = False
headers = []
body = b""
if self.command == "HEAD":
nobody = True
# Response code
for i in range(2):
dprint("Reading response code")
line = self.client_fp.readline(MAX_LINE)
if line == b"\r\n":
line = self.client_fp.readline(MAX_LINE)
try:
resp = int(line.split()[1])
except ValueError:
if line == b"":
dprint("Client closed connection")
return 444, nobody
dprint("Bad response %s" % line)
if b"connection established" in line.lower() or resp == 204 or resp == 304:
nobody = True
dprint("Response code: %d " % resp + str(nobody))
# Get response again if 100-Continue
if not (expect and resp == 100):
break
# Headers
cl = None
chk = False
dprint("Reading response headers")
while not EXIT:
line = self.client_fp.readline(MAX_LINE).decode("utf-8")
if line == b"":
dprint("Client closed connection: %s" % resp)
return 444, None, None
if line == "\r\n":
break
nv = line.split(":", 1)
if len(nv) != 2:
dprint("Bad header =>%s<=" % line)
continue
name = nv[0].strip()
value = nv[1].strip()
headers.append((name, value))
dprint("Received header %s = %s" % (name, value))
if name.lower() == "content-length":
cl = int(value)
if not cl:
nobody = True
elif name.lower() == "transfer-encoding" and value.lower() == "chunked":
chk = True
# Data
dprint("Reading response data")
if not nobody:
if cl:
dprint("Content length %d" % cl)
body = self.client_fp.read(cl)
elif chk:
dprint("Chunked encoding")
while not EXIT:
line = self.client_fp.readline(MAX_LINE).decode("utf-8").strip()
try:
csize = int(line.strip(), 16)
dprint("Chunk size %d" % csize)
except ValueError:
dprint("Bad chunk size '%s'" % line)
continue
if csize == 0:
dprint("No more chunks")
break
d = self.client_fp.read(csize)
if len(d) < csize:
dprint("Chunk doesn't match data")
break
body += d
headers.append(("Content-Length", str(len(body))))
else:
dprint("Not sure how much")
while not EXIT:
time.sleep(0.1)
d = self.client_fp.read(1024)
if len(d) < 1024:
break
body += d
return resp, headers, body
def do_transaction(self):
dprint("Entering")
ipport = self.get_destination()
if ipport != None:
dprint("Skipping NTLM proxying")
resp, headers, body = self.do_socket(destination=ipport)
else:
# Check for NTLM auth
ntlm = NtlmMessageGenerator()
ntlm_resp = ntlm.get_response()
if ntlm_resp is None:
dprint("Bad NTLM response")
return 503, None, None
resp, headers, body = self.do_socket({
"Proxy-Authorization": "NTLM %s" % ntlm_resp
})
if resp == 407:
dprint("Auth required")
ntlm_challenge = ""
for header in headers:
if header[0] == "Proxy-Authenticate" and "NTLM" in header[1]:
ntlm_challenge = header[1].split()[1]
break
if ntlm_challenge:
dprint("Challenged")
ntlm_resp = ntlm.get_response(ntlm_challenge)
if ntlm_resp is None:
dprint("Bad NTLM response")
return 503, None, None
resp, headers, body = self.do_socket({
"Proxy-Authorization": "NTLM %s" % ntlm_resp
})
return resp, headers, body
else:
dprint("Didn't get challenge, not NTLM proxy")
elif resp > 400:
return resp, None, None
else:
dprint("No auth required")
return resp, headers, body
def do_HEAD(self):
dprint("Entering")
self.do_GET()
dprint("Done")
def do_GET(self):
dprint("Entering")
resp, headers, body = self.do_transaction()
if resp >= 400:
dprint("Error %d" % resp)
self.send_error(resp)
else:
self.fwd_resp(resp, headers, body)
dprint("Done")
def do_POST(self):
dprint("Entering")
self.do_GET()
dprint("Done")
def do_PUT(self):
dprint("Entering")
self.do_GET()
dprint("Done")
def do_DELETE(self):
dprint("Entering")
self.do_GET()
dprint("Done")
def do_PATCH(self):
dprint("Entering")
self.do_GET()
dprint("Done")
def do_CONNECT(self):
dprint("Entering")
cl = 0
resp, headers, body = self.do_transaction()
if resp >= 400:
dprint("Error %d" % resp)
self.send_error(resp)
else:
dprint("Tunneling through proxy")
self.send_response(200, "Connection established")
self.send_header("Proxy-Agent", self.version_string())
self.end_headers()
rlist = [self.connection, self.client_socket]
wlist = []
count = 0
while not EXIT:
count += 1
(ins, _, exs) = select.select(rlist, wlist, rlist, 1)
if exs:
break
if ins:
for i in ins:
if i is self.client_socket:
out = self.connection
else:
out = self.client_socket
data = i.recv(4096)
if data:
out.send(data)
count = 0
cl += len(data)
if count == MAX_IDLE:
break
dprint("Transferred %d bytes" % cl)
dprint("Done")
def fwd_resp(self, resp, headers, body):
dprint("Entering")
self.send_response(resp)
for header in headers:
if header[0].lower() != "transfer-encoding":
dprint("Returning %s: %s" % (header[0], header[1]))
self.send_header(header[0], header[1])
self.end_headers()
try:
self.wfile.write(body)
except:
pass
dprint("Done")
def get_destination(self):
if NOPROXY.size:
netloc = self.path
path = "/"
if self.command != "CONNECT":
parse = urlparse.urlparse(self.path, allow_fragments=False)
if parse.netloc:
netloc = parse.netloc
if ":" not in netloc:
port = parse.port
if not port:
if parse.scheme == "http":
port = 80
elif parse.scheme == "https":
port = 443
netloc = netloc + ":" + str(port)
path = parse.path or "/"
if parse.params:
path = path + ";" + parse.params
if parse.query:
path = path + "?" + parse.query
dprint(netloc)
spl = netloc.split(":", 1)
addr = socket.getaddrinfo(spl[0], int(spl[1]))
if len(addr) and len(addr[0]) == 5:
ipport = addr[0][4]
dprint("%s => %s + %s" % (self.path, ipport, path))
if ipport[0] in NOPROXY:
self.path = path
return ipport
return None
###
# Multi-processing and multi-threading
class PoolMixIn(socketserver.ThreadingMixIn):
def process_request(self, request, client_address):
self.pool.submit(self.process_request_thread, request, client_address)
def verify_request(self, request, client_address):
global ALLOWLOCAL
global ALLOW
global GATEWAY_IPADDRESSES
global ALLOWLOCAL_NEXTREFRESH
dprint("Client address: %s" % client_address[0])
if ALLOWLOCAL:
if (ALLOWLOCAL_NEXTREFRESH is None) or (ALLOWLOCAL_NEXTREFRESH < datetime.datetime.now()):
ips = socket.getaddrinfo(socket.gethostname(), 80, socket.AF_INET)
newgatewayips = netaddr.IPSet(ip[4][0] for ip in ips)
newgatewayips.add("127.0.0.1")
newgatewayips = newgatewayips | ALLOW # IPSet.add() not implemented for IPSets...
if newgatewayips != GATEWAY_IPADDRESSES:
GATEWAY_IPADDRESSES=newgatewayips
dprint("Allow connections from: %s" % (", ".join(str(ip) for ip in GATEWAY_IPADDRESSES.iter_cidrs())))
ALLOWLOCAL_NEXTREFRESH = datetime.datetime.now() + datetime.timedelta(seconds=MAX_ALLOWLOCAL_TTL)
if (client_address[0] in GATEWAY_IPADDRESSES):
return True
dprint("Client not allowed: %s" % client_address[0])
return False
class ThreadedTCPServer(PoolMixIn, socketserver.TCPServer):
daemon_threads = True
allow_reuse_address = True
try:
# Workaround bad thread naming code in Python 3.6+, fixed in master
pool = concurrent.futures.ThreadPoolExecutor(max_workers=MAX_THREADS, thread_name_prefix="Thread")
except:
pool = concurrent.futures.ThreadPoolExecutor(max_workers=MAX_THREADS)
def serve_forever(httpd):
global EXIT
signal.signal(signal.SIGINT, signal.SIG_DFL)
try:
httpd.serve_forever()
except KeyboardInterrupt:
dprint("Exiting")
EXIT = True
httpd.shutdown()
def start_worker(pipeout):
parsecli()
httpd = ThreadedTCPServer((LISTEN, PORT), Proxy, bind_and_activate=False)
mainsock = socket.fromshare(pipeout.recv())
httpd.socket = mainsock
serve_forever(httpd)
def runpool():
try:
httpd = ThreadedTCPServer((LISTEN, PORT), Proxy)
except OSError as exc:
print(exc)
return
mainsock = httpd.socket
if hasattr(socket, "fromshare"):
workers = MAX_WORKERS
for i in range(workers-1):
(pipeout, pipein) = multiprocessing.Pipe()
p = multiprocessing.Process(target=start_worker, args=(pipeout,))
p.daemon = True
p.start()
while p.pid is None:
time.sleep(1)
pipein.send(mainsock.share(p.pid))
serve_forever(httpd)
###
# Parse settings and command line
def parseproxy(proxystr):
global NTLM_PROXY
NTLM_PROXY = proxystr.split(":")
if len(NTLM_PROXY) == 1:
NTLM_PROXY.append(80)
else:
NTLM_PROXY[1] = int(NTLM_PROXY[1])
NTLM_PROXY = tuple(NTLM_PROXY)
def parseipranges(iprangesconfig):
ipranges = netaddr.IPSet([])
iprangessplit = [i.strip() for i in iprangesconfig.split(",")]
for iprange in iprangessplit:
if not iprange:
continue
try:
if "-" in iprange:
spl = iprange.split("-", 1)
ipns = netaddr.IPRange(spl[0], spl[1])
elif "*" in iprange:
ipns = netaddr.IPGlob(iprange)
else:
ipns = netaddr.IPNetwork(iprange)
ipranges.add(ipns)
except:
print("Bad IP definition: %s" % iprangesconfig)
sys.exit()
return ipranges
def parseallow(allow):
global ALLOW
ALLOW = parseipranges(allow)
def parsenoproxy(noproxy):
global NOPROXY
NOPROXY = parseipranges(noproxy)
def parsecli():
global DEBUG
global LISTEN
global LOGGER
global MAX_IDLE
global MAX_WORKERS
global PORT
global ALLOWLOCAL
global ALLOW
global GATEWAY_IPADDRESSES
if "--debug" in sys.argv:
LOGGER = Log("debug-%s.log" % multiprocessing.current_process().name, "w")
DEBUG = True
if getattr(sys, "frozen", False):
attachConsole()
if os.path.exists(INI):
config = configparser.ConfigParser()
config.read(INI)
if "proxy" in config.sections():
if "server" in config.options("proxy"):
server = config.get("proxy", "server").strip()
if server:
parseproxy(server)
if "port" in config.options("proxy"):
port = config.get("proxy", "port").strip()
try:
PORT = int(port)
except ValueError:
pass
if "listen" in config.options("proxy"):
listen = config.get("proxy", "listen").strip()
if listen:
LISTEN = listen
if "allow" in config.options("proxy"):
parseallow(config.get("proxy", "allow"))
if "allowlocal" in config.options("proxy"):
if config.get("proxy", "allowlocal") == "1":
ALLOWLOCAL = True
if "gateway" in config.options("proxy"):
if config.get("proxy", "gateway") == "1":
LISTEN = ''
if "noproxy" in config.options("proxy"):
parsenoproxy(config.get("proxy", "noproxy"))
if "settings" in config.sections():
if "workers" in config.options("settings"):
workers = config.get("settings", "workers").strip()
try:
MAX_WORKERS = int(workers)
except ValueError:
pass
if "threads" in config.options("settings"):
threads = config.get("settings", "threads").strip()
try:
MAX_THREADS = int(threads)
except ValueError:
pass
if "idle" in config.options("settings"):
idle = config.get("settings", "idle").strip()
try:
MAX_IDLE = int(idle)
except ValueError:
pass
if "log" in config.options("settings"):
if config.get("settings", "log") == "1":
LOGGER = Log("debug-%s.log" % multiprocessing.current_process().name, "w")
DEBUG = True
for i in range(len(sys.argv)):
if "--proxy=" in sys.argv[i]:
parseproxy(sys.argv[i].split("=")[1])
elif "--noproxy=" in sys.argv[i]:
parsenoproxy(sys.argv[i].split("=")[1])
elif "--allow=" in sys.argv[i]:
parseallow(sys.argv[i].split("=")[1])
elif "--allowlocal" in sys.argv[i]:
ALLOWLOCAL=True
if "--gateway" in sys.argv:
LISTEN = ''
if "--install" in sys.argv:
install()
elif "--uninstall" in sys.argv:
uninstall()
elif "--quit" in sys.argv:
quit()
if NTLM_PROXY is None:
print("No proxy defined")
sys.exit()
if ALLOW is None:
if ALLOWLOCAL:
ALLOW = netaddr.IPSet()
else:
ALLOW = netaddr.IPGlob("*.*.*.*")
GATEWAY_IPADDRESSES = ALLOW # Default. Will be overriden in verify_request() if allowlocal is used
print("Serving at %s:%d proc %s" % (LISTEN, PORT, multiprocessing.current_process().name))
if getattr(sys, "frozen", False):
detachConsole()
###
# Exit related
def quit():
count = 0
mypids = [os.getpid(), os.getppid()]
for pid in sorted(psutil.pids(), reverse=True):
if pid in mypids:
continue
try:
p = psutil.Process(pid)
if p.exe().lower() == sys.executable.lower():
p.send_signal(signal.CTRL_C_EVENT)
count += 1
except:
pass
if count != 0:
print("Quiting Px")
else:
print("Px is not running")
sys.exit()
def handle_exceptions(type, value, tb):
# Create traceback log
lst = traceback.format_tb(tb, None) + traceback.format_exception_only(type, value)
tracelog = '\nTraceback (most recent call last):\n' + "%-20s%s\n" % ("".join(lst[:-1]), lst[-1])
if LOGGER != None:
print(tracelog)
else:
sys.stderr.write(tracelog)
# Save to debug.log
dbg = open('debug-%s.log' % multiprocessing.current_process().name, 'w')
dbg.write(tracelog)
dbg.close()
###
# Install Px to startup
def get_script_path():
if getattr(sys, "frozen", False):
# Script mode
return os.path.normpath(os.path.join(os.getcwd(), sys.argv[0]))
else:
# Frozen mode
return sys.executable
def get_script_cmd():
spath = get_script_path()
if spath != sys.executable:
return sys.executable + ' "%s"' % spath
return spath
def check_installed():
ret = True
runkey = winreg.OpenKey(winreg.HKEY_CURRENT_USER, r"Software\Microsoft\Windows\CurrentVersion\Run", 0, winreg.KEY_READ)
try:
value = winreg.QueryValueEx(runkey, "Px")
except:
ret = False
winreg.CloseKey(runkey)
return ret
def install():
if check_installed() is False:
runkey = winreg.OpenKey(winreg.HKEY_CURRENT_USER, r"Software\Microsoft\Windows\CurrentVersion\Run", 0, winreg.KEY_WRITE)
winreg.SetValueEx(runkey, "Px", 0, winreg.REG_EXPAND_SZ, get_script_cmd())
winreg.CloseKey(runkey)
print("Px installed successfully")
else:
print("Px already installed")
sys.exit()
def uninstall():
if check_installed() is True:
runkey = winreg.OpenKey(winreg.HKEY_CURRENT_USER, r"Software\Microsoft\Windows\CurrentVersion\Run", 0, winreg.KEY_WRITE)
winreg.DeleteValue(runkey, "Px")
winreg.CloseKey(runkey)
print("Px uninstalled successfully")
else:
print("Px is not installed")
sys.exit()
###
# Attach/detach console
def attachConsole():
if ctypes.windll.kernel32.GetConsoleWindow() != 0:
dprint("Already attached to a console")
return
# Find parent cmd.exe if exists
pid = os.getpid()
while True:
try:
p = psutil.Process(pid)
except psutil.NoSuchProcess:
# No such parent - started without console
pid = -1
break
if p.cmdline()[0] == "cmd":
# Found it
break
# Search parent
pid = p.ppid()
# Not found, started without console
if pid == -1:
return
dprint("Attaching to console " + str(pid))
if ctypes.windll.kernel32.AttachConsole(pid) == 0:
dprint("Attach failed with error " + str(ctypes.windll.kernel32.GetLastError()))
return
if ctypes.windll.kernel32.GetConsoleWindow() == 0:
dprint("Not a console window")
return
reopen_stdout()
def detachConsole():
if ctypes.windll.kernel32.GetConsoleWindow() == 0:
return
restore_stdout()
if not ctypes.windll.kernel32.FreeConsole():
dprint("Free console failed with error " + str(ctypes.windll.kernel32.GetLastError()))
else:
dprint("Freed console successfully")
###
# Startup
if __name__ == "__main__":
multiprocessing.freeze_support()
sys.excepthook = handle_exceptions
parsecli()
runpool()