forked from Musixal/Rathole-Tunnel
-
Notifications
You must be signed in to change notification settings - Fork 0
/
rathole.sh
1480 lines (1219 loc) · 42.5 KB
/
rathole.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
# 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"
read -p "Press any key to continue..."
exit 1
fi
fi
}
# Install unzip
install_unzip
# 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"
read -p "Press any key to continue..."
exit 1
fi
fi
}
# Install jq
install_jq
install_iptables() {
if ! command -v iptables &> /dev/null; then
# Check if the system is using apt package manager
if command -v apt-get &> /dev/null; then
echo -e "${RED}iptables is not installed. Installing...${NC}"
sleep 1
sudo apt-get update
sudo apt-get install -y iptables
else
echo -e "${RED}Error: Unsupported package manager. Please install iptables manually.${NC}\n"
read -p "Press any key to continue..."
exit 1
fi
fi
}
# Install iptables
install_iptables
install_bc() {
if ! command -v bc &> /dev/null; then
# Check if the system is using apt package manager
if command -v apt-get &> /dev/null; then
echo -e "${RED}bc is not installed. Installing...${NC}"
sleep 1
sudo apt-get update
sudo apt-get install -y bc
else
echo -e "${RED}Error: Unsupported package manager. Please install bc manually.${NC}\n"
read -p "Press any key to continue..."
exit 1
fi
fi
}
# Install bc
install_bc
config_dir="/root/rathole-core"
# Function to download and extract Rathole Core
download_and_extract_rathole() {
# check if core installed already
if [[ -d "$config_dir" ]]; then
echo -e "${GREEN}Rathole Core is already installed.${NC}"
sleep 1
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 using ip-api.com
SERVER_COUNTRY=$(curl -sS "http://ip-api.com/json/$SERVER_IP" | jq -r '.country')
# Fetch server isp using ip-api.com
SERVER_ISP=$(curl -sS "http://ip-api.com/json/$SERVER_IP" | jq -r '.isp')
# Function to display ASCII logo
display_logo() {
echo -e "${CYAN}"
cat << "EOF"
__ .__ .__
____________ _/ |_| |__ ____ | | ____
\_ __ \__ \\ __| | \ / _ \| | _/ __ \
| | \// __ \| | | Y ( <_> | |_\ ___/
|__| (____ |__| |___| /\____/|____/\___ >
\/ \/ \/
EOF
echo -e "${NC}${GREEN}"
echo -e "${YELLOW}High-performance reverse tunnel${GREEN}"
echo -e "Version: ${YELLOW}v1.3.2${GREEN}"
echo -e "Developer: ${YELLOW}Musixal${GREEN}"
echo -e "Github: ${YELLOW}github.com/Musixal/Rathole-Tunnel${GREEN}"
echo -e "Telegram Channel: ${YELLOW}@Gozar_Xray${NC}"
}
# Function to display server location and IP
display_server_info() {
echo -e "\e[93m═════════════════════════════════════════════\e[0m"
echo -e "${CYAN}Server Country:${NC} $SERVER_COUNTRY"
echo -e "${CYAN}Server IP:${NC} $SERVER_IP"
echo -e "${CYAN}Server ISP:${NC} $SERVER_ISP"
}
# Function to display Rathole Core installation status
display_rathole_core_status() {
if [[ -d "$config_dir" ]]; 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 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 option 8.${NC}\n"
read -p "Press Enter to continue..."
return 1
fi
clear
echo -e "${YELLOW}Configurating RatHole Tunnel...${NC}"
echo -e "\e[93m═════════════════════════════════════════════\e[0m"
echo ''
echo -e "1. For ${GREEN}IRAN${NC} Server\n"
echo -e "2. For ${CYAN}Kharej${NC} Server\n"
read -p "Enter your choice: " configure_choice
case "$configure_choice" in
1) iran_server_configuration ;;
2) kharej_server_configuration ;;
*) echo -e "${RED}Invalid option!${NC}" && sleep 1 ;;
esac
echo ''
read -p "Press Enter to continue..."
}
#Global Variables
iran_config_file="${config_dir}/server.toml"
iran_service_name="rathole-iran.service"
iran_service_file="/etc/systemd/system/${iran_service_name}"
kharej_config_file="${config_dir}/client*.toml"
kharej_service_name="rathole-kharej.service"
kharej_service_file="/etc/systemd/system/${kharej_service_name}"
# 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
}
# Function to configure Iran server
iran_server_configuration() {
clear
echo -e "${YELLOW}Configuring IRAN server...${NC}\n"
# Read the tunnel port
read -p "Enter the tunnel port: " tunnel_port
while ! [[ "$tunnel_port" =~ ^[0-9]+$ ]]; do
echo -e "${RED}Please enter a valid port number.${NC}"
read -p "Enter the tunnel port: " tunnel_port
done
echo ''
# Read the number of config ports and read each port
read -p "Enter the number of your configs: " num_ports
while ! [[ "$num_ports" =~ ^[0-9]+$ ]]; do
echo -e "${RED}Please enter a valid number.${NC}"
read -p "Enter the number of your configs: " num_ports
done
echo ''
config_ports=()
for ((i=1; i<=$num_ports; i++)); do
read -p "Enter Config Port $i: " port
while ! [[ "$port" =~ ^[0-9]+$ ]]; do
echo -e "${RED}Please enter a valid port number.${NC}"
read -p "Enter Config Port $i: " port
done
config_ports+=("$port")
done
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
read -p "Enter transport type (tcp/udp): " transport
# Check if the input is either tcp or udp
if [[ "$transport" != "tcp" && "$transport" != "udp" ]]; then
echo -e "${RED}Invalid transport type. Please enter 'tcp' or 'udp'.${NC}"
fi
done
echo ''
# Initialize nodelay variable
local nodelay=""
# Keep prompting the user until a valid input is provided
while [[ "$nodelay" != "true" && "$nodelay" != "false" ]]; do
read -p "TCP No-Delay (true / false): " nodelay
if [[ "$nodelay" != "true" && "$nodelay" != "false" ]]; then
echo -e "${RED}Invalid nodelay input. Please enter 'true' or 'false'.${NC}"
fi
done
echo ''
local_ip='0.0.0.0'
#Add IPv6 Support
read -p "Do you want to use IPv6 for connecting? (yes/no): " answer
echo ''
if [ "$answer" = "yes" ]; then
echo -e "${CYAN}IPv6 selected.${NC}"
local_ip='[::]'
elif [ "$answer" = "no" ]; then
echo -e "${CYAN}IPv4 selected.${NC}"
else
echo -e "${YELLOW}Invalid choice. IPv4 selected by default.${NC}"
fi
sleep 1
# Generate server configuration file
cat << EOF > "$iran_config_file"
[server]
bind_addr = "${local_ip}:${tunnel_port}"
default_token = "musixal_tunnel"
heartbeat_interval = 30
[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 >> "$iran_config_file"
[server.services.${port}]
type = "$transport"
bind_addr = "${local_ip}:${port}"
EOF
done
echo ''
echo -e "${GREEN}IRAN server configuration completed.${NC}\n"
echo -e "Starting Rathole server as a service...\n"
# Create the systemd service unit file
cat << EOF > "$iran_service_file"
[Unit]
Description=Rathole Server (Iran)
After=network.target
[Service]
Type=simple
ExecStart=${config_dir}/rathole ${iran_config_file}
Restart=always
RestartSec=3
[Install]
WantedBy=multi-user.target
EOF
# Reload systemd to read the new unit file
if systemctl daemon-reload; then
echo "Systemd daemon reloaded."
else
echo -e "${RED}Failed to reload systemd daemon. Please check your system configuration.${NC}"
return 1
fi
# Enable the service to start on boot
if systemctl enable "$iran_service_name" >/dev/null 2>&1; then
echo -e "${GREEN}Service '$iran_service_name' enabled to start on boot.${NC}"
else
echo -e "${RED}Failed to enable service '$iran_service_name'. Please check your system configuration.${NC}"
return 1
fi
# Start the service
if systemctl start "$iran_service_name"; then
echo -e "${GREEN}Service '$iran_service_name' started.${NC}"
else
echo -e "${RED}Failed to start service '$service_name'. Please check your system configuration.${NC}"
return 1
fi
}
# Function for configuring Kharej server
kharej_server_configuration() {
clear
echo -e "${YELLOW}Configuring kharej server...${NC}\n"
while true; do
read -p "How many IRAN servers do you have: " SERVER_NUM
if [[ $SERVER_NUM =~ ^[0-9]+$ ]] && [ $SERVER_NUM -ge 1 ] && [ $SERVER_NUM -le 99 ]; then
break
else
echo -e "${RED}Please enter a number between 1 and 99${NC}"
fi
done
local EXEC_COMMAND="/bin/bash -c '"
#___________________________________________________________________ Start of the loop
for ((j=1; j<=$SERVER_NUM; j++)); do
clear
echo -e "${CYAN}Let's create a tunnel for server $j${NC}"
echo -e "\e[93m═════════════════════════════════════════════\e[0m"
echo ''
# Read the server address
read -p "Enter the IRAN server address [IPv4/IPv6]: " SERVER_ADDR
echo ''
# Read the tunnel port
read -p "Enter the tunnel port: " tunnel_port
while ! [[ "$tunnel_port" =~ ^[0-9]+$ ]]; do
echo -e "${RED}Please enter a valid port number.${NC}"
read -p "Enter the tunnel port: " tunnel_port
done
echo ''
# Read the number of config ports and read each port
read -p "Enter the number of your configs: " num_ports
while ! [[ "$num_ports" =~ ^[0-9]+$ ]]; do
echo -e "${RED}Please enter a valid number.${NC}"
read -p "Enter the number of your configs: " num_ports
done
echo ''
config_ports=()
for ((i=1; i<=$num_ports; i++)); do
read -p "Enter Config Port $i: " port
while ! [[ "$port" =~ ^[0-9]+$ ]]; do
echo -e "${RED}Please enter a valid port number.${NC}"
read -p "Enter Config Port $i: " port
done
config_ports+=("$port")
done
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
read -p "Enter transport type (tcp/udp): " transport
# Check if the input is either tcp or udp
if [[ "$transport" != "tcp" && "$transport" != "udp" ]]; then
echo -e "${RED}Invalid transport type. Please enter 'tcp' or 'udp'.${NC}"
fi
done
echo ''
# Initialize nodelay variable
local nodelay=""
# Keep prompting the user until a valid input is provided
while [[ "$nodelay" != "true" && "$nodelay" != "false" ]]; do
read -p "TCP No-Delay (true / false): " nodelay
if [[ "$nodelay" != "true" && "$nodelay" != "false" ]]; then
echo -e "${RED}Invalid nodelay input. Please enter 'true' or 'false'.${NC}"
fi
done
#this new format allow us to build various client_port.toml
local kharej_config_file="${config_dir}/client_p${tunnel_port}.toml"
#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 > "$kharej_config_file"
[client]
remote_addr = "${SERVER_ADDR}:${tunnel_port}"
default_token = "musixal_tunnel"
heartbeat_timeout = 40
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 >> "$kharej_config_file"
[client.services.${port}]
type = "$transport"
local_addr = "${local_ip}:${port}"
EOF
done
# Now modify ExecCommand for our service file
EXEC_COMMAND+="${config_dir}/rathole ${kharej_config_file} & "
sleep 1
done
#______________________________________________________________________________End of the loop
#delete last &
EXEC_COMMAND="${EXEC_COMMAND% & }"
#Need that last '
EXEC_COMMAND+="'"
echo ''
echo -e "${GREEN}Kharej server configuration completed.${NC}\n"
echo -e "${GREEN}Starting Rathole server as a service...${NC}\n"
# Create the systemd service unit file
cat << EOF > "$kharej_service_file"
[Unit]
Description=Rathole Server (Kharej)
After=network.target
[Service]
Type=simple
ExecStart=$EXEC_COMMAND
Restart=always
RestartSec=3
[Install]
WantedBy=multi-user.target
EOF
# Reload systemd to read the new unit file
if systemctl daemon-reload; then
echo "Systemd daemon reloaded."
else
echo -e "${RED}Failed to reload systemd daemon. Please check your system configuration.${NC}"
return 1
fi
# Enable the service to start on boot
if systemctl enable "$kharej_service_name" >/dev/null 2>&1; then
echo -e "${GREEN}Service '$kharej_service_name' enabled to start on boot.${NC}"
else
echo -e "${RED}Failed to enable service '$kharej_service_name'. Please check your system configuration.${NC}"
return 1
fi
# Start the service
if systemctl start "$kharej_service_name"; then
echo -e "${GREEN}Service '$kharej_service_name' started.${NC}"
else
echo -e "${RED}Failed to start service '$kharej_service_name'. Please check your system configuration.${NC}"
return 1
fi
}
# Function for destroying tunnel
destroy_tunnel() {
echo ''
echo -e "${YELLOW}Destroying tunnel...${NC}\n"
sleep 1
# Prompt to confirm before removing Rathole-core directory
read -p "Are you sure you want to remove Rathole-core? (y/n): " confirm
echo ''
if [[ $confirm == [yY] ]]; then
if [[ -d "$config_dir" ]]; then
rm -rf "$config_dir"
echo -e "${GREEN}Rathole-core directory removed.${NC}\n"
else
echo -e "${RED}Rathole-core directory not found.${NC}\n"
fi
else
echo -e "${YELLOW}Rathole core removal canceled.${NC}\n"
fi
# Check if server.toml exists and delete it
if [ -f "$iran_config_file" ]; then
rm -f "$iran_config_file"
fi
# Check if client.toml exists and delete it
if ls $kharej_config_file 1> /dev/null 2>&1; then
for file in $kharej_config_file; do
rm -f $file
done
fi
# remove cronjob created by thi script
delete_cron_job
echo ''
# Stop and disable the client service if it exists
if [[ -f "$kharej_service_file" ]]; then
if systemctl is-active "$kharej_service_name" &>/dev/null; then
systemctl stop "$kharej_service_name"
systemctl disable "$kharej_service_name"
fi
rm -f "$kharej_service_file"
fi
# Stop and disable the Iran server service if it exists
if [[ -f "$iran_service_file" ]]; then
if systemctl is-active "$iran_service_name" &>/dev/null; then
systemctl stop "$iran_service_name"
systemctl disable "$iran_service_name"
fi
rm -f "$iran_service_file"
fi
echo ''
# Reload systemd to read the new unit file
if systemctl daemon-reload; 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}\n"
read -p "Press Enter to continue..."
}
# Function for checking tunnel status
check_tunnel_status() {
echo ''
echo -e "${YELLOW}Checking tunnel status...${NC}\n"
sleep 1
# Check if the rathole-client-kharej service is active
if systemctl is-active --quiet "$kharej_service_name"; then
echo -e "${GREEN}Kharej service is running on this server.${NC}"
else
echo -e "${RED}Kharej service is not running on this server.${NC}"
fi
echo ''
# Check if the rathole-server-iran service is active
if systemctl is-active --quiet "$iran_service_name"; then
echo -e "${GREEN}IRAN service is running on this server..${NC}"
else
echo -e "${RED}IRAN service is not running on this server..${NC}"
fi
echo ''
read -p "Press Enter to continue..."
}
#Function to restart services
restart_services() {
echo ''
echo -e "${YELLOW}Restarting IRAN & Kharej services...${NC}\n"
sleep 1
# Check if rathole-client-kharej.service exists
if systemctl list-units --type=service | grep -q "$kharej_service_name"; then
systemctl restart "$kharej_service_name"
echo -e "${GREEN}Kharej service restarted.${NC}"
fi
# Check if rathole-server-iran.service exists
if systemctl list-units --type=service | grep -q "$iran_service_name"; then
systemctl restart "$iran_service_name"
echo -e "${GREEN}IRAN service restarted.${NC}"
fi
# If neither service exists
if ! systemctl list-units --type=service | grep -q "$kharej_service_name" && \
! systemctl list-units --type=service | grep -q "$iran_service_name"; then
echo -e "${RED}There is no service to restart.${NC}"
fi
echo ''
read -p "Press Enter to continue..."
}
# Function to add cron-tab job
add_cron_job() {
local reset_path=$1
local restart_time=$2
# 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 # Added by rathole_script" >> /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() {
# Delete all cron jobs added by this script
crontab -l | grep -v '# Added by rathole_script' | crontab -
rm -f /etc/reset.sh >/dev/null 2>&1
echo -e "${GREEN}Cron jobs added by this script have been deleted successfully.${NC}"
}
# Main function to add or delete cron job for restarting services
cronjob_main() {
clear
# Prompt user for action
echo -e "Select an option: \n"
echo -e "${CYAN}1. Add a cron-job to restart a service${NC}\n"
echo -e "${RED}2. Delete cron jobs added by this script${NC}\n"
read -p "Enter your choice: " action_choice
echo ''
# Validate user input
case $action_choice in
1)
add_cron_job_menu
;;
2)
delete_cron_job
;;
*)
echo -e "${RED}Invalid choice. Please enter 1 or 2.${NC}"
return 1
;;
esac
echo ''
read -p "Press Enter to continue..."
}
add_cron_job_menu() {
clear
# Prompt user to choose a service
echo -e "Select the service you want to restart:\n"
echo -e "${CYAN}1. Kharej service${NC}"
echo -e "${GREEN}2. IRAN service${NC}"
echo ''
read -p "Enter your choice: " service_choice
echo ''
# Validate user input
case $service_choice in
1)
service_name="$kharej_service_name"
;;
2)
service_name="$iran_service_name"
;;
*)
echo -e "${RED}Invalid choice. Please enter 1 or 2.${NC}"
return 1
;;
esac
# Prompt user to choose a restart time interval
echo "Select the restart time interval:"
echo ''
echo "1. Every 30th minute"
echo "2. Every 1 hour"
echo "3. Every 2 hours"
echo "4. Every 4 hours"
echo "5. Every 6 hours"
echo "6. Every 12 hours"
echo "7. Every 24 hours"
echo ''
read -p "Enter your choice: " time_choice
echo ''
# Validate user input for restart time interval
case $time_choice in
1)
restart_time="*/30 * * * *"
;;
2)
restart_time="0 * * * *"
;;
3)
restart_time="0 */2 * * *"
;;
4)
restart_time="0 */4 * * *"
;;
5)
restart_time="0 */6 * * *"
;;
6)
restart_time="0 */12 * * *"
;;
7)
restart_time="0 0 * * *"
;;
*)
echo -e "${RED}Invalid choice. Please enter a number between 1 and 7.${NC}\n"
return 1
;;
esac
# remove cronjob created by thi script
delete_cron_job > /dev/null 2>&1
# Path ro reset file
reset_path='/etc/reset.sh'
#add cron job to kill the running rathole processes
cat << EOF > "$reset_path"
#! /bin/bash
pids=\$(pgrep rathole)
sudo kill -9 \$pids
sudo systemctl daemon-reload
sudo systemctl restart $service_name
EOF
# make it +x !
chmod +x "$reset_path"
# Add cron job to restart the specified service at the chosen time
add_cron_job "$reset_path" "$restart_time"
echo -e "${GREEN}Cron-job added successfully to restart the service '$service_name'.${NC}"
}
# main maenu for showing ports monitoring options
ports_monitor_menu(){
clear
# Prompt user to choose a option
echo -e "Select the option you want to do:\n"
echo -e "${CYAN}1. Add ports for monitoring traffic${NC}\n"
echo -e "${GREEN}2. View traffic usage${NC}\n"
echo -e "${RED}3. Remove iptables rules${NC}\n"
read -p "Enter your choice: " option_choice
echo ''
# Validate user input
case $option_choice in
1)
add_iptables_rules
;;
2)
view_traffic_usage
;;
3)
del_iptables_rules
;;
*)
echo -e "${RED}Invalid choice. Please enter valid number.${NC}"
sleep 1
return 1
;;
esac
}
add_iptables_rules() {
echo ''
# Prompt user to enter ports
read -p "Enter the desired ports separated by commas : " ports
IFS=',' read -r -a port_array <<< "$ports"
echo ''
for port in "${port_array[@]}"; do
# Check if the entered value is a valid integer
if grep -wqE '^[0-9]+$' <<< "$port"; then
# Check if the port with comment "rathole" already exists
if ! iptables -C INPUT -p tcp --dport "$port" -j ACCEPT -m comment --comment "rathole" &>/dev/null; then
iptables -A INPUT -p tcp --dport "$port" -j ACCEPT -m comment --comment "rathole"
echo -e "${GREEN}Port $port added to iptables.${NC}"
else
echo -e "${YELLOW}Port $port already exists in iptables. Skipping...${NC}"
fi
else
echo -e "${RED}Invalid port number: $port. Skipping...${NC}"
fi
done
echo ''
echo -e "${GREEN}All desired ports added to iptables successfully${NC}"
echo ''
read -p "Press any key to continue..."
}
# Function to draw a horizontal line
draw_line() {
printf "$+----------+------------+\n"
}
# Function to draw table rows
draw_row() {
printf "| %-8s | %-10s |\n" "$1" "$2"
}
# Main function to draw the table
view_traffic_usage() {
clear
draw_line
draw_row "Port" "Traffic (B)"
draw_line
# Use command substitution to get port numbers dynamically
ports=$(iptables -L -v --numeric | grep -i -w "rathole" | grep -o 'tcp dpt:[0-9]\+' | awk -F':' '{print $2}')
# Use command substitution to get traffic information dynamically
traffic=$(iptables -L -v --numeric | grep -i -w "rathole" | awk '{print $2}')
for port in $ports; do
# Find the corresponding traffic value for each port
index=$(echo $ports | tr ' ' '\n' | grep -n -w $port | cut -d ':' -f1)
traffic_val=$(echo $traffic | tr ' ' '\n' | sed -n ${index}p)
draw_row "$port" "$traffic_val"
done
draw_line
echo ''
read -p "Press any key to continue..."
}
del_iptables_rules(){
iptables-save | grep -v 'rathole' > /tmp/iptables-filtered.rules
iptables-restore < /tmp/iptables-filtered.rules
echo -e "${GREEN}All iptables rules related to this script deleted successfully${NC}"
echo ''
read -p "Press any key to continue..."
}
# Function to check the security token
check_security_token() {
echo ''
echo -e "${RED}IMPORTANT!${NC} ${CYAN}The security token must be same in the iran and kharej server.${NC}\n"
# Check if server.toml exists and update it
if [ -f "$iran_config_file" ]; then
port=$(cat "$iran_config_file" | grep -oP 'bind_addr = "0\.0\.0\.0:\K[0-9]+' | head -n1)
change_security_token "$iran_config_file" "$port"
restart_services
return 0
fi
# Check if client.toml exists and update it
if ls $kharej_config_file 1> /dev/null 2>&1; then
for file in $kharej_config_file; do
filename=$(basename "$file")
change_security_token "$file" "${filename:8:-5}"
echo -e "${CYAN} _____________________________________________ ${NC}"
echo ''
sleep 1
done
restart_services
return 0
fi
echo -e "${RED}Configs files not found!${NC}\n"
read -p "Press any key to continue..."
}
# Function to update the security token
change_security_token() {
local file_path=$1
local port_num=$2
# Show the current token
current_token=$(grep -Po '(?<=^default_token = ")[^"]*' "$file_path")
if [ -z "$current_token" ]; then
echo -e "${RED}default_token not found in $file_path${NC}"
return 1
fi
echo -e "${GREEN}Current tunnel port number:${NC} ${MAGENTA}$port_num${NC}"
echo -e "${GREEN}Current token:${NC} ${MAGENTA}$current_token${NC}"
echo ''
random_token=$(tr -dc 'a-zA-Z0-9' < /dev/urandom | head -c 32)
echo -e "${GREEN}Random generated token:${NC} ${MAGENTA}$random_token${NC}"
echo ''
# Ask user for new token
read -p "Enter new token (or press Enter to use default value): " new_token
# Set default token if user didn't enter anything
if [ -z "$new_token" ]; then
new_token="musixal_tunnel"
fi
# Update the token in the file
sed -i "s/^default_token = \".*\"/default_token = \"$new_token\"/" "$file_path"
echo''
echo -e "${GREEN}Token updated successfully in $file_path${NC}\n"
}
update_script(){
# Define the destination path
DEST_DIR="/usr/bin/"
RATHOLE_SCRIPT="rathole"
SCRIPT_URL="https://github.com/Musixal/rathole-tunnel/raw/main/rathole.sh"
echo ''
# Check if rathole.sh exists in /bin/bash
if [ -f "$DEST_DIR/$RATHOLE_SCRIPT" ]; then
# Remove the existing rathole
rm "$DEST_DIR/$RATHOLE_SCRIPT"
if [ $? -eq 0 ]; then
echo -e "${GREEN}Existing $RATHOLE_SCRIPT has been successfully removed from $DEST_DIR.${NC}"
else
echo -e "${RED}Failed to remove existing $RATHOLE_SCRIPT from $DEST_DIR.${NC}"
sleep 1
return 1