-
Notifications
You must be signed in to change notification settings - Fork 0
/
cloudflare-ddns
executable file
·287 lines (235 loc) · 8.12 KB
/
cloudflare-ddns
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
#!/bin/bash
#
# Cloudflare DDNS functions script
# set -o xtrace
############################
# --- Global Variables --- #
############################
export CF_ACCESS_TOKEN="" # Start with "Bearer "
export ZONE_IDENTIFIER=""
export RECORD_NAME=""
LAN_IP_SEGMENTS="^$"
LAN_IP_SEGMENTS="${LAN_IP_SEGMENTS}|(^10\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$)"
LAN_IP_SEGMENTS="${LAN_IP_SEGMENTS}|(^127\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$)"
LAN_IP_SEGMENTS="${LAN_IP_SEGMENTS}|(^169\.254\.[0-9]{1,3}\.[0-9]{1,3}$)"
LAN_IP_SEGMENTS="${LAN_IP_SEGMENTS}|(^172\.(1[6-9]|2[0-9]|3[0-1])\.[0-9]{1,3}\.[0-9]{1,3}$)"
LAN_IP_SEGMENTS="${LAN_IP_SEGMENTS}|(^192\.168\.[0-9]{1,3}\.[0-9]{1,3}$)"
readonly LAN_IP_SEGMENTS
############################
# -- Utilities Function -- #
############################
err() {
echo >&2 "[ERROR] | $(date +'%Y-%m-%dT%H:%M:%S') | $*"
}
info() {
echo >&2 "[INFO] | $(date +'%Y-%m-%dT%H:%M:%S') | $*"
}
############################
# Cloudflare-ddns Section #
############################
#######################################
# Get WAN ipv4 address via command-line tool `ip`,
# if not available, or behind NAT, via remote api.
# Globals:
# LAN_IP_SEGMENTS
# Arguments:
# None
# Outputs:
# None
# Returns:
# Host ipv4 address, non-zero on error.
#######################################
get_wan_ipv4_addr() {
local ipv4_addr
if [[ ! "$(uname)" == "Linux" ]]; then
err "non-Linux Platform is not supported."
return 1
fi
ipv4_addr=""
info "Getting Network Ip locally using cli-program ip..."
ipv4_addr=$(
ip -oneline -4 address |
grep -v -E '\slo|\sdocker' |
awk '{ print $4 }' |
cut -d'/' -f1 |
grep -v -E "${LAN_IP_SEGMENTS}"
)
if [[ -z "${ipv4_addr}" ]]; then
err "Failed to Get Network Ip locally."
info "Using api.ipify.org to retrieve ip..."
if command -v curl >/dev/null 2>&1; then
info "Using curl..."
ipv4_addr=$(curl --silent -L https://api.ipify.org)
info "api called from ip.ipify.org => ${ipv4_addr}"
else
err "curl is unavailable/uninstalled. "
err "Please install curl to resolve dependency problem"
return 1
fi
else
info "command-line tool ip => ${ipv4_addr}"
fi
echo "${ipv4_addr}"
}
#######################################
# Get DNS Record detail from cloudflare v4 api using curl GET.
# https://api.cloudflare.com/#dns-records-for-a-zone-list-dns-records
# Globals:
# ZONE_IDENTIFIER
# CF_ACCESS_TOKEN
# RECORD_NAME
# Arguments:
# None
# Outputs:
# None
# Returns:
# json-formatted: { "record_id": $id, "record_ip": $ip }
# , non-zero on error.
#######################################
getCurrent4Record() {
local _retrieve_json
local _active_record_count
local current_record_ip
local current_record_id
info "Curl to Cloudflare v4 api..."
_retrieve_json=$(
curl --silent -X GET "https://api.cloudflare.com/client/v4/zones/${ZONE_IDENTIFIER}/dns_records?name=${RECORD_NAME}&type=A" \
-H "Authorization: ${CF_ACCESS_TOKEN}" \
-H "Content-Type: application/json"
)
_active_record_count=$(echo "${_retrieve_json}" | jq -r '.result_info.count')
if [[ ${_active_record_count} == 0 ]]; then
err "Record NOT Found."
return 127
fi
current_record_ip=$(echo "${_retrieve_json}" | jq -r '.result[0].content')
current_record_id=$(echo "${_retrieve_json}" | jq -r '.result[0].id')
info "${RECORD_NAME} has cloudflare-side id: ${current_record_id}"
info "${RECORD_NAME} currently points to --> ${current_record_ip}"
jq -r -c --null-input \
--arg id "${current_record_id}" \
--arg ip "${current_record_ip}" \
'{ record_id: $id, record_ip: $ip }'
}
#######################################
# Create DNS Record using curl POST via cloudflare v4 api.
# https://api.cloudflare.com/#dns-records-for-a-zone-create-dns-record
# Globals:
# ZONE_IDENTIFIER
# CF_ACCESS_TOKEN
# RECORD_NAME
# Arguments:
# host_ip: Host ipv4 address obtained from get_wan_ipv4_addr()
# Outputs:
# None
# Returns:
# None
#
# *Exists* Exit route for shell script.
#######################################
create4RecordIfNotExists() {
local host_ip="$1"
local _retrieve_json
info "Attempting to CREATE record via curl POST..."
_retrieve_json=$(
curl --silent -X POST "https://api.cloudflare.com/client/v4/zones/${ZONE_IDENTIFIER}/dns_records" \
-H "Authorization: ${CF_ACCESS_TOKEN}" \
-H "Content-Type: application/json" \
--data "$(
jq -r -c --null-input \
--arg record_name "${RECORD_NAME}" \
--arg record_ip "${host_ip}" \
'{"type": "A", "name": $record_name, "content": $record_ip, "ttl": 100, "proxied": false}'
)"
)
if [[ $(echo "${_retrieve_json}" | jq -r '.success') == "true" ]]; then
info "${RECORD_NAME} is CREATED."
info "If this is the first time you run this script."
info "Don't worry, it ran well. Proceed to next step in Documentation."
info "Record detail will follow in 3 seconds......"
info "If NOT --> (Be advised) Your record name is not found on cloudflare."
info ", which leads to auto-re-creation of the record."
sleep 3
info "$(getCurrent4Record)"
exit 0
else
err "${RECORD_NAME} creation failed. Result pretty print as below."
err "${_retrieve_json}" | jq -r '.'
exit 1
fi
}
#######################################
# Update specific DNS record detail to cloudflare v4 api using curl PUT.
# https://api.cloudflare.com/#dns-records-for-a-zone-update-dns-record
# Globals:
# ZONE_IDENTIFIER
# CF_ACCESS_TOKEN
# RECORD_NAME
# Arguments:
# pending_record_id: dns record id which needs updated.
# pending_record_ip: dns record ip/content which needs updates
# Outputs:
# None
# Returns:
# 0 if record is updated successfully, non-zero on error.
#######################################
updateCurrent4Record() {
local pending_record_id="$1"
local pending_record_ip="$2"
local _retrieve_json
info "Attempting to point record id ${pending_record_id} to ${pending_record_ip} via curl PUT..."
_retrieve_json=$(
curl --silent -X PUT "https://api.cloudflare.com/client/v4/zones/${ZONE_IDENTIFIER}/dns_records/${pending_record_id}" \
-H "Authorization: ${CF_ACCESS_TOKEN}" \
-H "Content-Type: application/json" \
--data "$(
jq -r -c --null-input \
--arg record_name "${RECORD_NAME}" \
--arg record_ip "${pending_record_ip}" \
'{"type": "A", "name": $record_name, "content": $record_ip, "ttl": 100, "proxied": false}'
)"
)
if [[ $(echo "${_retrieve_json}" | jq -r '.success') == "true" ]]; then
info "${RECORD_NAME} is updated, now points to ${pending_record_ip}"
return 0
else
err "${RECORD_NAME} update failed. Result pretty print as below."
err $(echo "${_retrieve_json}" | jq -r '.')
return 1
fi
return 0
}
main() {
local _error
local _return_tmp
local record_id
local record_ip
local host_ip
info "Getting Host Ip Address"
host_ip=$(get_wan_ipv4_addr)
_error="$?"
if [[ "${_error}" -ne 0 ]]; then
return 1
fi
info "Getting Record Ip from Cloudflare"
_return_tmp=$(getCurrent4Record)
_error="$?"
if [[ "${_error}" -eq 0 ]]; then
record_id=$(echo "${_return_tmp}" | jq -r '.record_id')
record_ip=$(echo "${_return_tmp}" | jq -r '.record_ip')
elif [[ "${_error}" -eq 127 ]]; then
create4RecordIfNotExists ${host_ip}
else
return 1
fi
if [[ "${host_ip}" == "${record_ip}" ]]; then
info "Ip stays the same, no need to update. Exiting."
return 0
fi
info "Updating Record Ip"
updateCurrent4Record "${record_id}" "${host_ip}"
_error="$?"
if [[ "${_error}" -ne 0 ]]; then
return 1
fi
}