-
-
Notifications
You must be signed in to change notification settings - Fork 6
/
cloudflare-dns.sh
2188 lines (1851 loc) · 77.6 KB
/
cloudflare-dns.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
# Cloudflare DNS Management Script (cloudflareDNS.sh)
# Copyright (c) 2024 Jose Manuel Requena Plens
# License: GNU General Public License v3.0
# This script allows you to manage your Cloudflare DNS records using the Cloudflare API.
# It can be used to update your DNS records with your current IP address, and it supports
# both IPv4 and IPv6 addresses. You can also enable or disable proxied mode for your records.
# The script can be run manually or scheduled to run periodically using cron or systemd timers.
#
# For more information, please visit:
# https://github.com/jmrplens/Cloudflare-DNS-Updater
# Pipefail is required to catch errors in jq commands. If any command in a pipeline fails, the
# pipeline will return a non-zero status code, which will be caught by the script.
set -euo pipefail
VERSION="1.0.0"
#==============================================================================
# SCRIPT SETTINGS
#==============================================================================
# shellcheck disable=SC2034
SCRIPT_NAME="Cloudflare DNS Management Script"
# shellcheck disable=SC2034
SCRIPT_VERSION="$VERSION"
# shellcheck disable=SC2034
SCRIPT_DESCRIPTION="Manage your Cloudflare DNS records with ease"
# shellcheck disable=SC2034
SCRIPT_URL=""
# shellcheck disable=SC2034
SCRIPT_AUTHOR="Jose Manuel Requena Plens"
# shellcheck disable=SC2034
SCRIPT_AUTHOR_URL=""
# shellcheck disable=SC2034
SCRIPT_LICENSE="GNU General Public License v3.0"
#==============================================================================
# CONFIGURATION
#==============================================================================
# Default configuration values
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
CONFIG_FILE="${SCRIPT_DIR}/cloudflare-dns.yaml"
RETRY_ATTEMPTS=3
RETRY_INTERVAL=5
MAX_PARALLEL_JOBS=1
# Default global settings
DEFAULT_GLOBAL_IPV4=true
DEFAULT_GLOBAL_IPV6=true
DEFAULT_GLOBAL_PROXIED=true
DEFAULT_GLOBAL_TTL="auto"
DEFAULT_ENABLE_CREATE_RECORD=false
# Log configuration
LOG_FILE="cloudflare-dns.log"
LOG_DIR="."
LOG_TO_TERMINAL=true
VERBOSITY="success"
ENABLE_ROTATE_LOG=false
MAX_LOG_SIZE=$((10 * 1024 * 1024)) # 10 MB
LOG_ROTATE_COUNT=5
LOG_COMPRESS_DAYS=7
LOG_CLEAN_DAYS=30
LOG_TO_SYSTEM=true
SANITIZE_LOGS=true
# Cloudflare API settings
ZONE_ID=""
ZONE_API_TOKEN=""
# Command-line override for record creation
CLI_ENABLE_CREATE_RECORD=""
# Notification plugins
declare -A NOTIFICATION_PLUGINS=(["telegram"]=false ["email"]=false ["slack"]=false ["discord"]=false)
# Colors for terminal output
declare -A COLORS=(
# From \033[0;30m to \033[0;37m
[BLACK]='\033[0;30m'
[RED]='\033[0;31m'
[GREEN]='\033[0;32m'
[YELLOW]='\033[0;33m'
[BLUE]='\033[0;34m'
[MAGENTA]='\033[0;35m'
[CYAN]='\033[0;36m'
[GRAY]='\033[0;37m'
# From \033[1;30m to \033[1;37m
[DARK_GRAY]='\033[1;30m'
[LIGHT_RED]='\033[1;31m'
[LIGHT_GREEN]='\033[1;32m'
[LIGHT_YELLOW]='\033[1;33m'
[LIGHT_BLUE]='\033[1;34m'
[LIGHT_MAGENTA]='\033[1;35m'
[LIGHT_CYAN]='\033[1;36m'
[WHITE]='\033[1;37m'
# Special formatting
[BOLD]='\033[1m'
[UNDERLINE]='\033[4m'
[INVERT]='\033[7m'
[NO_BOLD]='\033[22m'
[NO_UNDERLINE]='\033[24m'
[NO_INVERT]='\033[27m'
# Reset all attributes
[RESET]='\033[0m'
)
#==============================================================================
# UTILITY FUNCTIONS
#==============================================================================
# Date function compatible with both Linux and macOS
date_compat() {
# Host is macOS
if [[ "$OSTYPE" == "darwin"* ]]; then
if command -v gdate &>/dev/null; then
gdate "$@"
else
log_error "GNU date (gdate) is required on macOS. Please install it using Homebrew:"
log_error "brew install coreutils"
exit 1
fi
else
date "$@"
fi
}
# Enhanced logging function
log() {
local message="$1"
local level="${2:-success}"
local timestamp
local color="${COLORS[RESET]}"
local caller_func="${FUNCNAME[2]:-${FUNCNAME[1]:-main}}"
timestamp=$(date_compat +"%Y-%m-%d %H:%M:%S")
case "$level" in
error) color="${COLORS[RED]}" ;;
warning) color="${COLORS[YELLOW]}" ;;
info) color="${COLORS[BLUE]}" ;;
debug) color="${COLORS[MAGENTA]}" ;;
debug_logging) color="${COLORS[GRAY]}" ;;
success) color="" ;;
esac
# Only rotate log if it's not a debug message
if [[ "$level" != "debug_logging" && "$ENABLE_ROTATE_LOG" == true ]]; then
rotate_log "$LOG_FILE" "$MAX_LOG_SIZE" "$LOG_ROTATE_COUNT"
fi
# Log to file
echo "$timestamp - ${level^^}: [${caller_func}] ${message}" >> "$LOG_FILE"
# Log to system if enabled
[[ "$LOG_TO_SYSTEM" == "true" ]] && log_to_system "$message" "$level"
# Check if the current log level should be displayed based on verbosity
if should_log "$level"; then
if [[ "$LOG_TO_TERMINAL" == true ]] && [[ $color ]]; then
echo -e "${color}${timestamp} - ${level^^}: [${caller_func}] ${message}${COLORS[RESET]}" >&2
else
echo "${timestamp} - ${level^^}: [${caller_func}] ${message}" >&2
fi
fi
}
# Function to determine if a message should be logged based on verbosity
should_log() {
local level="$1"
local verbosity="$VERBOSITY"
case "$verbosity" in
debug_logging) return 0 ;;
debug) [[ "$level" != "debug_logging" ]] && return 0 ;;
info) [[ "$level" != "debug" && "$level" != "debug_logging" ]] && return 0 ;;
warning) [[ "$level" != "debug" && "$level" != "info" && "$level" != "debug_logging" ]] && return 0 ;;
error) [[ "$level" == "error" ]] && return 0 ;;
success) [[ "$level" == "success" || "$level" == "error" ]] && return 0 ;;
*) return 1 ;;
esac
return 1
}
rotate_log() {
local log_file="$1"
local max_size="$2"
local rotate_count="$3"
log_debug_logging "rotate_log called with: log_file=$log_file, max_size=$max_size, rotate_count=$rotate_count"
# Check if log file exists
if [[ ! -f "$log_file" ]]; then
log_debug "Log file does not exist: $log_file"
return 1
fi
log_debug_logging "Log file exists: $log_file"
# Check if log file is readable
if [[ ! -r "$log_file" ]]; then
log_debug "Log file is not readable: $log_file"
return 1
fi
log_debug_logging "Log file is readable: $log_file"
# Get file size using find (compatible with both Linux and macOS)
local current_size
current_size=$(find "$log_file" -type f -printf "%s" 2>/dev/null || find "$log_file" -type f -exec stat -f "%z" {} +)
if [[ -z "$current_size" ]]; then
log_debug "Failed to get size of log file: $log_file"
return 1
fi
log_debug_logging "Current log file size: $current_size bytes"
# Check if rotation is needed
if [[ $current_size -gt $max_size && $ENABLE_ROTATE_LOG == true ]]; then
log_debug "Log rotation needed. Current size: $current_size, Max size: $max_size"
# Perform rotation
local i
for i in $(seq $((rotate_count - 1)) -1 1); do
if [[ -f "${log_file}.$i" ]]; then
if mv "${log_file}.$i" "${log_file}.$((i+1))"; then
log_debug "Moved ${log_file}.$i to ${log_file}.$((i+1))"
else
log_debug "Failed to move ${log_file}.$i to ${log_file}.$((i+1))"
fi
fi
done
if mv "$log_file" "${log_file}.1"; then
log_debug "Rotated log file: ${log_file} -> ${log_file}.1"
if touch "$log_file"; then
log_debug "Created new log file: $log_file"
else
log_debug "Failed to create new log file: $log_file"
fi
else
log_debug "Failed to rotate log file: $log_file"
fi
else
log_debug_logging "Log rotation not needed. Current size ($current_size bytes) is within limit."
fi
}
# Function to compress old logs
compress_old_logs() {
find "$LOG_DIR" -name "${LOG_FILE}.*" -mtime "+$LOG_COMPRESS_DAYS" -exec gzip {} \;
}
# Function to clean old logs
clean_old_logs() {
find "$LOG_DIR" -name "${LOG_FILE}.*" -mtime "+$LOG_CLEAN_DAYS" -delete
}
# Function to log to system
log_to_system() {
local message="$1"
local level="$2"
local syslog_priority
# Skip debug_logging messages unless specifically requested
if [[ "$level" == "debug_logging" && "$VERBOSITY" != "debug_logging" ]]; then
return
fi
case "$level" in
error) syslog_priority="err" ;;
success) syslog_priority="notice" ;;
warning) syslog_priority="warning" ;;
info) syslog_priority="info" ;;
debug) syslog_priority="debug" ;;
debug_logging) syslog_priority="debug" ;;
esac
if command -v logger &>/dev/null; then
logger -p "user.$syslog_priority" -t "cloudflare-dns" "$message"
elif [[ -e /dev/log ]]; then
echo "<$syslog_priority>cloudflare-dns: $message" > /dev/log
fi
}
# Shorthand logging functions
log_success() { log "$1" "success"; }
log_error() { log "$1" "error"; }
log_warning() { log "$1" "warning"; }
log_info() { log "$1" "info"; }
log_debug() { log "$1" "debug"; }
log_debug_logging() {
if should_log "debug_logging"; then
log "$1" "debug_logging";
fi
}
# Format terminal titles
print_centered_title() {
local title="$1"
local total_len="$2"
local fill_char="${3:-=}"
local format="${4}"
# Title length
local title_len=${#title}
# Remaining space to fill
local total_fill=$((total_len - title_len))
# Half of the remaining space
local half_fill=$((total_fill / 2))
# Padding on the left and right
local left_padding
left_padding=$(printf '%*s' "$half_fill" '' | tr ' ' "$fill_char")
local right_padding
right_padding=$(printf '%*s' "$((total_fill - half_fill))" '' | tr ' ' "$fill_char")
local title="${left_padding} ${title} ${right_padding}"
# If format is not empty, apply it
[[ -n "$format" ]] && title="${format}${title}${COLORS[RESET]}"
echo -e "$title"
}
# Ensure the log file exists and is writable
ensure_log_file() {
if [[ ! -f $LOG_FILE ]]; then
touch "$LOG_FILE" 2>/dev/null || {
log_error "Error: Unable to create log file at $LOG_FILE."
log_error "Please check permissions or specify a different path."
exit 1
}
elif [[ ! -w $LOG_FILE ]]; then
log_error "Error: Log file $LOG_FILE exists but is not writable."
log_error "Please check file permissions."
exit 1
fi
}
# Retry mechanism for running commands with retries upon failure
# $1: Maximum number of attempts (optional, defaults to $RETRY_ATTEMPTS)
# $2: Delay between attempts in seconds (optional, defaults to $RETRY_INTERVAL)
# $3: List of error codes that should not be retried (optional, comma-separated)
# $4+: The command to be executed
# Returns the output of the successful command execution
retry_command() {
local max_attempts="${1:-$RETRY_ATTEMPTS}"
local delay="${2:-$RETRY_INTERVAL}"
local no_retry_errors="$3"
shift 3
local command="$*"
local attempts=0
local output
local exit_code
log_debug "Executing command with retry: $(sanitize_log "$command")"
log_debug "Max attempts: $max_attempts, Delay: $delay, No-retry errors: $no_retry_errors"
until [[ $attempts -ge $max_attempts ]]; do
if output=$("$@" 2>&1); then
exit_code=$?
log_debug "Command succeeded on attempt $((attempts + 1))"
echo "$output"
return $exit_code
fi
exit_code=$?
attempts=$((attempts + 1))
if [[ -n "$no_retry_errors" && ",${no_retry_errors}," == *",$exit_code,"* ]]; then
log_debug "Command failed with no-retry error code $exit_code. Stopping retries."
echo "$output"
return $exit_code
fi
log_debug "Command failed with exit code $exit_code: attempt $attempts of $max_attempts. Retrying in $delay seconds..."
log_debug "Command output: $(sanitize_log "$output")"
sleep "$delay"
done
log_error "Command failed after $max_attempts attempts with exit code $exit_code."
log_debug "Final command output: $(sanitize_log "$output")"
echo "$output"
return $exit_code
}
sanitize_log() {
local input="$1"
# If sanitization is disabled, return the input unchanged
if [[ "$SANITIZE_LOGS" != "true" ]]; then
echo "$input"
return
fi
local sanitized="$input"
local ipv6_regex_part1="([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:"
local ipv6_regex_part2="([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}"
local ipv6_regex_part3="([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}"
local ipv6_regex_part4="([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})"
local ipv6_regex_part5=":((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}"
local ipv6_regex_part6="::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])"
local ipv6_regex_part7="([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])"
local patterns=(
's/Bearer [a-zA-Z0-9._-]+/Bearer [REDACTED]/g'
's/[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}/[EMAIL REDACTED]/g'
's/[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}/[IPv4 REDACTED]/g'
's/("password":\s*")[^"]+"/\1[REDACTED]"/g'
's/("api_key":\s*")[^"]+"/\1[REDACTED]"/g'
's/("secret":\s*")[^"]+"/\1[REDACTED]"/g'
's/("token":\s*")[^"]+"/\1[REDACTED]"/g'
's|zones/([a-f0-9]{32})/dns_records|zones/[ZONE_ID_REDACTED]/dns_records|g'
's/"id":"[a-f0-9]{32}"/"id":"[ID_REDACTED]"/g'
's/"zone_id":"[a-f0-9]{32}"/"zone_id":"[ZONE_ID_REDACTED]"/g'
's|dns_records/([a-f0-9]{32})|dns_records/[RECORD_ID_REDACTED]|g'
"s/$ipv6_regex_part1|$ipv6_regex_part2|$ipv6_regex_part3|$ipv6_regex_part4|$ipv6_regex_part5|$ipv6_regex_part6|$ipv6_regex_part7/[IPv6 REDACTED]/g"
)
local pattern
for pattern in "${patterns[@]}"; do
sanitized=$(echo "$sanitized" | sed -E "$pattern")
done
echo "$sanitized"
}
# Function to toggle log sanitization
toggle_log_sanitization() {
if [[ "$SANITIZE_LOGS" == "true" ]]; then
SANITIZE_LOGS=false
log_info "Log sanitization disabled"
else
SANITIZE_LOGS=true
log_info "Log sanitization enabled"
fi
}
# Translate Curl error codes to descriptive messages
# $1: Error code
# Returns: Descriptive error message
get_error_description() {
local error_code="$1"
case "$error_code" in
1) echo "Unsupported protocol" ;;
2) echo "Failed to initialize" ;;
3) echo "URL malformed" ;;
5) echo "Couldn't resolve proxy" ;;
6) echo "Couldn't resolve host" ;;
7) echo "Failed to connect to host" ;;
9) echo "Access denied to resource" ;;
22) echo "HTTP page not retrieved" ;;
23) echo "Write error" ;;
26) echo "Read error" ;;
28) echo "Operation timeout" ;;
35) echo "SSL/TLS handshake issue" ;;
51) echo "The remote server doesn't support SSL/TLS" ;;
52) echo "Failed to get the response header" ;;
53) echo "SSL/TLS engine error" ;;
54) echo "SSL/TLS engine failed to set the client certificate" ;;
55) echo "Failed sending network data" ;;
56) echo "Failure in receiving network data" ;;
*) echo "Curl error (code $error_code)" ;;
esac
}
# Check API connectivity and get ping time
check_api_connectivity() {
local start_time
local end_time
local duration
local response
start_time=$(date_compat +%s%N)
response=$(curl -s -o /dev/null -w "%{http_code}" -X GET "https://api.cloudflare.com/client/v4/user/tokens/verify" \
-H "Authorization: Bearer ${ZONE_API_TOKEN}" \
-H "Content-Type: application/json")
end_time=$(date_compat +%s%N)
duration=$(( (end_time - start_time) / 1000000 ))
if [[ "$response" == "200" ]]; then
echo -e "${COLORS[GREEN]}${COLORS[INVERT]} OK ${COLORS[NO_INVERT]} (ping ${duration} ms)${COLORS[RESET]}"
log_debug "API connectivity check successful. Ping time: ${duration} ms"
else
echo -e "${COLORS[RED]}${COLORS[INVERT]} Failed ${COLORS[NO_INVERT]} (HTTP $response)${COLORS[RESET]}"
log_error "API connectivity check failed. HTTP response code: $response"
fi
}
# Function to validate IPv4 format
validate_ipv4_format() {
local ip="$1"
# Check basic format
if [[ ! $ip =~ ^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$ ]]; then
return 1
fi
# Check each octet
IFS='.' read -ra ADDR <<< "$ip"
for i in "${ADDR[@]}"; do
if (( i < 0 || i > 255 )); then
return 1
fi
done
return 0
}
# Function to validate IPv6 format
validate_ipv6_format() {
local ip="$1"
# Remove IPv6 zone index if present
ip=${ip%\%*}
# Check for empty address
if [[ -z $ip ]]; then
return 1
fi
# Check for too many segments
if [[ $(grep -o ":" <<< "$ip" | wc -l) -gt 7 ]]; then
return 1
fi
# Check for invalid characters
if [[ $ip =~ [^0-9a-fA-F:] ]]; then
return 1
fi
# Check for valid use of ::
if [[ $ip =~ "::" ]]; then
if [[ $(grep -o "::" <<< "$ip" | wc -l) -gt 1 || $ip =~ ^:[^:]+ || $ip =~ [^:]+:$ ]]; then
return 1
fi
fi
# Split into segments and check each
IFS=':' read -ra ADDR <<< "$ip"
for i in "${ADDR[@]}"; do
if [[ ${#i} -gt 4 ]]; then
return 1
fi
done
return 0
}
# Main function to validate IP format
validate_ip_format() {
local ip="$1"
local type="$2"
if [[ "$type" == "ipv4" ]]; then
validate_ipv4_format "$ip"
elif [[ "$type" == "ipv6" ]]; then
validate_ipv6_format "$ip"
else
return 1
fi
}
# Method using icanhazip.com
get_ip_icanhazip() {
local ip_type="$1"
local ip
if [[ "$ip_type" == "ipv4" ]]; then
ip=$(curl -s -4 icanhazip.com)
else
ip=$(curl -s -6 icanhazip.com)
fi
if [[ -n "$ip" ]] && validate_ip_format "$ip" "$ip_type"; then
echo "$ip"
return 0
fi
return 1
}
# Method using ip4.me/ip6.me API
get_ip_ipme() {
local ip_type="$1"
local url
if [[ "$ip_type" == "ipv4" ]]; then
url="https://ip4only.me/api/"
else
url="https://ip6only.me/api/"
fi
local response
response=$(curl -s "$url")
local ip
ip=$(echo "$response" | cut -d',' -f2)
if [[ -n "$ip" ]] && validate_ip_format "$ip" "$ip_type"; then
echo "$ip"
return 0
fi
return 1
}
# Method using ifconfig.co
get_ip_ifconfig_co() {
local ip_type="$1"
local ip
if [[ "$ip_type" == "ipv4" ]]; then
ip=$(curl -s -4 https://ifconfig.co)
else
ip=$(curl -s -6 https://ifconfig.co)
fi
if [[ -n "$ip" ]] && validate_ip_format "$ip" "$ip_type"; then
echo "$ip"
return 0
fi
return 1
}
# Main function to get IP address
get_ip() {
local ip_type="$1"
local ip
local methods=("icanhazip" "ipme" "ifconfig_co")
local method
for method in "${methods[@]}"; do
ip=$(get_ip_"$method" "$ip_type")
if [[ $? -eq 0 ]]; then
echo "$ip"
return 0
fi
log_debug "Failed to get $ip_type address using $method method"
done
log_warning "Failed to get $ip_type address from all methods"
return 1
}
# Print current IPv4 and IPv6 addresses
get_current_ips() {
local ipv4
local ipv6
ipv4=$(get_ip "ipv4")
if [[ $GLOBAL_IPV6 == "true" ]]; then
ipv6=$(get_ip "ipv6")
fi
[[ -z "$ipv6" ]] && ipv6="disabled"
# Print with pretty formatting
echo -e "IPv4: ${COLORS[CYAN]}${COLORS[BOLD]}$ipv4${COLORS[RESET]}"
echo -e "IPv6: ${COLORS[CYAN]}${COLORS[BOLD]}$ipv6${COLORS[RESET]}"
}
# Display domains to be processed
display_domains_to_process() {
local max_length="${1:-0}"
local domain_config
local ipv4_enabled
local ipv6_enabled
local proxied
local ttl
local index=1
IFS=',' read -ra DOMAIN_ARRAY <<< "$DOMAINS"
# Display domains
for domain in "${DOMAIN_ARRAY[@]}"; do
domain_config=$(yq ".domains[] | select(.name == \"$domain\")" "$CONFIG_FILE")
ipv4_enabled=$(echo "$domain_config" | yq ".ipv4 // \"$GLOBAL_IPV4\"")
ipv6_enabled=$(echo "$domain_config" | yq ".ipv6 // \"$GLOBAL_IPV6\"")
proxied=$(echo "$domain_config" | yq ".proxied // \"$GLOBAL_PROXIED\"")
ttl=$(echo "$domain_config" | yq ".ttl // \"${GLOBAL_TTL}\"")
# Remove quotes if present
ipv4_enabled=$(echo "$ipv4_enabled" | tr -d '"')
ipv6_enabled=$(echo "$ipv6_enabled" | tr -d '"')
proxied=$(echo "$proxied" | tr -d '"')
ttl=$(echo "$ttl" | tr -d '"')
# Construct the settings string
local settings=""
[[ "$ipv4_enabled" == "true" ]] && settings+="IPv4, "
[[ "$ipv6_enabled" == "true" ]] && settings+="IPv6, "
[[ "$proxied" == "true" ]] && settings+="Proxied, "
settings+="TTL: $ttl"
# Check if using global settings
local global_indicator=""
if [[ -z "$(echo "$domain_config" | yq '.ipv4')" && \
-z "$(echo "$domain_config" | yq '.ipv6')" && \
-z "$(echo "$domain_config" | yq '.proxied')" && \
-z "$(echo "$domain_config" | yq '.ttl')" ]]; then
global_indicator=" (using global settings)"
fi
printf "${COLORS[BOLD]}%2d${COLORS[NO_BOLD]}. %-$((max_length + 2))s -> %s%s\n" \
"$index" "$domain" \
"$settings" \
"$global_indicator"
((index++))
done
echo # New line
}
# Display detailed summary of changes
display_summary() {
local max_length="${1:-0}"
local msg_notification=""
local domain_ ip_v4_changes_ ip_v6_changes_ proxied_v4_changes_ proxied_v6_changes_ ttl_v4_changes_ ttl_v6_changes_ ipv4_enabled_ ipv6_enabled_ duration_
print_centered_title "Summary" $((max_length + 60)) "=" "${COLORS[BLUE]}${COLORS[BOLD]}"
echo "Total domains processed: ${#DOMAIN_ARRAY[@]}"
echo "Create missing records: $ENABLE_CREATE_RECORD"
echo "Details:"
if [[ ! -f "$TEMP_CHANGES_FILE" ]]; then
log_error "Temporary changes file not found. Expected at: $TEMP_CHANGES_FILE"
return 1
fi
if [[ ! -s "$TEMP_CHANGES_FILE" ]]; then
log_warning "No changes were recorded. No summary to display. (Empty changes file)"
return 0
fi
msg_notification=$(printf "%s\n" "Domains updated:")
while IFS='|' read -r domain_ ip_v4_changes_ ip_v6_changes_ proxied_v4_changes_ proxied_v6_changes_ ttl_v4_changes_ ttl_v6_changes_ ipv4_enabled_ ipv6_enabled_ duration_; do
log_debug "Processing domain: $domain_"
if [[ -z "$domain_" ]]; then
log_error "Empty domain name encountered."
continue
fi
local formatted_changes
formatted_changes=$(format_domain_changes \
"$domain_" "$ip_v4_changes_" "$ip_v6_changes_" "$proxied_v4_changes_" "$proxied_v6_changes_" \
"$ttl_v4_changes_" "$ttl_v6_changes_" "$ipv4_enabled_" "$ipv6_enabled_" "$max_length")
echo -e "$formatted_changes"
msg_notification+=$(printf "%s\n" "${formatted_changes}")
done < "$TEMP_CHANGES_FILE"
send_notification "$msg_notification"
log_info "Summary display completed."
}
# Format changes for a single domain
format_domain_changes() {
local domain="$1"
local ip_v4_changes="$2"
local ip_v6_changes="$3"
local proxied_v4_changes="$4"
local proxied_v6_changes="$5"
local ttl_v4_changes="$6"
local ttl_v6_changes="$7"
local ipv4_enabled="$8"
local ipv6_enabled="$9"
local max_length="${10}"
local changes=""
local status=""
local domain_len gap_texts gap_texts_items
domain_len=${#domain}
gap_texts=$(printf '%*s' "$((max_length-domain_len))" '')
gap_texts_items=$(printf '%*s' "$((max_length+7))" '')
if [[ "$ip_v4_changes" == "no_change" && "$ip_v6_changes" == "no_change" && \
"$proxied_v4_changes" == "no_change" && "$proxied_v6_changes" == "no_change" && \
"$ttl_v4_changes" == "no_change" && "$ttl_v6_changes" == "no_change" ]]; then
status=$(printf "%s\n" "${gap_texts}👍 No changes needed")
else
status=$(printf "%s\n" "${gap_texts}👍 Updated!")
[[ "$ipv4_enabled" == "true" && "$ip_v4_changes" != "no_change" && "$ip_v4_changes" != "disabled" ]] && changes+=$(printf "%s" "${gap_texts_items}· IPv4: $ip_v4_changes\n")
[[ "$ipv4_enabled" == "false" && "$ip_v4_changes" == "disabled" ]] && changes+=$(printf "%s" "${gap_texts_items}· IPv4: Disabled\n")
[[ "$ipv6_enabled" == "true" && "$ip_v6_changes" != "no_change" && "$ip_v6_changes" != "disabled" ]] && changes+=$(printf "%s" "${gap_texts_items}· IPv6: $ip_v6_changes\n")
[[ "$ipv6_enabled" == "false" && "$ip_v6_changes" == "disabled" ]] && changes+=$(printf "%s" "${gap_texts_items}· IPv6: Disabled\n")
[[ "$ipv4_enabled" == "true" && "$proxied_v4_changes" != "no_change" && "$ip_v4_changes" != "disabled" ]] && changes+=$(printf "%s" "${gap_texts_items}· Proxied (IPv4): $proxied_v4_changes\n")
[[ "$ipv4_enabled" == "false" && "$ip_v4_changes" == "disabled" ]] && changes+=$(printf "%s" "${gap_texts_items}· Proxied (IPv4): Disabled\n")
[[ "$ipv6_enabled" == "true" && "$proxied_v6_changes" != "no_change" && "$ip_v6_changes" != "disabled" ]] && changes+=$(printf "%s" "${gap_texts_items}· Proxied (IPv6): $proxied_v6_changes\n")
[[ "$ipv6_enabled" == "false" && "$ip_v6_changes" == "disabled" ]] && changes+=$(printf "%s" "${gap_texts_items}· Proxied (IPv6): Disabled\n")
[[ "$ipv4_enabled" == "true" && "$ttl_v4_changes" != "no_change" && "$ip_v4_changes" != "disabled" ]] && changes+=$(printf "%s" "${gap_texts_items}· TTL (IPv4): $ttl_v4_changes\n")
[[ "$ipv4_enabled" == "false" && "$ip_v4_changes" == "disabled" ]] && changes+=$(printf "%s" "${gap_texts_items}· TTL (IPv4): Disabled\n")
[[ "$ipv6_enabled" == "true" && "$ttl_v6_changes" != "no_change" && "$ip_v6_changes" != "disabled" ]] && changes+=$(printf "%s" "${gap_texts_items}· TTL (IPv6): $ttl_v6_changes\n")
[[ "$ipv6_enabled" == "false" && "$ip_v6_changes" == "disabled" ]] && changes+=$(printf "%s" "${gap_texts_items}· TTL (IPv6): Disabled\n")
fi
printf " %s: %s\n%s" "$domain" "$status" "${changes%\\n}"
}
#==============================================================================
# YAML PARSING
#==============================================================================
# Load and parse the YAML configuration file
load_yaml() {
local config_file="$1"
if [[ ! -f "$config_file" ]]; then
log_error "Configuration file not found: $config_file"
exit 1
fi
if ! command -v yq &> /dev/null; then
log_error "yq is not installed. Please install yq to parse YAML files."
exit 1
fi
# Helper function to remove quotes from yq output
remove_quotes() {
echo "$1" | sed -e 's/^"//' -e 's/"$//'
}
# Load main configuration settings
ZONE_ID=$(remove_quotes "$(yq .cloudflare.zone_id "$config_file")")
ZONE_API_TOKEN=$(remove_quotes "$(yq .cloudflare.zone_api_token "$config_file")")
ENABLE_CREATE_RECORD=$(yq '.globals.enable_create_record // false' "$config_file")
RETRY_ATTEMPTS=$(yq .advanced.retry_attempts "$config_file")
RETRY_INTERVAL=$(yq .advanced.retry_interval "$config_file")
MAX_PARALLEL_JOBS=$(yq .advanced.max_parallel_jobs "$config_file")
# Use environment variables for sensitive data if available
ZONE_ID="${CF_ZONE_ID:-$ZONE_ID}"
ZONE_API_TOKEN="${CF_API_TOKEN:-$ZONE_API_TOKEN}"
# Load logging settings
LOG_FILE=$(remove_quotes "$(yq .logging.file "$config_file")")
LOG_DIR=$(dirname "$LOG_FILE")
LOG_TO_TERMINAL=$(yq .logging.terminal_output "$config_file")
VERBOSITY=$(remove_quotes "$(yq .logging.verbosity "$config_file")")
ENABLE_ROTATE_LOG=$(yq '.logging.rotate_log // false' "$config_file")
MAX_LOG_SIZE=$(yq '.logging.max_size // 10485760' "$config_file") # Default 10MB
LOG_ROTATE_COUNT=$(yq '.logging.rotate_count // 5' "$config_file")
LOG_COMPRESS_DAYS=$(yq '.logging.compress_days // 7' "$config_file")
LOG_CLEAN_DAYS=$(yq '.logging.clean_days // 30' "$config_file")
LOG_TO_SYSTEM=$(yq '.logging.log_to_system // false' "$config_file")
SANITIZE_LOGS=$(remove_quotes "$(yq '.logging.sanitize_logs' "$config_file")")
# Load global settings
GLOBAL_IPV4=$(yq '.globals.ipv4 // true' "$config_file")
GLOBAL_IPV6=$(yq '.globals.ipv6 // true' "$config_file")
GLOBAL_PROXIED=$(yq '.globals.proxied // true' "$config_file")
GLOBAL_TTL=$(remove_quotes "$(yq '.globals.ttl // 1' "$config_file")")
log_debug "Global settings: IPv4=$GLOBAL_IPV4, IPv6=$GLOBAL_IPV6, Proxied=$GLOBAL_PROXIED, TTL=$GLOBAL_TTL"
# Load domains
DOMAINS=$(yq '.domains[].name' "$config_file" | tr '\n' ',' | sed 's/,$//' | sed -e 's/"//g')
# Load notification settings
load_notification_settings "$config_file"
log_debug "Configuration loaded from $config_file"
log_debug "ENABLE_CREATE_RECORD set to: $ENABLE_CREATE_RECORD"
}
# Load notification settings from the configuration file
load_notification_settings() {
local config_file="$1"
if [[ $(yq .notifications.telegram.enabled "$config_file") == "true" ]]; then
log_debug "Telegram Notification loading."
NOTIFICATION_PLUGINS["telegram"]=true
TELEGRAM_BOT_TOKEN=$(remove_quotes "$(yq .notifications.telegram.bot_token "$config_file")")
TELEGRAM_CHAT_ID=$(remove_quotes "$(yq .notifications.telegram.chat_id "$config_file")")
fi
if [[ $(yq .notifications.email.enabled "$config_file") == "true" ]]; then
log_debug "Email Notification loading."
NOTIFICATION_PLUGINS["email"]=true
notifications_email_smtp_server=$(remove_quotes "$(yq .notifications.email.smtp_server "$config_file")")
notifications_email_smtp_port=$(remove_quotes "$(yq .notifications.email.smtp_port "$config_file")")
notifications_email_use_ssl=$(yq .notifications.email.use_ssl "$config_file")
notifications_email_username=$(remove_quotes "$(yq .notifications.email.username "$config_file")")
notifications_email_password=$(remove_quotes "$(yq .notifications.email.password "$config_file")")
notifications_email_from_address=$(remove_quotes "$(yq .notifications.email.from_address "$config_file")")
notifications_email_to_address=$(remove_quotes "$(yq .notifications.email.to_address "$config_file")")
fi
if [[ $(yq .notifications.slack.enabled "$config_file") == "true" ]]; then
log_debug "Slack Notification loading."
NOTIFICATION_PLUGINS["slack"]=true
notifications_slack_webhook_url=$(remove_quotes "$(yq .notifications.slack.webhook_url "$config_file")")
fi
if [[ $(yq .notifications.discord.enabled "$config_file") == "true" ]]; then
log_debug "Discord Notification loading."
NOTIFICATION_PLUGINS["discord"]=true
notifications_discord_webhook_url=$(remove_quotes "$(yq .notifications.discord.webhook_url "$config_file")")
fi
log_debug "Notification settings loaded"
}
#==============================================================================
# DNS MANAGEMENT
#==============================================================================
# Get domain-specific user configuration
get_domain_config() {
local domain="$1"
local config_file="$2"
local domain_config
local ipv4_enabled
local ipv6_enabled
local proxied
local ttl
domain_config=$(yq ".domains[] | select(.name == \"$domain\")" "$config_file")
ipv4_enabled=$(echo "$domain_config" | yq ".ipv4 // \"$GLOBAL_IPV4\"")
ipv6_enabled=$(echo "$domain_config" | yq ".ipv6 // \"$GLOBAL_IPV6\"")
proxied=$(echo "$domain_config" | yq ".proxied // \"$GLOBAL_PROXIED\"")
ttl=$(echo "$domain_config" | yq ".ttl // \"${GLOBAL_TTL}\"")
# Remove quotes if present
ipv4_enabled=$(echo "$ipv4_enabled" | tr -d '"')
ipv6_enabled=$(echo "$ipv6_enabled" | tr -d '"')
proxied=$(echo "$proxied" | tr -d '"')
ttl=$(echo "$ttl" | tr -d '"')
echo "$ipv4_enabled|$ipv6_enabled|$proxied|$ttl"
}
# Delete a DNS record
delete_dns_record() {
local zone_id="$1"
local record_name="$2"
local record_type="$3"
local record_info
local record_id
record_info=$(get_record_info "$zone_id" "$record_name" "$record_type")
record_id=$(echo "$record_info" | jq -r '.id')
if [[ -n "$record_id" && "$record_id" != "null" ]]; then
local response
response=$(curl -s -X DELETE "https://api.cloudflare.com/client/v4/zones/$zone_id/dns_records/$record_id" \
-H "Authorization: Bearer $ZONE_API_TOKEN" \
-H "Content-Type: application/json")
if [[ "$(echo "$response" | jq -r '.success')" == "true" ]]; then
echo "${record_type} record deleted"
else
echo "Failed to delete ${record_type} record"
fi
else
log_info "No ${record_type} record found. Nothing to delete."
fi
}
# Update or create a DNS record
update_dns_record() {
local zone_id="$1"
local record_name="$2"
local ip="$3"
local record_type="$4"
local proxied="$5"
local ttl="$6"
validate_update_params "$@" || return 1
local current_record
current_record=$(get_current_record_info "$zone_id" "$record_name" "$ip" "$record_type" "$proxied" "$ttl") || return 1
if [[ "$current_record" == "new_record" ]]; then
log_info "New record for $record_name ($record_type)"
echo "new_record|new_record|new_record"
return 0
fi
local changes
changes=$(compare_and_prepare_changes "$current_record" "$ip" "$proxied" "$ttl")
if [[ "$changes" == "no_changes" ]]; then
log_info "No changes needed for $record_name ($record_type)"
echo "no_change|no_change|no_change"
return 0
fi
update_record_api "$zone_id" "$current_record" "$record_name" "$ip" "$record_type" "$changes" || return 1
echo "$changes"
return 0
}
# Validates and normalizes the parameters for updating a DNS record
# Returns 0 if parameters are valid, 1 otherwise
validate_update_params() {
local zone_id="$1" record_name="$2" ip="$3" record_type="$4" proxied="$5" ttl="$6"
if [[ -z "$zone_id" || -z "$record_name" || -z "$ip" || -z "$record_type" || -z "$proxied" || -z "$ttl" ]]; then
log_error "Missing required parameters in update_dns_record function"
return 1
fi