-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathfmcsadmin.go
5505 lines (5025 loc) · 178 KB
/
fmcsadmin.go
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
/*
fmcsadmin
Copyright 2017-2024 Emic Corporation, https://www.emic.co.jp/
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package main
import (
"bufio"
"bytes"
"crypto/rsa"
"crypto/x509"
"encoding/base64"
"encoding/json"
"encoding/pem"
"errors"
"flag"
"fmt"
"io"
"net/http"
"net/url"
"os"
"path"
"path/filepath"
"reflect"
"regexp"
"runtime"
"strconv"
"strings"
"syscall"
"time"
jwt "github.com/golang-jwt/jwt/v5"
"github.com/mattn/go-scan"
"github.com/olekukonko/tablewriter"
"golang.org/x/term"
)
var version string
type cli struct {
outStream, errStream io.Writer
}
type output struct {
Response struct {
Status string `json:"status"`
Token string `json:"token"`
} `json:"response"`
Messages []struct {
Code string `json:"code"`
Text string `json:"text"`
} `json:"messages"`
}
type generalOldConfigInfo struct {
CacheSize int `json:"cacheSize"`
MaxFiles int `json:"maxFiles"`
MaxProConnections int `json:"maxProConnections"`
MaxPSOS int `json:"maxPSOS"`
StartupRestorationEnabled bool `json:"startupRestorationEnabled"`
}
type generalConfigInfo struct {
CacheSize int `json:"cacheSize"`
MaxFiles int `json:"maxFiles"`
MaxProConnections int `json:"maxProConnections"`
MaxPSOS int `json:"maxPSOS"`
}
type securityConfigInfo struct {
RequireSecureDB bool `json:"requireSecureDB"`
}
type authenticatedStreamConfigInfo struct {
AuthenticatedStream int `json:"authenticatedStream"`
}
type parallelBackupConfigInfo struct {
ParallelBackupEnabled bool `json:"parallelBackupEnabled"`
}
type persistentCacheConfigInfo struct {
PersistCacheEnabled bool `json:"persistentCache"`
SyncPersistCache bool `json:"persistentCacheSync"`
DatabaseServerAutoRestart bool `json:"databaseServerAutoRestart"`
}
type blockNewUsersConfigInfo struct {
BlockNewUsersEnabled bool `json:"blockNewUsers"`
}
type phpConfigInfo struct {
Enabled bool `json:"enabled"`
CharacterEncoding string `json:"characterEncoding"`
ErrorMessageLanguage string `json:"errorMessageLanguage"`
DataPreValidation bool `json:"dataPreValidation"`
UseFileMakerPhp bool `json:"useFileMakerPhp"`
}
type xmlConfigInfo struct {
Enabled bool `json:"enabled"`
}
type dbInfo struct {
Status string `json:"status"`
Key string `json:"key"`
SaveKey bool `json:"saveKey"`
}
type closeMessageInfo struct {
Status string `json:"status"`
MessageText string `json:"messageText"`
Force bool `json:"force"`
}
type statusInfo struct {
Status string `json:"status"`
}
type messageInfo struct {
MessageText string `json:"messageText"`
}
type scheduleSettingInfo struct {
Enabled bool `json:"enabled"`
}
type creatingCsrInfo struct {
Subject string `json:"subject"`
Password string `json:"password"`
}
type importingCertificateInfo struct {
Certificate string `json:"certificate"`
PrivateKey string `json:"privateKey"`
IntermediateCertificates string `json:"intermediateCertificates"`
Password string `json:"password"`
}
type params struct {
command string
key string
messageText string
force bool
retry int
status string
enabled string
cachesize int
maxfiles int
maxproconnections int
maxpsos int
startuprestorationenabled bool
startuprestorationbuiltin bool
requiresecuredb string
authenticatedstream int
parallelbackupenabled string
persistcacheenabled string
syncpersistcache string
databaseserverautorestart string
blocknewusersenabled string
characterencoding string
errormessagelanguage string
dataprevalidation bool
usefilemakerphp bool
saveKey bool
subject string
password string
certificate string
privateKey string
intermediateCertificates string
printRefreshToken bool
identityFile string
}
type commandOptions struct {
helpFlag bool
versionFlag bool
yesFlag bool
statsFlag bool
forceFlag bool
saveKeyFlag bool
fqdn string
hostname string
username string
password string
key string
message string
keyFile string
keyFilePass string
intermediateCA string
clientID int
graceTime int
identityFile string
}
func main() {
cli := &cli{outStream: os.Stdout, errStream: os.Stderr}
os.Exit(cli.Run(os.Args))
}
func (c *cli) Run(args []string) int {
var exitStatus int
token := ""
exitStatus = 0
helpFlag := false
versionFlag := false
yesFlag := false
statsFlag := false
forceFlag := false
saveKeyFlag := false
graceTime := 90
fqdn := ""
hostname := ""
username := ""
password := ""
key := ""
clientID := -1
message := ""
keyFile := ""
keyFilePassOption := false
keyFilePass := ""
intermediateCA := ""
identityFile := ""
commandOptions := commandOptions{}
commandOptions.helpFlag = false
commandOptions.versionFlag = false
commandOptions.yesFlag = false
commandOptions.statsFlag = false
commandOptions.forceFlag = false
commandOptions.saveKeyFlag = false
commandOptions.fqdn = ""
commandOptions.hostname = ""
commandOptions.username = ""
commandOptions.password = ""
commandOptions.key = ""
commandOptions.message = ""
commandOptions.keyFile = ""
commandOptions.keyFilePass = ""
commandOptions.intermediateCA = ""
commandOptions.clientID = -1
commandOptions.graceTime = 90
commandOptions.identityFile = ""
// detect an invalid command
cmdArgs, cFlags, err := getFlags(args, commandOptions)
if err != nil {
fmt.Fprintln(c.outStream, flag.ErrHelp)
exitStatus = outputInvalidCommandErrorMessage(c)
return exitStatus
}
// detect an invalid option
for i := 0; i < len(args); i++ {
var invalidOption bool
if regexp.MustCompile(`\-(\d+)`).Match([]byte(args[i])) {
// Allow option (ex.: "fmcsadmin get backuptime -1")
invalidOption = false
} else {
allowedOptions := []string{"-h", "-v", "-y", "-s", "-u", "-p", "-m", "-f", "-c", "-t", "-i", "--help", "--version", "--yes", "--stats", "--fqdn", "--host", "--username", "--password", "--key", "--message", "--force", "--client", "--gracetime", "--savekey", "--keyfile", "--KeyFile", "--keyfilepass", "--KeyFilePass", "--intermediateca", "--intermediateCA"}
for j := 0; j < len(allowedOptions); j++ {
if string([]rune(args[i])[:1]) == "-" {
invalidOption = true
for _, v := range allowedOptions {
if strings.ToLower(args[i]) == v {
if v == "--keyfilepass" {
keyFilePassOption = true
}
invalidOption = false
}
}
if invalidOption {
exitStatus = outputInvalidOptionErrorMessage(c, args[i])
return exitStatus
}
}
}
}
}
helpFlag = cFlags.helpFlag
versionFlag = cFlags.versionFlag
yesFlag = cFlags.yesFlag
statsFlag = cFlags.statsFlag
forceFlag = cFlags.forceFlag
saveKeyFlag = cFlags.saveKeyFlag
graceTime = cFlags.graceTime
key = cFlags.key
username = cFlags.username
password = cFlags.password
clientID = cFlags.clientID
message = cFlags.message
keyFile = cFlags.keyFile
keyFilePass = cFlags.keyFilePass
intermediateCA = cFlags.intermediateCA
identityFile = cFlags.identityFile
fqdn = cFlags.fqdn
hostname = cFlags.hostname
if len(fqdn) == 0 && len(hostname) > 0 && !strings.Contains(hostname, ".") {
fqdn = hostname + ".account.filemaker-cloud.com"
}
baseURI := getBaseURI(fqdn)
u, _ := url.Parse(baseURI)
usingCloud := false
if regexp.MustCompile(`https://(.*)\.account\.filemaker-cloud\.com/`).Match([]byte(baseURI)) {
// Not Supported
usingCloud = true
}
retry := 3
if len(username) > 0 && len(password) > 0 {
// Don't retry when specifying username and password
retry = 0
}
if len(cmdArgs) > 0 {
switch strings.ToLower(cmdArgs[0]) {
case "cancel":
if usingCloud {
exitStatus = 21
} else {
if len(cmdArgs[1:]) > 0 {
switch strings.ToLower(cmdArgs[1]) {
case "backup":
running := true
u.Path = path.Join(getAPIBasePath(), "server", "metadata")
_, err := http.Get(u.String())
if err != nil {
running = false
}
if running {
token, exitStatus, err = login(baseURI, username, password, params{retry: retry, identityFile: identityFile})
if token != "" && exitStatus == 0 && err == nil {
version := getServerVersion(u.String(), token)
if !usingCloud && version >= 19.5 {
u.Path = path.Join(getAPIBasePath(), "server", "cancelbackup")
exitStatus, _, err = sendRequest("POST", u.String(), token, params{command: "cancel backup"})
if err == nil {
fmt.Fprintln(c.outStream, "Command finished")
} else {
fmt.Fprintln(c.outStream, err.Error())
}
} else {
exitStatus = outputInvalidCommandErrorMessage(c)
}
logout(baseURI, token)
} else if detectHostUnreachable(exitStatus) {
exitStatus = 10502
}
} else {
exitStatus = 10502
}
default:
exitStatus = outputInvalidCommandErrorMessage(c)
}
} else {
exitStatus = outputInvalidCommandErrorMessage(c)
}
}
case "certificate":
if usingCloud {
exitStatus = 21
} else {
if len(cmdArgs[1:]) > 0 {
switch strings.ToLower(cmdArgs[1]) {
case "create":
running := true
u.Path = path.Join(getAPIBasePath(), "server", "metadata")
_, err := http.Get(u.String())
if err != nil {
running = false
}
if running {
token, exitStatus, err = login(baseURI, username, password, params{retry: retry, identityFile: identityFile})
if token != "" && exitStatus == 0 && err == nil {
version := getServerVersion(u.String(), token)
if version >= 19.2 {
if len(cmdArgs) < 3 {
fmt.Fprintln(c.outStream, "Certificate subject is not specified.")
exitStatus = 10001
}
if exitStatus == 0 {
if keyFilePassOption {
fmt.Fprintln(c.outStream, "Encryption password for the private key file is not specified.")
exitStatus = 10001
} else if keyFilePass == "" {
fmt.Fprintln(c.outStream, "Invalid parameter for option: --KeyFilePass")
exitStatus = 10001
} else {
u.Path = path.Join(getAPIBasePath(), "server", "certificate", "csr")
exitStatus, _, err = sendRequest("PATCH", u.String(), token, params{command: "certificate create", subject: base64.StdEncoding.EncodeToString([]byte(cmdArgs[2])), password: keyFilePass})
if exitStatus == 1712 {
fmt.Fprintln(c.outStream, "Private key file already exists, please remove it and run the command again.")
exitStatus = 20406
} else {
if err != nil {
fmt.Fprintln(c.outStream, err.Error())
}
}
}
}
} else {
exitStatus = outputInvalidCommandErrorMessage(c)
}
logout(baseURI, token)
} else if detectHostUnreachable(exitStatus) {
exitStatus = 10502
}
} else {
exitStatus = 10502
}
case "import":
res := ""
if yesFlag {
res = "y"
} else {
r := bufio.NewReader(os.Stdin)
fmt.Fprint(c.outStream, "fmcsadmin: really import certificate? (y, n) (Warning: server needs to be restarted) ")
input, _ := r.ReadString('\n')
res = strings.ToLower(strings.TrimSpace(input))
}
if res == "y" {
token, exitStatus, err = login(baseURI, username, password, params{retry: retry, identityFile: identityFile})
if token != "" && exitStatus == 0 && err == nil {
u.Path = path.Join(getAPIBasePath(), "server", "metadata")
version := getServerVersion(u.String(), token)
if version >= 19.2 {
if len(cmdArgs[2:]) > 0 {
keyFileData := []byte("")
// reading certificate
var crt *x509.Certificate
certificateData, err := os.ReadFile(cmdArgs[2])
if err != nil {
if os.IsPermission(err) {
exitStatus = 20402
} else {
exitStatus = 20405
}
} else {
block, _ := pem.Decode(certificateData)
if block == nil {
exitStatus = 20408
} else {
crt, err = x509.ParseCertificate(block.Bytes)
if err != nil {
exitStatus = 20408
}
if time.Now().UTC().After(crt.NotAfter) {
// if expired
exitStatus = 20630
}
}
}
switch exitStatus {
case 20402:
fmt.Fprintln(c.outStream, "Cannot read certificate file")
case 20405:
fmt.Fprintln(c.outStream, "Certificate "+filepath.Clean(cmdArgs[2])+" does not exist.")
case 20408:
fmt.Fprintln(c.outStream, "The certificate file is not valid.")
case 20630:
fmt.Fprintln(c.outStream, "The certificate has expired.")
}
// reading private key
if exitStatus == 0 {
if keyFile != "" {
keyFileData, err = os.ReadFile(keyFile)
if err != nil {
if os.IsPermission(err) {
exitStatus = 20402
} else {
exitStatus = 20405
}
} else {
block, _ := pem.Decode(keyFileData)
if block == nil {
exitStatus = 20408
} else {
buf := block.Bytes
if x509.IsEncryptedPEMBlock(block) {
buf, err = x509.DecryptPEMBlock(block, []byte(keyFilePass))
if err != nil {
if err == x509.IncorrectPasswordError {
exitStatus = 20408
}
}
}
if exitStatus == 0 {
switch block.Type {
case "RSA PRIVATE KEY":
_, err = x509.ParsePKCS1PrivateKey(buf)
if err != nil {
exitStatus = 20408
}
case "PRIVATE KEY":
_, err := x509.ParsePKCS8PrivateKey(buf)
if err != nil {
exitStatus = 20408
}
case "EC PRIVATE KEY":
_, err := x509.ParseECPrivateKey(buf)
if err != nil {
exitStatus = 20408
}
default:
exitStatus = 20408
}
}
}
}
switch exitStatus {
case 20402, 20405:
fmt.Fprintln(c.outStream, "Cannot read private key file")
case 20408:
fmt.Fprintln(c.outStream, "Cannot decrypt the private key file with the password. Please make sure the key file and password are correct.")
}
} else {
fmt.Fprintln(c.outStream, "Private key file does not exist.")
exitStatus = 20405
}
}
// reading intermediate CA
intermediateCAData := []byte("")
intermediateCAExpired := false
if exitStatus == 0 {
if intermediateCA != "" {
intermediateCAData, err = os.ReadFile(intermediateCA)
if err != nil {
if os.IsPermission(err) {
exitStatus = 20402
} else {
exitStatus = 20405
}
} else {
var block *pem.Block
rest := intermediateCAData
for {
block, rest = pem.Decode(rest)
if block == nil {
exitStatus = 20632
break
} else {
crt, err = x509.ParseCertificate(block.Bytes)
if err != nil {
exitStatus = 20632
break
}
if time.Now().UTC().After(crt.NotAfter) {
// if expired
intermediateCAExpired = true
}
}
if len(rest) == 0 {
break
}
}
}
}
}
switch exitStatus {
case 20402, 20405:
fmt.Fprintln(c.outStream, "Cannot read intermediate CA file")
case 20632:
fmt.Fprintln(c.outStream, "Failed to verify the intermediate CA certificate.")
}
// import SSL certficates
if exitStatus == 0 {
u.Path = path.Join(getAPIBasePath(), "server", "certificate", "import")
exitStatus, _, err = sendRequest("PATCH", u.String(), token, params{command: "certificate import", certificate: string(certificateData), privateKey: string(keyFileData), intermediateCertificates: string(intermediateCAData), password: keyFilePass})
if exitStatus == 1712 {
fmt.Fprintln(c.outStream, "Private key file already exists, please remove it and run the command again.")
exitStatus = 20406
} else if exitStatus == -1 && intermediateCAExpired {
fmt.Fprintln(c.outStream, "Failed to verify the intermediate CA certificate.")
exitStatus = 20630
} else {
if err != nil {
fmt.Fprintln(c.outStream, err.Error())
}
}
if exitStatus == 0 && err == nil {
fmt.Fprintln(c.outStream, "Restart the FileMaker Server background processes to apply the change.")
}
}
} else {
fmt.Fprintln(c.outStream, "Certificate file is not specified.")
exitStatus = 10001
}
} else {
exitStatus = outputInvalidCommandErrorMessage(c)
}
logout(baseURI, token)
} else if detectHostUnreachable(exitStatus) {
exitStatus = 10502
}
}
case "delete":
res := ""
if yesFlag {
res = "y"
} else {
r := bufio.NewReader(os.Stdin)
fmt.Fprint(c.outStream, "fmcsadmin: really delete certificate? (y, n) (Warning: server needs to be restarted) ")
input, _ := r.ReadString('\n')
res = strings.ToLower(strings.TrimSpace(input))
}
if res == "y" {
token, exitStatus, err = login(baseURI, username, password, params{retry: retry, identityFile: identityFile})
if token != "" && exitStatus == 0 && err == nil {
u.Path = path.Join(getAPIBasePath(), "server", "metadata")
version := getServerVersion(u.String(), token)
if version >= 19.2 {
u.Path = path.Join(getAPIBasePath(), "server", "certificate", "delete")
exitStatus, _, err = sendRequest("DELETE", u.String(), token, params{})
if err != nil {
fmt.Fprintln(c.outStream, err.Error())
}
if exitStatus == 0 && err == nil {
fmt.Fprintln(c.outStream, "Restart the FileMaker Server background processes to apply the change.")
}
} else {
exitStatus = outputInvalidCommandErrorMessage(c)
}
logout(baseURI, token)
} else if detectHostUnreachable(exitStatus) {
exitStatus = 10502
}
}
default:
exitStatus = outputInvalidCommandErrorMessage(c)
}
} else {
exitStatus = outputInvalidCommandErrorMessage(c)
}
}
case "close":
res := ""
if yesFlag {
res = "y"
} else {
r := bufio.NewReader(os.Stdin)
fmt.Fprint(c.outStream, "fmcsadmin: really close database(s)? (y, n) ")
input, _ := r.ReadString('\n')
res = strings.ToLower(strings.TrimSpace(input))
}
if res == "y" {
token, exitStatus, err = login(baseURI, username, password, params{retry: retry, identityFile: identityFile})
if token != "" && exitStatus == 0 && err == nil {
u.Path = path.Join(getAPIBasePath(), "databases")
args = []string{""}
if len(cmdArgs[1:]) > 0 {
args = cmdArgs[1:]
}
idList, nameList, _ := getDatabases(u.String(), token, args, "NORMAL", false)
if len(idList) > 0 {
for i := 0; i < len(idList); i++ {
fmt.Fprintln(c.outStream, "File Closing: "+nameList[i])
}
connectedClients := getClients(u.String(), token, args)
for i := 0; i < len(idList); i++ {
u.Path = path.Join(getAPIBasePath(), "databases", strconv.Itoa(idList[i]))
exitStatus, _, err = sendRequest("PATCH", u.String(), token, params{command: "close", messageText: message, force: forceFlag})
if exitStatus == 0 && err == nil && len(connectedClients) == 0 {
// Don't output this message when the clients connected to the specified databases are existing
fmt.Fprintln(c.outStream, "File Closed: "+nameList[i])
}
}
} else {
exitStatus = 10904
}
logout(baseURI, token)
} else if detectHostUnreachable(exitStatus) {
exitStatus = 10502
}
}
case "delete":
if len(cmdArgs[1:]) > 0 {
switch strings.ToLower(cmdArgs[1]) {
case "schedule":
res := ""
if yesFlag {
res = "y"
} else {
r := bufio.NewReader(os.Stdin)
fmt.Fprint(c.outStream, "fmcsadmin: really delete a schedule? (y, n) ")
input, _ := r.ReadString('\n')
res = strings.ToLower(strings.TrimSpace(input))
}
if res == "y" {
token, exitStatus, err = login(baseURI, username, password, params{retry: retry, identityFile: identityFile})
if token != "" && exitStatus == 0 && err == nil {
id := 0
if len(cmdArgs) >= 3 {
sid, err := strconv.Atoi(cmdArgs[2])
if err == nil {
id = sid
}
}
if id > 0 {
u.Path = path.Join(getAPIBasePath(), "schedules", strconv.Itoa(id))
scheduleName := getScheduleName(u.String(), token, id)
exitStatus, _, err = sendRequest("DELETE", u.String(), token, params{})
if err != nil {
fmt.Fprintln(c.outStream, err.Error())
}
if exitStatus == 0 && err == nil {
if scheduleName != "" {
fmt.Fprintln(c.outStream, "Schedule Deleted: "+scheduleName)
} else {
exitStatus = 10600
}
}
} else {
exitStatus = 10600
}
logout(baseURI, token)
} else if detectHostUnreachable(exitStatus) {
exitStatus = 10502
}
}
}
} else {
exitStatus = outputInvalidCommandErrorMessage(c)
}
case "disable":
if len(cmdArgs[1:]) > 0 {
switch strings.ToLower(cmdArgs[1]) {
case "schedule":
res := ""
if yesFlag {
res = "y"
} else {
r := bufio.NewReader(os.Stdin)
fmt.Fprint(c.outStream, "fmcsadmin: really disable schedule(s)? (y, n) ")
input, _ := r.ReadString('\n')
res = strings.ToLower(strings.TrimSpace(input))
}
if res == "y" {
token, exitStatus, err = login(baseURI, username, password, params{retry: retry, identityFile: identityFile})
if token != "" && exitStatus == 0 && err == nil {
id := 0
if len(cmdArgs) >= 3 {
sid, err := strconv.Atoi(cmdArgs[2])
if err == nil {
id = sid
}
}
if id > 0 {
u.Path = path.Join(getAPIBasePath(), "schedules", strconv.Itoa(id))
exitStatus, _, err = sendRequest("PATCH", u.String(), token, params{command: "disable"})
if exitStatus == 0 && err == nil {
u.Path = path.Join(getAPIBasePath(), "schedules")
exitStatus = listSchedules(u.String(), token, id)
}
} else {
exitStatus = 10600
}
logout(baseURI, token)
} else if detectHostUnreachable(exitStatus) {
exitStatus = 10502
}
}
default:
exitStatus = -1
}
} else {
exitStatus = outputInvalidCommandErrorMessage(c)
}
case "disconnect":
if len(cmdArgs[1:]) > 0 {
switch strings.ToLower(cmdArgs[1]) {
case "client":
res := ""
if yesFlag {
res = "y"
} else {
r := bufio.NewReader(os.Stdin)
fmt.Fprint(c.outStream, "fmcsadmin: really disconnect client(s)? (y, n) ")
input, _ := r.ReadString('\n')
res = strings.ToLower(strings.TrimSpace(input))
}
if res == "y" {
token, exitStatus, err = login(baseURI, username, password, params{retry: retry, identityFile: identityFile})
if token != "" && exitStatus == 0 && err == nil {
id := 0
if len(cmdArgs) >= 3 {
cid, err := strconv.Atoi(cmdArgs[2])
if err == nil {
id = cid
}
if cid == 0 {
exitStatus = 11005
}
}
if id > -1 && exitStatus == 0 {
if id == 0 {
// disconnect clients
exitStatus, _ = disconnectAllClient(u, token, message, graceTime)
} else {
// check the client connection
u.Path = path.Join(getAPIBasePath(), "clients")
idList := getClients(u.String(), token, []string{""})
connected := false
if len(idList) > 0 && id > 0 {
for i := 0; i < len(idList); i++ {
if id == idList[i] {
connected = true
break
}
}
}
if connected {
// disconnect a client
u.Path = path.Join(getAPIBasePath(), "clients", strconv.Itoa(id))
u.RawQuery = "messageText=" + url.QueryEscape(message) + "&graceTime=" + url.QueryEscape(strconv.Itoa(graceTime))
exitStatus, _, _ = sendRequest("DELETE", u.String(), token, params{command: "disconnect"})
} else {
exitStatus = 11005
}
}
if exitStatus == 0 {
fmt.Fprintln(c.outStream, "Client(s) being disconnected.")
}
}
logout(baseURI, token)
} else if detectHostUnreachable(exitStatus) {
exitStatus = 10502
}
}
default:
exitStatus = outputInvalidCommandErrorMessage(c)
}
} else {
exitStatus = outputInvalidCommandErrorMessage(c)
}
case "enable":
if len(cmdArgs[1:]) > 0 {
token, exitStatus, err = login(baseURI, username, password, params{retry: retry, identityFile: identityFile})
if token != "" && exitStatus == 0 && err == nil {
switch strings.ToLower(cmdArgs[1]) {
case "schedule":
id := 0
if len(cmdArgs) >= 3 {
sid, err := strconv.Atoi(cmdArgs[2])
if err == nil {
id = sid
}
}
if id > 0 {
u.Path = path.Join(getAPIBasePath(), "schedules", strconv.Itoa(id))
exitStatus, _, err = sendRequest("PATCH", u.String(), token, params{command: "enable"})
if exitStatus == 0 && err == nil {
u.Path = path.Join(getAPIBasePath(), "schedules")
exitStatus = listSchedules(u.String(), token, id)
}
} else {
exitStatus = 10600
}
default:
exitStatus = 11002
}
logout(baseURI, token)
} else if detectHostUnreachable(exitStatus) {
exitStatus = 10502
}
} else {
exitStatus = outputInvalidCommandErrorMessage(c)
}
case "get":
if len(cmdArgs[1:]) > 0 {
switch strings.ToLower(cmdArgs[1]) {
case "backuptime":
if usingCloud {
exitStatus = 21
} else {
token, exitStatus, err = login(baseURI, username, password, params{retry: retry, identityFile: identityFile})
if token != "" && exitStatus == 0 && err == nil {
id := 0
if len(cmdArgs) >= 3 {
sid, err := strconv.Atoi(cmdArgs[2])
if err == nil {
id = sid
}
}
u.Path = path.Join(getAPIBasePath(), "schedules")
exitStatus = getBackupTime(u.String(), token, id)
logout(baseURI, token)
} else if detectHostUnreachable(exitStatus) {
exitStatus = 10502
}
}
case "cwpconfig":
if usingCloud {
exitStatus = 21
} else {
printOptions := []string{}
if len(cmdArgs[2:]) > 0 {
for i := 0; i < len(cmdArgs[2:]); i++ {
switch strings.ToLower(cmdArgs[2:][i]) {
case "enablephp":
printOptions = append(printOptions, "enablephp")
case "enablexml":
printOptions = append(printOptions, "enablexml")
case "encoding":
printOptions = append(printOptions, "encoding")
case "locale":
printOptions = append(printOptions, "locale")
case "prevalidation":
printOptions = append(printOptions, "prevalidation")
case "usefmphp":
printOptions = append(printOptions, "usefmphp")
default:
exitStatus = 10001
}
if exitStatus != 0 {
break
}
}
} else {
printOptions = append(printOptions, "enablephp")
printOptions = append(printOptions, "enablexml")
printOptions = append(printOptions, "encoding")
printOptions = append(printOptions, "locale")
printOptions = append(printOptions, "prevalidation")
printOptions = append(printOptions, "usefmphp")
}
for i := 0; i < len(cmdArgs[2:]); i++ {
if regexp.MustCompile(`(.*)`).Match([]byte(cmdArgs[2:][i])) {
rep := regexp.MustCompile(`(.*)`)
option := rep.ReplaceAllString(cmdArgs[2:][i], "$1")
switch strings.ToLower(option) {
case "enablephp", "enablexml", "encoding", "locale", "prevalidation", "usefmphp":
default:
exitStatus = 10001
}
if exitStatus == 10001 {
fmt.Fprintln(c.outStream, "Invalid configuration name: "+option)
break
}
}
}
if exitStatus == 0 {
token, exitStatus, err = login(baseURI, username, password, params{retry: retry, identityFile: identityFile})
if token != "" && exitStatus == 0 && err == nil {
u.Path = path.Join(getAPIBasePath(), "server", "metadata")
version := getServerVersion(u.String(), token)
if runtime.GOOS == "linux" && fqdn == "" && version < 19.6 {
// Not Supported
exitStatus = 21
} else {
if exitStatus == 0 {
_, exitStatus, _ = getWebTechnologyConfigurations(baseURI, getAPIBasePath(), token, printOptions)
}
}
logout(baseURI, token)
} else if detectHostUnreachable(exitStatus) {
exitStatus = 10502
}
}
}
case "refreshtoken":
if usingCloud {
token, exitStatus, err = login(baseURI, username, password, params{printRefreshToken: true, retry: retry, identityFile: identityFile})
if token != "" && exitStatus == 0 && err == nil {
logout(baseURI, token)
} else if detectHostUnreachable(exitStatus) {
exitStatus = 10502
}
} else {
exitStatus = outputInvalidCommandErrorMessage(c)