mirror of
https://github.com/Justuser3310/jetwork.git
synced 2026-06-14 06:11:02 +00:00
Compare commits
39 Commits
fa68dda1cf
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
| 9ff83b0c0a | |||
| 59aeeaac33 | |||
| 6e96b0dfb3 | |||
| f06c6f963c | |||
| 1c4a7bb11a | |||
| dfd5d61db7 | |||
| d3a25ee190 | |||
| c5a0111fab | |||
| dfc37d6ea7 | |||
| e83bee6b08 | |||
| ca1e5422a2 | |||
| 54a4692cac | |||
| a44099a9e0 | |||
| b9aaef110f | |||
| 311cde3b15 | |||
| b6652cf5d6 | |||
| 2abe6dfb87 | |||
| 5cec15dbd5 | |||
| 6ce7dbc771 | |||
| 89e34cd473 | |||
| 27eba1fbf4 | |||
| f89269a1f6 | |||
| ce628c40d6 | |||
| f09daea63e | |||
| 9d2645d7ca | |||
| 81f2b20866 | |||
| 393e02477e | |||
| 19349a0946 | |||
| ffcf047286 | |||
| ec0523d52c | |||
| e72996af3c | |||
| 78202f027e | |||
| 91678cdf48 | |||
| 07954059e2 | |||
| 4eb0143970 | |||
| c6a9b37325 | |||
| a73a370f0a | |||
| fecbc8787a | |||
| d78533c72b |
@@ -6,6 +6,13 @@ https://t.me/justuser31_chat
|
||||
<br>
|
||||
<br>
|
||||
|
||||
# 📃 Документация (ТУТ ВСЁ)
|
||||
[**>>> ДОКУМЕНТАЦИЯ <<<**](https://docs.del.pw/books/jetwork) <br>
|
||||
(Там всё есть!!!)
|
||||
|
||||
<br>
|
||||
<br>
|
||||
|
||||
## 🔼 План развития
|
||||
* Обновление диаграм
|
||||
* Обновление документации
|
||||
@@ -16,114 +23,3 @@ https://t.me/justuser31_chat
|
||||
* Реализация динамических сайтов
|
||||
* Устранение утечки памяти при поиске портов
|
||||
|
||||
<br>
|
||||
<br>
|
||||
|
||||
# 📃 Документация
|
||||
Читайте "начало работы", если хотите, чтобы последующие действия работали.
|
||||
|
||||
<br>
|
||||
|
||||
## 📋 Содержание
|
||||
- ▶️ Начало работы
|
||||
- 🌐 Установка на сервер
|
||||
- 🔓 Открытие любых портов
|
||||
- 📎 Публикация статичного сайта
|
||||
- 📎 Публикация динамичного сайта
|
||||
- 🪄 Как это работает
|
||||
|
||||
|
||||
<br>
|
||||
<br>
|
||||
|
||||
### ▶️ Начало работы
|
||||
|
||||
<br>
|
||||
|
||||
#### 🐧 Linux
|
||||
1. Установить python: `sudo apt install python3`
|
||||
2. Установить git: `sudo apt install git`
|
||||
3. Установить tar: `sudo apt install tar`
|
||||
4. Клонировать репозиторий: `git clone https://github.com/Justuser3310/jetwork.git`
|
||||
5. Запустить setup.py: `cd jetwork && python setup.py`
|
||||
6. Запустить клиент: `python main.py`
|
||||
7. Зайти на `http://127.0.0.1:5555`
|
||||
|
||||
<br>
|
||||
<br>
|
||||
|
||||
#### 🪟 Windows
|
||||
1. Установить python: https://www.python.org/downloads/release/python-3122/ (Windows installer)
|
||||
2. Установить git: https://git-scm.com/download/win (Windows setup)
|
||||
3. Клонировать репозиторий: `git clone https://github.com/Justuser3310/jetwork.git`
|
||||
4. Запустить setup.py: `cd jetwork && python setup.py`
|
||||
5. Запустить клиент: `python main.py`
|
||||
6. Зайти на `http://127.0.0.1:5555`
|
||||
|
||||
<br>
|
||||
<br>
|
||||
|
||||
#### 📱 Termux
|
||||
Следовать инструкции для Linux.
|
||||
Только заменить `sudo apt` на `pkg` в 1-3 шагах.
|
||||
|
||||
<br>
|
||||
<br>
|
||||
|
||||
### 🌐 Начало работы
|
||||
|
||||
1. Выполнить шаги в начале работы до 5 включительно (Linux) или 4 (Windows)
|
||||
2. Запустить серверный клиент: `python srv_main.py`
|
||||
( Отключён скан портов, чтобы снизить нагрузку и избежать утечки памяти )
|
||||
3. Зайти на `http://127.0.0.1:5555`
|
||||
|
||||
<br>
|
||||
<br>
|
||||
|
||||
### 🔓 Открытие любых портов
|
||||
Открыть порт 25565: \
|
||||
`python port_open.py` \
|
||||
Далее вводим `25565`
|
||||
|
||||
<br>
|
||||
<br>
|
||||
|
||||
### 📎 Публикация статичного сайта
|
||||
`python site_creator.py`
|
||||
|
||||
Далее следовать подсказкам.
|
||||
Существование index.html ОБЯЗАТЕЛЬНО.
|
||||
|
||||
<br>
|
||||
<br>
|
||||
|
||||
### 📎 Публикация динамичного сайта
|
||||
|
||||
Скоро...
|
||||
|
||||
<br>
|
||||
<br>
|
||||
|
||||
### 🪄 Как это работает
|
||||
|
||||
<br>
|
||||
|
||||
***
|
||||
#### Клиент
|
||||
|
||||

|
||||
|
||||
<br>
|
||||
|
||||
***
|
||||
#### Статичный сайт
|
||||
|
||||

|
||||
|
||||
<br>
|
||||
|
||||
***
|
||||
#### Динамичный сайт
|
||||
|
||||

|
||||
|
||||
|
||||
@@ -2,19 +2,19 @@ import os
|
||||
import json
|
||||
|
||||
if not os.path.exists('config.json'):
|
||||
db = {"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)
|
||||
|
||||
@@ -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"}
|
||||
@@ -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"}
|
||||
+13
-5
@@ -1,15 +1,23 @@
|
||||
from re import compile, sub
|
||||
domains = ['jet', 'mirror', 'me']
|
||||
|
||||
def domain_ok(domain):
|
||||
domains = ["jet", "jw", "404", "dash", "awesome", "mirror"]
|
||||
|
||||
if domain.count(".") == 1:
|
||||
if domain.split(".")[1] in domains:
|
||||
global domains
|
||||
if domain.count('.') == 1:
|
||||
if domain.split('.')[1] in domains:
|
||||
# ../some => some
|
||||
# Защита от проверки папок выше, чем нужно и др.
|
||||
regex = compile('[^a-z.-]')
|
||||
regex = compile('[^a-z0-9.-]')
|
||||
c_domain = regex.sub('', domain)
|
||||
if domain == c_domain:
|
||||
return domain
|
||||
|
||||
return False
|
||||
|
||||
def domain_list():
|
||||
global domains
|
||||
out = ''
|
||||
for i in domains:
|
||||
out += f'{i}, '
|
||||
out = out[:-2]
|
||||
return out
|
||||
|
||||
+6
-5
@@ -67,16 +67,17 @@ 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 = []
|
||||
for i in next(walk('cached/'), (None, None, []))[1]:
|
||||
res.append(html.Div([ dcc.Link(children=i, href=f'{domain}/{i}',
|
||||
conf = read(f'cached/{i}/config.json')
|
||||
res.append(html.Div([ dcc.Link(children=i, href=f'http://{i}',
|
||||
target='_blank') ], className='sites_elem'))
|
||||
return res
|
||||
|
||||
@@ -90,4 +91,4 @@ def update_search(n):
|
||||
return res
|
||||
|
||||
#app.run(debug=True, port = 5555)
|
||||
app.run(debug=False, port = 5555)
|
||||
app.run(debug=False, host = '0.0.0.0', port = 5555)
|
||||
|
||||
@@ -7,7 +7,9 @@ from multiprocessing import Process
|
||||
from network import *
|
||||
from updater import *
|
||||
from proxy import *
|
||||
from web_proxy import *
|
||||
from status import *
|
||||
|
||||
from db import *
|
||||
|
||||
#
|
||||
@@ -47,9 +49,12 @@ def main():
|
||||
# http сервер
|
||||
http = Thread(target = server_http)
|
||||
http.start()
|
||||
# сервер обработки запросов
|
||||
# Cервер обработки запросов
|
||||
srv = Thread(target = server, args=(http_port,))
|
||||
srv.start()
|
||||
# Прокси для браузера
|
||||
http_proxy = Thread(target = web_proxy)
|
||||
http_proxy.start()
|
||||
|
||||
# Стартуем авто-поиск портов и авто-обновление сайтов
|
||||
updater = Thread(target = update_demon, args=(serv_port,))
|
||||
|
||||
+21
-16
@@ -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:
|
||||
@@ -82,11 +85,10 @@ def server(http_port):
|
||||
conn.send("not_exist".encode())
|
||||
elif op[:8] == "publish_":
|
||||
data = op[8:]
|
||||
site, port = data.split("<>")
|
||||
site = domain_ok(site)
|
||||
if site:
|
||||
site, u_port = data.split("<>")
|
||||
if domain_ok(site):
|
||||
conn.send("accepted".encode())
|
||||
client(port, f"get_{site}")
|
||||
client(u_port, f"get_{site}")
|
||||
elif op == "check_all":
|
||||
try:
|
||||
sites = next(os.walk('cached/'), (None, None, []))[1]
|
||||
@@ -105,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)
|
||||
|
||||
|
||||
@@ -121,11 +123,11 @@ def recv(s, data_out):
|
||||
okay = True
|
||||
except:
|
||||
pass
|
||||
print(data)
|
||||
ic(data)
|
||||
data_out.put(data)
|
||||
|
||||
# op = operation
|
||||
def client(port, op = "ping", host = 'bore.pub'):
|
||||
def client(port, op = "ping", host = 'bore.del.pw'):
|
||||
# Если порт не определён
|
||||
if not port:
|
||||
return None
|
||||
@@ -174,8 +176,11 @@ def client(port, op = "ping", host = 'bore.pub'):
|
||||
return "old"
|
||||
|
||||
# Скачиваем файлы
|
||||
g_site = get(f"http://{host}:{str(port)}/{site}.zip")
|
||||
print('SIZE: ', g_site.headers['Content-Length']) # Размер
|
||||
try:
|
||||
g_site = get(f"http://{host}:{str(port)}/{site}.zip")
|
||||
except:
|
||||
return 'error'
|
||||
ic('SIZE: ', g_site.headers['Content-Length']) # Размер
|
||||
|
||||
with open(f"verify/{site}.zip", "wb") as f:
|
||||
f.write(g_site.content)
|
||||
@@ -212,10 +217,10 @@ def client(port, op = "ping", host = 'bore.pub'):
|
||||
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")
|
||||
@@ -233,11 +238,11 @@ def client(port, op = "ping", host = 'bore.pub'):
|
||||
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")
|
||||
|
||||
@@ -1,17 +0,0 @@
|
||||
from os import system, name
|
||||
from network import port_gen
|
||||
|
||||
port = input("Введите порт: ")
|
||||
dest = port_gen(25300, 25500)
|
||||
|
||||
print(f"\nУдалённый ПОРТ: {dest}")
|
||||
print("\n[!] Не закрывайте это окно [!]\n")
|
||||
|
||||
if name == "posix":
|
||||
system(f"./bore local {port} --to bore.pub --port {dest}")
|
||||
elif name == "nt":
|
||||
system(f"bore.exe local {port} --to bore.pub --port {dest}")
|
||||
else:
|
||||
print("Увы, вероятно Ваша ОС не поддерживается.")
|
||||
print("Завершение работы...")
|
||||
exit()
|
||||
@@ -1,24 +1,27 @@
|
||||
from os import system, name
|
||||
from os import system
|
||||
from threading import Thread
|
||||
from time import sleep
|
||||
|
||||
from status import *
|
||||
from db import read
|
||||
|
||||
global http_out ; http_out = None
|
||||
def proxy_http(port):
|
||||
global http_out
|
||||
if name == "posix":
|
||||
http_out = system(f"./bore local 8000 --to bore.pub --port {port}")
|
||||
elif name == "nt":
|
||||
http_out = system(f"bore local 8000 --to bore.pub --port {port}")
|
||||
os = read()['os']
|
||||
if os == 'Linux':
|
||||
http_out = system(f'./bore local 8000 --to bore.del.pw --port {port}')
|
||||
elif os == 'Windows' or os == 'Android':
|
||||
http_out = system(f'bore local 8000 --to bore.del.pw --port {port}')
|
||||
|
||||
global serv_out ; serv_out = None
|
||||
def proxy_serv(port):
|
||||
global serv_out
|
||||
if name == "posix":
|
||||
http_out = system(f"./bore local 8001 --to bore.pub --port {port}")
|
||||
elif name == "nt":
|
||||
http_out = system(f"bore local 8001 --to bore.pub --port {port}")
|
||||
os = read()['os']
|
||||
if os == 'Linux':
|
||||
http_out = system(f'./bore local 8001 --to bore.del.pw --port {port}')
|
||||
elif os == 'Windows' or os == 'Android':
|
||||
http_out = system(f'bore local 8001 --to bore.del.pw --port {port}')
|
||||
|
||||
|
||||
def watch_http(port):
|
||||
|
||||
@@ -2,3 +2,4 @@ cryptography
|
||||
requests
|
||||
tqdm
|
||||
dash
|
||||
icecream
|
||||
|
||||
@@ -1,51 +1,68 @@
|
||||
from os import system, name
|
||||
from os import system
|
||||
from urllib.request import urlretrieve as download
|
||||
|
||||
from db import *
|
||||
config = {}
|
||||
|
||||
# Устанавливаем зависимости
|
||||
system("pip install -r requirements.txt")
|
||||
print('''1. Linux
|
||||
2. Windows
|
||||
3. Android (Termux)''')
|
||||
raw_os = input('ОС установки >> ')
|
||||
oses = {'1': 'Linux', '2': 'Windows', '3': 'Android'}
|
||||
os = oses[raw_os]
|
||||
|
||||
# Скачиваем bore (для проброса портов)
|
||||
if name == "posix":
|
||||
download("https://github.com/ekzhang/bore/releases/download/v0.5.0/bore-v0.5.0-x86_64-unknown-linux-musl.tar.gz", "bore.tar.gz")
|
||||
system("tar -zxvf bore.tar.gz")
|
||||
system("rm -rf bore.tar.gz")
|
||||
# Записываем ОС в конфиг
|
||||
conf = read()
|
||||
conf['os'] = os
|
||||
write(conf)
|
||||
|
||||
import getpass
|
||||
user = getpass.getuser()
|
||||
if os == 'Android':
|
||||
print('''---
|
||||
Устанавливаем зависимости rust...
|
||||
---''')
|
||||
system('pkg install rust')
|
||||
|
||||
#system("mkdir ~/.streamlit")
|
||||
#with open(f"/home/{user}/.streamlit/credentials.toml", "w") as f:
|
||||
# f.write('[general]\nemail = "a@a.a"')
|
||||
#f.close()
|
||||
elif name == "nt":
|
||||
print('''---
|
||||
[1/3] Устанавливаем зависимости Python...
|
||||
---''')
|
||||
system('pip install -r requirements.txt')
|
||||
|
||||
print('''---
|
||||
[2/3] Скачиваем обратный прокси...
|
||||
---''')
|
||||
if os == 'Linux':
|
||||
download('https://github.com/ekzhang/bore/releases/download/v0.5.0/bore-v0.5.0-x86_64-unknown-linux-musl.tar.gz', 'bore.tar.gz')
|
||||
system('tar -zxvf bore.tar.gz')
|
||||
system('rm -rf bore.tar.gz')
|
||||
elif os == 'Windows':
|
||||
from shutil import unpack_archive as unpack
|
||||
download("https://github.com/ekzhang/bore/releases/download/v0.5.0/bore-v0.5.0-x86_64-pc-windows-msvc.zip", "bore.zip")
|
||||
unpack("bore.zip")
|
||||
system("del bore.zip")
|
||||
|
||||
#system("mkdir C:\\Users\\windows\\.streamlit")
|
||||
#with open("C:\\Users\\windows\\.streamlit\\credentials.toml", "w") as f:
|
||||
# f.write('[general]\nemail = "a@a.a"')
|
||||
#f.close()
|
||||
download('https://github.com/ekzhang/bore/releases/download/v0.5.0/bore-v0.5.0-x86_64-pc-windows-msvc.zip', 'bore.zip')
|
||||
unpack('bore.zip')
|
||||
system('del bore.zip')
|
||||
elif os == 'Android':
|
||||
system('pkg install bore')
|
||||
else:
|
||||
print("Увы, вероятно Ваша ОС не поддерживается.")
|
||||
print("Завершение работы...")
|
||||
print('Увы, вероятно Ваша ОС не поддерживается.')
|
||||
print('Завершение работы...')
|
||||
exit()
|
||||
|
||||
# Создаём папку для кэшированных сайтов
|
||||
system("mkdir cached")
|
||||
system("mkdir verify")
|
||||
system("mkdir mysites")
|
||||
print('''---
|
||||
[3/3] Создаём папки для работы...
|
||||
---''')
|
||||
system('mkdir cached')
|
||||
system('mkdir verify')
|
||||
system('mkdir mysites')
|
||||
|
||||
# TODO
|
||||
#print("Максимальный размер для кэшированных файлов. (в гигабайтах)")
|
||||
#print("Укажите 0 для отключения ограничения.")
|
||||
#max = input(">> ")
|
||||
#print('Максимальный размер для кэшированных файлов. (в гигабайтах)')
|
||||
#print('Укажите 0 для отключения ограничения.')
|
||||
#max = input('>> ')
|
||||
# Записываем в конфиг
|
||||
#config["max"] = max
|
||||
#config['max'] = max
|
||||
#write(config)
|
||||
|
||||
print("\nЧтобы подключится к jetwork выполните: python main.py")
|
||||
print('''
|
||||
---
|
||||
Установка завершена!
|
||||
|
||||
Чтобы подключится к jetwork выполните: python main.py
|
||||
---''')
|
||||
|
||||
+109
-114
@@ -1,4 +1,4 @@
|
||||
from os import system, mkdir
|
||||
from os import system, mkdir, walk
|
||||
from db import *
|
||||
from shutil import copyfile, make_archive, rmtree, copytree
|
||||
from tqdm import tqdm
|
||||
@@ -6,176 +6,171 @@ from time import sleep
|
||||
|
||||
from verify import *
|
||||
from network import *
|
||||
from domain_check import domain_list
|
||||
|
||||
print("(1) Создать сайт")
|
||||
print("(2) Обновить сайт")
|
||||
print("(3) Сменить тип")
|
||||
print("(4) Авто-раздача сайта")
|
||||
print("Enter для просто публикации.")
|
||||
def your_sites():
|
||||
sites = {}; num = 1
|
||||
for i in next(walk('cached/'), (None, None, []))[1]:
|
||||
sites[str(num)] = i
|
||||
print(f'{str(num)}. {i}')
|
||||
num += 1
|
||||
return sites
|
||||
|
||||
op = input(">> ")
|
||||
print('(1) Создать сайт')
|
||||
print('(2) Обновить сайт')
|
||||
print('(3) Сменить тип')
|
||||
print('(4) Авто-раздача сайта')
|
||||
print('Enter для просто публикации.')
|
||||
|
||||
if op == "1":
|
||||
op = input('>> ')
|
||||
|
||||
if op == '1':
|
||||
from domain_check import *
|
||||
|
||||
print("\nДомены: .jet, .jw, .404, .dash, .awesome, .mirror")
|
||||
domain = input("Домен сайта: ")
|
||||
print(f'\nДоступные 1 lvl домены: {domain_list()}')
|
||||
domain = input('Домен сайта: ')
|
||||
if not domain_ok(domain):
|
||||
print("Неправильный формат или домен.")
|
||||
print('Неправильный формат или домен.')
|
||||
exit()
|
||||
print("\n(1) Статичный / (2) Динамический")
|
||||
type = input("Тип: ")
|
||||
print('\n(1) Статичный / (2) Динамический')
|
||||
type = input('Тип: ')
|
||||
|
||||
# Создаём папку и ключи для подписи
|
||||
mkdir(f"mysites/{domain}")
|
||||
key_gen(f"mysites/{domain}")
|
||||
mkdir(f'mysites/{domain}')
|
||||
key_gen(f'mysites/{domain}')
|
||||
|
||||
if type == "1":
|
||||
conf = {"type": "static", "ver": 1}
|
||||
print("ПРИМЕЧАНИЕ: index.html обязателен.")
|
||||
elif type == "2":
|
||||
port = input("Порт сервера: ")
|
||||
conf = {"type": "dynamic", "ver": 1, "port": int(port)}
|
||||
write(conf, f"mysites/{domain}/config.json")
|
||||
|
||||
if type == "1":
|
||||
if type == '1':
|
||||
conf = {'type': 'static', 'ver': 1}
|
||||
print('\nПРИМЕЧАНИЕ: index.html обязателен.')
|
||||
# Создаём index.html для загрузки сайта
|
||||
with open(f"mysites/{domain}/index.html", "w") as f:
|
||||
f.write("<h1> Hello jetwork! </h1>")
|
||||
with open(f'mysites/{domain}/index.html', 'w') as f:
|
||||
f.write('<h1> Hello jetwork! </h1>')
|
||||
f.close()
|
||||
elif type == '2':
|
||||
port = input('Порт сервера: ')
|
||||
conf = {'type': 'dynamic', 'ver': 1, 'port': int(port)}
|
||||
write(conf, f'mysites/{domain}/config.json')
|
||||
|
||||
# Архивируем и создаём сигнатуру для подтверждения неизменности архива
|
||||
make_archive(f"mysites/{domain}", "zip", f"mysites/{domain}")
|
||||
sign(f"mysites/{domain}.zip", f"mysites/{domain}.key", f"mysites/{domain}")
|
||||
make_archive(f'mysites/{domain}', 'zip', f'mysites/{domain}')
|
||||
sign(f'mysites/{domain}.zip', f'mysites/{domain}.key', f'mysites/{domain}')
|
||||
|
||||
elif op == "2":
|
||||
domain = input("\nДомен сайта: ")
|
||||
if not os.path.exists(f"mysites/{domain}"):
|
||||
print("Не существует такого сайта.")
|
||||
exit()
|
||||
elif op == '2':
|
||||
print()
|
||||
sites = your_sites()
|
||||
|
||||
conf = read(f"mysites/{domain}/config.json")
|
||||
type = conf["type"]
|
||||
if type == "dynamic":
|
||||
port = input("Порт сервера: ")
|
||||
conf["port"] = port
|
||||
write(conf, f"mysites/{domain}/config.json")
|
||||
domain = sites[input('Домен сайта: ')]
|
||||
|
||||
conf = read(f'mysites/{domain}/config.json')
|
||||
type = conf['type']
|
||||
if type == 'dynamic':
|
||||
port = input('Порт сервера: ')
|
||||
conf['port'] = port
|
||||
write(conf, f'mysites/{domain}/config.json')
|
||||
|
||||
# Обновляем версию
|
||||
conf = read(f"mysites/{domain}/config.json")
|
||||
conf["ver"] = conf["ver"] + 1
|
||||
write(conf, f"mysites/{domain}/config.json")
|
||||
conf = read(f'mysites/{domain}/config.json')
|
||||
conf['ver'] = conf['ver'] + 1
|
||||
write(conf, f'mysites/{domain}/config.json')
|
||||
|
||||
# Архивируем и создаём сигнатуру для подтверждения неизменности архива
|
||||
make_archive(f"mysites/{domain}", "zip", f"mysites/{domain}")
|
||||
sign(f"mysites/{domain}.zip", f"mysites/{domain}.key", f"mysites/{domain}")
|
||||
make_archive(f'mysites/{domain}', 'zip', f'mysites/{domain}')
|
||||
sign(f'mysites/{domain}.zip', f'mysites/{domain}.key', f'mysites/{domain}')
|
||||
|
||||
elif op == "3":
|
||||
elif op == '3':
|
||||
from os import rmdir
|
||||
|
||||
domain = input("\nДомен сайта: ")
|
||||
if not os.path.exists(f"mysites/{domain}"):
|
||||
print("Не существует такого сайта.")
|
||||
exit()
|
||||
print()
|
||||
sites = your_sites()
|
||||
domain = sites[input('Домен сайта: ')]
|
||||
|
||||
print("\n(1) Статичный / (2) Динамический")
|
||||
type = input("Тип: ")
|
||||
print('\n(1) Статичный / (2) Динамический')
|
||||
type = input('Тип: ')
|
||||
|
||||
if type == "1":
|
||||
conf = read(f"mysites/{domain}/config.json")
|
||||
conf["type"] = "static"
|
||||
conf.pop("port")
|
||||
with open(f"mysites/{domain}/index.html", "w") as f:
|
||||
f.write("<h1> Hello jetwork! </h1>")
|
||||
if type == '1':
|
||||
conf = read(f'mysites/{domain}/config.json')
|
||||
conf['type'] = 'static'
|
||||
conf.pop('port')
|
||||
with open(f'mysites/{domain}/index.html', 'w') as f:
|
||||
f.write('<h1> Hello jetwork! </h1>')
|
||||
f.close()
|
||||
elif type == "2":
|
||||
conf = read(f"mysites/{domain}/config.json")
|
||||
port = input("Порт сервера: ")
|
||||
elif type == '2':
|
||||
conf = read(f'mysites/{domain}/config.json')
|
||||
port = input('Порт сервера: ')
|
||||
|
||||
clean = input("Удалить все лишние файлы сайта (y/n): ")
|
||||
if clean == "y":
|
||||
clean = input('Удалить все лишние файлы сайта (y/n): ')
|
||||
if clean == 'y':
|
||||
# Удаляем папку, сохраняем конфиг и копируем публичный ключ
|
||||
rmtree(f"mysites/{domain}")
|
||||
rmtree(f'mysites/{domain}')
|
||||
sleep(0.1)
|
||||
system(f"mkdir mysites/{domain}")
|
||||
system(f'mkdir mysites/{domain}')
|
||||
|
||||
conf["type"] = "dynamic"
|
||||
conf["port"] = int(port)
|
||||
write(conf, f"mysites/{domain}/config.json")
|
||||
conf['type'] = 'dynamic'
|
||||
conf['port'] = int(port)
|
||||
write(conf, f'mysites/{domain}/config.json')
|
||||
|
||||
# Обновляем версию
|
||||
conf = read(f"mysites/{domain}/config.json")
|
||||
conf["ver"] = conf["ver"] + 1
|
||||
write(conf, f"mysites/{domain}/config.json")
|
||||
conf = read(f'mysites/{domain}/config.json')
|
||||
conf['ver'] = conf['ver'] + 1
|
||||
write(conf, f'mysites/{domain}/config.json')
|
||||
|
||||
# Архивируем и создаём сигнатуру для подтверждения неизменности архива
|
||||
make_archive(f"mysites/{domain}", "zip", f"mysites/{domain}")
|
||||
sign(f"mysites/{domain}.zip", f"mysites/{domain}.key", f"mysites/{domain}")
|
||||
make_archive(f'mysites/{domain}', 'zip', f'mysites/{domain}')
|
||||
sign(f'mysites/{domain}.zip', f'mysites/{domain}.key', f'mysites/{domain}')
|
||||
|
||||
elif op == "4":
|
||||
domain = input("\nДомен сайта: ")
|
||||
if not os.path.exists(f"mysites/{domain}"):
|
||||
print("Не существует такого сайта.")
|
||||
exit()
|
||||
elif op == '4':
|
||||
print()
|
||||
sites = your_sites()
|
||||
domain = sites[input('Домен сайта: ')]
|
||||
|
||||
print("\nВведите ваш порт сервера (при запуске main.py)")
|
||||
serv_port = int(input(">> "))
|
||||
http_port = client(serv_port, f"is_{domain}")
|
||||
serv_port = int( read()['our_port'] )
|
||||
http_port = client(serv_port, f'is_{domain}')
|
||||
|
||||
print("\nСтарт вечной раздачи...")
|
||||
print('\nСтарт вечной раздачи...')
|
||||
while True:
|
||||
ports = port_check(serv_port)
|
||||
sleep(1)
|
||||
for port in tqdm(ports):
|
||||
client(port, f"publish_{domain}<>{http_port}")
|
||||
client(port, f'publish_{domain}<>{http_port}')
|
||||
sleep(5)
|
||||
|
||||
elif op == "":
|
||||
domain = input("\nДомен сайта: ")
|
||||
if not os.path.exists(f"mysites/{domain}"):
|
||||
print("Не существует такого сайта.")
|
||||
exit()
|
||||
pub = "y"
|
||||
host = 'bore.del.pw'
|
||||
# Проверяем тип сайта
|
||||
type = read(f'mysites//{domain}/config.json')['type']
|
||||
# Если динамический - вставляем спец страницу
|
||||
if type == 'dynamic':
|
||||
port = read(f'mysites//{domain}/config.json')['port']
|
||||
with open(f'mysites//{domain}/index.html', 'w') as f:
|
||||
f.write(f"<iframe src='http://{host}:{port}' style='position:fixed; top:0; left:0; bottom:0; right:0; width:100%; height:100%; border:none; margin:0; padding:0; overflow:hidden; z-index:999999;'></iframe>")
|
||||
f.close()
|
||||
|
||||
|
||||
# Копируем файлы из mysites в cached
|
||||
try:
|
||||
rmtree(f"cached/{domain}")
|
||||
rmtree(f'cached/{domain}')
|
||||
except:
|
||||
pass
|
||||
copytree(f"mysites/{domain}", f"cached/{domain}")
|
||||
copyfile(f"mysites/{domain}.pem", f"cached/{domain}.pem")
|
||||
copyfile(f"mysites/{domain}.sig", f"cached/{domain}.sig")
|
||||
copyfile(f"mysites/{domain}.zip", f"cached/{domain}.zip")
|
||||
copytree(f'mysites/{domain}', f'cached/{domain}')
|
||||
copyfile(f'mysites/{domain}.pem', f'cached/{domain}.pem')
|
||||
copyfile(f'mysites/{domain}.sig', f'cached/{domain}.sig')
|
||||
copyfile(f'mysites/{domain}.zip', f'cached/{domain}.zip')
|
||||
|
||||
|
||||
host = "jetwork.404.mn"
|
||||
# Проверяем тип сайта
|
||||
type = read(f"cached/{domain}/config.json")["type"]
|
||||
# Если динамический
|
||||
if type == "dynamic":
|
||||
port = read(f"cached/{domain}/config.json")["port"]
|
||||
with open(f"cached/{domain}/index.html", "w") as f:
|
||||
f.write(f'<iframe src="http://{host}:{port}" style="position:fixed; top:0; left:0; bottom:0; right:0; width:100%; height:100%; border:none; margin:0; padding:0; overflow:hidden; z-index:999999;"></iframe>')
|
||||
f.close()
|
||||
if op != '':
|
||||
print('\nОпубликовать сайт?')
|
||||
pub = input('y/n >> ')
|
||||
|
||||
|
||||
if op != "":
|
||||
print("Опубликовать сайт?")
|
||||
pub = input("y/n >> ")
|
||||
|
||||
if pub == "n":
|
||||
if pub == 'n':
|
||||
exit()
|
||||
|
||||
print("Введите ваш порт сервера (при запуске main.py)")
|
||||
serv_port = int(input(">> "))
|
||||
http_port = client(serv_port, f"is_{domain}")
|
||||
serv_port = int( read()['our_port'] )
|
||||
http_port = client(serv_port, f'is_{domain}')
|
||||
|
||||
print("Получаем все порты...")
|
||||
print('Получаем все порты...')
|
||||
ports = port_check(serv_port)
|
||||
|
||||
print(ports)
|
||||
|
||||
print("Публикуем сайт...")
|
||||
print('Публикуем сайт...')
|
||||
for port in tqdm(ports):
|
||||
client(port, f"publish_{domain}<>{http_port}")
|
||||
client(port, f'publish_{domain}<>{http_port}')
|
||||
|
||||
@@ -0,0 +1,10 @@
|
||||
while true
|
||||
do
|
||||
killall python
|
||||
sleep 1s
|
||||
killall python #Чтоб наверняка
|
||||
sleep 60s # Ждём, чтобы не было ошибки при перезапуске "данный порт уже используется"
|
||||
|
||||
nohup python srv_main.py &
|
||||
sleep 6h
|
||||
done
|
||||
@@ -0,0 +1,79 @@
|
||||
from dash import Dash, dcc, html, Input, Output, callback
|
||||
app = Dash(__name__, title='Jetwork', update_title=None)
|
||||
|
||||
from db import *
|
||||
from status import *
|
||||
|
||||
from os import walk
|
||||
from os import system as sys
|
||||
from platform import system
|
||||
from threading import Thread
|
||||
|
||||
app.layout = html.Div([ html.Div([
|
||||
|
||||
dcc.ConfirmDialog(id='shut_mess', message='Ты совсем гений?'),
|
||||
html.Button("Выключить клиент", className='off_btn', n_clicks=0, id='off_btn'),
|
||||
html.Div([], id='our_port', className='our_port'),
|
||||
html.Div([], id='servers', className='servers'),
|
||||
html.Div([], id='sites', className='sites'),
|
||||
dcc.Dropdown(options=[], id='search', placeholder='Поиск...'),
|
||||
|
||||
dcc.Interval(id='interval-component', interval=1*1000, n_intervals=0)
|
||||
|
||||
], className='main')], className='content')
|
||||
|
||||
|
||||
# Кнопка выключения
|
||||
@callback(
|
||||
Output('shut_mess', 'displayed'),
|
||||
Input('off_btn', 'n_clicks'),
|
||||
prevent_initial_call=True
|
||||
)
|
||||
def shut_btn(n_clicks):
|
||||
return True
|
||||
|
||||
# Обновление нашего порта (зачем?)
|
||||
@callback(Output('our_port', 'children'),
|
||||
Input('interval-component', 'n_intervals'))
|
||||
def update_our_port(n):
|
||||
return f"Ваш порт: {read()['our_port']}"
|
||||
|
||||
# Обновление доступных узлов
|
||||
@callback(Output('servers', 'children'),
|
||||
Input('interval-component', 'n_intervals'))
|
||||
def update_servers(n):
|
||||
res = []
|
||||
for i in read()['ports']:
|
||||
res.append(html.Div([i], className='serv_elem'))
|
||||
return res
|
||||
|
||||
# Обновление доступных сайтов
|
||||
@callback(Output('sites', 'children'),
|
||||
Input('interval-component', 'n_intervals'),
|
||||
Input('search', 'value'))
|
||||
def update_sites(n, s_val):
|
||||
# Префикс
|
||||
base_url = read()['base_url']
|
||||
# Если есть элемент в поиске
|
||||
if s_val:
|
||||
return html.Div([ dcc.Link(children=i, href=f'{base_url}/{s_val}',
|
||||
target='_blank') ], className='sites_elem')
|
||||
|
||||
res = []
|
||||
for i in next(walk('cached/'), (None, None, []))[1]:
|
||||
conf = read(f'cached/{i}/config.json')
|
||||
res.append(html.Div([ dcc.Link(children=i, href=f'http://{i}',
|
||||
target='_blank') ], className='sites_elem'))
|
||||
return res
|
||||
|
||||
# Обновление доступных сайтов в поиске
|
||||
@callback(Output('search', 'options'),
|
||||
Input('interval-component', 'n_intervals'))
|
||||
def update_search(n):
|
||||
res = []
|
||||
for i in next(walk('cached/'), (None, None, []))[1]:
|
||||
res.append(i)
|
||||
return res
|
||||
|
||||
#app.run(debug=True, port = 5555)
|
||||
app.run(debug=False, host = '0.0.0.0', port = 5555)
|
||||
+9
-3
@@ -7,7 +7,9 @@ from multiprocessing import Process
|
||||
from network import *
|
||||
from updater import *
|
||||
from proxy import *
|
||||
from web_proxy import *
|
||||
from status import *
|
||||
|
||||
from db import *
|
||||
|
||||
#
|
||||
@@ -21,7 +23,7 @@ def main():
|
||||
print('Проверка обновлений...')
|
||||
system('git pull')
|
||||
print('Перезагрузка скрипта...')
|
||||
system('python main.py updated')
|
||||
system('python srv_main.py updated')
|
||||
exit()
|
||||
print('\nУспешно перезагружено!')
|
||||
|
||||
@@ -55,15 +57,19 @@ def main():
|
||||
#updater = Thread(target = update_demon, args=(serv_port,))
|
||||
#updater.start()
|
||||
|
||||
# Прокси для браузера
|
||||
http_proxy = Thread(target = web_proxy)
|
||||
http_proxy.start()
|
||||
|
||||
# Стартуем интерфейс
|
||||
system('python interface.py')
|
||||
system('python srv_interface.py')
|
||||
|
||||
if __name__ == '__main__':
|
||||
# Запускаем главный процесс, чтобы потом легко убить его
|
||||
p = Process(target=main)
|
||||
p.start()
|
||||
|
||||
status_set(True) # Устанавливаем статус, что программа работает
|
||||
status_set('work') # Устанавливаем статус, что программа работает
|
||||
|
||||
st = status_check()
|
||||
while st:
|
||||
|
||||
@@ -1,8 +0,0 @@
|
||||
#
|
||||
# Установка/проверка статуса завершения
|
||||
#
|
||||
|
||||
import os
|
||||
|
||||
if not os.path.exists('status'):
|
||||
|
||||
@@ -0,0 +1,3 @@
|
||||
killall ./srv.sh
|
||||
killall python
|
||||
killall bore
|
||||
+7
-4
@@ -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)
|
||||
|
||||
@@ -0,0 +1,82 @@
|
||||
import http.server
|
||||
import socketserver
|
||||
import urllib.request
|
||||
import logging
|
||||
from os.path import exists
|
||||
|
||||
from db import *
|
||||
base_url = read()['base_url']
|
||||
|
||||
# Логирование
|
||||
from icecream import ic
|
||||
ic.disable() # Выключить отладку
|
||||
|
||||
class Proxy(http.server.SimpleHTTPRequestHandler):
|
||||
# Отключение всех сообщений (чтобы не забивать вывод)
|
||||
def log_message(self, format, *args):
|
||||
pass
|
||||
def do_GET(self):
|
||||
ic(f"Request for: {self.path}")
|
||||
|
||||
# 'js-check.jet/favicon.ico' -> '127.0.0.1:8000/favicon.ico'
|
||||
target = self.path
|
||||
domain = target[7:]
|
||||
domain = domain[:domain.find('/')]
|
||||
|
||||
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())
|
||||
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):
|
||||
ic(f"Request for: {self.path}")
|
||||
|
||||
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:
|
||||
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)}")
|
||||
|
||||
def web_proxy():
|
||||
PORT = 8080
|
||||
with socketserver.TCPServer(("", PORT), Proxy) as httpd:
|
||||
print(f"HTTP proxy on port {PORT}")
|
||||
httpd.serve_forever()
|
||||
Reference in New Issue
Block a user