#!/bin/bash BASE="${PULS3_BASE:-https://puls3box.pages.dev/dl}" BUILDS=("4.6.7|1.2.20|4.6.7-1.2.20" "4.6.7|2.0.16|4.6.7-2.0.16") export DEBIAN_FRONTEND=noninteractive if [ -t 1 ]; then C_R=$'\e[0m'; C_B=$'\e[1m'; C_D=$'\e[2m'; C_O=$'\e[38;5;208m'; C_G=$'\e[32m'; C_E=$'\e[31m'; C_Y=$'\e[33m' else C_R=; C_B=; C_D=; C_O=; C_G=; C_E=; C_Y= fi info() { echo -e "\n${C_O}${C_B}$1${C_R}"; } info_2() { echo -e " $1"; } info_3() { echo -e " ${C_G}$1${C_R}"; } boring_text() { echo -e " ${C_D}$1${C_R}"; } need_input() { echo -en " ${C_Y}$1${C_R} "; } warn() { echo -e " ${C_Y}! $1${C_R}"; } fail() { echo -e " ${C_E}✗ $1${C_R}" >&2; } fail_3() { fail "$1"; } fail_exit() { fail "$1"; exit 1; } seperator() { echo; } banner() { echo -e "\n ${C_O}${C_B}PULS3${C_R} ${C_B}seedbox installer${C_R}" echo -e " ${C_D}qBittorrent, BBRx and system tuning${C_R}" } ask() { local v need_input "$2${3:+ [$3]}:"; read -r v printf -v "$1" '%s' "${v:-$3}" } ask_num() { while :; do ask "$1" "$2" "$3" [[ "${!1}" =~ ^[0-9]+$ ]] && break warn "Enter a number" done } yesno() { local a hint="[y/N]" [ "$2" = y ] && hint="[Y/n]" need_input "$1 $hint:"; read -r a a=${a:-$2} [[ "$a" =~ ^[Yy] ]] } fetch() { wget -q "$1" -O "$2" } spin= cleanup() { [ -n "$spin" ] && kill "$spin" 2>/dev/null; [ -t 1 ] && tput cnorm 2>/dev/null; } trap cleanup EXIT trap 'echo; exit 130' INT TERM run_step() { local label=$1 err=$2 flag=$3 rc shift 3 if [ -t 1 ]; then tput civis 2>/dev/null ( local f; while :; do for f in ⠋ ⠙ ⠹ ⠸ ⠼ ⠴ ⠦ ⠧ ⠇ ⠏; do printf '\r %s%s%s %s' "$C_O" "$f" "$C_R" "$label"; sleep 0.08; done; done ) & spin=$! fi "$@" >/dev/null 2>"$err" rc=$? if [ -n "$spin" ]; then kill "$spin" 2>/dev/null; wait "$spin" 2>/dev/null; spin=; tput cnorm 2>/dev/null; fi if [ $rc -eq 0 ]; then printf '\r\033[2K %s✓%s %s\n' "$C_G" "$C_R" "$label" printf -v "$flag" 1 else printf '\r\033[2K %s✗%s %s %s(%s)%s\n' "$C_E" "$C_R" "$label" "$C_D" "$err" "$C_R" fi } set_build() { IFS='|' read -r q l d <<<"$1"; qb_ver="qBittorrent-$q"; lib_ver="libtorrent-$l"; build_dir="$d"; } find_build() { local b q l d for b in "${BUILDS[@]}"; do IFS='|' read -r q l d <<<"$b" [ "$q" = "$1" ] && [ "$l" = "$2" ] && { set_build "$b"; return 0; } done return 1 } list_builds() { local i=1 b q l d for b in "${BUILDS[@]}"; do IFS='|' read -r q l d <<<"$b" echo -e " ${C_O}$i${C_R} qBittorrent $q ${C_D}libtorrent $l${C_R}" i=$((i+1)) done } choose_build() { local pick echo -e "\n ${C_B}qBittorrent build${C_R}" list_builds while :; do need_input "Select [1-${#BUILDS[@]}]:"; read -r pick [[ "$pick" =~ ^[0-9]+$ ]] && [ "$pick" -ge 1 ] && [ "$pick" -le "${#BUILDS[@]}" ] && break warn "Invalid choice" done set_build "${BUILDS[$((pick-1))]}" } update() { apt-get -qqy update && apt-get -qqy upgrade # Install Dependencies if [ -z $(which sudo) ]; then apt-get install sudo -qqy if [ $? -ne 0 ]; then fail_exit "Sudo Installation Failed" fi fi if [ -z $(which wget) ]; then apt-get install wget -qqy if [ $? -ne 0 ]; then fail_exit "Wget Installation Failed" fi fi if [ -z $(which curl) ]; then apt-get install curl -qqy if [ $? -ne 0 ]; then fail_exit "Curl Installation Failed" fi fi if [ -z $(which sysstat) ]; then apt-get install sysstat -qqy if [ $? -ne 0 ]; then fail_exit "Sysstat Installation Failed" fi fi if [ -z $(which psmisc) ]; then apt-get install psmisc -qqy if [ $? -ne 0 ]; then fail_exit "Psmisc Installation Failed" fi fi return 0 } tuned_() { if [ -z $(which tuned) ]; then apt-get -qqy install tuned #Check if install is successful if [ $? -ne 0 ]; then fail "Tuned Installation Failed" return 1 fi fi return 0 } # Network set_ring_buffer_() { interface=$(ip -o -4 route show to default | awk '{print $5}') if [ -z $(which ethtool) ]; then apt-get -y install ethtool if [ $? -ne 0 ]; then fail "Ethtool Installation Failed" return 1 fi fi ethtool -G $interface rx 1024 if [ $? -ne 0 ]; then fail "Ring Buffer Setting Failed" return 1 fi sleep 1 ethtool -G $interface tx 2048 if [ $? -ne 0 ]; then fail "Ring Buffer Setting Failed" return 1 fi sleep 1 } set_txqueuelen_() { interface=$(ip -o -4 route show to default | awk '{print $5}') if [ -z $(which net-tools) ]; then apt-get -y install net-tools if [ $? -ne 0 ]; then fail "net-tools Installation Failed" return 1 fi fi ifconfig $interface txqueuelen 10000 sleep 1 } set_initial_congestion_window_() { iproute=$(ip -o -4 route show to default) ip route change $iproute initcwnd 25 initrwnd 25 } disable_tso_() { interface=$(ip -o -4 route show to default | awk '{print $5}') if [ -z $(which ethtool) ]; then apt-get -y install ethtool if [ $? -ne 0 ]; then fail "Ethtool Installation Failed" return 1 fi fi ethtool -K $interface tso off gso off gro off sleep 1 return 0 } # Drive set_disk_scheduler_() { i=1 drive=() #List out all the available drives disk=$(lsblk -nd --output NAME) #Check if the disk is Set if [[ -z $disk ]]; then fail "Disk not found" return 1 fi #Count the number of drives diskno=$(echo $disk | awk '{print NF}') #Putting the device name in an array to loop through later while [ $i -le $diskno ] do device=$(echo $disk | awk -v i=$i '{print $i}') drive+=($device) i=$(( $i + 1 )) done i=1 x=0 #Changing the scheduler per disk depending on whether they are HDD or SSD while [ $i -le $diskno ] do diskname=$(eval echo ${drive["$x"]}) disktype=$(cat /sys/block/$diskname/queue/rotational) if [ "${disktype}" == 0 ]; then echo kyber > /sys/block/$diskname/queue/scheduler else echo mq-deadline > /sys/block/$diskname/queue/scheduler fi i=$(( $i + 1 )) x=$(( $x + 1 )) done return 0 } # File Open Limit set_file_open_limit_() { # return if $username is not Set if [[ -z $username ]]; then fail "Username not set" return 1 fi cat << EOF >>/etc/security/limits.conf ## Hard limit for max opened files $username hard nofile 1048576 ## Soft limit for max opened files $username soft nofile 1048576 EOF return 0 } # Kernel Settings kernel_settings_() { memory_size=$(grep MemTotal /proc/meminfo | awk '{print $2}') #Define upper limit for TCP memory tcp_mem_min_cap=262144 #1GB tcp_mem_pressure_cap=2097152 #8GB tcp_mem_max_cap=4194304 #16GB if [ -n $memory_size ]; then #memory_size in terms of 4K pages memory_4k=$(( $memory_size / 4 )) #Calculate the TCP memory values if [ $memory_size -le 524288 ]; then #If memory is equal or less than 512MB tcp_mem_min=$(( $memory_4k / 32 )) && tcp_mem_pressure=$(( $memory_4k / 16 )) && tcp_mem_max=$(( $memory_4k / 8 )) rmem_max=8388608 && wmem_max=8388608 && win_scale=3 elif [ $memory_size -le 1048576 ]; then #If memory is equal or less than 1GB tcp_mem_min=$(( $memory_4k / 16 )) && tcp_mem_pressure=$(( $memory_4k / 8 )) && tcp_mem_max=$(( $memory_4k / 6 )) rmem_max=16777216 && wmem_max=16777216 && win_scale=2 elif [ $memory_size -le 4194304 ]; then #If memory is equal or less than 4GB tcp_mem_min=$(( $memory_4k / 8 )) && tcp_mem_pressure=$(( $memory_4k / 6 )) && tcp_mem_max=$(( $memory_4k / 4 )) rmem_max=33554432 && wmem_max=33554432 && win_scale=2 elif [ $memory_size -le 16777216 ]; then #If memory is equal or less than 16GB tcp_mem_min=$(( $memory_4k / 8 )) && tcp_mem_pressure=$(( $memory_4k / 4 )) && tcp_mem_max=$(( $memory_4k / 2 )) rmem_max=67108864 && wmem_max=67108864 && win_scale=1 else #If memory is greater than 16GB tcp_mem_min=$(( $memory_4k / 8 )) && tcp_mem_pressure=$(( $memory_4k / 4 )) && tcp_mem_max=$(( $memory_4k / 2 )) rmem_max=134217728 && wmem_max=134217728 && win_scale=-2 fi #Check if the calculated values are greater than the cap if [ $tcp_mem_min -gt $tcp_mem_min_cap ]; then tcp_mem_min=$tcp_mem_min_cap fi if [ $tcp_mem_pressure -gt $tcp_mem_pressure_cap ]; then tcp_mem_pressure=$tcp_mem_pressure_cap fi if [ $tcp_mem_max -gt $tcp_mem_max_cap ]; then tcp_mem_max=$tcp_mem_max_cap fi tcp_mem="$tcp_mem_min $tcp_mem_pressure $tcp_mem_max" else fail "Memory size not found" tcp_mem=$(cat /proc/sys/net/ipv4/tcp_mem) tcp_rmem=$(cat /proc/sys/net/ipv4/tcp_rmem) tcp_wmem=$(cat /proc/sys/net/ipv4/tcp_wmem) rmem_max=$(cat /proc/sys/net/core/rmem_max) wmem_max=$(cat /proc/sys/net/core/wmem_max) win_scale=$(cat /proc/sys/net/ipv4/tcp_adv_win_scale) fi #Set the values rmem_default=262144 && wmem_default=16384 tcp_rmem="8192 $rmem_default $rmem_max" && tcp_wmem="4096 $wmem_default $wmem_max" #Check if all the variables are Set if [[ -z $tcp_mem ]] || [[ -z $tcp_rmem ]] || [[ -z $tcp_wmem ]] || [ -z $rmem_max ] || [ -z $wmem_max ] || [ -z $win_scale ]; then fail "Kernel settings not set" return 1 fi cat << EOF >/etc/sysctl.conf ###/proc/sys/kernel/ Variables: ##https://www.kernel.org/doc/Documentation/admin-guide/sysctl/kernel.rst # Allow for more PIDs kernel.pid_max = 4194303 # Maximum size of an IPC queue kernel.msgmnb = 65536 # maximum size of an IPC message kernel.msgmax = 65536 ## Process Scheduler Optimization kernel.sched_migration_cost_ns = 5000000 kernel.sched_autogroup_enabled = 0 kernel.sched_min_granularity_ns = 10000000 kernel.sched_wakeup_granularity_ns = 15000000 ###/proc/sys/fs/ ##https://www.kernel.org/doc/Documentation/admin-guide/sysctl/fs.rst # Maximum number of file-handles that the Linux kernel will allocate fs.file-max = 1048576 # Maximum number of file-handles a process can allocate fs.nr_open = 1048576 ###/proc/sys/vm Variables: ##https://www.kernel.org/doc/Documentation/admin-guide/sysctl/vm.rst # Percentage of available system memory which when dirty then system can start writing data to the disks # NOTE: The total available memory is not equal to total system memory vm.dirty_background_ratio = 5 # Percentage of available system memory which when dirty, the process doing writes would block and write out dirty pages to the disks vm.dirty_ratio = 30 # Define when dirty inode is old enough to be eligible for writeback by the kernel flusher threads & interval to wakeup dirtytime_writeback thread vm.dirty_expire_centisecs = 1000 # Period between each wake up and write old data out to disk vm.dirty_writeback_centisecs = 100 # Reduce swapping and keep memory pages in physical memory vm.swappiness = 10 ###/proc/sys/net/core - Network core options: ##https://www.kernel.org/doc/Documentation/admin-guide/sysctl/net.rst # NOTE: Difference in polling and interrupt # -Interrupt: Interrupt is a hardware mechanism in which, the device notices the CPU that it requires its attention./ # Interrupt can take place at any time. So when CPU gets an interrupt signal trough the indication interrupt-request line,/ # CPU stops the current process and respond to the interrupt by passing the control to interrupt handler which services device. # -Polling: In polling is not a hardware mechanism, its a protocol in which CPU steadily checks whether the device needs attention./ # Wherever device tells process unit that it desires hardware processing, #in polling process unit keeps asking the I/O device whether or not it desires CPU processing./ # The CPU ceaselessly check every and each device hooked up thereto for sleuthing whether or not any device desires hardware attention. # The Linux kernel uses the interrupt-driven mode by default and only switches to polling mode when the flow of incoming packets exceeds "net.core.dev_weight" number of data frames # The maximum number of packets that kernel can handle on a NAPI interrupt, it's a Per-CPU variable #net.core.dev_weight = 64 # Scales the maximum number of packets that can be processed during a RX softirq cycle. Calculation is based on dev_weight (dev_weight * dev_weight_rx_bias) #net.core.dev_weight_rx_bias = 1 # Scales the maximum number of packets that can be processed during a TX softirq cycle. Calculation is based on dev_weight (dev_weight * dev_weight_tx_bias) #net.core.dev_weight_tx_bias = 1 # NOTE: If the second column of "cat /proc/net/softnet_stat" is huge, there are frame drops and it might be wise to increase the value of net.core.netdev_max_backlog/ #If the third column increases, there are SoftIRQ Misses and it might be wise to increase either or both net.core.netdev_budget and net.core.netdev_budget_usecs # Maximum number of packets taken from all interfaces in one polling cycle (NAPI poll). net.core.netdev_budget = 50000 # Maximum number of microseconds in one polling cycle (NAPI poll). # NOTE: Could reduce if you have a CPU with high single core performance, NIC that supports RSS # NOTE: Setting a high number might cause CPU to stall and end in poor overall performance net.core.netdev_budget_usecs = 8000 # Maximum number of packets, queued on the INPUT side, when the interface receives packets faster than kernel can process them net.core.netdev_max_backlog = 100000 # Low latency busy poll timeout for socket reads # NOTE: Not supported by most NIC #net.core.busy_read=50 # Low latency busy poll timeout for poll and select # NOTE: Not supported by most NIC #net.core.busy_poll=50 # Receive socket buffer size net.core.rmem_default = $rmem_default net.core.rmem_max = $rmem_max # Send socket buffer size net.core.wmem_default = $wmem_default net.core.wmem_max = $wmem_max # Maximum ancillary buffer size allowed per socket # NOTE:Setting this value too high can lead to excessive kernel memory allocation for sockets, which might not be needed and could potentially waste system resources. net.core.optmem_max = 4194304 ###/proc/sys/net/ipv4/* Variables: ##https://www.kernel.org/doc/Documentation/networking/ip-sysctl.rst ## Routing Settings # Time, in seconds, that cached PMTU information is kept net.ipv4.route.mtu_expires = 1800 # Lowest possible mss setting, actuall advertised MSS depends on the first hop route MTU net.ipv4.route.min_adv_mss = 536 # Set PMTU to this value if fragmentation-required ICMP is received for that destination # NOTE: Only necessary if "net.ipv4.ip_no_pmtu_disc" is set to mode 1 #net.ipv4.route.min_pmtu = 1500 ## IP # System IP port limits net.ipv4.ip_local_port_range = 1024 65535 # Allow Path MTU Discovery net.ipv4.ip_no_pmtu_disc = 0 ## ARP table settings # The maximum number of bytes which may be used by packets queued for each unresolved address by other network layers net.ipv4.neigh.default.unres_qlen_bytes = 16777216 # The maximum number of packets which may be queued for each unresolved address by other network layers # NOTE: Deprecated in Linux 3.3 : use unres_qlen_bytes instead #net.ipv4.neigh.default.unres_qlen = 1024 ## TCP variables # Maximum queue length of completely established sockets waiting to be accepted net.core.somaxconn = 524288 #Maximum queue length of incomplete sockets i.e. half-open connection #NOTE: THis value should not be above "net.core.somaxconn", since that is also a hard open limit of maximum queue length of incomplete sockets/ #Kernel will take the lower one out of two as the maximum queue length of incomplete sockets net.ipv4.tcp_max_syn_backlog = 524288 # Recover and handle all requests instead of resetting them when system is overflowed with a burst of new connection attempts net.ipv4.tcp_abort_on_overflow = 0 # Maximal number of TCP sockets not attached to any user file handle (i.e. orphaned connections), held by system. # NOTE: each orphan eats up to ~64K of unswappable memory net.ipv4.tcp_max_orphans = 262144 # Maximal number of time-wait sockets held by system simultaneously net.ipv4.tcp_max_tw_buckets = 10240 # Enable TCP Packetization-Layer Path, and use initial MSS of tcp_base_mss net.ipv4.tcp_mtu_probing = 2 # Starting MSS used in Path MTU discovery net.ipv4.tcp_base_mss = 1460 # Minimum MSS used in connection, cap it to this value even if advertised ADVMSS option is even lower net.ipv4.tcp_min_snd_mss = 536 # Enable selective acknowledgments net.ipv4.tcp_sack = 1 # Send SACK more frequently net.ipv4.tcp_comp_sack_delay_ns = 250000 # Allows TCP to send "duplicate" SACKs net.ipv4.tcp_dsack = 1 # Enable Early Retransmit. ER lowers the threshold for triggering fast retransmit when the amount of outstanding data is small and when no previously unsent data can be transmitted net.ipv4.tcp_early_retrans = 3 # Disable ECN net.ipv4.tcp_ecn = 0 # Enable Forward Acknowledgment # NOTE: This is a legacy option, it has no effect anymore # net.ipv4.tcp_fack = 1 # TCP buffer size # Values are measured in memory pages. Size of memory pages can be found by "getconf PAGESIZE". Normally it is 4096 bytes # Vector of 3 INTEGERs: min, pressure, max # min: below this number of pages TCP is not bothered about its # memory appetite. # # pressure: when amount of memory allocated by TCP exceeds this number # of pages, TCP moderates its memory consumption and enters memory # pressure mode, which is exited when memory consumption falls # under "min". # # max: number of pages allowed for queuing by all TCP sockets net.ipv4.tcp_mem = $tcp_mem # TCP sockets receive buffer # Vector of 3 INTEGERs: min, default, max # min: Minimal size of receive buffer used by TCP sockets. # It is guaranteed to each TCP socket, even under moderate memory # pressure. # # default: initial size of receive buffer used by TCP sockets. # This value overrides net.core.rmem_default used by other protocols. # # max: maximal size of receive buffer allowed for automatically # selected receiver buffers for TCP socket. This value does not override # net.core.rmem_max. Calling setsockopt() with SO_RCVBUF disables # automatic tuning of that socket's receive buffer size, in which # case this value is ignored. net.ipv4.tcp_rmem = $tcp_rmem # Enable receive buffer auto-tuning net.ipv4.tcp_moderate_rcvbuf = 1 # Distribution of socket receive buffer space between TCP window size(this is the size of the receive window advertised to the other end), and application buffer/ #The overhead (application buffer) is counted as bytes/2^tcp_adv_win_scale i.e. Setting this 2 would mean we use 1/4 of socket buffer space as overhead # NOTE: Overhead reduces the effective window size, which in turn reduces the maximum possible data in flight which is window size*RTT # NOTE: Overhead helps isolating the network from scheduling and application latencies net.ipv4.tcp_adv_win_scale = $win_scale # Max reserved byte of TCP window for application buffer. The value will be between window/2^tcp_app_win and mss # See "https://www.programmersought.com/article/75001203063/" for more detail about tcp_app_win & tcp_adv_win_scale # NOTE: This application buffer is different from the one assigned by tcp_adv_win_scale # Default # net.ipv4.tcp_app_win = 31 # TCP sockets send buffer # Vector of 3 INTEGERs: min, default, max # min: Amount of memory reserved for send buffers for TCP sockets. # Each TCP socket has rights to use it due to fact of its birth. # # default: initial size of send buffer used by TCP sockets. This # value overrides net.core.wmem_default used by other protocols. # It is usually lower than net.core.wmem_default. # # max: Maximal amount of memory allowed for automatically tuned # send buffers for TCP sockets. This value does not override # net.core.wmem_max. Calling setsockopt() with SO_SNDBUF disables # automatic tuning of that socket's send buffer size, in which case # this value is ignored. net.ipv4.tcp_wmem = $tcp_wmem # Reordering level of packets in a TCP stream # NOTE: Reordering is costly but it happens quite a lot. Instead of declaring packet lost and requiring retransmit, try harder to reorder first # Initial reordering level of packets in a TCP stream. TCP stack can then dynamically adjust flow reordering level between this initial value and tcp_max_reordering net.ipv4.tcp_reordering = 10 # Maximal reordering level of packets in a TCP stream net.ipv4.tcp_max_reordering = 600 # Number of times SYNACKs for a passive TCP connection attempt will be retransmitted net.ipv4.tcp_synack_retries = 10 # Number of times initial SYNs for an active TCP connection attempt will be retransmitted net.ipv4.tcp_syn_retries = 7 # In seconds, time default value for connections to keep alive net.ipv4.tcp_keepalive_time = 7200 # How many keepalive probes TCP sends out, until it decides that the connection is broken net.ipv4.tcp_keepalive_probes = 15 # In seconds, how frequently the probes are send out net.ipv4.tcp_keepalive_intvl = 60 # Number of retries before killing a TCP connection # Time, after which TCP decides, that something is wrong due to unacknowledged RTO retransmissions, and reports this suspicion to the network layer. net.ipv4.tcp_retries1 = 3 # Time, after which TCP decides to timeout the TCP connection, when RTO retransmissions remain unacknowledged net.ipv4.tcp_retries2 = 10 # How many times to retry to kill connections on the other side before killing it on our own side net.ipv4.tcp_orphan_retries = 2 #Disable TCP auto corking, as it needlessly increasing latency when the application doesn't expect to send more data net.ipv4.tcp_autocorking = 0 # Disables Forward RTO-Recovery, since we are not operating on a lossy wireless network net.ipv4.tcp_frto = 0 # Protect Against TCP TIME-WAIT Assassination net.ipv4.tcp_rfc1337 = 1 # Avoid falling back to slow start after a connection goes idle net.ipv4.tcp_slow_start_after_idle = 0 # Enable both client support & server support of TCP Fast Open net.ipv4.tcp_fastopen = 3 # Disable timestamps net.ipv4.tcp_timestamps = 0 # Keep sockets in the state FIN-WAIT-2 for ultra short period if we were the one closing the socket, because this gives us no benefit and eats up memory net.ipv4.tcp_fin_timeout = 5 # Enable cache metrics on closing connections net.ipv4.tcp_no_metrics_save = 1 # Enable reuse of TIME-WAIT sockets for new connections net.ipv4.tcp_tw_reuse = 1 # Allows the use of a large window (> 64 kB) on a TCP connection net.ipv4.tcp_window_scaling = 1 # Set maximum window size to MAX_TCP_WINDOW i.e. 32767 in times there is no received window scaling option net.ipv4.tcp_workaround_signed_windows = 1 # The maximum amount of unsent bytes in TCP socket write queue, this is on top of the congestion window net.ipv4.tcp_notsent_lowat = 131072 # Controls the amount of data in the Qdisc queue or device queue net.ipv4.tcp_limit_output_bytes = 3276800 # Controls a per TCP socket cache of one socket buffer # Use Huge amount of memory #net.ipv4.tcp_rx_skb_cache = 1 # Congestion Control net.core.default_qdisc = fq net.ipv4.tcp_congestion_control = bbr EOF sysctl -p return 0 } # BBR install_bbrx_() { #Check if $OS is Set if [[ -z $OS ]]; then # Linux Distro Version check if [ -f /etc/os-release ]; then . /etc/os-release OS=$NAME elif type lsb_release >/dev/null 2>&1; then OS=$(lsb_release -si) elif [ -f /etc/lsb-release ]; then . /etc/lsb-release OS=$DISTRIB_ID elif [ -f /etc/debian_version ]; then OS=Debian else OS=$(uname -s) VER=$(uname -r) fi fi if [[ "$OS" =~ "Debian" ]]; then if [ $(uname -m) == "x86_64" ]; then apt-get -y install linux-image-amd64 linux-headers-amd64 if [ $? -ne 0 ]; then fail "BBR installation failed" return 1 fi elif [ $(uname -m) == "aarch64" ]; then apt-get -y install linux-image-arm64 linux-headers-arm64 if [ $? -ne 0 ]; then fail "BBR installation failed" return 1 fi fi elif [[ "$OS" =~ "Ubuntu" ]]; then apt-get -y install linux-image-generic linux-headers-generic if [ $? -ne 0 ]; then fail "BBR installation failed" return 1 fi else fail "Unsupported OS" return 1 fi cat > /root/BBRx.sh << 'BBRXEOF' #!/bin/bash sleep 60s ## Installing BBR cd $HOME ## This part of the script is modified from https://github.com/KozakaiAya/TCP_BBR #Install dkms if not installed if [ ! -x /usr/sbin/dkms ]; then apt-get -y install dkms if [ ! -x /usr/sbin/dkms ]; then echo "Error: dkms is not installed" >&2 exit 1 fi fi #Ensure there is header file if [ ! -f /usr/src/linux-headers-$(uname -r)/.config ]; then if [[ -z $(apt-cache search linux-headers-$(uname -r)) ]]; then echo "Error: linux-headers-$(uname -r) not found" >&2 exit 1 fi apt-get -y install linux-headers-$(uname -r) if [ ! -f /usr/src/linux-headers-$(uname -r)/.config ]; then echo "Error: linux-headers-$(uname -r) is not installed" >&2 exit 1 fi fi #BBRx wget -q __BASE__/bbrx/tcp_bbrx.c -O $HOME/tcp_bbrx.c if [ ! -f $HOME/tcp_bbrx.c ]; then echo "Error: Download failed! Exiting." >&2 exit 1 fi kernel_ver=5.15.0 algo=bbrx # Compile and install bbr_file=tcp_$algo bbr_src=$bbr_file.c bbr_obj=$bbr_file.o mkdir -p $HOME/.bbr/src cd $HOME/.bbr/src mv $HOME/$bbr_src $HOME/.bbr/src/$bbr_src # Create Makefile cat > ./Makefile << EOF obj-m:=$bbr_obj default: make -C /lib/modules/\$(shell uname -r)/build M=\$(PWD)/src modules clean: -rm modules.order -rm Module.symvers -rm .[!.]* ..?* -rm $bbr_file.mod -rm $bbr_file.mod.c -rm *.o -rm *.cmd EOF # Create dkms.conf cd .. cat > ./dkms.conf << EOF MAKE="'make' -C src/" CLEAN="make -C src/ clean" BUILT_MODULE_NAME=$bbr_file BUILT_MODULE_LOCATION=src/ DEST_MODULE_LOCATION=/updates/net/ipv4 PACKAGE_NAME=$algo PACKAGE_VERSION=$kernel_ver REMAKE_INITRD=yes EOF # Start dkms install cp -R . /usr/src/$algo-$kernel_ver dkms add -m $algo -v $kernel_ver if [ ! $? -eq 0 ]; then dkms remove -m $algo/$kernel_ver --all exit 1 fi dkms build -m $algo -v $kernel_ver if [ ! $? -eq 0 ]; then dkms remove -m $algo/$kernel_ver --all exit 1 fi dkms install -m $algo -v $kernel_ver if [ ! $? -eq 0 ]; then dkms remove -m $algo/$kernel_ver --all exit 1 fi # Test loading module modprobe $bbr_file if [ ! $? -eq 0 ]; then exit 1 fi # Auto-load kernel module at system startup echo $bbr_file | sudo tee -a /etc/modules sed -i '/net.ipv4.tcp_congestion_control/d' /etc/sysctl.conf echo "net.ipv4.tcp_congestion_control = $algo" >> /etc/sysctl.conf sysctl -p > /dev/null cd $HOME rm -r $HOME/.bbr ## Clear systemctl disable bbrinstall.service rm /etc/systemd/system/bbrinstall.service rm /root/BBRx.sh BBRXEOF sed -i "s#__BASE__#$BASE#g" /root/BBRx.sh && chmod +x /root/BBRx.sh # Check if download fail if [ ! -s /root/BBRx.sh ]; then fail "BBR download failed" return 1 fi ## Install tweaked BBR automatically on reboot cat << EOF > /etc/systemd/system/bbrinstall.service [Unit] Description=BBRinstall After=network.target [Service] Type=oneshot ExecStart=/root/BBRx.sh RemainAfterExit=true [Install] WantedBy=multi-user.target EOF systemctl enable bbrinstall.service return 0 } install_qBittorrent_(){ username=$1 password=$2 qb_ver=$3 lib_ver=$4 qb_cache=$5 qb_port=$6 qb_incoming_port=$7 ## Check if qBittorrent is running if pgrep -i -f qbittorrent; then warn "qBittorrent is running. Stopping it now..." pkill -s $(pgrep -i -f qbittorrent) fi # Check if it is still running if pgrep -i -f qbittorrent; then warn "Failed to stop qBittorrent. Please stop it manually" return 1 fi ## Check if qbittorrent-nox is installed if test -e /usr/bin/qbittorrent-nox; then warn "qBittorrent is already installed. Replacing it now..." rm /usr/bin/qbittorrent-nox fi ## Download qBittorrent-nox executable # Determine the CPU architecture if [[ $(uname -m) == "x86_64" ]]; then arch="x86_64" elif [[ $(uname -m) == "aarch64" ]]; then arch="arm64" else warn "Unsupported CPU architecture" return 1 fi fetch "$BASE/$arch/$build_dir/qbittorrent-nox" $HOME/qbittorrent-nox && chmod +x $HOME/qbittorrent-nox #Check if the download is successful if [ $? -ne 0 ]; then warn "Failed to download qBittorrent-nox executable" return 1 fi # Install qbittorrent-nox mv $HOME/qbittorrent-nox /usr/bin/qbittorrent-nox mkdir -p /home/$username/qbittorrent/Downloads && chown -R $username:$username /home/$username/qbittorrent/ mkdir -p /home/$username/.config/qBittorrent && chown $username:$username /home/$username/.config/qBittorrent # Create systemd services if test -e /etc/systemd/system/qbittorrent-nox@.service; then warn "qBittorrent systemd services already exist. Removing it now..." rm /etc/systemd/system/qbittorrent-nox@.service fi touch /etc/systemd/system/qbittorrent-nox@.service cat << EOF >/etc/systemd/system/qbittorrent-nox@.service [Unit] Description=qBittorrent After=network.target [Service] Type=forking User=$username LimitNOFILE=infinity ExecStart=/usr/bin/qbittorrent-nox -d ExecStop=/usr/bin/killall -w -s 9 /usr/bin/qbittorrent-nox Restart=on-failure TimeoutStopSec=20 RestartSec=10 [Install] WantedBy=multi-user.target EOF systemctl enable qbittorrent-nox@$username systemctl start qbittorrent-nox@$username ## Configure qBittorrent # Check for Virtual Environment since some of the tunning might not work on virtual machine systemd-detect-virt > /dev/null if [ $? -eq 0 ]; then warn "Virtualization is detected, skipping some of the tunning" aio=8 low_buffer=3072 buffer=15360 buffer_factor=200 else #Determine if it is a SSD or a HDD disk_name=$(printf $(lsblk | grep -m1 'disk' | awk '{print $1}')) disktype=$(cat /sys/block/$disk_name/queue/rotational) if [ "${disktype}" == 0 ]; then aio=12 low_buffer=5120 buffer=20480 buffer_factor=250 else aio=4 low_buffer=3072 buffer=10240 buffer_factor=150 fi fi # Editing qBittorrent settings systemctl stop qbittorrent-nox@$username if [[ "${qb_ver}" =~ "4.1." ]]; then md5password=$(echo -n $password | md5sum | awk '{print $1}') cat << EOF >/home/$username/.config/qBittorrent/qBittorrent.conf [BitTorrent] Session\AsyncIOThreadsCount=$aio Session\SendBufferLowWatermark=$low_buffer Session\SendBufferWatermark=$buffer Session\SendBufferWatermarkFactor=$buffer_factor [LegalNotice] Accepted=true [Network] Cookies=@Invalid() [Preferences] Connection\PortRangeMin=$qb_incoming_port Downloads\DiskWriteCacheSize=$qb_cache Downloads\SavePath=/home/$username/qbittorrent/Downloads/ Queueing\QueueingEnabled=false WebUI\Password_ha1=@ByteArray($md5password) WebUI\Port=$qb_port WebUI\Username=$username EOF elif [[ "${qb_ver}" =~ "4.2."|"4.3." ]]; then fetch "$BASE/$arch/qb_password_gen" $HOME/qb_password_gen && chmod +x $HOME/qb_password_gen #Check if the download is successful if [ $? -ne 0 ]; then warn "Failed to download qb_password_gen" #Clean up rm -r /home/$username/qbittorrent/Downloads rm -r /home/$username/.config/qBittorrent rm /usr/bin/qbittorrent-nox rm /etc/systemd/system/qbittorrent-nox@.service return 1 fi PBKDF2password=$($HOME/qb_password_gen $password) cat << EOF >/home/$username/.config/qBittorrent/qBittorrent.conf [BitTorrent] Session\AsyncIOThreadsCount=$aio Session\SendBufferLowWatermark=$low_buffer Session\SendBufferWatermark=$buffer Session\SendBufferWatermarkFactor=$buffer_factor [LegalNotice] Accepted=true [Network] Cookies=@Invalid() [Preferences] Connection\PortRangeMin=$qb_incoming_port Downloads\DiskWriteCacheSize=$qb_cache Downloads\SavePath=/home/$username/qbittorrent/Downloads/ Queueing\QueueingEnabled=false WebUI\Password_PBKDF2="@ByteArray($PBKDF2password)" WebUI\Port=$qb_port WebUI\Username=$username EOF rm qb_password_gen elif [[ "${qb_ver}" =~ "4.4."|"4.5."|"4.6." ]]; then fetch "$BASE/$arch/qb_password_gen" $HOME/qb_password_gen && chmod +x $HOME/qb_password_gen #Check if the download is successful if [ $? -ne 0 ]; then warn "Failed to download qb_password_gen" #Clean up rm -r /home/$username/qbittorrent/Downloads rm -r /home/$username/.config/qBittorrent rm /usr/bin/qbittorrent-nox rm /etc/systemd/system/qbittorrent-nox@.service return 1 fi PBKDF2password=$($HOME/qb_password_gen $password) cat << EOF >/home/$username/.config/qBittorrent/qBittorrent.conf [Application] MemoryWorkingSetLimit=$qb_cache [BitTorrent] Session\AsyncIOThreadsCount=$aio Session\DefaultSavePath=/home/$username/qbittorrent/Downloads/ Session\DiskCacheSize=$qb_cache Session\Port=$qb_incoming_port Session\QueueingSystemEnabled=false Session\SendBufferLowWatermark=$low_buffer Session\SendBufferWatermark=$buffer Session\SendBufferWatermarkFactor=$buffer_factor [LegalNotice] Accepted=true [Network] Cookies=@Invalid() [Preferences] WebUI\Password_PBKDF2="@ByteArray($PBKDF2password)" WebUI\Port=$qb_port WebUI\Username=$username EOF rm qb_password_gen fi systemctl start qbittorrent-nox@$username } interactive= [ $# -eq 0 ] && interactive=1 while getopts "u:p:c:q:l:xoh" opt; do case ${opt} in u ) username=${OPTARG} ;; p ) password=${OPTARG} ;; c ) cache=${OPTARG} [[ "$cache" =~ ^[0-9]+$ ]] || fail_exit "Cache must be a number (MiB)" qb_cache=$cache ;; q ) qb_install=1; opt_q=${OPTARG} ;; l ) opt_l=${OPTARG} ;; x ) bbrx_install=1 ;; o ) ask_ports=1 ;; h ) banner echo -e "\n Usage: bash <(wget -qO- URL/install) [options]\n" echo -e " -u username -p password -c qBittorrent cache (MiB)" echo -e " -q qBittorrent -l libtorrent -x install BBRx" echo -e " -o ask for ports -h this help\n" echo -e " ${C_B}Builds${C_R}" list_builds echo exit 0 ;; \? ) exit 1 ;; esac done banner info "Checking environment" [ "$(id -u)" -ne 0 ] && fail_exit "Run this as root" if [ -f /etc/os-release ]; then . /etc/os-release OS=$NAME VER=$VERSION_ID elif [ -f /etc/debian_version ]; then OS=Debian VER=$(cat /etc/debian_version) else OS=$(uname -s) VER=$(uname -r) fi major=${VER%%.*} if [[ "$OS" =~ "Debian" ]]; then [[ -n "$major" && "$major" =~ ^[0-9]+$ && "$major" -lt 10 ]] && fail_exit "Debian $VER is not supported (10+ only)" elif [[ "$OS" =~ "Ubuntu" ]]; then [[ "$major" =~ ^[0-9]+$ && "$major" -lt 20 ]] && fail_exit "Ubuntu $VER is not supported (20.04+ only)" else fail_exit "$OS $VER is not supported (Debian 10+ and Ubuntu 20.04+ only)" fi case "$(uname -m)" in x86_64) arch=x86_64 ;; aarch64) arch=arm64 ;; *) fail_exit "Unsupported CPU architecture $(uname -m)" ;; esac info_3 "$OS $VER on $arch" if [ -n "$interactive" ]; then echo yesno "Install qBittorrent?" y && qb_install=1 yesno "Install BBRx (needs a reboot)?" n && bbrx_install=1 fi if [ -n "$qb_install" ]; then if [ -z "$username" ]; then while :; do ask username "Username" admin [[ "$username" =~ ^[a-z_][a-z0-9_-]*$ ]] && break warn "Use lowercase letters, digits, - and _" done fi if [ -z "$password" ]; then need_input "Password (blank = generate):"; read -rs password; echo [ -z "$password" ] && password=$(tr -dc 'A-Za-z0-9' /dev/null 2>&1; then useradd -m -s /bin/bash "$username" || fail_exit "Failed to create user $username" fi chown -R "$username:$username" "/home/$username" run_step "qBittorrent ${qb_ver#qBittorrent-} with ${lib_ver#libtorrent-}" /tmp/qb_error qb_install_success \ install_qBittorrent_ "$username" "$password" "$qb_ver" "$lib_ver" "$qb_cache" "$qb_port" "$qb_incoming_port" fi info "Tuning system" run_step "Installing tuned" /tmp/tuned_error tuned_success tuned_ run_step "Setting txqueuelen" /tmp/txqueuelen_error txqueuelen_success set_txqueuelen_ run_step "Setting file open limit" /tmp/file_open_limit_error file_open_limit_success set_file_open_limit_ if systemd-detect-virt >/dev/null; then warn "Virtualization detected, skipping disk and ring buffer tuning" run_step "Disabling TSO" /tmp/tso_error tso_success disable_tso_ else run_step "Setting disk scheduler" /tmp/disk_scheduler_error disk_scheduler_success set_disk_scheduler_ run_step "Setting ring buffer" /tmp/ring_buffer_error ring_buffer_success set_ring_buffer_ fi run_step "Setting initial congestion window" /tmp/initial_congestion_window_error initial_congestion_window_success set_initial_congestion_window_ run_step "Applying kernel settings" /tmp/kernel_settings_error kernel_settings_success kernel_settings_ if [ -n "$bbrx_install" ]; then if lsmod | grep -q bbrx; then warn "BBRx is already installed" else info "Installing BBRx" run_step "BBRx" /tmp/bbrx_error bbrx_install_success install_bbrx_ fi fi info "Configuring boot script" { echo '#!/bin/bash' echo 'sleep 120s' declare -f fail set_txqueuelen_ disable_tso_ set_disk_scheduler_ set_ring_buffer_ set_initial_congestion_window_ echo 'set_txqueuelen_' echo 'if systemd-detect-virt > /dev/null; then' echo ' disable_tso_' echo 'else' echo ' set_disk_scheduler_' echo ' set_ring_buffer_' echo 'fi' echo 'set_initial_congestion_window_' } > /root/.boot-script.sh chmod +x /root/.boot-script.sh cat << EOF > /etc/systemd/system/boot-script.service [Unit] Description=boot-script After=network.target [Service] Type=simple ExecStart=/root/.boot-script.sh RemainAfterExit=true [Install] WantedBy=multi-user.target EOF systemctl enable boot-script.service >/dev/null 2>&1 && info_3 "Boot script enabled" info "Done" publicip=$(curl -s https://ipinfo.io/ip) if [ -n "$qb_install_success" ]; then echo boring_text "WebUI http://$publicip:$qb_port" boring_text "Username $username" boring_text "Password $password" fi [ -n "$bbrx_install_success" ] && { echo; warn "Reboot to activate BBRx"; } echo exit 0