-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathserver.py
More file actions
920 lines (756 loc) · 30.2 KB
/
server.py
File metadata and controls
920 lines (756 loc) · 30.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
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
import fnmatch
import json
import logging
from flask import Flask, render_template, request, redirect, url_for, flash, jsonify, Response
from flask_cors import CORS
from werkzeug.utils import secure_filename as werkzeug_secure_filename
import os
from src.SendPayload import send_payload
from src.delete_payload import handle_delete_payload
from src.download_payload import handle_url_download
from src.repo_manager import update_payloads, add_repo_entry, delete_repo_entry
from src.ps5_utils import auto_replace_download0, patch_blocker
import time
import threading
import requests
import socket
from src.ftp_manager import list_ftp_directory, delete_item, create_directory, rename_item, download_file_content, upload_file_content
import io
from flask import send_file
import uuid
from src.dns_server import DNSServer
from src.backpork.core import BackporkEngine
from src.features import setup_logging, run_startup_tasks, get_logs
from src.system_manager import get_system_stats, power_control
from src.update_checker import check_for_updates
app = Flask(__name__)
app.secret_key = 'Nazky'
CORS(app)
dns_service = None
PAYLOAD_DIR = "payloads"
ELF_DIR = "payloads/elf"
DAT_DIR = "payloads/dat"
CONFIG_DIR = "static/config"
CONFIG_FILE = os.path.join(CONFIG_DIR, "settings.json")
PAYLOAD_CONFIG_FILE = os.path.join(CONFIG_DIR, "payload_config.json")
PAYLOAD_ORDER_FILE = os.path.join(CONFIG_DIR, "payload_order.json")
PAYLOAD_DELAYS_FILE = os.path.join(CONFIG_DIR, "payload_delays.json")
PAYLOAD_DELAY_FLAGS_FILE = os.path.join(CONFIG_DIR, "payload_delay_flags.json")
DNS_CONFIG_FILE = os.path.join(CONFIG_DIR, "dns_rules.json")
ALLOWED_EXTENSIONS = {'bin', 'elf', 'js', 'dat'}
url = "http://localhost:8000/send_payload"
os.makedirs(PAYLOAD_DIR, exist_ok=True)
os.makedirs(ELF_DIR, exist_ok=True)
os.makedirs(DAT_DIR, exist_ok=True)
os.makedirs(CONFIG_DIR, exist_ok=True)
os.makedirs('templates', exist_ok=True)
if not os.path.exists(CONFIG_FILE):
with open(CONFIG_FILE, 'w') as f:
json.dump({"ajb": "false", "ip": ""}, f)
def get_payload_config():
if not os.path.exists(PAYLOAD_CONFIG_FILE):
return {}
try:
with open(PAYLOAD_CONFIG_FILE, 'r') as f:
return json.load(f)
except:
return {}
def get_payload_order():
if not os.path.exists(PAYLOAD_ORDER_FILE):
return []
try:
with open(PAYLOAD_ORDER_FILE, 'r') as f:
return json.load(f)
except:
return []
def save_payload_order(order):
with open(PAYLOAD_ORDER_FILE, 'w') as f:
json.dump(order, f, indent=4)
def get_payload_delays():
if not os.path.exists(PAYLOAD_DELAYS_FILE):
return {}
try:
with open(PAYLOAD_DELAYS_FILE, 'r') as f:
return json.load(f)
except:
return {}
def save_payload_delays(data):
with open(PAYLOAD_DELAYS_FILE, 'w') as f:
json.dump(data, f, indent=4)
def save_payload_config(config):
with open(PAYLOAD_CONFIG_FILE, 'w') as f:
json.dump(config, f, indent=4)
def get_config():
if not os.path.exists(CONFIG_FILE):
return {"ajb": "false", "ip": ""}
try:
with open(CONFIG_FILE, 'r') as f:
return json.load(f)
except:
return {"ajb": "false", "ip": ""}
def update_config(key, value):
config = get_config()
config[key] = str(value)
with open(CONFIG_FILE, 'w') as f:
json.dump(config, f, indent=4)
def get_dns_rules():
if not os.path.exists(DNS_CONFIG_FILE):
return []
try:
with open(DNS_CONFIG_FILE, 'r') as f:
return json.load(f)
except:
return []
def save_dns_rules(rules):
with open(DNS_CONFIG_FILE, 'w') as f:
json.dump(rules, f, indent=4)
if dns_service:
dns_service.load_rules()
def allowed_file(filename):
return '.' in filename and \
filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
def secure_filename(filename):
import re
return re.sub(r'[^a-zA-Z0-9_.-]', '_', filename)
# suka nxj nezinau ka cia blet daryt kurwa.
def is_port_open(ip, port, timeout=2):
try:
with socket.create_connection((ip, port), timeout=timeout):
return True
except:
return False
def check_ajb():
# tikrinam ar nxj state ijungtas ar ne
last_port_state = False
while True:
try:
config = get_config()
# ajb ijungtas = pisam
if config.get("ajb", "false").lower() == "true":
ip_address = config.get("ip", "").strip()
if ip_address:
# duris atidarytos = pisam payloada
current_port_state = is_port_open(ip_address, 50000)
#bbd aiskint. pashol nxj debilai
if current_port_state and not last_port_state:
print(f"[AJB] Target {ip_address}:50000 detected OPEN. Initiating sequence...")
try:
response = requests.post(url, json={
"IP": ip_address,
"payload": ""
})
if response.status_code == 200:
print("[AJB] Sequence completed successfully.")
else:
print(f"[AJB] Error: {response.text}")
except Exception as req_e:
print(f"[AJB] Connection Error during trigger: {req_e}")
# tikrinam ar resetino tsage
# duris uzsidaro (ps issijungia or tt) , resetinam state
# kai ps injugs turetu veikt
elif not current_port_state and last_port_state:
print(f"[AJB] Target {ip_address}:50000 closed. Resetting automation state.")
# surasau paskutine duru state, kad zinot kada keistis
last_port_state = current_port_state
else:
print("[AJB] Enabled but IP missing")
else:
last_port_state = False
except Exception as e:
print("[AJB] Error:", str(e))
finally:
time.sleep(5)
@app.route("/")
def home():
return render_template('index.html')
@app.route('/api/payload_config', methods=['GET'])
def get_payload_config_route():
return jsonify(get_payload_config())
@app.route('/api/payload_config/toggle', methods=['POST'])
def toggle_payload_config():
try:
data = request.json
filename = data.get('filename')
enabled = data.get('enabled')
if not filename:
return jsonify({"error": "Missing filename"}), 400
config = get_payload_config()
config[filename] = enabled
save_payload_config(config)
return jsonify({"success": True})
except Exception as e:
return jsonify({"error": str(e)}), 500
@app.route('/api/payload_order', methods=['GET', 'POST'])
def handle_payload_order():
if request.method == 'GET':
return jsonify(get_payload_order())
if request.method == 'POST':
try:
order = request.json.get('order', [])
save_payload_order(order)
return jsonify({"success": True})
except Exception as e:
return jsonify({"error": str(e)}), 500
@app.route('/api/payload_delay', methods=['GET', 'POST'])
def handle_payload_delay():
if request.method == 'GET':
return jsonify(get_payload_delays())
if request.method == 'POST':
try:
data = request.json
filename = data.get('filename')
delay = data.get('delay')
if not filename:
return jsonify({"error": "Missing filename"}), 400
delays = get_payload_delays()
if delay is None or delay == "":
if filename in delays:
del delays[filename]
else:
delays[filename] = int(delay)
save_payload_delays(delays)
return jsonify({"success": True})
except Exception as e:
return jsonify({"error": str(e)}), 500
def get_payload_delay_flags():
if not os.path.exists(PAYLOAD_DELAY_FLAGS_FILE):
return {}
try:
with open(PAYLOAD_DELAY_FLAGS_FILE, 'r') as f:
return json.load(f)
except:
return {}
def save_payload_delay_flags(flags):
with open(PAYLOAD_DELAY_FLAGS_FILE, 'w') as f:
json.dump(flags, f, indent=4)
@app.route('/api/payload_delays', methods=['GET'])
def get_payload_delays_route():
return jsonify(get_payload_delay_flags())
@app.route('/api/payload_delays/toggle', methods=['POST'])
def toggle_payload_delay_flag():
try:
data = request.json
filename = data.get('filename')
enabled = data.get('enabled')
if not filename:
return jsonify({"error": "Missing filename"}), 400
flags = get_payload_delay_flags()
flags[filename] = enabled
save_payload_delay_flags(flags)
return jsonify({"success": True})
except Exception as e:
return jsonify({"error": str(e)}), 500
@app.route('/edit_ajb', methods=['POST'])
def edit_ajb():
new_content = request.json.get('content')
update_config("ajb", new_content)
return "Settings updated!"
@app.route('/edit_ip', methods=['POST'])
def edit_ip():
new_content = request.json.get('content')
update_config("ip", new_content)
return "Settings updated!"
@app.route('/list_payloads')
def list_files():
folder = "payloads"
payload_files = []
try:
for root, dirs, files in os.walk(folder):
for file in files:
if file.lower().endswith(('.bin', '.elf', '.js', '.dat')):
full_path = os.path.join(root, file)
rel_path = os.path.relpath(full_path, folder)
rel_path = rel_path.replace("\\", "/")
payload_files.append(rel_path)
order = get_payload_order()
weights = {name: i for i, name in enumerate(order)}
payload_files.sort(key=lambda x: weights.get(x, 9999))
return jsonify(payload_files)
except Exception as e:
return jsonify({"error": "Folder not found"}), 404
@app.route('/upload_payload', methods=['POST'])
def upload_payload():
if 'file' not in request.files:
return jsonify({'error': 'No file part'}), 400
file = request.files['file']
if file == '':
return jsonify({'error': 'No selected file'}), 400
if file and allowed_file(file.filename):
filename = secure_filename(file.filename)
if filename.lower().endswith('.elf'):
save_path = os.path.join(ELF_DIR, filename)
else:
save_path = os.path.join(PAYLOAD_DIR, filename)
try:
file.save(save_path)
print(f"[UPLOAD] Saved {filename}")
return jsonify({
'success': True,
'filename': filename,
'path': save_path
})
except Exception as e:
return jsonify({'error': str(e)}), 500
return jsonify({'error': 'File type not allowed'}), 400
@app.route('/download_payload_url', methods=['POST'])
def download_payload_url():
try:
data = request.get_json()
url = data.get('url')
print(f"[DOWNLOAD] Fetching from {url}...")
response, status_code = handle_url_download(url, PAYLOAD_DIR, ALLOWED_EXTENSIONS)
if status_code == 200:
filename = response.get('filename')
if filename:
entry = {
"type": "direct",
"url": url,
"save_path": f"payloads/{filename}"
}
add_repo_entry(filename, entry)
return jsonify(response), status_code
except Exception as e:
return jsonify({'error': str(e)}), 500
@app.route("/send_payload", methods=["POST"])
def sending_payload():
try:
data = request.get_json()
host = data.get("IP")
payload = data.get("payload")
if not host:
return jsonify({"error": "Missing IP parameter"}), 400
if not payload:
print("--- Starting Auto-Jailbreak Sequence ---")
config = get_payload_config()
print(f"[SEND] lapse.js -> {host}:50000")
result = send_payload(file_path='payloads/js/lapse.js', host=host, port=50000)
time.sleep(10)
if result:
global_config = get_config()
kstuff_enabled = global_config.get("kstuff", "true") == "true"
kstuff_result = True
if kstuff_enabled:
kstuff_path = os.path.join(ELF_DIR, 'kstuff.elf')
if not os.path.exists(kstuff_path):
kstuff_path = 'payloads/kstuff.elf'
print(f"[SEND] kstuff.elf -> {host}:9021")
kstuff_result = send_payload(file_path=kstuff_path, host=host, port=9021)
time.sleep(10)
else:
print("[SKIP] kstuff.elf (Disabled in Settings)")
if kstuff_result:
files = []
for root, _, filenames in os.walk(PAYLOAD_DIR):
for f in filenames:
rel_path = os.path.relpath(os.path.join(root, f), PAYLOAD_DIR).replace("\\", "/")
files.append(rel_path)
try:
order = get_payload_order()
weights = {name: i for i, name in enumerate(order)}
files.sort(key=lambda x: weights.get(x, 9999))
except Exception as e:
print(f"[SORT] Error sorting payloads: {e}")
active_payloads = []
for f in files:
if (config.get(f, True) and config.get(os.path.basename(f), True)):
active_payloads.append(f)
print(f"--- Active Payloads in Queue: {len(active_payloads)} ---")
for p in active_payloads:
print(f" • {p}")
print("-----------------------------------")
delay_flags = get_payload_delay_flags()
global_config = get_config()
try:
delay_time = float(global_config.get("global_delay", "5"))
except:
delay_time = 5.0
for filename in files:
if not config.get(filename, True) or not config.get(os.path.basename(filename), True):
continue
if (fnmatch.fnmatch(filename, '*.bin') or fnmatch.fnmatch(filename, '*.elf')) and 'kstuff.elf' not in filename:
print(f"[SEND] {filename} -> {host}:9021")
result = send_payload(file_path=os.path.join(PAYLOAD_DIR,filename), host=host, port=9021)
if delay_flags.get(filename, False):
print(f"[WAIT] Sleeping {delay_time}s for {filename}...")
time.sleep(delay_time)
else:
time.sleep(0.5)
if not result:
print(f"[FAIL] Could not send {filename}")
return jsonify({"error": f"Failed to send {filename}"}), 500
print("--- Auto-Jailbreak Sequence Complete ---")
return jsonify({"success": True, "message": "All payloads sent successfully"})
else:
return jsonify({"error": "Failed to send kstuff.elf"}), 500
else:
return jsonify({"error": "Failed to send lapse.js"}), 500
else:
port = 9021
if payload.lower().endswith('.js'):
port = 50000
print(f"[MANUAL] Sending {payload} -> {host}:{port}")
result = send_payload(file_path=payload, host=host, port=port)
if result:
return jsonify({"success": True, "message": "Custom payload sent"})
else:
return jsonify({"error": "Failed to send custom payload"}), 500
except Exception as e:
print(f"[ERROR] {str(e)}")
return jsonify({"error": str(e)}), 500
@app.route('/delete_payload', methods=['POST'])
def delete_payload():
try:
data = request.get_json()
print(f"[DELETE] Request: {data}")
response, status_code = handle_delete_payload(data, PAYLOAD_DIR, ALLOWED_EXTENSIONS)
return jsonify(response), status_code
except Exception as e:
return jsonify({
'error': str(e),
'message': 'Failed to delete file'
}), 500
@app.route('/list_repos')
def list_repos():
try:
repo_file = os.path.join("static", "config", "repos.json")
with open(repo_file, 'r') as f:
repos = json.load(f)
return jsonify(list(repos.keys()))
except:
return jsonify([])
@app.route('/update_repos', methods=['POST'])
def update_repos():
try:
data = request.get_json() or {}
targets = data.get('targets', ['all'])
print(f"[REPO] Updating targets: {targets}")
result = update_payloads(targets)
return jsonify(result)
except Exception as e:
return jsonify({"error": str(e)}), 500
@app.route('/settings/repos')
def repo_manager_ui():
return render_template('repos.html')
@app.route('/api/repos/list')
def get_repo_list():
try:
with open(os.path.join("static", "config", "repos.json"), 'r') as f:
return jsonify(json.load(f))
except:
return jsonify({})
@app.route('/api/repos/add', methods=['POST'])
def add_new_repo():
try:
data = request.json
name = data.get('name')
old_name = data.get('old_name')
if not name:
return jsonify({"error": "Missing name"}), 400
if old_name and old_name != name:
delete_repo_entry(old_name)
config_data = {k:v for k,v in data.items() if k not in ['name', 'old_name']}
add_repo_entry(name, config_data)
return jsonify({"success": True})
except Exception as e:
return jsonify({"error": str(e)}), 500
@app.route('/api/repos/delete', methods=['POST'])
def remove_repo():
try:
data = request.json
name = data.get('name')
delete_repo_entry(name)
return jsonify({"success": True})
except Exception as e:
return jsonify({"error": str(e)}), 500
@app.route('/edit_ftp_port', methods=['POST'])
def edit_ftp_port():
new_content = request.json.get('content')
update_config("ftp_port", new_content)
return "Settings updated!"
@app.route('/tools/update_download0', methods=['POST'])
def run_update_download0():
config = get_config()
ip = config.get("ip")
port = config.get("ftp_port", "1337")
if not ip:
return jsonify({"success": False, "message": "IP Address not set"}), 400
print(f"[TOOL] Installing download0.dat to {ip}...")
success, message = auto_replace_download0(ip, port)
if success:
return jsonify({"success": True, "message": message})
else:
return jsonify({"success": False, "message": message}), 500
@app.route('/tools/block_updates', methods=['POST'])
def run_block_updates():
config = get_config()
ip = config.get("ip")
port = config.get("ftp_port", "1337")
if not ip:
return jsonify({"success": False, "message": "IP Address not set"}), 400
print(f"[TOOL] Blocking updates on {ip}...")
success, message = patch_blocker(ip, port)
if success:
return jsonify({"success": True, "message": message})
else:
return jsonify({"success": False, "message": message}), 500
@app.route('/credits')
def credits_page():
return render_template('credits.html')
@app.route('/settings')
def settings_page():
return render_template('settings.html')
@app.route('/api/settings', methods=['GET', 'POST'])
def handle_settings():
if request.method == 'GET':
return jsonify(get_config())
if request.method == 'POST':
try:
new_settings = request.get_json()
current_config = get_config()
valid_keys = [
'ip', 'ajb', 'ftp_port', 'global_delay',
'ui_animations', 'kstuff', 'debug_mode',
'auto_update_repos', 'dns_auto_start', 'compact_mode'
]
for key in valid_keys:
if key in new_settings:
current_config[key] = str(new_settings[key])
with open(CONFIG_FILE, 'w') as f:
json.dump(current_config, f, indent=4)
return jsonify({"success": True, "message": "Settings saved successfully"})
except Exception as e:
return jsonify({"success": False, "error": str(e)}), 500
@app.route('/api/network_info')
def network_info():
try:
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.connect(("8.8.8.8", 80))
server_ip = s.getsockname()[0]
s.close()
except:
server_ip = "Unknown"
client_ip = request.remote_addr
return jsonify({
"server_ip": server_ip,
"client_ip": client_ip
})
@app.route('/ftp')
def ftp_page():
return render_template('ftp.html')
@app.route('/api/ftp/list', methods=['POST'])
def api_ftp_list():
config = get_config()
ip = config.get("ip")
port = config.get("ftp_port", "1337")
path = request.json.get('path', '/')
if not ip:
return jsonify({"success": False, "error": "IP not configured"}), 400
result = list_ftp_directory(ip, port, path)
if result['success']:
return jsonify(result)
else:
return jsonify(result), 500
@app.route('/api/ftp/download_file', methods=['POST'])
def api_ftp_download():
config = get_config()
ip = config.get("ip")
port = config.get("ftp_port", "1337")
path = request.json.get('path')
result = download_file_content(ip, port, path)
if result['success']:
if request.json.get('as_text'):
try:
return jsonify({"success": True, "content": result['content'].decode('utf-8')})
except:
return jsonify({"success": False, "error": "Could not decode file as text"})
filename = os.path.basename(path)
return send_file(
io.BytesIO(result['content']),
as_attachment=True,
download_name=filename,
mimetype='application/octet-stream'
)
return jsonify(result), 500
@app.route('/api/ftp/upload_file', methods=['POST'])
def api_ftp_upload():
config = get_config()
ip = config.get("ip")
port = config.get("ftp_port", "1337")
path = request.form.get('path')
file = request.files.get('file')
text_content = request.form.get('content')
if text_content is not None:
result = upload_file_content(ip, port, path, text_content.encode('utf-8'))
return jsonify(result)
if file:
file_content = file.read()
filename = secure_filename(file.filename)
full_path = f"{path.rstrip('/')}/{filename}"
result = upload_file_content(ip, port, full_path, file_content)
return jsonify(result)
return jsonify({"success": False, "error": "No data provided"}), 400
@app.route('/api/ftp/action', methods=['POST'])
def api_ftp_action():
config = get_config()
ip = config.get("ip")
port = config.get("ftp_port", "1337")
data = request.json
action = data.get('action')
path = data.get('path')
if action == 'delete':
return jsonify(delete_item(ip, port, path, data.get('is_dir', False)))
elif action == 'mkdir':
return jsonify(create_directory(ip, port, path))
elif action == 'rename':
return jsonify(rename_item(ip, port, path, data.get('new_path')))
return jsonify({"success": False, "error": "Invalid action"}), 400
@app.route('/dns')
def dns_page():
return render_template('dns.html')
@app.route('/api/dns/list')
def api_dns_list():
return jsonify(get_dns_rules())
@app.route('/api/dns/add', methods=['POST'])
def api_dns_add():
try:
data = request.json
name = data.get('name')
domain = data.get('domain')
target = data.get('target', '0.0.0.0')
if not name or not domain:
return jsonify({"error": "Name and Domain are required"}), 400
rules = get_dns_rules()
new_rule = {
"id": str(uuid.uuid4()),
"name": name,
"domain": domain,
"target": target
}
rules.append(new_rule)
save_dns_rules(rules)
return jsonify({"success": True})
except Exception as e:
return jsonify({"error": str(e)}), 500
@app.route('/api/dns/delete', methods=['POST'])
def api_dns_delete():
try:
rule_id = request.json.get('id')
rules = get_dns_rules()
rules = [r for r in rules if r.get('id') != rule_id]
save_dns_rules(rules)
return jsonify({"success": True})
except Exception as e:
return jsonify({"error": str(e)}), 500
@app.route('/api/dns/import', methods=['POST'])
def api_dns_import():
try:
raw_text = None
if 'file' in request.files:
file = request.files['file']
if file and file.filename:
raw_text = file.read().decode('utf-8', errors='ignore')
if not raw_text:
raw_text = request.form.get('text', '') or (request.json or {}).get('text', '')
if not raw_text or not raw_text.strip():
return jsonify({"error": "No data provided"}), 400
rules = get_dns_rules()
existing_domains = {r.get('domain', '').lower().rstrip('.') for r in rules}
imported = 0
skipped = 0
for line in raw_text.splitlines():
line = line.strip()
if not line or line.startswith('#'):
continue
domain = line.lower().rstrip('.')
if domain in existing_domains:
skipped += 1
continue
rules.append({
"id": str(uuid.uuid4()),
"name": f"Block {domain.split('.')[0]}",
"domain": domain,
"target": "0.0.0.0"
})
existing_domains.add(domain)
imported += 1
save_dns_rules(rules)
print(f"[DNS] Imported {imported} rules, skipped {skipped} duplicates")
return jsonify({"success": True, "imported": imported, "skipped": skipped})
except Exception as e:
return jsonify({"error": str(e)}), 500
@app.route('/api/dns/clear', methods=['POST'])
def api_dns_clear():
try:
save_dns_rules([])
print("[DNS] All rules cleared")
return jsonify({"success": True})
except Exception as e:
return jsonify({"error": str(e)}), 500
@app.route('/backpork')
def backpork_page():
pairs = [{"id": i, "label": f"Pair {i}"} for i in range(1, 11)]
return render_template('backpork.html', sdk_pairs=pairs)
@app.route("/api/backpork/settings", methods=['GET', 'POST'])
def handle_backpork_settings():
if request.method == 'GET':
return jsonify(BackporkEngine.load_config())
if request.method == 'POST':
BackporkEngine.save_config(request.json)
return jsonify({"success": True})
@app.route("/api/backpork/run", methods=['POST'])
def run_backpork_process():
data = request.json
return Response(BackporkEngine.run_process(data), mimetype='text/event-stream')
@app.route('/logs')
def logs_page():
return render_template('logs.html')
@app.route('/api/logs')
def api_logs():
return jsonify({"logs": get_logs()})
@app.route('/system')
def system_page():
return render_template('system.html')
@app.route('/api/system/stats')
def api_system_stats():
return jsonify(get_system_stats())
@app.route('/api/system/power', methods=['POST'])
def api_system_power():
data = request.json
action = data.get('action')
if action not in ['reboot', 'shutdown']:
return jsonify({"success": False, "error": "Invalid action"}), 400
success, message = power_control(action)
if success:
return jsonify({"success": True, "message": message})
else:
return jsonify({"success": False, "error": message}), 500
@app.route('/api/update_check')
def api_update_check():
force = request.args.get('force', 'false').lower() == 'true'
return jsonify(check_for_updates(force=force))
if __name__ == "__main__":
config = get_config()
setup_logging(config)
# nu ka dede
debug_mode = config.get("debug_mode") == "true"
is_reloader_process = os.environ.get("WERKZEUG_RUN_MAIN") == "true"
# tikiuosi kad veiks, nemanau bet ok
# debug ijungtas = tada reloaderio prcoesssasassasasasassas.
if not debug_mode or is_reloader_process:
run_startup_tasks(config)
threading.Thread(target=check_ajb, daemon=True).start()
# permetu dns kad nemaisytu ajb ir kitas funkcijas, nes gali buti problemu su threading ir flask debug mode
try:
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.connect(("1.1.1.1", 80))
local_ip = s.getsockname()[0]
s.close()
except:
local_ip = "127.0.0.1"
if config.get("dns_auto_start", "true") == "true":
print(f"--- Initializing DNS Server on {local_ip} ---")
dns_service = DNSServer(config_file=DNS_CONFIG_FILE, host_ip=local_ip)
threading.Thread(target=dns_service.start, daemon=True).start()
else:
print("[STARTUP] DNS Server disabled by settings")
app.run(host="0.0.0.0", port=8000, debug=debug_mode)