chore: cleanup code

This commit is contained in:
t@marin
2023-03-21 05:06:15 +07:00
parent 0902d1e6f2
commit 2309fbfbbd
3 changed files with 53 additions and 130 deletions

View File

@@ -30,4 +30,5 @@ if [ -f "${data_box}/settings.ini" ]; then
service_control
else
echo "${now} [ERROR] settings.ini file not found" > "${run_path}/error.inotify.log"
exit 1
fi

View File

@@ -12,10 +12,8 @@ delete_logs() {
mv "${run_path}/${bin}.log" "${run_path}/${bin}-$(date +%Y-%m-%d-%H-%M-%S).log"
fi
done
# Delete other log files
find "${run_path}" -type f \( -name "root" -o -name "*.yaml" -o -name "*.list" -o -name "*.inotify.log" -o -name "*-report.log" \) -exec rm -f {} \; || log warn "Error deleting other log files"
# Delete logs that are three days old or older
find "${run_path}" -type f -name "*.log" -mtime +2 -exec rm -f {} \; || log warn "Error deleting old log"
}
@@ -43,7 +41,6 @@ still_alive() {
log error "Please check ${bin_name}.log for more information."
exit 1
fi
if ! kill -0 "${pid}" 2>/dev/null; then
log error "${bin_name} service is not running."
log error "Killing stale pid ${pid}."
@@ -119,12 +116,10 @@ check_in_bin() {
log error "Error: '${bin_path}' not found or not executable."
exit 1
fi
if [ ! -f "${bin_path}" ] || [ ! -x "${bin_path}" ]; then
log error "Error: '${bin_path}' is not a valid file or cannot be executed."
exit 1
fi
case "${bin_name}" in
clash)
if ! "${bin_path}" -v >/dev/null 2>&1; then
@@ -142,15 +137,14 @@ check_in_bin() {
}
create_tun() {
# Mengaktifkan IP forwarding
# Enable IP forwarding
sysctl net.ipv4.ip_forward=1 >/dev/null 2>&1
# Membuat symlink untuk /dev/tun jika belum ada
# Creates a symlink for /dev/tun if it doesn't already exist
if [ ! -c "/dev/net/tun" ]; then
if ! mkdir -p /dev/net; then
log warn "Cannot create directory /dev/net" >&2
exit 1
fi
if ! mknod /dev/net/tun c 10 200; then
log warn "Cannot create /dev/net/tun. Possible reasons:"
log warn "This script is not executed as root user."
@@ -253,7 +247,7 @@ run_box() {
exit 1
;;
esac
rm -rf ${run_path}/${bin_name}-report.log
rm -f "${run_path}/${bin_name}-report.log"
}
cgroup_limit() {
@@ -274,29 +268,23 @@ fi
bin_usage() {
# Get the process ID of the binary
bin_pid=$(pidof ${bin_name})
if [ -z "${bin_pid}" ]; then
log error "${bin_name} is not running"
return
fi
# Get the memory usage of the binary
rss=$(grep VmRSS /proc/${bin_pid}/status | awk '{print $2}')
[ "${rss}" -ge 1024 ] && bin_rss="$(expr ${rss} / 1024) MB" || bin_rss="${rss} KB"
swap=$(grep VmSwap /proc/${bin_pid}/status | awk '{print $2}')
[ "${swap}" -ge 1024 ] && bin_swap="$(expr ${swap} / 1024) MB" || bin_swap="${swap} KB"
# Get the state of the binary
state=$(grep State /proc/${bin_pid}/status | awk '{print $2}')
# Get the user and group of the binary
user_group=$(stat -c %U:%G /proc/${bin_pid})
# Log the information
log info "${bin_name} has started with the ${user_group} user group."
log info "${bin_name} status: ${state}, PID: (${bin_pid})"
log info "${bin_name} memory usage: ${bin_rss}, swap: ${bin_swap}"
# Get the CPU usage of the binary
cpu=$(/system/bin/ps -p ${bin_pid} -o pcpu | awk 'NR==2{print $1}' 2> /dev/null)
if [ -n "${cpu}" ]; then
@@ -304,7 +292,6 @@ bin_usage() {
else
log info "${bin_name} cpu usage: not available"
fi
# Get the running time of the binary
running_time=$(/system/bin/ps -p ${bin_pid} -o etime | awk 'NR==2{print $1}' 2> /dev/null)
if [ -n "${running_time}" ]; then
@@ -312,58 +299,52 @@ bin_usage() {
else
log info "${bin_name} running time: not available"
fi
# Save the process ID to the pid file
echo -n ${bin_pid} > ${pid_file}
echo -n "${bin_pid}" > "${pid_file}"
}
display_bin_pid() {
# Mengecek apakah bin_name sudah didefinisikan
# Checks if bin_name is defined
if [ -z "${bin_name}" ]; then
log error "bin_name: ${bin_name} not defined"
return 1
fi
# Mencari PID dari bin_name
# Look up the PID of bin_name
bin_pid=$(pidof "${bin_name}")
# Mengecek apakah bin_name sedang berjalan
# Checks if bin_name is running
if [ -n "${bin_pid}" ]; then
# Jika iya, mencetak pesan dan memanggil fungsi bin_usage
# If so, prints a message and calls the bin_usage function
log info "${bin_name} service is running. (PID: ${bin_pid})."
bin_usage
else
# Jika tidak, mencetak pesan dan mengembalikan status 1
# Otherwise, it prints a message and returns status 1
log warn "${bin_name} service is stopped."
return 1
fi
}
crontab_alive() {
# Memulai crond dengan opsi "-c" dan menyimpannya di background
# Start crond with the "-c" option and keep it in the background
nohup crond -c "${run_path}" > /dev/null 2>&1 &
# Menghapus crontab sebelumnya dan membuat crontab baru
# Delete the previous crontab and create a new crontab
crontab -c "${run_path}" -r
touch "${run_path}/root"
chmod 0600 "${run_path}/root"
# Menambahkan cron job untuk memanggil box.tool keepdns setiap menit
# Added a cron job to call box.tool keptns every minute
if [ "${intervaldns}" != "" ]; then
echo "${intervaldns} ${scripts_dir}/box.tool keepdns" >> "${run_path}/root"
log info "DNS remains open."
fi
# Menampilkan pesan konfigurasi jika bin_name adalah "clash"
# Displays a configuration message if bin_name is "clash"
if [ "${bin_name}" = "clash" ]; then
log info "Configuration ${clash_config}."
fi
# Menjalankan fungsi crontab_geo untuk menambahkan cron job berdasarkan lokasi geografis
# Running the geo crontab function
crontab_geo
}
start_box() {
# Mengosongkan file log dan menambahkan timestamp dan garis pembatas
# Cleared the log file and added the timestamp and delimiter
echo -n "" > "${logs_file}"
# Then use the chmod command to set file permissions to 755
if [ -t 1 ]; then
@@ -373,8 +354,7 @@ start_box() {
echo "$(date)" | tee -a "${logs_file}" > /dev/null 2>&1
echo "--------------------------------------------" | tee -a "${logs_file}" > /dev/null 2>&1
fi
# Memperbarui iptables jika bin_name masih berjalan
# Update iptables if bin_name is still running
if bin_pid=$(pidof "${bin_name}"); then
log info "${bin_name} service is still running, refreshing iptables"
if "${scripts_dir}/box.iptables" renew; then
@@ -387,8 +367,7 @@ start_box() {
else
log info "Good day"
fi
# Memeriksa izin, memeriksa keberadaan bin, menghapus log lama, membuat TUN, menjalankan box, dan menunggu selama 1 detik
# Checked permissions, checked for bin existence, deleted old logs, created a TUN, ran box, and waited for 1 second
check_permission
check_in_bin
delete_logs
@@ -396,14 +375,13 @@ start_box() {
create_tun
fi
run_box && sleep 1
# Menjalankan crontab_alive jika crontab_sec tidak sama dengan "false"
# Executes crontab_alive if crontab_sec is not equal to "false"
if [ "${crontab_sec}" != "false" ]; then
crontab_alive
else
log info "crontab: disabled."
fi
# Menjalankan cgroup_limit, menunggu selama 1 detik, mendeteksi port yang digunakan, menunggu selama 1 detik, dan menampilkan PID bin
# Runs cgroup limit, waits 1 second, detects the port in use, waits 1 second, and displays the PID of bin
cgroup_limit
sleep 1
detected_port
@@ -413,23 +391,21 @@ start_box() {
}
stop_box() {
# Menggunakan perintah `pgrep` untuk mencari PID cronjob
# Using `pgrep` command to find cronjob PID
cronkill=$(pgrep -f "crond -c ${run_path}")
for cron in ${cronkill[@]}; do
kill -15 ${cron}
log warn "Killing cron process ${cron}"
kill -15 "${cron}"
done
# Menggunakan loop untuk membunuh setiap binary
# Using a loop to kill each binary
for bin in ${bin_list[@]}; do
# Use `pkill` to kill the binary with signal 15
pkill "${bin}" || killall "${bin}"
done
sleep 1
# Mengecek apakah binary sudah terhenti
# Check if the binary has stopped
if ! pidof ${bin_name} >/dev/null 2>&1; then
# Menghapus file `box.pid` jika ada
# Delete the `box.pid` file if it exists
if [ -f ${run_path}/box.pid ]; then
rm ${run_path}/box.pid
sleep 0.5

View File

@@ -8,9 +8,9 @@ user_agent="${bin_name}"
# set meta and dev flags
meta=true
# if meta flag is true, download clash.meta
dev=true
dev=false
# membuat log pada terminal
# log on terminal
logs() {
export TZ=Asia/Jakarta
now=$(date +"%I.%M %p %Z")
@@ -35,7 +35,7 @@ logs() {
fi
}
# Memeriksa koneksi internet dengan mlbox
# Check internet connection with mlbox
testing() {
logs info "dns="
for network in $(${data_dir}/bin/mlbox -timeout=5 -dns="-qtype=A -domain=asia.pool.ntp.org" | grep -v 'timeout' | grep -E '[1-9][0-9]{0,2}(\.[0-9]{1,3}){3}'); do
@@ -45,7 +45,6 @@ testing() {
if [ -n "${ntpip}" ]; then
logs success "done"
logs testing "http="
httpIP=$(${data_dir}/bin/mlbox -timeout=5 -http="http://182.254.116.116/d?dn=reddit.com&clientip=1" 2>&1 | grep -Ev 'timeout|httpGetResponse' | grep -E '[1-9][0-9]{0,2}(\.[0-9]{1,3}){3}')
if [ -n "${httpIP}" ]; then
@@ -54,7 +53,6 @@ testing() {
else
logs failed "failed"
fi
logs testing "https="
httpsResp=$(${data_dir}/bin/mlbox -timeout=5 -http="https://api.infoip.io" 2>&1 | grep -Ev 'timeout|httpGetResponse' | grep -E '[1-9][0-9]{0,2}(\.[0-9]{1,3}){3}')
[ -n "${httpsResp}" ] && logs success "done" || logs failed "failed"
@@ -66,11 +64,10 @@ testing() {
else
logs failed "failed"
fi
[ -t 1 ] && echo -e "\033[1;31m\033[0m" || echo "" | tee -a ${logs_file} >> /dev/null 2>&1
}
# Memeriksa koneksi internet dengan mlbox
# Check internet connection with mlbox
network_check() {
if [ -f "${data_dir}/bin/mlbox" ]; then
logs info "Checking internet connection... "
@@ -90,7 +87,7 @@ network_check() {
[ "${flags}" != "false" ] || exit 1
}
# Memeriksa apakah suatu binary berjalan dengan mengecek file pid dan cmdline
# Check if a binary is running by checking the pid file and cmdline
probe_bin_alive() {
if [ -f "${pid_file}" ]; then
cmd_file="/proc/$(pidof "${bin_name}")/cmdline"
@@ -104,7 +101,7 @@ probe_bin_alive() {
fi
}
# Restart binary, setelah dihentikan dan dijalankan kembali
# Restart the binary, after stopping and running again
restart_box() {
${scripts_dir}/box.service restart
sleep 0.5
@@ -116,7 +113,7 @@ restart_box() {
fi
}
# Set DNS secara manual, mengubah net.ipv4.ip_forward dan net.ipv6.conf.all.forwarding menjadi 1
# Set DNS manually, change net.ipv4.ip_forward and net.ipv6.conf.all.forwarding to 1
keep_dns() {
local_dns1=$(getprop net.dns1)
local_dns2=$(getprop net.dns2)
@@ -134,22 +131,19 @@ keep_dns() {
unset local_dns2
}
# Memperbarui file dari URL
# Updating files from URLs
update_file() {
local file="$1"
local update_url="$2"
local file_bak="${file}.bak"
file="$1"
update_url="$2"
file_bak="${file}.bak"
if [ -f "${file}" ]; then
mv "${file}" "${file_bak}" || return 1
fi
local request="wget"
local request+=" --no-check-certificate"
local request+=" --user-agent ${user_agent}"
local request+=" -O ${file}"
local request+=" ${update_url}"
request="wget"
request+=" --no-check-certificate"
request+=" --user-agent ${user_agent}"
request+=" -O ${file}"
request+=" ${update_url}"
echo ${request}
${request} >&2 || {
if [ -f "${file_bak}" ]; then
@@ -157,7 +151,6 @@ update_file() {
fi
return 1
}
return 0
}
@@ -191,12 +184,10 @@ update_subgeo() {
log debug "Update geo $(date +"%Y-%m-%d %I.%M %p")"
flag=false
fi
if [ "${bin_name}" = "clash" ] && [ "${auto_update_subscription}" = "true" ] && update_file "${clash_config}" "${subscription_url}"; then
flag=true
log debug "Downloading ${clash_config}"
fi
if [ -f "${pid_file}" ] && [ "${flag}" = "true" ]; then
restart_box
fi
@@ -213,7 +204,6 @@ port_detection() {
log debug "Warning: 'ss' command not found, skipping port detection." >&2
return
fi
# Log the detected ports
logs debug "${bin_name} port detected: "
while read -r port ; do
@@ -232,8 +222,8 @@ port_detection() {
# kill bin
kill_alive() {
for list in "${bin_list[@]}" ; do
if pgrep "$list" >/dev/null ; then
kill -9 $(pgrep "$list") >/dev/null 2>&1 || killall -9 "$list" >/dev/null 2>&1
if pidof "${list}" >/dev/null ; then
pkill -9 "${list}" >/dev/null 2>&1 || killall -9 "${list}" >/dev/null 2>&1
fi
done
}
@@ -248,7 +238,7 @@ update_kernel() {
"x86_64") arch="amd64"; platform="linux" ;;
*) log warn "Unsupported architecture: $(uname -m)" >&2; exit 1 ;;
esac
# Lakukan hal lainnya di bawah ini
# Do anything else below
file_kernel="${bin_name}-${arch}"
case "${bin_name}" in
sing-box)
@@ -316,7 +306,7 @@ update_kernel() {
"aarch64") download_file="v2ray-android-arm64-v8a.zip" ;;
*) log error "Unsupported architecture: $(uname -m)" >&2; exit 1 ;;
esac
# Lakukan hal lainnya di bawah ini
# Do anything else below
download_link="https://github.com/v2fly/v2ray-core/releases"
log debug "Downloading ${download_link}/download/${latest_version}/${download_file}"
update_file "${data_dir}/${file_kernel}.zip" "${download_link}/download/${latest_version}/${download_file}"
@@ -345,22 +335,11 @@ update_kernel() {
log warn "failed to extract ${data_dir}/${file_kernel}.tar.gz" && flag="false"
fi
;;
v2fly)
v2fly|xray)
[ "${bin_name}" = "xray" ] && bin='xray' || bin='v2ray'
unzip_command=$(command -v unzip >/dev/null 2>&1 && echo "unzip" || echo "${busybox_path} unzip")
if ${unzip_command} -o "${data_dir}/${file_kernel}.zip" "v2ray" -d "${bin_kernel}" >&2; then
if mv "${bin_kernel}/v2ray" "${bin_kernel}/v2fly"; then
[ -f "${pid_file}" ] && restart_box || log debug "${bin_name} does not need to be restarted"
else
log error "failed to move the kernel"
fi
else
log warn "failed to extract ${data_dir}/${file_kernel}.zip"
fi
;;
xray)
unzip_command=$(command -v unzip >/dev/null 2>&1 && echo "unzip" || echo "${busybox_path} unzip")
if ${unzip_command} -o "${data_dir}/${file_kernel}.zip" "xray" -d "${bin_kernel}" >&2; then
if mv "${bin_kernel}/xray" "${bin_kernel}/xray"; then
if mv "${bin_kernel}/${bin}" "${bin_kernel}/${bin_name}"; then
[ -f "${pid_file}" ] && restart_box || log debug "${bin_name} does not need to be restarted"
else
log error "failed to move the kernel"
@@ -386,7 +365,6 @@ cgroup_limit() {
log warn "cgroup_memory_limit is not set"
return 1
fi
# Check if cgroup_memory_path is set and exists
if [ -z "${cgroup_memory_path}" ]; then
local cgroup_memory_path=$(mount | grep cgroup | awk '/memory/{print $3}' | head -1)
@@ -398,7 +376,6 @@ cgroup_limit() {
log warn "${cgroup_memory_path} does not exist"
return 1
fi
# Check if pid_file is set and exists
if [ -z "${pid_file}" ]; then
log warn "pid_file is not set"
@@ -407,18 +384,15 @@ cgroup_limit() {
log warn "${pid_file} does not exist"
return 1
fi
# Create cgroup directory and move process to cgroup
local bin_name=$(basename "$0")
mkdir -p "${cgroup_memory_path}/${bin_name}"
local pid=$(cat "${pid_file}")
echo "${pid}" > "${cgroup_memory_path}/${bin_name}/cgroup.procs" \
&& log info "Moved process ${pid} to ${cgroup_memory_path}/${bin_name}/cgroup.procs"
# Set memory limit for cgroup
echo "${cgroup_memory_limit}" > "${cgroup_memory_path}/${bin_name}/memory.limit_in_bytes" \
&& log info "Set memory limit to ${cgroup_memory_limit} for ${cgroup_memory_path}/${bin_name}/memory.limit_in_bytes"
return 0
}
@@ -438,31 +412,6 @@ update_dashboard() {
fi
}
run_base64() {
acc_file="${data_dir}/sing-box/acc.txt"
proxy_file="${data_dir}/dashboard/dist/proxy.txt"
if [ -s "$acc_file" ]; then
log info "$(cat "$acc_file" 2>&1)"
base64 "${acc_file}" > "${proxy_file}"
log info "Generated ${proxy_file}"
log info "Done"
else
log warn "${acc_file} is empty or does not exist"
exit 1
fi
}
# copy bin ke system/bin
cp_bin() {
if cp /data/adb/box/bin/* /data/adb/modules/box_for_magisk/system/bin/; then
log debug "File copy completed successfully."
else
log debug "File copy failed." >&2
exit 1
fi
}
reload() {
case "${bin_name}" in
sing-box)
@@ -502,9 +451,6 @@ case "$1" in
connect)
network_check
;;
rbase64)
run_base64
;;
upyacd)
update_dashboard
;;
@@ -517,14 +463,14 @@ case "$1" in
port)
port_detection
;;
reload)
reload
;;
subgeo)
update_subgeo
find "${data_dir}/${bin_name}" -type f -name "*.db.bak" -delete
find "${data_dir}/${bin_name}" -type f -name "*.dat.bak" -delete
;;
reload)
reload
;;
all)
for list in "${bin_list[@]}" ; do
bin_name="${list}"
@@ -533,7 +479,7 @@ case "$1" in
done
;;
*)
echo "$0: usage: $0 {reload|testing|keepdns|connect|rbase64|upyacd|upcore|cgroup|port|subgeo|all}"
echo "$0: usage: $0 {reload|testing|keepdns|connect|upyacd|upcore|cgroup|port|subgeo|all}"
exit 1
;;
esac