-
Notifications
You must be signed in to change notification settings - Fork 0
/
Cloudflare-CLI.sh
1390 lines (1247 loc) · 31.8 KB
/
Cloudflare-CLI.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
#!/usr/bin/env bash
###############################################################################
# Cloudflare-CLI #
# https://github.com/cvc90/Cloudflare-CLI/ #
# #
# CLI utility that manages Cloudflare services through the Cloudflare API #
# #
# Script file Cloudflare-CLI.sh #
# A script that manages Cloudflare services through the Cloudflare API #
# #
# Usage: ./Cloudflare-CLI.sh #
###############################################################################
# -------------------------------------------------- #
# -- Variables
# -------------------------------------------------- #
VERSION=1.0
DEBUG=0
details=0
quiet=0
NL=$'\n'
TA=$'\t'
CF_API_ENDPOINT=https://api.cloudflare.com/client/v4
APIv4_ENDPOINT=$CF_API_ENDPOINT # Remove eventually
# -- Colors
RED="\e[31m"
GREEN="\e[32m"
CYAN="\e[36m"
BLUEBG="\e[44m"
YELLOWBG="\e[43m"
GREENBG="\e[42m"
DARKGREYBG="\e[100m"
ECOL="\e[0m"
# -- HELP_VERSION
HELP_VERSION=\
"Version: $VERSION
"
# -- HELP
HELP=\
"
Help
Usage: cloudflare [Options] <command> <parameters>
${HELP_OPTIONS}
Commands:
list - Show information about an object
zone <zone>
zones
settings <zone>
records <zone>
access-lists <zone>
add - Create Object
zone
record
whitelist
blacklist
challenge
delete - Delete Objects
zone
record
listing
change - Change Object
zone
record
clear - Clear cache
everything
invalidate <url>
help - Full help
Environment variables:
CF_ACCOUNT - email address (as -E option)
CF_TOKEN - API token (as -T option)
Configuration file for credentials:
Create a file in \$HOME/.cloudflare with both CF_ACCOUNT and CF_TOKEN defined.
CF_TOKEN=<token>
${HELP_EXAMPLES}
${HELP_VERSION}
Enter \"cloudflare help\" to list available commands."
# -- HELP_CMDS
HELP_CMDS=\
"Commands:
list, add, delete, change, clear, invalidate, check
list zone, zones, settings, records, listing
add zone, record, whitelist, blacklist, challenge
delete zone, record, listing
change zone, record
clear cache"
# -- HELP_OPTIONS
HELP_OPTIONS=\
"Options:
--details, -d Display detailed info where possible
--debug, -D Display API debugging info
--quiet, -q Less verbose
-E <email>
-T <api_token>"
# -- USAGE
HELP_USAGE=\
"Usage: cloudflare [Options] <command> <parameters>
${HELP_CMDS}
${HELP_OPTIONS}
${HELP_EXAMPLES}
${HELP_VERSION}
Enter \"cloudflare help\" to list available commands."
# -- EXAMPLES
HELP_EXAMPLES=\
"Examples:
$ cloudflare show settings example.net
advanced_ddos off
always_online on
automatic_https_rewrites off
...
$ cloudflare show records example.net
www auto CNAME example.net. ; proxiable,proxied #IDSTRING
@ auto A 198.51.100.1 ; proxiable,proxied #IDSTRING
* 3600 A 198.51.100.2 ; #IDSTRING
...
$ cloudflare show records example.net
www auto CNAME example.net. ; proxiable,proxied #IDSTRING
@ auto A 198.51.100.1 ; proxiable,proxied #IDSTRING
* 3600 A 198.51.100.2 ; #IDSTRING
..."
HELP_SHOW=\
"${HELP_CMDS}
Usage: cloudflare list [zones|zone <zone>|settings <zone>|records <zone>|access-lists <zone>]
Commands:
zones -List all zones under account.
zone -List basic information for <zone>.
settings -List settings for <zone>
records -List records for <zone>
access-lists -List access lists for <zone>
Options:
<zone> domain zone to register the record in, see 'show zones' command
${HELP_VERSION}"
HELP_ADD_RECORD=\
"${HELP_CMDS}
Usage: cloudflare add record <zone> <type> <name> <content> [ttl] [prio | proxied] [service] [protocol] [weight] [port]
<zone> domain zone to register the record in, see 'show zones' command
<type> one of: A, AAAA, CNAME, MX, NS, SRV, TXT (Contain in double quotes ""), SPF, LOC
<name> subdomain name, or \"@\" to refer to the domain's root
<content> IP address for A, AAAA
FQDN for CNAME, MX, NS, SRV
any text for TXT, spf definition text for SPF
coordinates for LOC (see RFC 1876 section 3)
Additional Options
[ttl] Time To Live, 1 = auto
MX records:
[prio] required only by MX and SRV records, enter \"10\" if unsure
A or CNAME records:
[proxied] Proxied, true or false. For A or CNAME records only.
SRV records:
[service] service name, eg. \"sip\"
[protocol] tcp, udp, tls
[weight] relative weight for records with the same priority
[port] layer-4 port number
${HELP_VERSION}"
# -------------------------------------------------- #
# -- Functions
# -------------------------------------------------- #
# -- help
HELP () {
cmd1=$1
shift
case "$cmd1" in
# -- usage
usage|USAGE)
echo "$HELP_USAGE"
;;
# -- help
help|HELP)
echo "$HELP"
;;
# -- add
add)
cmd2="$2"
case "$cmd2" in
record)
echo "$HELP_ADD_RECORD"
;;
esac
;;
show)
echo "$HELP_SHOW"
;;
esac
}
# ----------------------
# -- Messaging Functions
# ----------------------
_error () {
echo -e "${RED}** ERROR ** - $1 ${ECOL}"
}
_success () {
echo -e "${GREEN}** SUCCESS ** - $@ ${ECOL}"
}
_running () {
echo -e "${BLUEBG}${@}${ECOL}"
}
_creating () {
echo -e "${DARKGREYBG}${@}${ECOL}"
}
_separator () {
echo -e "${YELLOWBG}****************${ECOL}"
}
_debug () {
if [ $DEBUG == "1" ]; then
echo -e "${CYAN}** DEBUG: $@${ECOL}"
fi
}
# -- die
_die() {
if [ -n "$1" ]; then
_error "$1"
fi
exit ${2:-1}
}
# -- check_bash - check version of bash
check_bash () {
# - Check bash version and die if not at least 4.0
if [ $BASH_VERSINFO -lt 4 ]; then
_die "Sorry, you need at least bash 4.0 to run this script." 1
fi
}
# -- is_* functions
is_debug() { [ "$DEBUG" = 1 ]; }
is_quiet() { [ "$quiet" = 1 ]; }
is_integer() { expr "$1" : '[0-9]\+$' >/dev/null; }
is_hex() { expr "$1" : '[0-9a-fA-F]\+$' >/dev/null; }
# -- CURL_CF - New Cloudflare api call
#
# Invocation - CURL_CF <METHOD> <PATH> [PARAMETERS] [-- JSON_DECODER-ARGS]
# Example - call_cf_v4 GET /zones -- .result %"%s$TA%s$TA#%s$TA%s$TA%s$NL" ,name,status,id,original_name_servers,name_servers
# ---------------------------------------------------------------------------
CURL_CF() {
# Variables
local CURL_METHOD API_PATH FORMTYPE EXITCODE QUERYSTRING PAGE PER_PAGE
declare -a CURL_OPTS
CURL_OPTS=()
# Params
CURL_METHOD=${1^^} # Set $CURL_METHOD to all uppercase
shift
API_PATH=$1
shift
# Set content-type and form type
# -o = OPTION NAME
# ${1:0:1} get first characater of $1
# if first character of $1 is { then set $FORMTYPE to form
if [ "$CURL_METHOD" != POST -o "${1:0:1}" = '{' ]; then
CURL_OPTS+=(-H "Content-Type: application/json")
FORMTYPE=data
else
FORMTYPE=form
fi
_debug "Formtype: $FORMTYPE"
# If GET method then set CURL_OPTS --get
if [[ "$CURL_METHOD" = GET ]];then
CURL_OPTS+=(--get)
fi
_debug "CURL_OPTS: $CURL_OPTS"
# If $1 contains -- do nothing else set curl_opts to (--$FORMTYPE "$1")
while [ -n "$1" ]; do
if [ ."$1" = .-- ]; then
shift
break
else
CURL_OPTS+=(--$FORMTYPE "$1")
fi
shift
done
_debug "CURL_OPTS: $CURL_OPTS"
# if $1 is zero, ?
if [ -z "$1" ];then
set -- '&?success?"success"?"failed"'
_debug "$1"
fi
# Cloudflare page and results options
PAGE=1
PER_PAGE=100
while true;do
QUERY_STRING="?page=${PAGE}&per_page=${PER_PAGE}"
# if is_debug; then
# echo "<<< curl -X $CURL_METHOD ${CURL_OPTS[*]} ${CF_API_ENDPOINT}${API_API_PATH}${QUERYSTRING}" >&2
# fi
# if [[ $DEBUG == "1" ]];then set -x;fi
CURL_OUTPUT=$(curl -sS -H "X-Auth-Email: ${CF_ACCOUNT}" \
-H "X-Auth-Key: ${CF_TOKEN}" \
-X "${CURL_METHOD}" \
"${CURL_OPTS[@]}" \
"${CF_API_ENDPOINT}${API_PATH}${QUERYSTRING}" | json_decode "$@")
# if [[ $DEBUG == "1" ]];then set +x;fi
EXIT_CODE=$?
# _debug "Curl OUTPUT: $CURL_OUTPUT"
_debug "Exit Code: $EXIT_CODE"
sed -e '/^!/d' <<<"$CURL_OUTPUT"
if [[ $(grep -qE '^!has_more' <<< "$CURL_OUTPUT") ]]; then
_debug "More pages"
let PAGE++
else
_debug "No more pages"
break
fi
done
return $EXIT_CODE
}
# -- call_cf_v4 - Main call to cloudflare using curl
call_cf_v4() {
# Invocation: call_cf_v4 <METHOD> <PATH> [PARAMETERS] [-- JSON-DECODER-ARGS]
local method path formtype exitcode querystring page per_page
declare -a curl_opts
curl_opts=()
method=${1^^}
shift
path=$1
shift
if [ "$method" != POST -o "${1:0:1}" = '{' ]
then
curl_opts+=(-H "Content-Type: application/json")
formtype=data
else
formtype=form
fi
if [ "$method" = GET ]
then
curl_opts+=(--get)
fi
while [ -n "$1" ]
do
if [ ."$1" = .-- ]
then
shift
break
else
curl_opts+=(--$formtype "$1")
fi
shift
done
if [ -z "$1" ]
then
set -- '&?success?"success"?"failed"'
fi
page=1
per_page=50
while true
do
querystring="?page=$page&per_page=$per_page"
if is_debug
then
echo "<<< curl -X $method ${curl_opts[*]} $APIv4_ENDPOINT$path$querystring" >&2
fi
output=`curl -sS -H "X-Auth-Email: $CF_ACCOUNT" -H "X-Auth-Key: $CF_TOKEN" \
-X "$method" "${curl_opts[@]}" \
"$APIv4_ENDPOINT$path$querystring" | json_decode "$@"`
exitcode=$?
sed -e '/^!/d' <<<"$output"
if grep -qE '^!has_more' <<<"$output"
then
let page++
else
break
fi
done
return $exitcode
}
# -- json_decode - php code to decode json
json_decode()
{
# Parameter Synatx
#
# .key1.key11.key111
# dive into array
# %format
# set output formatting
# table
# display as a table
# ,mod1,mod2,...
# see modifiers
# &mod1&mod2&...
# modifiers per line
#
#
# Modifier Synatx
#
# ?modCondition?modTrue?modFalse
# tenary expression
# ||key1||key2||key3||...
# find a true-ish value
# key.subkey.subsubkey
# dive into array
# !key
# implode non-zero elements of key
# !!key1 key2 key3 ...
# implode values of keys if they are not false
# <code
# evaluate code, keyN are in $keyN
# "string"
# literal
# @suffixKey@stringKey
# trim suffix from string
# key
# represent the value
php -r '
function notzero($e)
{
return $e!=0;
}
function repr_array($a, $brackets=false)
{
if(is_array($a))
{
$o = array();
foreach($a as $k => $v)
{
$o[] = (is_int($k) ? "" : "$k=") . repr_array($v, true);
}
if(count($o) > 1 and $brackets)
return "[" . implode(",", $o) . "]";
else
return implode(",", $o);
}
else
return $a;
}
function pfmt($fmt, &$array, $care_null=1)
{
if(preg_match("/^\?(.*?)\?(.*?)\?(.*)/", $fmt, $grp))
{
$out = pfmt($grp[1], $array, 0) ? pfmt($grp[2], $array) : pfmt($grp[3], $array);
}
elseif(preg_match("/^!!(.*)/", $fmt, $grp))
{
$out = implode(",", array_filter(preg_split("/\s+/", $grp[1]), function($k) use($array){ return !!$array[$k]; }));
}
elseif(preg_match("/^!(.*)/", $fmt, $grp))
{
$out = implode(",", array_keys(array_filter($array[$grp[1]], "notzero")));
}
elseif(preg_match("/^<(.*)/", $fmt, $grp))
{
$code = $grp[1];
extract($array, EXTR_SKIP);
$out = eval("return $code;");
}
elseif(preg_match("/^\x22(.*?)\x22/", $fmt, $grp))
{
$out = $grp[1];
}
elseif(preg_match("/^@(.*?)@(.*)/", $fmt, $grp))
{
$out = substr($array[$grp[2]], 0, -strlen(".".$array[$grp[1]]));
if($out == "") $out = "@";
}
elseif(preg_match("/^\|\|/", $fmt))
{
while(preg_match("/^\|\|(.*?)(\|\|.*|$)/", $fmt, $grp))
{
if(pfmt($grp[1], $array, 0) != false or !preg_match("/^\|\|/", $grp[2]))
{
$out = pfmt($grp[1], $array, $care_null);
break;
}
$fmt = $grp[2];
}
}
elseif(preg_match("/(.+?)\.(.+)/", $fmt, $grp))
{
if(is_array(@$array[$grp[1]]))
$out = pfmt($grp[2], $array[$grp[1]], $care_null);
else
$out = NULL;
}
else
{
/* Fix Cludflare´s DNS notation.
We must use FQDN with the trailing dot if no $ORIGIN declared. */
if(in_array(@$array["type"], explode(",", "CNAME,MX,NS,SRV")) and isset($array["content"]) and substr($array["content"], -1) != ".")
{
$array["content"] .= ".";
}
if(is_array(@$array[$fmt]))
{
$out = repr_array($array[$fmt]);
}
else
{
$out = $care_null ? (array_key_exists($fmt, $array) ? (isset($array[$fmt]) ? $array[$fmt] : "NULL" ) : "NA") : @$array[$fmt];
}
}
return $out;
}
$data0 = json_decode(file_get_contents("php://stdin"), true);
if('$DEBUG') file_put_contents("php://stderr", var_export($data0, 1));
if(@$data0["result"] == "error")
{
echo $data0["msg"] . "\n";
exit(2);
}
if(array_key_exists("success", $data0) and !$data0["success"])
{
function prnt_error($e)
{
printf("E%s: %s\n", $e["code"], $e["message"]);
foreach((array)@$e["error_chain"] as $e) prnt_error($e);
}
foreach($data0["errors"] as $e) prnt_error($e);
exit(2);
}
if(isset($data0["result_info"]["page"]) and $data0["result_info"]["page"] < $data0["result_info"]["total_pages"])
{
echo "!has_more\n";
}
array_shift($argv);
$data = $data0;
foreach($argv as $param)
{
if($param == "")
{
continue;
}
if(substr($param, 0, 1) == ".")
{
$data = $data0;
foreach(explode(".", $param) as $p)
{
if($p != "")
{
if(array_key_exists($p, $data))
{
if($p == "objs" and @$data["has_more"])
{
echo "!has_more\n";
echo "!count=", $data["count"], "\n";
}
$data = $data[$p];
}
else
{
$data = array();
break;
}
}
}
}
if(substr($param, 0, 1) == "%")
{
$outfmt = substr($param, 1);
}
if($param == "table")
{
ksort($data);
$maxlength = 0;
foreach($data as $key=>$elem)
{
if(strlen($key) > $maxlength)
{
$maxlength = strlen($key);
}
}
foreach($data as $key=>$elem)
{
printf("%-".$maxlength."s\t%s\n", $key, (string)$elem);
}
}
if(substr($param, 0, 1) == ",")
{
foreach($data as $key=>$elem)
{
$out = array();
foreach(preg_split("/(?<!,),(?!,)/", $param) as $p)
{
$p = str_replace(",,", ",", $p);
if($p != "")
{
$out[] = pfmt($p, $elem);
}
}
if(isset($outfmt))
{
vprintf($outfmt, $out);
}
else
{
echo implode("\t", $out), "\n";
}
}
}
if(substr($param, 0, 1) == "&")
{
foreach(explode("&", $param) as $p)
{
if($p!="")
{
echo pfmt($p, $data), "\n";
}
}
}
}
' "$@"
}
# -- findout_record
#
# Arguments:
# $1 - record name (eg: sub.example.com)
# $2 - record type, optional (eg: CNAME)
# $3 - 0/1, stop searching at first match, optional
# $4 - record content to match to
# writes global variables: zone, zone_id, record_id, record_type, record_ttl, record_content
#
# Return code:
# 0 - zone and record are found and stored in zone, zone_id, record_id, record_type, record_ttl, record_content
# 2 - no suitable zone found
# 3 - no matching record found
# 4 - more than 1 matching record found
findout_record() {
local record_name=${1,,}
declare -g record_type=${2^^}
local first_match=$3
local record_oldcontent=$4
local zname_zid
local zid
local test_record
declare -g zone_id=''
declare -g zone=''
declare -g record_id=''
declare -g record_ttl=''
declare -g record_content=''
is_quiet || echo -n "Searching zone ... " >&2
for zname_zid in `call_cf_v4 GET /zones -- .result %"%s:%s$NL" ,name,id`
do
zone=${zname_zid%%:*}
zone=${zone,,}
zid=${zname_zid##*:}
if [[ "$record_name" =~ ^((.*)\.|)$zone$ ]]
then
subdomain=${BASH_REMATCH[2]}
zone_id=$zid
break
fi
done
[ -z "$zone_id" ] && { is_quiet || echo >&2; return 2; }
is_quiet || echo -n "$zone, searching record ... " >&2
rec_found=0
oldIFS=$IFS
IFS=$NL
for test_record in `call_cf_v4 GET /zones/$zone_id/dns_records -- .result ,name,type,id,ttl,content`
do
IFS=$oldIFS
set -- $test_record
test_record_name=$1
shift
if [ "$test_record_name" = "$record_name" ]
then
test_record_type=$1
shift
test_record_id=$1
shift
test_record_ttl=$1
shift
test_record_content=$*
if [ \( -z "$record_type" -o "$test_record_type" = "$record_type" \) -a \( -z "$record_oldcontent" -o "$test_record_content" = "$record_oldcontent" \) ]
then
let rec_found++
[ $rec_found -gt 1 ] && { is_quiet || echo >&2; return 4; }
record_type=$test_record_type
record_id=$test_record_id
record_ttl=$test_record_ttl
record_content=$test_record_content
if [ "$first_match" = 1 ]
then
# accept first matching record
break
fi
fi
fi
IFS=$NL
done
IFS=$oldIFS
is_quiet || echo "$record_id" >&2
[ -z "$record_id" ] && return 3
return 0
}
# -- get_zone_id - get Cloudflare zone id
get_zone_id()
{
zone_id=`call_cf_v4 GET /zones name="$1" -- .result ,id`
if [ -z "$zone_id" ]
then
_error "No such DNS zone found"
_die
fi
}
# ------------
# -- Main loop
# ------------
# -- Check for options
while [ -n "$1" ]
do
case "$1" in
-E) shift
CF_ACCOUNT=$1;;
-T) shift
CF_TOKEN=$1;;
-D|--debug)
DEBUG=1;;
-d|--detail|--detailed|--details)
details=1;;
-q|--quiet)
quiet=1;;
-h|--help)
_error "$USAGE" 0
_die
;;
--) shift
break;;
-*) false;;
*) break;;
esac
shift
done
# -- Check for .cloudflare credentials
if [ ! -f "$HOME/.cloudflare" ]
then
echo "No .cloudflare file."
if [ -z "$CF_ACCOUNT" ]
then
_error "No \$CF_ACCOUNT set."
HELP usage
_die
fi
if [ -z "$CF_TOKEN" ]
then
_error "No \$CF_TOKEN set."
HELP usage
_die
fi
else
if is_debug; then echo "Found .cloudflare file."; fi
source $HOME/.cloudflare
if is_debug; then echo "Sourced CF_ACCOUNT: $CF_ACCOUNT CF_TOKEN: $CF_TOKEN"; fi
if [ -z "$CF_ACCOUNT" ]
then
_error "No \$CF_ACCOUNT set in config."
HELP usage
_die
fi
if [ -z "$CF_TOKEN" ]
then
_error "No \$CF_TOKEN set in config.
$USAGE"
fi
fi
# -- Check for command
if [ -z "$1" ]; then
HELP usage
_die "Missing arguments" 1
fi
# -- run commands
CMD1=$1
shift
case "$CMD1" in
# --------------------------
# -- show command @SHOW
# --------------------------
show|list)
CMD2=$1
shift
case "$CMD2" in
# -- zone
zone)
# -- Invocation - CURL_CF <METHOD> <PATH> [PARAMETERS] [-- JSON_DECODER-ARGS]
#CURL_CF GET /zone --
echo "test"
;;
# -- zone
zones)
# -- Max per page=1000 and max results = 2000
# TODO figure out how to get all zones in one call, or warn there is more than 1000 and add an option for second set of results etc.
#call_cf_v4 GET /zones -- .result %"%s$TA%s$TA#%s$TA%s$TA%s$NL" ,name,status,id,original_name_servers,name_servers
CURL_CF GET '/zones?per_page=1000' -- .result %"%s$TA%s$TA#%s$TA%s$TA%s$NL" ,name,status,id,original_name_servers,name_servers
;;
# -- settings
setting|settings)
[ -z "$1" ] && _error "Usage: cloudflare $CMD1 settings <zone>"
if is_hex "$1"
then
zone_id=$1
else
get_zone_id "$1"
fi
if [ "$details" = 1 ]
then
fieldspec=,id,value,'?editable?"Editable"?""','?modified_on?<",, mod: $modified_on"?""'
else
fieldspec=,id,value,\"\",\"\"
fi
call_cf_v4 GET /zones/$zone_id/settings -- .result %"%-30s %s$TA%s%s$NL" "$fieldspec"
;;
# -- record
record|records)
[ -z "$1" ] && _error "Usage: cloudflare $CMD1 records <zone>"
if is_hex "$1"
then
zone_id=$1
else
get_zone_id "$1"
fi
call_cf_v4 GET /zones/$zone_id/dns_records -- .result %"%-20s %11s %-8s %s %s$TA; %s #%s$NL" \
',@zone_name@name,?<$ttl==1?"auto"?ttl,type,||priority||data.priority||"",content,!!proxiable proxied locked,id'
;;
# -- access-rules
access-rules|listing|listings|blocking|blockings)
call_cf_v4 GET /user/firewall/access_rules/rules -- .result %"%s$TA%s$TA%s$TA# %s$NL" ',<$configuration["value"],mode,modified_on,notes'
;;
# -- no command catchall
*)
HELP show
if [[ -n $CMD2 ]]; then
_die "Unknown command $CMD2" 1
else
_die "No command provided" 1
fi
;;
esac
;;
# -------------------
# -- add command @ADD
# -------------------
add)
CMD2=$1
shift
case "$CMD2" in
record)
[ $# -lt 4 ] && _error "Missing arguments"; HELP add record;
zone=$1
shift
type=${1^^}
shift
name=$1
shift
content=$1
ttl=$2
if [[ "$type" == "A" ]] || [[ "$type" == "CNAME" ]]; then
proxied=$3
elif [[ "$type" == "MX" ]] || [[ "$type" == "SRV" ]]; then
prio=$3
fi
service=$4
protocol=$5
weight=$6
port=$7
[ -n "$proxied" ] || proxied=true
[ -n "$ttl" ] || ttl=1
[ -n "$prio" ] || prio=10
if [[ $content =~ ^127.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$ ]] && [[ "$type" == "A" ]]; then _error "Can't proxy 127.0.0.0/8 using an A record"; fi
get_zone_id "$zone"
case "$type" in
MX)
call_cf_v4 POST /zones/$zone_id/dns_records "{\"type\":\"$type\",\"name\":\"$name\",\"content\":\"$content\",\"ttl\":$ttl,\"priority\":$prio}"
;;
LOC)
locdata=''
data_separated=1
if [ -n "${content//[! ]/}" ]
then
data_separated=0
set -- $content
fi
for key in lat_degrees lat_minutes lat_seconds lat_direction \
long_degrees long_minutes long_seconds long_direction \
altitude size precision_horz precision_vert
do
value=$1
value=${value%m}
locdata="$locdata${locdata:+,}\"$key\":\"$value\""
shift
done
if [ $data_separated = 1 ]
then
ttl=${1:-1}
fi
call_cf_v4 POST /zones/$zone_id/dns_records "{\"type\":\"$type\",\"ttl\":$ttl,\"name\":\"$name\",\"data\":{$locdata}}"
;;
SRV)
[ "${service:0:1}" = _ ] || service="_$service"
[ "${protocol:0:1}" = _ ] || protocol="_$protocol"
[ -n "$weight" ] || weight=1
target=$content
call_cf_v4 POST /zones/$zone_id/dns_records "{
\"type\":\"$type\",
\"ttl\":$ttl,
\"data\":{
\"service\":\"$service\",
\"proto\":\"$protocol\",
\"name\":\"$name\",
\"priority\":$prio,