mirror of
https://github.com/Justuser3310/jetwork.git
synced 2025-02-07 17:34:39 +00:00
Compare commits
9 Commits
54a4692cac
...
6e96b0dfb3
Author | SHA1 | Date | |
---|---|---|---|
|
6e96b0dfb3 | ||
|
f06c6f963c | ||
|
1c4a7bb11a | ||
|
dfd5d61db7 | ||
|
d3a25ee190 | ||
|
c5a0111fab | ||
|
dfc37d6ea7 | ||
|
e83bee6b08 | ||
|
ca1e5422a2 |
8
db.py
8
db.py
@ -2,19 +2,19 @@ import os
|
||||
import json
|
||||
|
||||
if not os.path.exists('config.json'):
|
||||
db = {"os": None,"our_port": 0000, "ports": [], "domain": "http://0.0.0.0:8000"}
|
||||
db = {'os': None,'our_port': 0000, 'ports': [], 'base_url': 'http://0.0.0.0:8000'}
|
||||
js = json.dumps(db, indent=2)
|
||||
with open("config.json", "w") as outfile:
|
||||
with open('config.json', 'w') as outfile:
|
||||
outfile.write(js)
|
||||
print('Created new config.json')
|
||||
|
||||
|
||||
def read(file = 'config.json'):
|
||||
with open(file, "r", encoding="utf-8") as openfile:
|
||||
with open(file, 'r', encoding='utf-8') as openfile:
|
||||
db = json.load(openfile)
|
||||
return db
|
||||
|
||||
def write(db, file = 'config.json'):
|
||||
js = json.dumps(db, indent=2, ensure_ascii=False)
|
||||
with open(file, "w", encoding="utf-8") as outfile:
|
||||
with open(file, 'w', encoding='utf-8') as outfile:
|
||||
outfile.write(js)
|
||||
|
1
docs/proxy_LOCAL.json
Normal file
1
docs/proxy_LOCAL.json
Normal file
@ -0,0 +1 @@
|
||||
{"activeProfileId":"InternalProfile_SmartRules","defaultProxyServerId":"usundlzx4uvk2","firstEverInstallNotified":true,"options":{"syncSettings":false,"syncActiveProfile":true,"syncActiveProxy":true,"detectRequestFailures":true,"displayFailedOnBadge":true,"displayAppliedProxyOnBadge":true,"displayMatchedRuleOnBadge":true,"refreshTabOnConfigChanges":false,"proxyPerOrigin":true,"enableShortcuts":true,"shortcutNotification":true,"themeType":0,"themesDark":"themes-cosmo-dark"},"product":"SmartProxy","proxyProfiles":[{"enabled":true,"proxyRules":[],"rulesSubscriptions":[],"profileId":"InternalProfile_Direct","profileType":0,"profileTypeConfig":{"builtin":true,"editable":false,"selectable":true,"supportsSubscriptions":false,"supportsProfileProxy":false,"customProxyPerRule":false,"canBeDisabled":false,"supportsRuleActionWhitelist":false,"defaultRuleActionIsWhitelist":null},"profileName":"Direct (No Proxy)","profileProxyServerId":null},{"enabled":true,"proxyRules":[{"enabled":true,"whiteList":false,"ruleId":99411781,"autoGeneratePattern":true,"ruleType":0,"hostName":"jet","rulePattern":"*.jet/*","ruleRegex":"","ruleExact":"","proxy":{"name":"jet_local","id":"ezgallzykftxq","order":1,"host":"127.0.0.1","port":"8080","protocol":"HTTP","username":"","password":"","proxyDNS":true,"failoverTimeout":null},"proxyServerId":"ezgallzykftxq"},{"enabled":true,"whiteList":false,"ruleId":274078801725,"autoGeneratePattern":true,"ruleType":0,"hostName":"mirror","rulePattern":"*.mirror/*","ruleRegex":"","ruleExact":"","proxy":{"name":"jet_local","id":"ezgallzykftxq","order":1,"host":"127.0.0.1","port":"8080","protocol":"HTTP","username":"","password":"","proxyDNS":true,"failoverTimeout":null},"proxyServerId":"ezgallzykftxq"},{"enabled":true,"whiteList":false,"ruleId":597907496,"autoGeneratePattern":true,"ruleType":0,"hostName":"me","rulePattern":"*.me/*","ruleRegex":"","ruleExact":"","proxy":{"name":"jet_local","id":"ezgallzykftxq","order":1,"host":"127.0.0.1","port":"8080","protocol":"HTTP","username":"","password":"","proxyDNS":true,"failoverTimeout":null},"proxyServerId":"ezgallzykftxq"}],"rulesSubscriptions":[],"profileId":"InternalProfile_SmartRules","profileType":2,"profileTypeConfig":{"builtin":true,"editable":true,"selectable":true,"supportsSubscriptions":true,"supportsProfileProxy":true,"customProxyPerRule":true,"canBeDisabled":true,"supportsRuleActionWhitelist":true,"defaultRuleActionIsWhitelist":false},"profileName":"Smart Proxy","profileProxyServerId":""},{"enabled":true,"proxyRules":[],"rulesSubscriptions":[],"profileId":"InternalProfile_AlwaysEnabled","profileType":3,"profileTypeConfig":{"builtin":true,"editable":true,"selectable":true,"supportsSubscriptions":true,"supportsProfileProxy":true,"customProxyPerRule":true,"canBeDisabled":true,"supportsRuleActionWhitelist":true,"defaultRuleActionIsWhitelist":true},"profileName":"Always Enable","profileProxyServerId":null},{"enabled":true,"proxyRules":[],"rulesSubscriptions":[],"profileId":"InternalProfile_SystemProxy","profileType":1,"profileTypeConfig":{"builtin":true,"editable":false,"selectable":true,"supportsSubscriptions":false,"supportsProfileProxy":false,"customProxyPerRule":false,"canBeDisabled":false,"supportsRuleActionWhitelist":false,"defaultRuleActionIsWhitelist":null},"profileName":"System Proxy","profileProxyServerId":null},{"enabled":true,"proxyRules":[],"rulesSubscriptions":[],"profileType":4,"profileTypeConfig":{"builtin":true,"editable":false,"selectable":false,"supportsSubscriptions":false,"supportsProfileProxy":false,"customProxyPerRule":false,"canBeDisabled":false,"supportsRuleActionWhitelist":false,"defaultRuleActionIsWhitelist":null},"profileName":"Ignore Failure Rules","profileId":"profile-ms5zflzx4opc8"}],"proxyServerSubscriptions":[],"proxyServers":[{"name":"jet_public","id":"usundlzx4uvk2","order":3,"host":"jet.del.pw","port":"8080","protocol":"HTTP","username":"","password":"","proxyDNS":true,"failoverTimeout":null},{"name":"jet_local","id":"ezgallzykftxq","order":1,"host":"127.0.0.1","port":"8080","protocol":"HTTP","username":"","password":"","proxyDNS":true,"failoverTimeout":null}],"updateInfo":{"updateIsAvailable":false,"downloadPage":null,"version":null,"versionName":null,"isBrowserSpecific":true},"version":"1.5"}
|
1
docs/proxy_PUBLIC.json
Normal file
1
docs/proxy_PUBLIC.json
Normal file
@ -0,0 +1 @@
|
||||
{"activeProfileId":"InternalProfile_SmartRules","defaultProxyServerId":"usundlzx4uvk2","firstEverInstallNotified":true,"options":{"syncSettings":false,"syncActiveProfile":true,"syncActiveProxy":true,"detectRequestFailures":true,"displayFailedOnBadge":true,"displayAppliedProxyOnBadge":true,"displayMatchedRuleOnBadge":true,"refreshTabOnConfigChanges":false,"proxyPerOrigin":true,"enableShortcuts":true,"shortcutNotification":true,"themeType":0,"themesDark":"themes-cosmo-dark"},"product":"SmartProxy","proxyProfiles":[{"enabled":true,"proxyRules":[],"rulesSubscriptions":[],"profileId":"InternalProfile_Direct","profileType":0,"profileTypeConfig":{"builtin":true,"editable":false,"selectable":true,"supportsSubscriptions":false,"supportsProfileProxy":false,"customProxyPerRule":false,"canBeDisabled":false,"supportsRuleActionWhitelist":false,"defaultRuleActionIsWhitelist":null},"profileName":"Direct (No Proxy)","profileProxyServerId":null},{"enabled":true,"proxyRules":[{"enabled":true,"whiteList":false,"ruleId":42142459831829816,"autoGeneratePattern":true,"ruleType":0,"hostName":"jet","rulePattern":"*.jet/*","ruleRegex":"","ruleExact":"","proxy":{"name":"jet_public","id":"usundlzx4uvk2","order":3,"host":"jet.del.pw","port":"8080","protocol":"HTTP","username":"","password":"","proxyDNS":true,"failoverTimeout":null},"proxyServerId":"usundlzx4uvk2"},{"enabled":true,"whiteList":false,"ruleId":995421339685,"autoGeneratePattern":true,"ruleType":0,"hostName":"mirror","rulePattern":"*.mirror/*","ruleRegex":"","ruleExact":"","proxy":{"name":"jet_public","id":"usundlzx4uvk2","order":3,"host":"jet.del.pw","port":"8080","protocol":"HTTP","username":"","password":"","proxyDNS":true,"failoverTimeout":null},"proxyServerId":"usundlzx4uvk2"},{"enabled":true,"whiteList":false,"ruleId":7021094,"autoGeneratePattern":true,"ruleType":0,"hostName":"me","rulePattern":"*.me/*","ruleRegex":"","ruleExact":"","proxy":{"name":"jet_public","id":"usundlzx4uvk2","order":3,"host":"jet.del.pw","port":"8080","protocol":"HTTP","username":"","password":"","proxyDNS":true,"failoverTimeout":null},"proxyServerId":"usundlzx4uvk2"}],"rulesSubscriptions":[],"profileId":"InternalProfile_SmartRules","profileType":2,"profileTypeConfig":{"builtin":true,"editable":true,"selectable":true,"supportsSubscriptions":true,"supportsProfileProxy":true,"customProxyPerRule":true,"canBeDisabled":true,"supportsRuleActionWhitelist":true,"defaultRuleActionIsWhitelist":false},"profileName":"Smart Proxy","profileProxyServerId":""},{"enabled":true,"proxyRules":[],"rulesSubscriptions":[],"profileId":"InternalProfile_AlwaysEnabled","profileType":3,"profileTypeConfig":{"builtin":true,"editable":true,"selectable":true,"supportsSubscriptions":true,"supportsProfileProxy":true,"customProxyPerRule":true,"canBeDisabled":true,"supportsRuleActionWhitelist":true,"defaultRuleActionIsWhitelist":true},"profileName":"Always Enable","profileProxyServerId":null},{"enabled":true,"proxyRules":[],"rulesSubscriptions":[],"profileId":"InternalProfile_SystemProxy","profileType":1,"profileTypeConfig":{"builtin":true,"editable":false,"selectable":true,"supportsSubscriptions":false,"supportsProfileProxy":false,"customProxyPerRule":false,"canBeDisabled":false,"supportsRuleActionWhitelist":false,"defaultRuleActionIsWhitelist":null},"profileName":"System Proxy","profileProxyServerId":null},{"enabled":true,"proxyRules":[],"rulesSubscriptions":[],"profileType":4,"profileTypeConfig":{"builtin":true,"editable":false,"selectable":false,"supportsSubscriptions":false,"supportsProfileProxy":false,"customProxyPerRule":false,"canBeDisabled":false,"supportsRuleActionWhitelist":false,"defaultRuleActionIsWhitelist":null},"profileName":"Ignore Failure Rules","profileId":"profile-ms5zflzx4opc8"}],"proxyServerSubscriptions":[],"proxyServers":[{"name":"jet_public","id":"usundlzx4uvk2","order":3,"host":"jet.del.pw","port":"8080","protocol":"HTTP","username":"","password":"","proxyDNS":true,"failoverTimeout":null},{"name":"jet_local","id":"ezgallzykftxq","order":1,"host":"127.0.0.1","port":"8080","protocol":"HTTP","username":"","password":"","proxyDNS":true,"failoverTimeout":null}],"updateInfo":{"updateIsAvailable":false,"downloadPage":null,"version":null,"versionName":null,"isBrowserSpecific":true},"version":"1.5"}
|
@ -1,5 +1,5 @@
|
||||
from re import compile, sub
|
||||
domains = ['jet', 'dyn']
|
||||
domains = ['jet', 'mirror', 'me']
|
||||
|
||||
def domain_ok(domain):
|
||||
global domains
|
||||
|
@ -67,11 +67,11 @@ def update_servers(n):
|
||||
Input('interval-component', 'n_intervals'),
|
||||
Input('search', 'value'))
|
||||
def update_sites(n, s_val):
|
||||
# Домен по умолчанию
|
||||
domain = read()['domain']
|
||||
# Префикс
|
||||
base_url = read()['base_url']
|
||||
# Если есть элемент в поиске
|
||||
if s_val:
|
||||
return html.Div([ dcc.Link(children=i, href=f'{domain}/{s_val}',
|
||||
return html.Div([ dcc.Link(children=i, href=f'{base_url}/{s_val}',
|
||||
target='_blank') ], className='sites_elem')
|
||||
|
||||
res = []
|
||||
|
23
network.py
23
network.py
@ -13,6 +13,9 @@ from db import read
|
||||
from json import loads
|
||||
# Логирование ошибок
|
||||
import logging
|
||||
# Просто логирование
|
||||
from icecream import ic
|
||||
ic.disable() # Отключение логирования
|
||||
|
||||
from verify import *
|
||||
from domain_check import *
|
||||
@ -43,7 +46,7 @@ def server_http():
|
||||
except KeyboardInterrupt:
|
||||
run = False
|
||||
except Exception as e:
|
||||
print("SERVER_HTTP FALLED")
|
||||
ic("SERVER_HTTP FALLED")
|
||||
logging.critical(e, exc_info=True)
|
||||
|
||||
def server(http_port):
|
||||
@ -59,7 +62,7 @@ def server(http_port):
|
||||
s.listen(2)
|
||||
conn, address = s.accept()
|
||||
|
||||
print("Connection from: " + str(address))
|
||||
ic("Connection from: " + str(address))
|
||||
|
||||
while True:
|
||||
try:
|
||||
@ -104,7 +107,7 @@ def server(http_port):
|
||||
conn.close()
|
||||
|
||||
except Exception as e:
|
||||
print("SERVER_HTTP FALLED")
|
||||
ic("SERVER_HTTP FALLED")
|
||||
logging.critical(e, exc_info=True)
|
||||
|
||||
|
||||
@ -120,7 +123,7 @@ def recv(s, data_out):
|
||||
okay = True
|
||||
except:
|
||||
pass
|
||||
print(data)
|
||||
ic(data)
|
||||
data_out.put(data)
|
||||
|
||||
# op = operation
|
||||
@ -177,7 +180,7 @@ def client(port, op = "ping", host = 'bore.del.pw'):
|
||||
g_site = get(f"http://{host}:{str(port)}/{site}.zip")
|
||||
except:
|
||||
return 'error'
|
||||
print('SIZE: ', g_site.headers['Content-Length']) # Размер
|
||||
ic('SIZE: ', g_site.headers['Content-Length']) # Размер
|
||||
|
||||
with open(f"verify/{site}.zip", "wb") as f:
|
||||
f.write(g_site.content)
|
||||
@ -214,10 +217,10 @@ def client(port, op = "ping", host = 'bore.del.pw'):
|
||||
our_ver = our_conf["ver"]
|
||||
# Если версия не новее - злоумышленник
|
||||
if our_ver >= dest_ver:
|
||||
print("[!] Обнаружена подмена версии сайта.")
|
||||
ic("[!] Обнаружена подмена версии сайта.")
|
||||
# Сохраняем ключ злоумышленника
|
||||
os.replace(f"verify/{site}.pem", f"verify/{site}.pem.FAKE")
|
||||
print(f"[!] Порт злоумышленника: {port}")
|
||||
ic(f"[!] Порт злоумышленника: {port}")
|
||||
# Удаляем фальшивые файлы
|
||||
os.remove(f"verify/{site}.zip")
|
||||
os.remove(f"verify/{site}.sig")
|
||||
@ -235,11 +238,11 @@ def client(port, op = "ping", host = 'bore.del.pw'):
|
||||
copytree(f"verify/{site}", f"cached/{site}")
|
||||
rmtree(f"verify/{site}")
|
||||
else:
|
||||
print("[!] Обнаружена подмена сайта.")
|
||||
ic("[!] Обнаружена подмена сайта.")
|
||||
# Сохраняем ключ злоумышленника
|
||||
os.replace(f"verify/{site}.pem", f"verify/{site}.pem.FAKE")
|
||||
print(f"[!] Порт злоумышленника: {port}")
|
||||
print(f"[!] Ключ (вероятно) злоумышленника сохранён в verify/{site}.pem.FAKE\n")
|
||||
ic(f"[!] Порт злоумышленника: {port}")
|
||||
ic(f"[!] Ключ (вероятно) злоумышленника сохранён в verify/{site}.pem.FAKE\n")
|
||||
# Удаляем фальшивые файлы
|
||||
os.remove(f"verify/{site}.zip")
|
||||
os.remove(f"verify/{site}.sig")
|
||||
|
10
setup.py
10
setup.py
@ -15,8 +15,14 @@ conf = read()
|
||||
conf['os'] = os
|
||||
write(conf)
|
||||
|
||||
if os == 'Android':
|
||||
print('''---
|
||||
[1/3] Устанавливаем зависимости python...
|
||||
Устанавливаем зависимости rust...
|
||||
---''')
|
||||
system('pkg install rust')
|
||||
|
||||
print('''---
|
||||
[1/3] Устанавливаем зависимости Python...
|
||||
---''')
|
||||
system('pip install -r requirements.txt')
|
||||
|
||||
@ -33,7 +39,7 @@ elif os == 'Windows':
|
||||
unpack('bore.zip')
|
||||
system('del bore.zip')
|
||||
elif os == 'Android':
|
||||
system('pkg install bore-cli')
|
||||
system('pkg install bore')
|
||||
else:
|
||||
print('Увы, вероятно Ваша ОС не поддерживается.')
|
||||
print('Завершение работы...')
|
||||
|
@ -52,11 +52,11 @@ def update_servers(n):
|
||||
Input('interval-component', 'n_intervals'),
|
||||
Input('search', 'value'))
|
||||
def update_sites(n, s_val):
|
||||
# Домен по умолчанию
|
||||
domain = read()['domain']
|
||||
# Префикс
|
||||
base_url = read()['base_url']
|
||||
# Если есть элемент в поиске
|
||||
if s_val:
|
||||
return html.Div([ dcc.Link(children=i, href=f'{domain}/{s_val}',
|
||||
return html.Div([ dcc.Link(children=i, href=f'{base_url}/{s_val}',
|
||||
target='_blank') ], className='sites_elem')
|
||||
|
||||
res = []
|
||||
|
11
updater.py
11
updater.py
@ -6,6 +6,9 @@ from network import *
|
||||
|
||||
# Логирование ошибок
|
||||
import logging
|
||||
# Просто логирование
|
||||
from icecream import ic
|
||||
ic.disable() # Отключение логирования
|
||||
|
||||
def update_demon(serv_port):
|
||||
while True:
|
||||
@ -40,23 +43,23 @@ def update_demon(serv_port):
|
||||
if check[0] == el:
|
||||
# Сверяем версии
|
||||
if check[1] >= ver:
|
||||
print("Ver_ok: ", el)
|
||||
ic("Ver_ok: ", el)
|
||||
pass
|
||||
else:
|
||||
# Если версия новее
|
||||
print("Ver_new: ", el)
|
||||
ic("Ver_new: ", el)
|
||||
http_port = client(port, f"is_{el}")
|
||||
client(http_port, f"get_{el}")
|
||||
found = True
|
||||
break # Если нашли - выходим
|
||||
|
||||
if not found:
|
||||
print("Not_found: ", el)
|
||||
ic("Not_found: ", el)
|
||||
http_port = client(port, f"is_{el}")
|
||||
client(http_port, f"get_{el}")
|
||||
except:
|
||||
pass
|
||||
|
||||
except Exception as e:
|
||||
print("UPDATER FALLED")
|
||||
ic("UPDATER FALLED")
|
||||
logging.critical(e, exc_info=True)
|
||||
|
57
web_proxy.py
57
web_proxy.py
@ -2,34 +2,42 @@ import http.server
|
||||
import socketserver
|
||||
import urllib.request
|
||||
import logging
|
||||
from os.path import exists
|
||||
|
||||
from db import *
|
||||
domain = read()['domain']
|
||||
base_url = read()['base_url']
|
||||
|
||||
# Логирование
|
||||
#logging.basicConfig(level=ic, format='%(asctime)s - %(message)s')
|
||||
from icecream import ic
|
||||
ic.disable() # Выключить отладку
|
||||
|
||||
class Proxy(http.server.SimpleHTTPRequestHandler):
|
||||
# Отключение всех сообщений (чтобы не забивать вывод)
|
||||
def log_message(self, format, *args):
|
||||
pass
|
||||
def do_GET(self):
|
||||
# Log the requested domain
|
||||
ic(f"Request for: {self.path}")
|
||||
|
||||
# 'js-check.jet/favicon.ico' -> '127.0.0.1:8000/favicon.ico'
|
||||
target = self.path
|
||||
# Если статичный
|
||||
if 'jet' in target:
|
||||
target = f'{domain}/{target[7:]}' # http://127.0.0.1:8000 / js-check.jet
|
||||
ic(f"Modded request: {target}")
|
||||
elif 'dyn' in target:
|
||||
addr = target[target.find('://')+3:]
|
||||
addr = addr[:addr.find('/')]
|
||||
port = read(f'cached/{addr}/config.json')['port']
|
||||
target = f'http://bore.del.pw:{port}/{target[target.find("dyn")+4:]}'
|
||||
ic(f"Modded request: {target}")
|
||||
domain = target[7:]
|
||||
domain = domain[:domain.find('/')]
|
||||
|
||||
# Forward the request to the actual server
|
||||
if not exists(f'cached/{domain}'):
|
||||
self.send_error(404, f"Site not found")
|
||||
return 404
|
||||
|
||||
# Если статичный
|
||||
if read(f'cached/{domain}/config.json')['type'] == 'static':
|
||||
target = f'{base_url}/{target[7:]}' # http://127.0.0.1:8000 / js-check.jet
|
||||
# Если динамический
|
||||
elif read(f'cached/{domain}/config.json')['type'] == 'dynamic':
|
||||
port = read(f'cached/{domain}/config.json')['port']
|
||||
target = f'http://bore.del.pw:{port}/{target.replace(f"http://{domain}/", "")}'
|
||||
|
||||
ic(f"Modded request: {target}")
|
||||
|
||||
# Направление запроса по адресу
|
||||
try:
|
||||
with urllib.request.urlopen(target) as response:
|
||||
self.send_response(response.getcode())
|
||||
@ -40,16 +48,21 @@ class Proxy(http.server.SimpleHTTPRequestHandler):
|
||||
self.send_error(500, f"Error: {str(e)}")
|
||||
|
||||
def do_POST(self):
|
||||
# Log the requested domain
|
||||
ic(f"Request for: {self.path}")
|
||||
|
||||
if 'jet' in target:
|
||||
target = f'{domain}/{target[7:]}' # http://127.0.0.1:8000 / js-check.jet
|
||||
ic(f"Modded request: {target}")
|
||||
else:
|
||||
pass
|
||||
if not exists(f'cached/{domain}'):
|
||||
self.send_error(404, f"Site not found")
|
||||
return 404
|
||||
|
||||
# Forward the request to the actual server
|
||||
if read(f'cached/{domain}/config.json')['type'] == 'static':
|
||||
target = f'{base_url}/{target[7:]}' # http://127.0.0.1:8000 / js-check.jet
|
||||
elif read(f'cached/{domain}/config.json')['type'] == 'dynamic':
|
||||
port = read(f'cached/{domain}/config.json')['port']
|
||||
target = f'http://bore.del.pw:{port}/{target.replace(f"http://{domain}/", "")}'
|
||||
|
||||
ic(f"Modded request: {target}")
|
||||
|
||||
# Направление запроса по адресу
|
||||
try:
|
||||
content_length = int(self.headers['Content-Length'])
|
||||
post_data = self.rfile.read(content_length)
|
||||
@ -65,5 +78,5 @@ class Proxy(http.server.SimpleHTTPRequestHandler):
|
||||
def web_proxy():
|
||||
PORT = 8080
|
||||
with socketserver.TCPServer(("", PORT), Proxy) as httpd:
|
||||
ic(f"Serving on port {PORT}")
|
||||
print(f"HTTP proxy on port {PORT}")
|
||||
httpd.serve_forever()
|
||||
|
@ -1,71 +0,0 @@
|
||||
import http.server
|
||||
import socketserver
|
||||
import urllib.request
|
||||
import logging
|
||||
|
||||
from db import *
|
||||
domain = read()['domain']
|
||||
|
||||
# Логирование
|
||||
#logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(message)s')
|
||||
from icecream import ic
|
||||
|
||||
class Proxy(http.server.SimpleHTTPRequestHandler):
|
||||
def do_GET(self):
|
||||
# Log the requested domain
|
||||
logging.info(f"Request for: {self.path}")
|
||||
|
||||
# 'js-check.jet/favicon.ico' -> '127.0.0.1:8000/favicon.ico'
|
||||
target = self.path
|
||||
# Если статичный
|
||||
if 'jet' in target:
|
||||
target = f'{domain}/{target[7:]}' # http://127.0.0.1:8000 / js-check.jet
|
||||
logging.info(f"Modded request: {target}")
|
||||
elif 'dyn' in target:
|
||||
addr = target[target.find('://')+3:]
|
||||
addr = addr[:addr.find('/')]
|
||||
port = read(f'cached/{addr}/config.json')['port']
|
||||
target = f'http://bore.pub:{port}/{target[target.find("dyn")+4:]}'
|
||||
logging.info(f"Modded request: {target}")
|
||||
|
||||
# Forward the request to the actual server
|
||||
try:
|
||||
with urllib.request.urlopen(target) as response:
|
||||
self.send_response(response.getcode())
|
||||
self.send_header("Content-type", response.headers.get_content_type())
|
||||
self.end_headers()
|
||||
self.wfile.write(response.read())
|
||||
except Exception as e:
|
||||
self.send_error(500, f"Error: {str(e)}")
|
||||
|
||||
def do_POST(self):
|
||||
# Log the requested domain
|
||||
logging.info(f"Request for: {self.path}")
|
||||
|
||||
if 'jet' in target:
|
||||
target = f'{domain}/{target[7:]}' # http://127.0.0.1:8000 / js-check.jet
|
||||
logging.info(f"Modded request: {target}")
|
||||
else:
|
||||
pass
|
||||
|
||||
# Forward the request to the actual server
|
||||
try:
|
||||
content_length = int(self.headers['Content-Length'])
|
||||
post_data = self.rfile.read(content_length)
|
||||
req = urllib.request.Request(self.path, data=post_data, method='POST')
|
||||
with urllib.request.urlopen(req) as response:
|
||||
self.send_response(response.getcode())
|
||||
self.send_header("Content-type", response.headers.get_content_type())
|
||||
self.end_headers()
|
||||
self.wfile.write(response.read())
|
||||
except Exception as e:
|
||||
self.send_error(500, f"Error: {str(e)}")
|
||||
|
||||
#if __name__ == "__main__":
|
||||
def web_proxy():
|
||||
PORT = 8080
|
||||
with socketserver.TCPServer(("", PORT), Proxy) as httpd:
|
||||
logging.info(f"Serving on port {PORT}")
|
||||
httpd.serve_forever()
|
||||
|
||||
web_proxy()
|
Loading…
Reference in New Issue
Block a user