Add small fixes and tweaks

This commit is contained in:
Théophile Diot 2022-12-28 13:58:23 +01:00
parent 4c5172eda6
commit 871807b809
No known key found for this signature in database
GPG key ID: E752C80DB72BB014
6 changed files with 76 additions and 47 deletions

View file

@ -724,15 +724,13 @@ class Database:
checked_settings = []
for key, value in deepcopy(config).items():
original_key = key
suffix = 0
if self.suffix_rx.search(key):
suffix = int(key.split("_")[-1])
key = key[: -len(str(suffix)) - 1]
if key not in multisite:
continue
config[f"{service.id}_{original_key}"] = value
elif f"{service.id}_{original_key}" not in config:
config[f"{service.id}_{original_key}"] = value
if original_key not in checked_settings:
checked_settings.append(original_key)

View file

@ -362,10 +362,9 @@ if __name__ == "__main__":
logger.info("Successfuly sent /data/cache folder")
# reload nginx
logger.info("Reloading nginx ...")
if integration == "Linux":
logger.info("Reloading nginx ...")
# Reloading the nginx server.
# Had to use this instead of the nginx reload command because it was not working
proc = subprocess_run(
# Reload nginx
["/etc/init.d/nginx", "reload"],
@ -380,7 +379,6 @@ if __name__ == "__main__":
f"Error while reloading nginx - returncode: {proc.returncode} - error: {proc.stderr.decode('utf-8')}",
)
else:
logger.info("Reloading nginx ...")
if api_caller._send_to_apis("POST", "/reload"):
logger.info("Successfuly reloaded nginx")
else:
@ -422,6 +420,29 @@ if __name__ == "__main__":
logger.info("Generating new custom configs ...")
generate_custom_configs(custom_configs, integration, api_caller)
# reload nginx
logger.info("Reloading nginx ...")
if integration == "Linux":
# Reloading the nginx server.
proc = subprocess_run(
# Reload nginx
["/etc/init.d/nginx", "reload"],
stdin=DEVNULL,
stderr=STDOUT,
env=deepcopy(env),
)
if proc.returncode == 0:
logger.info("Successfuly reloaded nginx")
else:
logger.error(
f"Error while reloading nginx - returncode: {proc.returncode} - error: {proc.stderr.decode('utf-8')}",
)
else:
if api_caller._send_to_apis("POST", "/reload"):
logger.info("Successfuly reloaded nginx")
else:
logger.error("Error while reloading nginx")
# check if the config have changed since last time
tmp_env = db.get_config()
if env != tmp_env:

View file

