forked from bunkerity/bunkerweb
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.py
executable file
·1219 lines (1033 loc) · 44.4 KB
/
main.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import os
from shutil import rmtree, copytree, chown
from logging import getLogger, INFO, ERROR, StreamHandler, Formatter
from flask import (
Flask,
flash,
jsonify,
redirect,
render_template,
request,
send_file,
url_for,
)
from flask_login import LoginManager, login_required, login_user, logout_user
from flask_wtf.csrf import CSRFProtect, CSRFError
from json import JSONDecodeError, load as json_load
from bs4 import BeautifulSoup
from datetime import datetime, timezone
from dateutil.parser import parse as dateutil_parse
from requests import get
from requests.utils import default_headers
from sys import path as sys_path, exit as sys_exit
from copy import deepcopy
from docker import DockerClient
from docker.errors import (
NotFound as docker_NotFound,
APIError as docker_APIError,
DockerException,
)
from uuid import uuid4
from time import time
import tarfile
import zipfile
from ui.src.ConfigFiles import ConfigFiles
from ui.src.Config import Config
from ui.src.ReverseProxied import ReverseProxied
from ui.src.User import User
from ui.utils import (
check_settings,
env_to_summary_class,
form_plugin_gen,
form_service_gen,
form_service_gen_multiple,
form_service_gen_multiple_values,
gen_folders_tree_html,
get_variables,
path_to_dict,
)
sys_path.append("/opt/bunkerweb/utils")
from ui.src.Instances import Instances
from api.API import API
from utils.ApiCaller import ApiCaller
# Set up logger
logger = getLogger("flask_app")
logger.setLevel(INFO)
# create console handler with a higher log level
ch = StreamHandler()
ch.setLevel(ERROR)
# create formatter and add it to the handlers
formatter = Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
ch.setFormatter(formatter)
# add the handlers to logger
logger.addHandler(ch)
# Flask app
app = Flask(
__name__,
static_url_path="/",
static_folder="static",
template_folder="templates",
)
app.wsgi_app = ReverseProxied(app.wsgi_app)
# Set variables and instantiate objects
vars = get_variables()
if not vars["FLASK_ENV"] == "development" and vars["ADMIN_PASSWORD"] == "changeme":
logger.error("Please change the default admin password.")
sys_exit(1)
if not vars["FLASK_ENV"] == "development" and (
vars["ABSOLUTE_URI"].endswith("/changeme/")
or vars["ABSOLUTE_URI"].endswith("/changeme")
):
logger.error("Please change the default URL.")
sys_exit(1)
with open("/opt/bunkerweb/tmp/ui.pid", "w") as f:
f.write(str(os.getpid()))
login_manager = LoginManager()
login_manager.init_app(app)
login_manager.login_view = "login"
user = User(vars["ADMIN_USERNAME"], vars["ADMIN_PASSWORD"])
api_caller = ApiCaller()
PLUGIN_KEYS = [
"id",
"order",
"name",
"description",
"version",
"settings",
]
try:
docker_client: DockerClient = DockerClient(base_url=vars["DOCKER_HOST"])
except (docker_APIError, DockerException):
docker_client = None
if docker_client:
apis: list[API] = []
for container in docker_client.containers.list(filters={"label": "bunkerweb.UI"}):
env_variables = {
x[0]: x[1]
for x in [env.split("=") for env in container.attrs["Config"]["Env"]]
}
apis.append(
API(
f"http://{container.name}:{env_variables.get('API_HTTP_PORT', '5000')}",
env_variables.get("API_SERVER_NAME", "bwapi"),
)
)
api_caller._set_apis(apis)
try:
app.config.update(
DEBUG=True,
SECRET_KEY=vars["FLASK_SECRET"],
ABSOLUTE_URI=vars["ABSOLUTE_URI"],
INSTANCES=Instances(docker_client),
CONFIG=Config(),
CONFIGFILES=ConfigFiles(),
SESSION_COOKIE_DOMAIN=vars["ABSOLUTE_URI"]
.replace("http://", "")
.replace("https://", "")
.split("/")[0],
WTF_CSRF_SSL_STRICT=False,
USER=user,
SEND_FILE_MAX_AGE_DEFAULT=86400,
)
except FileNotFoundError as e:
logger.error(repr(e), e.filename)
sys_exit(1)
# Declare functions for jinja2
app.jinja_env.globals.update(env_to_summary_class=env_to_summary_class)
app.jinja_env.globals.update(form_plugin_gen=form_plugin_gen)
app.jinja_env.globals.update(form_service_gen=form_service_gen)
app.jinja_env.globals.update(form_service_gen_multiple=form_service_gen_multiple)
app.jinja_env.globals.update(
form_service_gen_multiple_values=form_service_gen_multiple_values
)
app.jinja_env.globals.update(gen_folders_tree_html=gen_folders_tree_html)
app.jinja_env.globals.update(check_settings=check_settings)
@login_manager.user_loader
def load_user(user_id):
return User(user_id, vars["ADMIN_PASSWORD"])
# CSRF protection
csrf = CSRFProtect()
csrf.init_app(app)
@app.errorhandler(CSRFError)
def handle_csrf_error(e):
"""
It takes a CSRFError exception as an argument, and returns a Flask response
:param e: The exception object
:return: A template with the error message and a 401 status code.
"""
logout_user()
flash("Wrong CSRF token !", "error")
return render_template("login.html"), 403
@app.route("/")
def index():
return redirect(url_for("login"))
@app.route("/loading")
@login_required
def loading():
next_url = request.values.get("next")
return render_template("loading.html", next=next_url)
@app.route("/home")
@login_required
def home():
"""
It returns the home page
:return: The home.html template is being rendered with the following variables:
check_version: a boolean indicating whether the local version is the same as the remote version
remote_version: the remote version
version: the local version
instances_number: the number of instances
services_number: the number of services
posts: a list of posts
"""
r = get(
"https://raw.githubusercontent.com/bunkerity/bunkerweb/master/VERSION",
)
remote_version = None
if r.status_code == 200:
remote_version = r.text.strip()
with open("/opt/bunkerweb/VERSION", "r") as f:
version = f.read().strip()
headers = default_headers()
headers.update({"User-Agent": "bunkerweb-ui"})
r = get(
"https://www.bunkerity.com/wp-json/wp/v2/posts",
headers=headers,
)
formatted_posts = None
if r.status_code == 200:
posts = r.json()
formatted_posts = []
for post in posts[:5]:
formatted_posts.append(
{
"link": post["link"],
"title": post["title"]["rendered"],
"description": BeautifulSoup(
post["content"]["rendered"][
post["content"]["rendered"].index("<em>")
+ 4 : post["content"]["rendered"].index("</em>")
],
features="html.parser",
).get_text()[:256]
+ ("..." if len(post["content"]["rendered"]) > 256 else ""),
"date": dateutil_parse(post["date"]).strftime("%B %d, %Y"),
"image_url": post["yoast_head_json"]["og_image"][0]["url"].replace(
"wwwdev", "www"
),
"reading_time": post["yoast_head_json"]["twitter_misc"][
"Est. reading time"
],
}
)
instances_number = len(app.config["INSTANCES"].get_instances())
services_number = len(app.config["CONFIG"].get_services())
return render_template(
"home.html",
check_version=not remote_version or version == remote_version,
remote_version=remote_version,
version=version,
instances_number=instances_number,
services_number=services_number,
posts=formatted_posts,
)
@app.route("/instances", methods=["GET", "POST"])
@login_required
def instances():
# Manage instances
if request.method == "POST":
# Check operation
if not "operation" in request.form or not request.form["operation"] in [
"reload",
"start",
"stop",
"restart",
]:
flash("Missing operation parameter on /instances.", "error")
return redirect(url_for("loading", next=url_for("instances")))
# Check that all fields are present
if not "INSTANCE_ID" in request.form:
flash("Missing INSTANCE_ID parameter.", "error")
return redirect(url_for("loading", next=url_for("instances")))
# Do the operation
if request.form["operation"] == "reload":
operation = app.config["INSTANCES"].reload_instance(
request.form["INSTANCE_ID"]
)
elif request.form["operation"] == "start":
operation = app.config["INSTANCES"].start_instance(
request.form["INSTANCE_ID"]
)
elif request.form["operation"] == "stop":
operation = app.config["INSTANCES"].stop_instance(
request.form["INSTANCE_ID"]
)
elif request.form["operation"] == "restart":
operation = app.config["INSTANCES"].restart_instance(
request.form["INSTANCE_ID"]
)
if operation.startswith("Can't"):
flash(operation, "error")
else:
flash(operation)
return redirect(url_for("loading", next=url_for("instances")))
# Display instances
instances = app.config["INSTANCES"].get_instances()
return render_template("instances.html", title="Instances", instances=instances)
@app.route("/services", methods=["GET", "POST"])
@login_required
def services():
if request.method == "POST":
# Check operation
if not "operation" in request.form or not request.form["operation"] in [
"new",
"edit",
"delete",
]:
flash("Missing operation parameter on /services.", "error")
return redirect(url_for("loading", next=url_for("services")))
# Check variables
variables = deepcopy(request.form.to_dict())
del variables["csrf_token"]
if (
not "OLD_SERVER_NAME" in request.form
and request.form["operation"] == "edit"
):
flash("Missing OLD_SERVER_NAME parameter.", "error")
return redirect(url_for("loading", next=url_for("services")))
if request.form["operation"] in ("new", "edit"):
del variables["operation"]
if request.form["operation"] == "edit":
del variables["OLD_SERVER_NAME"]
# Edit check fields and remove already existing ones
config = app.config["CONFIG"].get_config()
for variable in deepcopy(variables):
if variables[variable] == "on":
variables[variable] = "yes"
elif variables[variable] == "off":
variables[variable] = "no"
if (
request.form["operation"] == "edit"
and variable != "SERVER_NAME"
and variables[variable] == config.get(variable, None)
or not variables[variable].strip()
):
del variables[variable]
if not variables:
flash(
f"{variables['SERVER_NAME'].split(' ')[0]} was not edited because no values were changed."
)
return redirect(url_for("loading", next=url_for("services")))
error = app.config["CONFIG"].check_variables(variables)
if error:
return redirect(url_for("loading", next=url_for("services")))
# Delete
elif request.form["operation"] == "delete":
if not "SERVER_NAME" in request.form:
flash("Missing SERVER_NAME parameter.", "error")
return redirect(url_for("loading", next=url_for("services")))
error = app.config["CONFIG"].check_variables(
{"SERVER_NAME": request.form["SERVER_NAME"]}
)
if error:
return redirect(url_for("loading", next=url_for("services")))
error = 0
# Do the operation
if request.form["operation"] == "new":
operation, error = app.config["CONFIG"].new_service(variables)
elif request.form["operation"] == "edit":
operation = app.config["CONFIG"].edit_service(
request.form["OLD_SERVER_NAME"], variables
)
elif request.form["operation"] == "delete":
operation, error = app.config["CONFIG"].delete_service(
request.form["SERVER_NAME"]
)
if error:
flash(operation, "error")
return redirect(url_for("loading", next=url_for("services")))
flash(operation)
# Reload instances
_reloads = app.config["INSTANCES"].reload_instances()
if not _reloads:
for _reload in _reloads:
flash(f"Reload failed for the instance {_reload}", "error")
else:
flash("Successfully reloaded instances")
return redirect(url_for("loading", next=url_for("services")))
# Display services
services = app.config["CONFIG"].get_services()
return render_template("services.html", services=services)
@app.route("/global_config", methods=["GET", "POST"])
@login_required
def global_config():
if request.method == "POST":
# Check variables
variables = deepcopy(request.form.to_dict())
del variables["csrf_token"]
# Edit check fields and remove already existing ones
config = app.config["CONFIG"].get_config()
for variable in deepcopy(variables):
if variables[variable] == "on":
variables[variable] = "yes"
elif variables[variable] == "off":
variables[variable] = "no"
if (
variables[variable] == config.get(variable, None)
or not variables[variable].strip()
):
del variables[variable]
if not variables:
flash(
f"The global configuration was not edited because no values were changed."
)
return redirect(url_for("loading", next=url_for("global_config")))
error = app.config["CONFIG"].check_variables(variables, True)
if error:
return redirect(url_for("loading", next=url_for("global_config")))
error = 0
# Do the operation
operation = app.config["CONFIG"].edit_global_conf(variables)
if error:
flash(operation, "error")
return redirect(url_for("loading", next=url_for("global_config")))
flash(operation)
# Reload instances
_reloads = app.config["INSTANCES"].reload_instances()
if not _reloads:
for _reload in _reloads:
flash(f"Reload failed for the instance {_reload}", "error")
else:
flash("Successfully reloaded instances")
return redirect(url_for("loading", next=url_for("global_config")))
# Display services
services = app.config["CONFIG"].get_services()
return render_template("global_config.html", services=services)
@app.route("/configs", methods=["GET", "POST"])
@login_required
def configs():
if request.method == "POST":
operation = ""
# Check operation
if not "operation" in request.form or not request.form["operation"] in [
"new",
"edit",
"delete",
]:
flash("Missing operation parameter on /configs.", "error")
return redirect(url_for("loading", next=url_for("configs")))
# Check variables
variables = deepcopy(request.form.to_dict())
del variables["csrf_token"]
operation = app.config["CONFIGFILES"].check_path(variables["path"])
if operation:
flash(operation, "error")
return redirect(url_for("loading", next=url_for("configs"))), 500
if request.form["operation"] in ("new", "edit"):
if not app.config["CONFIGFILES"].check_name(variables["name"]):
flash(
f"Invalid {variables['type']} name. (Can only contain numbers, letters, underscores and hyphens (min 4 characters and max 32))",
"error",
)
return redirect(url_for("loading", next=url_for("configs")))
if variables["type"] == "file":
variables["name"] = f"{variables['name']}.conf"
variables["content"] = BeautifulSoup(
variables["content"], "html.parser"
).get_text()
if request.form["operation"] == "new":
if variables["type"] == "folder":
operation, error = app.config["CONFIGFILES"].create_folder(
variables["path"], variables["name"]
)
elif variables["type"] == "file":
operation, error = app.config["CONFIGFILES"].create_file(
variables["path"], variables["name"], variables["content"]
)
elif request.form["operation"] == "edit":
if variables["type"] == "folder":
operation, error = app.config["CONFIGFILES"].edit_folder(
variables["path"], variables["name"]
)
elif variables["type"] == "file":
operation, error = app.config["CONFIGFILES"].edit_file(
variables["path"], variables["name"], variables["content"]
)
if error:
flash(operation, "error")
return redirect(url_for("loading", next=url_for("configs")))
else:
operation, error = app.config["CONFIGFILES"].delete_path(variables["path"])
if error:
flash(operation, "error")
return redirect(url_for("loading", next=url_for("configs")))
flash(operation)
# Reload instances
_reloads = app.config["INSTANCES"].reload_instances()
if not _reloads:
for _reload in _reloads:
flash(f"Reload failed for the instance {_reload}", "error")
else:
flash("Successfully reloaded instances")
return redirect(url_for("loading", next=url_for("configs")))
return render_template(
"configs.html", folders=[path_to_dict("/opt/bunkerweb/configs")]
)
@app.route("/plugins", methods=["GET", "POST"])
@login_required
def plugins():
if request.method == "POST":
operation = ""
error = 0
if "operation" in request.form and request.form["operation"] == "delete":
# Check variables
variables = deepcopy(request.form.to_dict())
del variables["csrf_token"]
operation = app.config["CONFIGFILES"].check_path(
variables["path"], "/opt/bunkerweb/plugins/"
)
if operation:
flash(operation, "error")
return redirect(url_for("loading", next=url_for("plugins"))), 500
operation, error = app.config["CONFIGFILES"].delete_path(variables["path"])
if error:
flash(operation, "error")
return redirect(url_for("loading", next=url_for("plugins")))
else:
if not os.path.exists("/opt/bunkerweb/tmp/ui") or not os.listdir(
"/opt/bunkerweb/tmp/ui"
):
flash("Please upload new plugins to reload plugins", "error")
return redirect(url_for("loading", next=url_for("plugins")))
for file in os.listdir("/opt/bunkerweb/tmp/ui"):
if not os.path.isfile(f"/opt/bunkerweb/tmp/ui/{file}"):
continue
folder_name = ""
temp_folder_name = file.split(".")[0]
try:
if file.endswith(".zip"):
try:
with zipfile.ZipFile(
f"/opt/bunkerweb/tmp/ui/{file}"
) as zip_file:
try:
zip_file.getinfo("plugin.json")
zip_file.extractall(
f"/opt/bunkerweb/tmp/ui/{temp_folder_name}"
)
with open(
f"/opt/bunkerweb/tmp/ui/{temp_folder_name}/plugin.json",
"r",
) as f:
plugin_file = json_load(f)
if not all(
key in plugin_file.keys() for key in PLUGIN_KEYS
):
raise ValueError
folder_name = plugin_file["id"]
if not app.config["CONFIGFILES"].check_name(
folder_name
):
error = 1
flash(
f"Invalid plugin name for {temp_folder_name}. (Can only contain numbers, letters, underscores and hyphens (min 4 characters and max 32))",
"error",
)
raise Exception
if os.path.exists(
f"/opt/bunkerweb/plugins/{folder_name}"
):
raise FileExistsError
copytree(
f"/opt/bunkerweb/tmp/ui/{temp_folder_name}",
f"/opt/bunkerweb/plugins/{folder_name}",
)
except KeyError:
zip_file.extractall(
f"/opt/bunkerweb/tmp/ui/{temp_folder_name}"
)
dirs = [
d
for d in os.listdir(
f"/opt/bunkerweb/tmp/ui/{temp_folder_name}"
)
if os.path.isdir(
f"/opt/bunkerweb/tmp/ui/{temp_folder_name}/{d}"
)
]
if (
not dirs
or len(dirs) > 1
or not os.path.exists(
f"/opt/bunkerweb/tmp/ui/{temp_folder_name}/{dirs[0]}/plugin.json"
)
):
raise KeyError
with open(
f"/opt/bunkerweb/tmp/ui/{temp_folder_name}/{dirs[0]}/plugin.json",
"r",
) as f:
plugin_file = json_load(f)
if not all(
key in plugin_file.keys() for key in PLUGIN_KEYS
):
raise ValueError
folder_name = plugin_file["id"]
if not app.config["CONFIGFILES"].check_name(
folder_name
):
error = 1
flash(
f"Invalid plugin name for {temp_folder_name}. (Can only contain numbers, letters, underscores and hyphens (min 4 characters and max 32))",
"error",
)
raise Exception
if os.path.exists(
f"/opt/bunkerweb/plugins/{folder_name}"
):
raise FileExistsError
copytree(
f"/opt/bunkerweb/tmp/ui/{temp_folder_name}/{dirs[0]}",
f"/opt/bunkerweb/plugins/{folder_name}",
)
except zipfile.BadZipFile:
error = 1
flash(
f"{file} is not a valid zip file. ({folder_name if folder_name else temp_folder_name})",
"error",
)
else:
try:
with tarfile.open(
f"/opt/bunkerweb/tmp/ui/{file}",
errorlevel=2,
) as tar_file:
try:
tar_file.getmember("plugin.json")
tar_file.extractall(
f"/opt/bunkerweb/tmp/ui/{temp_folder_name}"
)
with open(
f"/opt/bunkerweb/tmp/ui/{temp_folder_name}/plugin.json",
"r",
) as f:
plugin_file = json_load(f)
if not all(
key in plugin_file.keys() for key in PLUGIN_KEYS
):
raise ValueError
folder_name = plugin_file["id"]
if not app.config["CONFIGFILES"].check_name(
folder_name
):
error = 1
flash(
f"Invalid plugin name for {temp_folder_name}. (Can only contain numbers, letters, underscores and hyphens (min 4 characters and max 32))",
"error",
)
raise Exception
if os.path.exists(
f"/opt/bunkerweb/plugins/{folder_name}"
):
raise FileExistsError
copytree(
f"/opt/bunkerweb/tmp/ui/{temp_folder_name}",
f"/opt/bunkerweb/plugins/{folder_name}",
)
except KeyError:
tar_file.extractall(
f"/opt/bunkerweb/tmp/ui/{temp_folder_name}",
)
dirs = [
d
for d in os.listdir(
f"/opt/bunkerweb/tmp/ui/{temp_folder_name}"
)
if os.path.isdir(
f"/opt/bunkerweb/tmp/ui/{temp_folder_name}/{d}"
)
]
if (
not dirs
or len(dirs) > 1
or not os.path.exists(
f"/opt/bunkerweb/tmp/ui/{temp_folder_name}/{dirs[0]}/plugin.json"
)
):
raise KeyError
with open(
f"/opt/bunkerweb/tmp/ui/{temp_folder_name}/{dirs[0]}/plugin.json",
"r",
) as f:
plugin_file = json_load(f)
if not all(
key in plugin_file.keys() for key in PLUGIN_KEYS
):
raise ValueError
folder_name = plugin_file["id"]
if not app.config["CONFIGFILES"].check_name(
folder_name
):
error = 1
flash(
f"Invalid plugin name for {temp_folder_name}. (Can only contain numbers, letters, underscores and hyphens (min 4 characters and max 32))",
"error",
)
raise Exception
if os.path.exists(
f"/opt/bunkerweb/plugins/{folder_name}"
):
raise FileExistsError
copytree(
f"/opt/bunkerweb/tmp/ui/{temp_folder_name}/{dirs[0]}",
f"/opt/bunkerweb/plugins/{folder_name}",
)
except tarfile.ReadError:
error = 1
flash(
f"Couldn't read file {file} ({folder_name if folder_name else temp_folder_name})",
"error",
)
except tarfile.CompressionError:
error = 1
flash(
f"{file} is not a valid tar file ({folder_name if folder_name else temp_folder_name})",
"error",
)
except tarfile.HeaderError:
error = 1
flash(
f"The file plugin.json in {file} is not valid ({folder_name if folder_name else temp_folder_name})",
"error",
)
except KeyError:
error = 1
flash(
f"{file} is not a valid plugin (plugin.json file is missing) ({folder_name if folder_name else temp_folder_name})",
"error",
)
except JSONDecodeError as e:
error = 1
flash(
f"The file plugin.json in {file} is not valid ({e.msg}: line {e.lineno} column {e.colno} (char {e.pos})) ({folder_name if folder_name else temp_folder_name})",
"error",
)
except ValueError:
error = 1
flash(
f"The file plugin.json is missing one or more of the following keys: <i>{', '.join(PLUGIN_KEYS)}</i> ({folder_name if folder_name else temp_folder_name})",
"error",
)
except FileExistsError:
error = 1
flash(
f"A plugin named {folder_name} already exists",
"error",
)
except (tarfile.TarError, OSError) as e:
error = 1
flash(f"{e}", "error")
except Exception:
pass
finally:
if error != 1:
flash(
f"Successfully created plugin: <b><i>{folder_name}</i></b>"
)
error = 0
for root, dirs, files in os.walk("/opt/bunkerweb/plugins", topdown=False):
for name in files + dirs:
chown(os.path.join(root, name), "nginx", "nginx")
os.chmod(os.path.join(root, name), 0o770)
app.config["CONFIG"].reload_config()
if operation:
flash(operation)
# Reload instances
_reloads = app.config["INSTANCES"].reload_instances()
if not _reloads:
for _reload in _reloads:
flash(f"Reload failed for the instance {_reload}", "error")
else:
flash("Successfully reloaded instances")
if os.path.exists("/opt/bunkerweb/tmp/ui"):
try:
rmtree("/opt/bunkerweb/tmp/ui")
except OSError:
pass
app.config["CONFIG"].reload_plugins()
return redirect(url_for("loading", next=url_for("plugins")))
plugins = [
{
"name": "plugins",
"type": "folder",
"path": "/opt/bunkerweb/plugins",
"can_create_files": False,
"can_create_folders": False,
"can_edit": False,
"can_delete": False,
"children": [
{
"name": _dir,
"type": "folder",
"path": f"/opt/bunkerweb/plugins/{_dir}",
"can_create_files": False,
"can_create_folders": False,
"can_edit": False,
"can_delete": True,
}
for _dir in os.listdir("/opt/bunkerweb/plugins")
],
}
]
return render_template("plugins.html", folders=plugins)
@app.route("/plugins/upload", methods=["POST"])
@login_required
def upload_plugin():
if not request.files:
return {"status": "ko"}, 400
if not os.path.exists("/opt/bunkerweb/tmp/ui"):
os.mkdir("/opt/bunkerweb/tmp/ui")
for file in request.files.values():
if not file.filename.endswith((".zip", ".tar.gz", ".tar.xz")):
return {"status": "ko"}, 422
with open(
f"/opt/bunkerweb/tmp/ui/{uuid4()}{file.filename[file.filename.index('.'):]}",
"wb",
) as f:
f.write(file.read())
return {"status": "ok"}, 201
@app.route("/cache", methods=["GET"])
@login_required
def cache():
return render_template(
"cache.html", folders=[path_to_dict("/opt/bunkerweb/cache", is_cache=True)]
)
@app.route("/cache/download", methods=["GET"])
@login_required
def cache_download():
path = request.args.get("path")
if not path:
return redirect(url_for("loading", next=url_for("cache"))), 400
operation = app.config["CONFIGFILES"].check_path(path, "/opt/bunkerweb/cache/")
if operation:
flash(operation, "error")
return redirect(url_for("loading", next=url_for("plugins"))), 500
return send_file(path, as_attachment=True)
@app.route("/logs", methods=["GET"])
@login_required
def logs():
instances = app.config["INSTANCES"].get_instances()
first_instance = instances[0] if instances else None
return render_template(
"logs.html", first_instance=first_instance, instances=instances
)
@app.route("/logs/local", methods=["GET"])
@login_required
def logs_linux():
if not os.path.exists("/usr/sbin/nginx"):
return (
jsonify(
{
"status": "ko",
"message": "There are no linux instances running",
}
),
404,
)
last_update = request.args.get("last_update")
raw_logs_access = []
raw_logs_error = []