forked from Musixal/Rathole-Tunnel
-
Notifications
You must be signed in to change notification settings - Fork 0
/
rathole_v2.sh
1667 lines (1361 loc) · 45.3 KB
/
rathole_v2.sh
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
#!/bin/bash
# Check if the script is run as root
if [[ $EUID -ne 0 ]]; then
echo "This script must be run as root"
sleep 1
exit 1
fi
# just press key to continue
press_key(){
read -p "Press any key to continue..."
}
# Define a function to colorize text
colorize() {
local color="$1"
local text="$2"
local style="${3:-normal}"
# Define ANSI color codes
local black="\033[30m"
local red="\033[31m"
local green="\033[32m"
local yellow="\033[33m"
local blue="\033[34m"
local magenta="\033[35m"
local cyan="\033[36m"
local white="\033[37m"
local reset="\033[0m"
# Define ANSI style codes
local normal="\033[0m"
local bold="\033[1m"
local underline="\033[4m"
# Select color code
local color_code
case $color in
black) color_code=$black ;;
red) color_code=$red ;;
green) color_code=$green ;;
yellow) color_code=$yellow ;;
blue) color_code=$blue ;;
magenta) color_code=$magenta ;;
cyan) color_code=$cyan ;;
white) color_code=$white ;;
*) color_code=$reset ;; # Default case, no color
esac
# Select style code
local style_code
case $style in
bold) style_code=$bold ;;
underline) style_code=$underline ;;
normal | *) style_code=$normal ;; # Default case, normal text
esac
# Print the colored and styled text
echo -e "${style_code}${color_code}${text}${reset}"
}
# Function to install unzip if not already installed
install_unzip() {
if ! command -v unzip &> /dev/null; then
# Check if the system is using apt package manager
if command -v apt-get &> /dev/null; then
echo -e "${RED}unzip is not installed. Installing...${NC}"
sleep 1
sudo apt-get update
sudo apt-get install -y unzip
else
echo -e "${RED}Error: Unsupported package manager. Please install unzip manually.${NC}\n"
press_key
exit 1
fi
fi
}
# Install unzip
install_unzip
#Function to install cron if not already installed
install_cron() {
if ! command -v cron &> /dev/null; then
# Check if the system is using apt package manager
if command -v apt-get &> /dev/null; then
echo -e "${RED}cron is not installed. Installing...${NC}"
sleep 1
sudo apt-get update
sudo apt-get install -y cron
else
echo -e "${RED}Error: Unsupported package manager. Please install cron manually.${NC}\n"
press_key
exit 1
fi
fi
}
# Install cron
install_cron
# Function to install jq if not already installed
install_jq() {
if ! command -v jq &> /dev/null; then
# Check if the system is using apt package manager
if command -v apt-get &> /dev/null; then
echo -e "${RED}jq is not installed. Installing...${NC}"
sleep 1
sudo apt-get update
sudo apt-get install -y jq
else
echo -e "${RED}Error: Unsupported package manager. Please install jq manually.${NC}\n"
press_key
exit 1
fi
fi
}
# Install jq
install_jq
config_dir="/root/rathole-core"
# Function to download and extract Rathole Core
download_and_extract_rathole() {
# check if core installed already
if [[ -f "${config_dir}/rathole" ]]; then
if [[ "$1" == "sleep" ]]; then
echo
colorize green "Rathole Core is already installed." bold
sleep 1
fi
return 1
fi
# Define the entry to check/add
ENTRY="185.199.108.133 raw.githubusercontent.com"
# Check if the github entry exists in /etc/hosts
if ! grep -q "$ENTRY" /etc/hosts; then
echo "Github Entry not found. Adding to /etc/hosts..."
echo "$ENTRY" >> /etc/hosts
else
echo "Github entry already exists in /etc/hosts."
fi
# Check operating system
if [[ $(uname) == "Linux" ]]; then
ARCH=$(uname -m)
DOWNLOAD_URL=$(curl -sSL https://api.github.com/repos/rapiz1/rathole/releases/latest | grep -o "https://.*$ARCH.*linux.*zip" | head -n 1)
else
echo -e "${RED}Unsupported operating system.${NC}"
sleep 1
exit 1
fi
if [[ "$ARCH" == "x86_64" ]]; then
DOWNLOAD_URL='https://github.com/Musixal/rathole-tunnel/raw/main/core/rathole.zip'
fi
if [ -z "$DOWNLOAD_URL" ]; then
echo -e "${RED}Failed to retrieve download URL.${NC}"
sleep 1
exit 1
fi
DOWNLOAD_DIR=$(mktemp -d)
echo -e "Downloading Rathole from $DOWNLOAD_URL...\n"
sleep 1
curl -sSL -o "$DOWNLOAD_DIR/rathole.zip" "$DOWNLOAD_URL"
echo -e "Extracting Rathole...\n"
sleep 1
unzip -q "$DOWNLOAD_DIR/rathole.zip" -d "$config_dir"
echo -e "${GREEN}Rathole installation completed.${NC}\n"
chmod u+x ${config_dir}/rathole
rm -rf "$DOWNLOAD_DIR"
}
#Download and extract the Rathole core
download_and_extract_rathole
# Get server IP
#SERVER_IP=$(hostname -I | awk '{print $1}')
# Fetch server country
SERVER_COUNTRY=$(curl -sS "http://ipwhois.app/json/$SERVER_IP" | jq -r '.country')
# Fetch server isp
SERVER_ISP=$(curl -sS "http://ipwhois.app/json/$SERVER_IP" | jq -r '.isp')
# Function to display ASCII logo
# Function to display ASCII logo
display_logo() {
echo -e "${CYAN}"
cat << "EOF"
__ .__ .__
____________ _/ |_| |__ ____ | | ____
\_ __ \__ \\ __| | \ / _ \| | _/ __ \
| | \// __ \| | | Y ( <_> | |_\ ___/
|__| (____ |__| |___| /\____/|____/\___ >
\/ \/ \/
EOF
echo -e "${NC}${GREEN}"
echo -e "Version: ${YELLOW}v2.0${GREEN}"
echo -e "Developer: ${YELLOW}Musixal (Russian Translation: ILYAGVC)${GREEN}"
echo -e "Github: ${YELLOW}github.com/ILYAGVC/Rathole-Tunnel-Ru${GREEN}"
}
# Function to display server location and IP
display_server_info() {
echo -e "\e[93m═════════════════════════════════════════════\e[0m"
# Hidden for security issues
#echo -e "${CYAN}IP Address:${NC} $SERVER_IP"
echo -e "${CYAN}Location:${NC} $SERVER_COUNTRY "
echo -e "${CYAN}Datacenter:${NC} $SERVER_ISP"
}
# Function to display Rathole Core installation status
display_rathole_core_status() {
if [[ -f "${config_dir}/rathole" ]]; then
echo -e "${CYAN}Rathole Core:${NC} ${GREEN}Installed${NC}"
else
echo -e "${CYAN}Rathole Core:${NC} ${RED}Not installed${NC}"
fi
echo -e "\e[93m═════════════════════════════════════════════\e[0m"
}
# Function to check if a given string is a valid IPv6 address
check_ipv6() {
local ip=$1
# Define the IPv6 regex pattern
ipv6_pattern="^([0-9a-fA-F]{1,4}:){7}([0-9a-fA-F]{1,4}|:)$|^(([0-9a-fA-F]{1,4}:){1,7}|:):((:[0-9a-fA-F]{1,4}){1,7}|:)$"
# Remove brackets if present
ip="${ip#[}"
ip="${ip%]}"
if [[ $ip =~ $ipv6_pattern ]]; then
return 0 # Valid IPv6 address
else
return 1 # Invalid IPv6 address
fi
}
check_port() {
local PORT=$1
local TRANSPORT=$2
if [ -z "$PORT" ]; then
echo "Usage: check_port <port> <transport>"
return 1
fi
if [[ "$TRANSPORT" == "tcp" ]]; then
if ss -tlnp "sport = :$PORT" | grep "$PORT" > /dev/null; then
return 0
else
return 1
fi
elif [[ "$TRANSPORT" == "udp" ]]; then
if ss -ulnp "sport = :$PORT" | grep "$PORT" > /dev/null; then
return 0
else
return 1
fi
else
return 1
fi
}
# Function for configuring tunnel
configure_tunnel() {
# check if the rathole-core installed or not
if [[ ! -d "$config_dir" ]]; then
echo -e "\n${RED}Rathole-core directory not found. Install it first through 'Install Rathole core' option.${NC}\n"
read -p "Press Enter to continue..."
return 1
fi
clear
colorize green "Essential tips:" bold
colorize yellow " Enable TCP_NODELAY to improve the latency but decrease the bandwidth.
For the high number of connections, I recommend turning off the Heartbeat option"
echo
colorize green "1) Configure for Russia server" bold
colorize magenta "2) Configure for Outside server" bold
echo
read -p "Enter your choice: " configure_choice
case "$configure_choice" in
1) Russia_server_configuration ;;
2) Outside_server_configuration ;;
*) echo -e "${RED}Invalid option!${NC}" && sleep 1 ;;
esac
echo
read -p "Press Enter to continue..."
}
#Global Variables
service_dir="/etc/systemd/system"
# Function to configure Russia server
Russia_server_configuration() {
clear
colorize cyan "Configuring Russia server" bold
echo
#Add IPv6 Support
local_ip='0.0.0.0'
read -p "[-] Listen for IPv6 address? (y/n): " answer
if [ "$answer" = "y" ] || [ "$answer" = "Y" ]; then
colorize yellow "IPv6 Enabled"
local_ip='[::]'
elif [ "$answer" = "n" ]; then
colorize yellow "IPv4 Enabled"
local_ip='0.0.0.0'
else
colorize yellow "Invalid choice. IPv4 enabled by default."
local_ip='0.0.0.0'
fi
echo
while true; do
echo -ne "[*] Tunnel port: "
read -r tunnel_port
if [[ "$tunnel_port" =~ ^[0-9]+$ ]] && [ "$tunnel_port" -gt 22 ] && [ "$tunnel_port" -le 65535 ]; then
if check_port "$tunnel_port" "tcp"; then
colorize red "Port $tunnel_port is in use."
else
break
fi
else
colorize red "Please enter a valid port number between 23 and 65535"
fi
done
echo
# Initialize nodelay variable
local nodelay=""
# Keep prompting the user until a valid input is provided
while [[ "$nodelay" != "true" && "$nodelay" != "false" ]]; do
echo -ne "[*] Enable TCP_NODELAY (true/false): "
read -r nodelay
if [[ "$nodelay" != "true" && "$nodelay" != "false" ]]; then
colorize red "Invalid TCP_NODELAY value. Please enter 'true' or 'false'"
fi
done
echo
# Initialize HEARTBEAT variable
local HEARTBEAT=""
# Keep prompting the user until a valid input is provided
while [[ "$HEARTBEAT" != "true" && "$HEARTBEAT" != "false" ]]; do
echo -ne "[*] Enable HEARTBEAT (true/false): "
read -r HEARTBEAT
if [[ "$HEARTBEAT" != "true" && "$HEARTBEAT" != "false" ]]; then
colorize red "Invalid HEARTBEAT value. Please enter 'true' or 'false'"
fi
done
if [[ "$HEARTBEAT" == "true" ]]; then
HEARTBEAT="30"
else
HEARTBEAT="0"
fi
echo
# Initialize transport variable
local transport=""
# Keep prompting the user until a valid input is provided
while [[ "$transport" != "tcp" && "$transport" != "udp" ]]; do
# Prompt the user to input transport type
echo -ne "[*] Transport type(tcp/udp): "
read -r transport
# Check if the input is either tcp or udp
if [[ "$transport" != "tcp" && "$transport" != "udp" ]]; then
colorize red "Invalid transport type. Please enter 'tcp' or 'udp'"
fi
done
echo
echo -ne "[-] Security Token (press enter to use default value): "
read -r token
if [[ -z "$token" ]]; then
token="musixal"
fi
echo
# Prompt for Ports
echo -ne "[*] Enter your ports separated by commas (e.g. 2070,2080): "
read -r input_ports
input_ports=$(echo "$input_ports" | tr -d ' ')
# Convert the input into an array, splitting by comma
IFS=',' read -r -a ports <<< "$input_ports"
declare -a config_ports
# Iterate through each port and perform an action
for port in "${ports[@]}"; do
if [[ "$port" =~ ^[0-9]+$ ]] && [ "$port" -gt 22 ] && [ "$port" -le 65535 ]; then
if check_port "$port" "$transport"; then
colorize red "[ERROR] Port $port is in use."
else
colorize green "[INFO] Port $port added to your configs"
config_ports+=("$port")
fi
else
colorize red "[ERROR] Port $port is Invalid. Please enter a valid port number between 23 and 65535"
fi
done
if [ ${#config_ports[@]} -eq 0 ]; then
colorize red "No ports were entered. Exiting." bold
sleep 2
return 1
fi
# Generate server configuration file
cat << EOF > "${config_dir}/Russia${tunnel_port}.toml"
[server]
bind_addr = "${local_ip}:${tunnel_port}"
default_token = "$token"
heartbeat_interval = $HEARTBEAT
[server.transport]
type = "tcp"
[server.transport.tcp]
nodelay = $nodelay
EOF
# Add each config port to the configuration file
for port in "${config_ports[@]}"; do
cat << EOF >> "${config_dir}/Russia${tunnel_port}.toml"
[server.services.${port}]
type = "$transport"
bind_addr = "${local_ip}:${port}"
EOF
done
echo
# Create the systemd service unit file
cat << EOF > "${service_dir}/rathole-Russia${tunnel_port}.service"
[Unit]
Description=Rathole Russia Port $tunnel_port (Russia)
After=network.target
[Service]
Type=simple
ExecStart=${config_dir}/rathole ${config_dir}/Russia${tunnel_port}.toml
Restart=always
RestartSec=3
[Install]
WantedBy=multi-user.target
EOF
# Reload systemd to read the new unit file
systemctl daemon-reload >/dev/null 2>&1
# Enable and start the service to start on boot
if systemctl enable --now "${service_dir}/rathole-Russia${tunnel_port}.service" >/dev/null 2>&1; then
colorize green "Russia service with port $tunnel_port enabled to start on boot and started."
else
colorize red "Failed to enable service with port $tunnel_port. Please check your system configuration."
return 1
fi
echo
colorize green "Russia server configuration completed successfully."
}
#Function for configuring Outside server
Outside_server_configuration() {
clear
colorize cyan "Configuring Outside server" bold
echo
# Prompt for Russia server IP address
while true; do
echo -ne "[*] Russia server IP address [IPv4/IPv6]: "
read -r SERVER_ADDR
if [[ -n "$SERVER_ADDR" ]]; then
break
else
colorize red "Server address cannot be empty. Please enter a valid address."
echo
fi
done
echo
# Read the tunnel port
while true; do
echo -ne "[*] Tunnel port: "
read -r tunnel_port
if [[ "$tunnel_port" =~ ^[0-9]+$ ]] && [ "$tunnel_port" -gt 22 ] && [ "$tunnel_port" -le 65535 ]; then
break
else
colorize red "Please enter a valid port number between 23 and 65535"
fi
done
echo
# Initialize nodelay variable
local nodelay=""
# Keep prompting the user until a valid input is provided
while [[ "$nodelay" != "true" && "$nodelay" != "false" ]]; do
echo -ne "[*] TCP_NODELAY (true/false): "
read -r nodelay
if [[ "$nodelay" != "true" && "$nodelay" != "false" ]]; then
colorize red "Invalid nodelay input. Please enter 'true' or 'false'"
fi
done
echo
# Initialize HEARTBEAT variable
local HEARTBEAT=""
# Keep prompting the user until a valid input is provided
while [[ "$HEARTBEAT" != "true" && "$HEARTBEAT" != "false" ]]; do
echo -ne "[*] Enable HEARTBEAT (true/false): "
read -r HEARTBEAT
if [[ "$HEARTBEAT" != "true" && "$HEARTBEAT" != "false" ]]; then
colorize red "Invalid HEARTBEAT value. Please enter 'true' or 'false'"
fi
done
if [[ "$HEARTBEAT" == "true" ]]; then
HEARTBEAT="40"
else
HEARTBEAT="0"
fi
echo
# Initialize transport variable
local transport=""
# Keep prompting the user until a valid input is provided
while [[ "$transport" != "tcp" && "$transport" != "udp" ]]; do
# Prompt the user to input transport type
echo -ne "[*] Transport type (tcp/udp): "
read -r transport
# Check if the input is either tcp or udp
if [[ "$transport" != "tcp" && "$transport" != "udp" ]]; then
colorize red "Invalid transport type. Please enter 'tcp' or 'udp'"
fi
done
echo
echo -ne "[-] Security Token (press enter to use default value): "
read -r token
if [[ -z "$token" ]]; then
token="musixal"
fi
echo
# Prompt for Ports
echo -ne "[*] Enter your ports separated by commas (e.g. 2070,2080): "
read -r input_ports
input_ports=$(echo "$input_ports" | tr -d ' ')
declare -a config_ports
# Convert the input into an array, splitting by comma
IFS=',' read -r -a ports <<< "$input_ports"
# Iterate through each port and perform an action
for port in "${ports[@]}"; do
if [[ "$port" =~ ^[0-9]+$ ]] && [ "$port" -gt 22 ] && [ "$port" -le 65535 ]; then
if ! check_port "$port" "$transport" ; then
colorize yellow "[INFO] Port $port is not in LISTENING state."
fi
colorize green "[INFO] Port $port added to your configs"
config_ports+=("$port")
else
colorize red "[ERROR] Port $port is Invalid. Please enter a valid port number between 23 and 65535"
fi
done
if [ ${#config_ports[@]} -eq 0 ]; then
colorize red "No ports were entered. Exiting." bold
sleep 2
return 1
fi
#Add IPv6 Support
local_ip='0.0.0.0'
if check_ipv6 "$SERVER_ADDR"; then
local_ip='[::]'
# Remove brackets if present
SERVER_ADDR="${SERVER_ADDR#[}"
SERVER_ADDR="${SERVER_ADDR%]}"
fi
# Generate server configuration file
cat << EOF > "${config_dir}/Outside${tunnel_port}.toml"
[client]
remote_addr = "${SERVER_ADDR}:${tunnel_port}"
default_token = "$token"
heartbeat_timeout = $HEARTBEAT
retry_interval = 1
[client.transport]
type = "tcp"
[client.transport.tcp]
nodelay = $nodelay
EOF
# Add each config port to the configuration file
for port in "${config_ports[@]}"; do
cat << EOF >> "${config_dir}/Outside${tunnel_port}.toml"
[client.services.${port}]
type = "$transport"
local_addr = "${local_ip}:${port}"
EOF
done
echo
# Create the systemd service unit file
cat << EOF > "${service_dir}/rathole-Outside${tunnel_port}.service"
[Unit]
Description=Rathole Outside Port $tunnel_port
After=network.target
[Service]
Type=simple
ExecStart=${config_dir}/rathole ${config_dir}/Outside${tunnel_port}.toml
Restart=always
RestartSec=3
[Install]
WantedBy=multi-user.target
EOF
# Reload systemd to read the new unit file
systemctl daemon-reload >/dev/null 2>&1
# Enable and start the service to start on boot
if systemctl enable --now "${service_dir}/rathole-Outside${tunnel_port}.service" >/dev/null 2>&1; then
colorize green "Outside service with port $tunnel_port enabled to start on boot and started."
else
colorize red "Failed to enable service with port $tunnel_port. Please check your system configuration."
return 1
fi
echo
colorize green "Outside server configuration completed successfully."
}
# Function for checking tunnel status
check_tunnel_status() {
echo
# Check for .toml files
if ! ls "$config_dir"/*.toml 1> /dev/null 2>&1; then
colorize red "No config files found in the rathole directory." bold
echo
press_key
return 1
fi
clear
colorize yellow "Checking all services status..." bold
sleep 1
echo
for config_path in "$config_dir"/Russia*.toml; do
if [ -f "$config_path" ]; then
# Extract config_name without directory path and change it to service name
config_name=$(basename "$config_path")
config_name="${config_name%.toml}"
service_name="rathole-${config_name}.service"
config_port="${config_name#Russia}"
# Check if the rathole-client-Outside service is active
if systemctl is-active --quiet "$service_name"; then
colorize green "Russia service with tunnel port $config_port is running"
else
colorize red "Russia service with tunnel port $config_port is not running"
fi
fi
done
for config_path in "$config_dir"/Outside*.toml; do
if [ -f "$config_path" ]; then
# Extract config_name without directory path and change it to service name
config_name=$(basename "$config_path")
config_name="${config_name%.toml}"
service_name="rathole-${config_name}.service"
config_port="${config_name#Outside}"
# Check if the rathole-client-Outside service is active
if systemctl is-active --quiet "$service_name"; then
colorize green "Outside service with tunnel port $config_port is running"
else
colorize red "Outside service with tunnel port $config_port is not running"
fi
fi
done
echo
press_key
}
# Function for destroying tunnel
tunnel_management() {
echo
# Check for .toml files
if ! ls "$config_dir"/*.toml 1> /dev/null 2>&1; then
colorize red "No config files found in the rathole directory." bold
echo
press_key
return 1
fi
clear
colorize cyan "List of existing services to manage:" bold
echo
#Variables
local index=1
declare -a configs
for config_path in "$config_dir"/Russia*.toml; do
if [ -f "$config_path" ]; then
# Extract config_name without directory path
config_name=$(basename "$config_path")
# Remove "Russia" prefix and ".toml" suffix
config_port="${config_name#Russia}"
config_port="${config_port%.toml}"
configs+=("$config_path")
echo -e "${MAGENTA}${index}${NC}) ${GREEN}Russia${NC} service, Tunnel port: ${YELLOW}$config_port${NC}"
((index++))
fi
done
for config_path in "$config_dir"/Outside*.toml; do
if [ -f "$config_path" ]; then
# Extract config_name without directory path
config_name=$(basename "$config_path")
# Remove "Outside" prefix and ".toml" suffix
config_port="${config_name#Outside}"
config_port="${config_port%.toml}"
configs+=("$config_path")
echo -e "${MAGENTA}${index}${NC}) ${GREEN}Outside${NC} service, Tunnel port: ${YELLOW}$config_port${NC}"
((index++))
fi
done
echo
echo -ne "Enter your choice (0 to return): "
read choice
# Check if the user chose to return
if (( choice == 0 )); then
return
fi
# validation
while ! [[ "$choice" =~ ^[0-9]+$ ]] || (( choice < 0 || choice > ${#configs[@]} )); do
colorize red "Invalid choice. Please enter a number between 1 and ${#configs[@]}." bold
echo
echo -ne "Enter your choice (0 to return): "
read choice
if (( choice == 0 )); then
return
fi
done
selected_config="${configs[$((choice - 1))]}"
config_name=$(basename "${selected_config%.toml}")
service_name="rathole-${config_name}.service"
clear
colorize cyan "List of available commands for $config_name:" bold
echo
colorize red "1) Remove this tunnel"
colorize yellow "2) Restart this tunnel"
colorize green "3) Add a new config for this tunnel"
colorize reset "4) Add a cronjob for this tunnel"
colorize reset "5) Remove existing cronjob for this tunnel"
colorize reset "6) View service logs"
colorize reset "7) View service status"
echo
read -p "Enter your choice (0 to return): " choice
case $choice in
1) destroy_tunnel "$selected_config" ;;
2) restart_service "$service_name" ;;
3) add_new_config "$selected_config" ;;
4) add_cron_job_menu "$service_name";;
5) delete_cron_job "$service_name";;
6) view_service_logs "$service_name" ;;
7) view_service_status "$service_name" ;;
0) return 1 ;;
*) echo -e "${RED}Invalid option!${NC}" && sleep 1 && return 1;;
esac
}
remove_core(){
echo
# If user try to remove core and still a service is running, we should prohibit this.
# Check if any .toml file exists
if find "$config_dir" -type f -name "*.toml" | grep -q .; then
colorize red "You should delete all services first and then delete the rathole-core."
sleep 3
return 1
else
colorize cyan "No .toml file found in the directory."
fi
echo
# Prompt to confirm before removing Rathole-core directory
colorize yellow "Do you want to remove rathole-core? (y/n)"
read -r confirm
echo
if [[ $confirm == [yY] ]]; then
if [[ -d "$config_dir" ]]; then
rm -rf "$config_dir" >/dev/null 2>&1
colorize green "Rathole-core directory removed." bold
else
colorize red "Rathole-core directory not found." bold
fi
else
colorize yellow "Rathole core removal canceled."
fi
echo
press_key
}
destroy_tunnel(){
echo
#Vaiables
config_path="$1"
config_name=$(basename "${config_path%.toml}")
service_name="rathole-${config_name}.service"
service_path="$service_dir/$service_name"
# Check if config exists and delete it
if [ -f "$config_path" ]; then
rm -f "$config_path" >/dev/null 2>&1
fi
delete_cron_job $service_name
# Stop and disable the client service if it exists
if [[ -f "$service_path" ]]; then
if systemctl is-active "$service_name" &>/dev/null; then
systemctl disable --now "$service_name" >/dev/null 2>&1
fi
rm -f "$service_path" >/dev/null 2>&1
fi
echo
# Reload systemd to read the new unit file
if systemctl daemon-reload >/dev/null 2>&1 ; then
echo -e "Systemd daemon reloaded.\n"
else
echo -e "${RED}Failed to reload systemd daemon. Please check your system configuration.${NC}"
fi
echo -e "${GREEN}Tunnel destroyed successfully! ${NC}"
echo
sleep 1
}
#Function to restart services
restart_service() {
echo
service_name="$1"
colorize yellow "Restarting $service_name" bold
echo
# Check if service exists
if systemctl list-units --type=service | grep -q "$service_name"; then
systemctl restart "$service_name"
colorize green "Service restarted successfully"
else
colorize red "Cannot restart the service"
fi
echo
press_key
}
# Function to add cron-tab job
add_cron_job() {
local restart_time="$1"
local reset_path="$2"
local service_name="$3"
# Save existing crontab to a temporary file
crontab -l > /tmp/crontab.tmp
# Append the new cron job to the temporary file
echo "$restart_time $reset_path #$service_name" >> /tmp/crontab.tmp
# Install the modified crontab from the temporary file
crontab /tmp/crontab.tmp
# Remove the temporary file
rm /tmp/crontab.tmp
}
delete_cron_job() {
echo
local service_name="$1"
crontab -l | grep -v "#$service_name" | crontab -
rm -f "$config_dir/${service_name%.service}.sh" >/dev/null 2>&1
colorize green "Cron job for $service_name deleted successfully." bold
sleep 2
}
add_new_config(){
echo
local config_path="$1"
#Add IPv6 Support
local_ip='0.0.0.0'
read -p "[-] Listen for IPv6 address? (y/n): " answer
if [ "$answer" = "y" ] || [ "$answer" = "Y" ]; then
colorize yellow "IPv6 Enabled"
local_ip='[::]'
elif [ "$answer" = "n" ]; then
colorize yellow "IPv4 Enabled"
local_ip='0.0.0.0'
else
colorize yellow "Invalid choice. IPv4 enabled by default."
local_ip='0.0.0.0'
fi
echo
# Initialize transport variable
local transport=""
# Keep prompting the user until a valid input is provided
while [[ "$transport" != "tcp" && "$transport" != "udp" ]]; do
# Prompt the user to input transport type
echo -ne "[*] Transport type(tcp/udp): "
read -r transport
# Check if the input is either tcp or udp
if [[ "$transport" != "tcp" && "$transport" != "udp" ]]; then
colorize red "Invalid transport type. Please enter 'tcp' or 'udp'"
fi
done
echo
# Prompt for Ports
echo -ne "[*] Enter your ports separated by commas (e.g. 2070,2080): "
read -r input_ports
input_ports=$(echo "$input_ports" | tr -d ' ')
# Convert the input into an array, splitting by comma
IFS=',' read -r -a ports <<< "$input_ports"
declare -a config_ports
# Iterate through each port and perform an action
for port in "${ports[@]}"; do
if [[ "$port" =~ ^[0-9]+$ ]] && [ "$port" -gt 22 ] && [ "$port" -le 65535 ]; then
config_ports+=("$port")
else
colorize red "[ERROR] Port $port is Invalid. Please enter a valid port number between 23 and 65535"
fi