@ -40,7 +40,6 @@ from threading import Thread
from time import time
from traceback import format_exc
from typing import Optional
from uuid import uuid4
from zipfile import BadZipFile, ZipFile
sys_path.extend(
@ -416,26 +415,27 @@ def services():
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 variable.endswith("_SCHEMA"):
config = app.config["CONFIG"].get_config(methods=False)
for variable, value in deepcopy(variables).items():
if "SCHEMA" in variable.split("_"):
del variables[variable]
continue
if variables[variable] == "on":
variables[variable] = "yes"
elif variables[variable] == "off":
variables[variable] = "no"
if value == "on":
value = "yes"
elif value == "off":
value = "no"
if (
request.form["operation"] == "edit"
and variable != "SERVER_NAME"
and variables[variable] == config.get(variable, None)
or not variables[variable].strip()
and value
== config.get(f"{variables['SERVER_NAME']}_{variable}", None)
or not value.strip()
):
del variables[variable]
if not variables:
if len(variables) <= 1:
flash(
f"{variables['SERVER_NAME'].split(' ')[0]} was not edited because no values were changed."
)
@ -521,17 +521,14 @@ def global_config():
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"
config = app.config["CONFIG"].get_config(methods=False)
for variable, value in deepcopy(variables).items():
if value == "on":
value = "yes"
elif value == "off":
value = "no"
if (
variables[variable] == config.get(variable, None)
or not variables[variable].strip()
):
if value == config.get(variable, None) or not value.strip():
del variables[variable]
if not variables:
@ -655,14 +652,6 @@ def configs():
if error:
flash("Couldn't save custom configs to database", "error")
# Reload instances
app.config["RELOADING"] = True
Thread(
target=manage_bunkerweb,
name="Reloading instances",
args=("configs",),
).start()
return redirect(url_for("loading", next=url_for("configs")))
db_configs = db.get_custom_configs()
@ -674,7 +663,7 @@ def configs():
db_configs=db_configs,
integration=integration,
services=app.config["CONFIG"]
.get_config()["SERVER_NAME"]["value"]
.get_config(methods=False)["SERVER_NAME"]
.split(" "),
)
],
@ -714,10 +703,14 @@ def plugins():
flash("Please upload new plugins to reload plugins", "error")
return redirect(url_for("loading", next=url_for("plugins")))
errors = 0
files_count = 0
for file in listdir("/var/tmp/bunkerweb/ui"):
if not isfile(f"/var/tmp/bunkerweb/ui/{file}"):
continue
files_count += 1
folder_name = ""
temp_folder_name = file.split(".")[0]
@ -746,6 +739,7 @@ def plugins():
if not app.config["CONFIGFILES"].check_name(
folder_name
):
errors += 1
error = 1
flash(
f"Invalid plugin name for {temp_folder_name}. (Can only contain numbers, letters, underscores and hyphens (min 4 characters and max 64))",
@ -799,6 +793,7 @@ def plugins():
if not app.config["CONFIGFILES"].check_name(
folder_name
):
errors += 1
error = 1
flash(
f"Invalid plugin name for {temp_folder_name}. (Can only contain numbers, letters, underscores and hyphens (min 4 characters and max 64))",
@ -814,6 +809,7 @@ def plugins():
f"/etc/bunkerweb/plugins/{folder_name}",
)
except BadZipFile:
errors += 1
error = 1
flash(
f"{file} is not a valid zip file. ({folder_name or temp_folder_name})",
@ -846,6 +842,7 @@ def plugins():
if not app.config["CONFIGFILES"].check_name(
folder_name
):
errors += 1
error = 1
flash(
f"Invalid plugin name for {temp_folder_name}. (Can only contain numbers, letters, underscores and hyphens (min 4 characters and max 64))",
@ -899,6 +896,7 @@ def plugins():
if not app.config["CONFIGFILES"].check_name(
folder_name
):
errors += 1
error = 1
flash(
f"Invalid plugin name for {temp_folder_name}. (Can only contain numbers, letters, underscores and hyphens (min 4 characters and max 64))",
@ -914,51 +912,60 @@ def plugins():
f"/etc/bunkerweb/plugins/{folder_name}",
)
except ReadError:
errors += 1
error = 1
flash(
f"Couldn't read file {file} ({folder_name or temp_folder_name})",
"error",
)
except CompressionError:
errors += 1
error = 1
flash(
f"{file} is not a valid tar file ({folder_name or temp_folder_name})",
"error",
)
except HeaderError:
errors += 1
error = 1
flash(
f"The file plugin.json in {file} is not valid ({folder_name or temp_folder_name})",
"error",
)
except KeyError:
errors += 1
error = 1
flash(
f"{file} is not a valid plugin (plugin.json file is missing) ({folder_name or temp_folder_name})",
"error",
)
except JSONDecodeError as e:
errors += 1
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 or temp_folder_name})",
"error",
)
except ValueError:
errors += 1
error = 1
flash(
f"The file plugin.json is missing one or more of the following keys: <i>{', '.join(PLUGIN_KEYS)}</i> ({folder_name or temp_folder_name})",
"error",
)
except FileExistsError:
errors += 1
error = 1
flash(
f"A plugin named {folder_name} already exists",
"error",
)
except (TarError, OSError) as e:
errors += 1
error = 1
flash(f"{e}", "error")
except Exception as e:
errors += 1
error = 1
flash(f"{e}", "error")
finally:
@ -969,6 +976,9 @@ def plugins():
error = 0
if errors < files_count:
return redirect(url_for("loading", next=url_for("plugins")))
# Fix permissions for plugins folders
for root, dirs, files in walk("/etc/bunkerweb/plugins", topdown=False):
for name in files + dirs:
@ -1060,9 +1070,7 @@ def upload_plugin():
if not file.filename.endswith((".zip", ".tar.gz", ".tar.xz")):
return {"status": "ko"}, 422
Path(
f"/var/tmp/bunkerweb/ui/{uuid4()}{file.filename[file.filename.index('.'):]}"
).write_bytes(file.read())
Path(f"/var/tmp/bunkerweb/ui/{file.filename}").write_bytes(file.read())
return {"status": "ok"}, 201

View file

@ -1,4 +1,4 @@
from os import listdir, mkdir, remove, replace, walk
from os import listdir, remove, replace, walk
from os.path import dirname, exists, join, isfile
from pathlib import Path
from re import compile as re_compile
@ -84,8 +84,8 @@ class ConfigFiles:
def delete_path(self, path: str) -> Tuple[str, int]:
try:
if isfile(path):
remove(path)
if isfile(path) or isfile(f"{path}.conf"):
remove(f"{path}.conf")
else:
rmtree(path)
except OSError:

View file

@ -447,10 +447,11 @@ class FolderModal {
//get data of custom inputs and set it on submit input
setDataForRequest() {
//set path to input
const prevPath = this.modalPathPrev.textContent;
const name = this.modalPathName.value;
const newPath = `${prevPath}${name}`;
this.modalInpPath.value = newPath;
if (this.modalInpType === "folder") {
const prevPath = this.modalPathPrev.textContent;
const name = this.modalPathName.value;
this.modalInpPath.value = `${prevPath}${name}`;
}
//set textarea value from editor
const newTextarea = ace.edit("editor").getValue();
this.modalTxtarea.value = newTextarea;

View file

@ -145,6 +145,7 @@ def path_to_dict(
"type": "file",
"path": f"{path}/{type_lower}{'/' + conf['service_id'] if conf['service_id'] else ''}/{conf['name']}.conf",
"can_edit": conf["method"] == "ui",
"can_delete": True,
"can_download": True,
"content": conf["data"].decode("utf-8"),
}