-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathconfigurator.go
1176 lines (915 loc) · 30.5 KB
/
configurator.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
package a2conf
import (
"errors"
"fmt"
"os"
"path/filepath"
"regexp"
"strings"
"github.com/r2dtools/a2conf/apache"
"github.com/r2dtools/a2conf/configurator"
"github.com/r2dtools/a2conf/entity"
"github.com/r2dtools/a2conf/logger"
opts "github.com/r2dtools/a2conf/options"
"github.com/r2dtools/a2conf/utils"
"github.com/unknwon/com"
)
const (
minApacheVersion = "2.4.0"
)
// ApacheConfigurator manipulates with apache configs
type ApacheConfigurator interface {
GetParser() *Parser
GetVhosts() ([]*entity.VirtualHost, error)
Save() error
DeployCertificate(serverName, certPath, certKeyPath, chainPath, fullChainPath string) error
EnableSite(vhost *entity.VirtualHost) error
PrepareHTTPSModules(temp bool) error
EnableModule(module string, temp bool) error
EnsurePortIsListening(port string, https bool) error
GetSuitableVhosts(serverName string, createIfNoSsl bool) ([]*entity.VirtualHost, error)
FindSuitableVhosts(serverName string) ([]*entity.VirtualHost, error)
CheckConfiguration() bool
RestartWebServer() error
SetLogger(logger logger.Logger)
Commit() error
Rollback() error
}
type apacheConfigurator struct {
parser *Parser
reverter *Reverter
ctl *apache.Ctl
site *apache.Site
logger logger.Logger
version string
vhosts []*entity.VirtualHost
options map[string]string
}
type vhsotNames struct {
ServerName string
ServerAliases []string
}
// GetParser returns augeas parser
func (ac *apacheConfigurator) GetParser() *Parser {
return ac.parser
}
// SetLogger sets configurator logger
func (ac *apacheConfigurator) SetLogger(logger logger.Logger) {
ac.logger = logger
ac.reverter.SetLogger(logger)
}
// GetVhosts returns configured Apache vhosts
func (ac *apacheConfigurator) GetVhosts() ([]*entity.VirtualHost, error) {
if ac.vhosts != nil {
return ac.vhosts, nil
}
filePaths := make(map[string]string)
internalPaths := make(map[string]map[string]bool)
var vhosts []*entity.VirtualHost
for vhostPath := range ac.parser.Paths {
paths, err := ac.parser.Augeas.Match(fmt.Sprintf("/files%s//*[label()=~regexp('VirtualHost', 'i')]", vhostPath))
if err != nil {
continue
}
for _, path := range paths {
if !strings.Contains(strings.ToLower(path), "virtualhost") {
continue
}
vhost, err := ac.createVhost(path)
if err != nil {
ac.logger.Error(fmt.Sprintf("error occured while creating vhost '%s': %v", vhost.FilePath, err))
continue
}
internalPath := utils.GetInternalAugPath(vhost.AugPath)
realPath, err := filepath.EvalSymlinks(vhost.FilePath)
if _, ok := internalPaths[realPath]; !ok {
internalPaths[realPath] = make(map[string]bool)
}
if err != nil {
ac.logger.Error(fmt.Sprintf("failed to eval symlinks for vhost '%s': %v", vhost.FilePath, err))
continue
}
if _, ok := filePaths[realPath]; !ok {
filePaths[realPath] = vhost.FilePath
if iPaths, ok := internalPaths[realPath]; !ok {
internalPaths[realPath] = map[string]bool{
internalPath: true,
}
} else {
if _, ok = iPaths[internalPath]; !ok {
iPaths[internalPath] = true
}
}
vhosts = append(vhosts, vhost)
} else if realPath == vhost.FilePath && realPath != filePaths[realPath] {
// Prefer "real" vhost paths instead of symlinked ones
// for example: sites-enabled/vh.conf -> sites-available/vh.conf
// remove old (most likely) symlinked one
var nVhosts []*entity.VirtualHost
for _, vh := range vhosts {
if vh.FilePath == filePaths[realPath] {
delete(internalPaths[realPath], utils.GetFilePathFromAugPath(vh.AugPath))
} else {
nVhosts = append(nVhosts, vh)
}
}
vhosts = nVhosts
filePaths[realPath] = realPath
internalPaths[realPath][internalPath] = true
vhosts = append(vhosts, vhost)
} else if _, ok = internalPaths[realPath][internalPath]; !ok {
internalPaths[realPath][internalPath] = true
vhosts = append(vhosts, vhost)
}
}
}
ac.vhosts = vhosts
return ac.vhosts, nil
}
// Save saves all changes
func (ac *apacheConfigurator) Save() error {
err := ac.parser.Save(ac.reverter)
if err != nil {
return fmt.Errorf("could not save changes: %v", err)
}
return nil
}
// Commit applies all current changes
func (ac *apacheConfigurator) Commit() error {
return ac.reverter.Commit()
}
// Rollback rollbacks all current changes
func (ac *apacheConfigurator) Rollback() error {
return ac.reverter.Rollback()
}
// DeployCertificate installs certificate to a domain
func (ac *apacheConfigurator) DeployCertificate(serverName, certPath, certKeyPath, chainPath, fullChainPath string) error {
var err error
var vhosts []*entity.VirtualHost
if vhosts, err = ac.GetSuitableVhosts(serverName, true); err != nil {
return err
}
if err = ac.prepareServerForHTTPS("443", false); err != nil {
return err
}
if _, ok := ac.parser.Modules["ssl_module"]; !ok {
return errors.New("could not find ssl_module")
}
for _, vhost := range vhosts {
if err = ac.cleanSSLVhost(vhost); err != nil {
return err
}
if err = ac.addDummySSLDirectives(vhost.AugPath); err != nil {
return err
}
augCertPath, err := ac.parser.FindDirective("SSLCertificateFile", "", vhost.AugPath, true)
if err != nil {
return fmt.Errorf("error while searching directive 'SSLCertificateFile': %v", err)
}
augCertKeyPath, err := ac.parser.FindDirective("SSLCertificateKeyFile", "", vhost.AugPath, true)
if err != nil {
return fmt.Errorf("error while searching directive 'SSLCertificateKeyFile': %v", err)
}
res, err := utils.CheckMinVersion(ac.version, "2.4.8")
if err != nil {
return err
}
if !res || (chainPath != "" && fullChainPath == "") {
if err = ac.parser.Augeas.Set(augCertPath[len(augCertPath)-1], certPath); err != nil {
return fmt.Errorf("could not set certificate path for vhost '%s': %v", serverName, err)
}
if err = ac.parser.Augeas.Set(augCertKeyPath[len(augCertKeyPath)-1], certKeyPath); err != nil {
return fmt.Errorf("could not set certificate key path for vhost '%s': %v", serverName, err)
}
if chainPath != "" {
if err = ac.parser.AddDirective(vhost.AugPath, "SSLCertificateChainFile", []string{chainPath}); err != nil {
return fmt.Errorf("could not add 'SSLCertificateChainFile' directive to vhost '%s': %v", serverName, err)
}
} else {
return fmt.Errorf("SSL certificate chain path is required for the current Apache version '%s', but is not specified", ac.version)
}
} else {
if fullChainPath == "" {
return errors.New("SSL certificate fullchain path is required, but is not specified")
}
if err = ac.parser.Augeas.Set(augCertPath[len(augCertPath)-1], fullChainPath); err != nil {
return fmt.Errorf("could not set certificate path for vhost '%s': %v", serverName, err)
}
if err = ac.parser.Augeas.Set(augCertKeyPath[len(augCertKeyPath)-1], certKeyPath); err != nil {
return fmt.Errorf("could not set certificate key path for vhost '%s': %v", serverName, err)
}
}
if !vhost.Enabled {
if err = ac.EnableSite(vhost); err != nil {
return err
}
}
}
return nil
}
// EnableSite enables an available site
func (ac *apacheConfigurator) EnableSite(vhost *entity.VirtualHost) error {
if vhost.Enabled {
ac.logger.Debug(fmt.Sprintf("virtual host '%s' is already enabled. Skip site enabling.", vhost.FilePath))
return nil
}
// First, try to enable vhost via a2ensite utility
err := ac.site.Enable(vhost.GetConfigName())
if err == nil {
ac.reverter.AddSiteConfigToDisable(vhost.GetConfigName())
vhost.Enabled = true
return nil
} else {
ac.logger.Debug(err.Error())
}
// If vhost could not be enabled via a2ensite, than try to enable it via Include directive in apache config
if !ac.parser.IsFilenameExistInOriginalPaths(vhost.FilePath) {
ac.logger.Debug(fmt.Sprintf("try to enable virtual host '%s' via 'include' directive.", vhost.FilePath))
if err := ac.parser.AddInclude(ac.parser.ConfigRoot, vhost.FilePath); err != nil {
return fmt.Errorf("could not enable vhsot '%s': %v", vhost.FilePath, err)
}
vhost.Enabled = true
}
return nil
}
// PrepareServerForHTTPS prepares server for https
func (ac *apacheConfigurator) prepareServerForHTTPS(port string, temp bool) error {
if err := ac.PrepareHTTPSModules(temp); err != nil {
return err
}
if err := ac.EnsurePortIsListening(port, true); err != nil {
return err
}
return nil
}
// PrepareHTTPSModules enables modules required for https
func (ac *apacheConfigurator) PrepareHTTPSModules(temp bool) error {
if _, ok := ac.parser.Modules["ssl_module"]; ok {
return nil
}
if err := ac.EnableModule("ssl", temp); err != nil {
return err
}
// save all changes before
if err := ac.Save(); err != nil {
return err
}
if err := ac.parser.Augeas.Load(); err != nil {
return err
}
if err := ac.parser.ResetModules(); err != nil {
return err
}
return nil
}
// EnableModule enables apache module
func (ac *apacheConfigurator) EnableModule(module string, temp bool) error {
return fmt.Errorf("apache needs to have module %s active. please install the module manually", module)
}
// EnsurePortIsListening ensures that the provided port is listening
// The port will be added to config file it is not listened
func (ac *apacheConfigurator) EnsurePortIsListening(port string, https bool) error {
var portService string
var listens []string
var listenDirs []string
if https && port != "443" {
// https://httpd.apache.org/docs/2.4/bind.html
// Listen 192.170.2.1:8443 https
// running an https site on port 8443 (if protocol is not specified than 443 is used by default for https)
portService = fmt.Sprintf("%s %s", port, "https")
} else {
portService = port
}
listenMatches, err := ac.parser.FindDirective("Listen", "", "", true)
if err != nil {
return err
}
for _, lMatch := range listenMatches {
listen, err := ac.parser.GetArg(lMatch)
if err != nil {
return err
}
// listenDirs contains only unique items
listenDirs = com.AppendStr(listenDirs, listen)
listens = append(listens, listen)
}
if configurator.IsPortListened(listens, port) {
ac.logger.Debug(fmt.Sprintf("port %s is already listended.", port))
return nil
}
if len(listens) == 0 {
listenDirs = append(listenDirs, portService)
}
for _, listen := range listens {
lParts := strings.Split(listen, ":")
// only port is specified -> all interfaces are listened
if len(lParts) == 1 {
if !com.IsSliceContainsStr(listenDirs, port) && !com.IsSliceContainsStr(listenDirs, portService) {
listenDirs = com.AppendStr(listenDirs, portService)
}
} else {
lDir := fmt.Sprintf("%s:%s", configurator.GetIPFromListen(listen), portService)
listenDirs = com.AppendStr(listenDirs, lDir)
}
}
if https {
err = ac.addListensForHTTPS(listenDirs, listens, port)
} else {
err = ac.addListensForHTTP(listenDirs, listens, port)
}
if err != nil {
return err
}
return nil
}
func (ac *apacheConfigurator) addDummySSLDirectives(vhPath string) error {
if err := ac.parser.AddDirective(vhPath, "SSLEngine", []string{"on"}); err != nil {
return fmt.Errorf("could not add 'SSLEngine' directive to vhost %s: %v", vhPath, err)
}
if err := ac.parser.AddDirective(vhPath, "SSLCertificateFile", []string{"insert_cert_file_path"}); err != nil {
return fmt.Errorf("could not add 'SSLCertificateFile' directive to vhost %s: %v", vhPath, err)
}
if err := ac.parser.AddDirective(vhPath, "SSLCertificateKeyFile", []string{"insert_key_file_path"}); err != nil {
return fmt.Errorf("could not add 'SSLCertificateKeyFile' directive to vhost %s: %v", vhPath, err)
}
return nil
}
func (ac *apacheConfigurator) cleanSSLVhost(vhost *entity.VirtualHost) error {
if err := ac.removeDirectives(vhost.AugPath, []string{"SSLEngine", "SSLCertificateFile", "SSLCertificateKeyFile", "SSLCertificateChainFile"}); err != nil {
return err
}
return nil
}
func (ac *apacheConfigurator) removeDirectives(vhPath string, directives []string) error {
for _, directive := range directives {
directivePaths, err := ac.parser.FindDirective(directive, "", vhPath, false)
if err != nil {
return err
}
reg := regexp.MustCompile(`/\w*$`)
for _, directivePath := range directivePaths {
ac.parser.Augeas.Remove(reg.ReplaceAllString(directivePath, ""))
}
}
return nil
}
func (ac *apacheConfigurator) addListensForHTTP(listens []string, listensOrigin []string, port string) error {
newListens := utils.StrSlicesDifference(listens, listensOrigin)
augListenPath := GetAugPath(ac.parser.СonfigListen)
if com.IsSliceContainsStr(newListens, port) {
if err := ac.parser.AddDirective(augListenPath, "Listen", []string{port}); err != nil {
return fmt.Errorf("could not add port %s to listen config: %v", port, err)
}
} else {
for _, listen := range listens {
if err := ac.parser.AddDirective(augListenPath, "Listen", strings.Split(listen, " ")); err != nil {
return fmt.Errorf("could not add port %s to listen config: %v", port, err)
}
}
}
return nil
}
func (ac *apacheConfigurator) addListensForHTTPS(listens []string, listensOrigin []string, port string) error {
var portService string
augListenPath := GetAugPath(ac.parser.СonfigListen)
newListens := utils.StrSlicesDifference(listens, listensOrigin)
if port != "443" {
portService = fmt.Sprintf("%s %s", port, "https")
} else {
portService = port
}
if com.IsSliceContainsStr(newListens, port) || com.IsSliceContainsStr(newListens, portService) {
if err := ac.parser.AddDirectiveToIfModSSL(augListenPath, "Listen", strings.Split(portService, " ")); err != nil {
return fmt.Errorf("could not add port %s to listen config: %v", port, err)
}
} else {
for _, listen := range listens {
if err := ac.parser.AddDirectiveToIfModSSL(augListenPath, "Listen", strings.Split(listen, " ")); err != nil {
return fmt.Errorf("could not add port %s to listen config: %v", port, err)
}
}
}
return nil
}
// GetSuitableVhosts returns suitable virtual hosts for provided serverName.
// If createIfNoSsl is true then ssl part will be created if neccessary.
func (ac *apacheConfigurator) GetSuitableVhosts(serverName string, createIfNoSsl bool) ([]*entity.VirtualHost, error) {
var suitableVhosts []*entity.VirtualHost
suitableVhosts, err := ac.FindSuitableVhosts(serverName)
if err != nil {
return nil, err
}
if len(suitableVhosts) == 0 {
return nil, fmt.Errorf("could not find suitable virtual hosts with ServerName: %s", serverName)
}
if !createIfNoSsl {
return suitableVhosts, nil
}
return ac.makeSslVhosts(suitableVhosts)
}
// FindSuitableVhosts tries to find a suitable virtual host for provided serverName.
func (ac *apacheConfigurator) FindSuitableVhosts(serverName string) ([]*entity.VirtualHost, error) {
vhosts, err := ac.GetVhosts()
if err != nil {
return nil, err
}
var suitableVhosts []*entity.VirtualHost
var suitableNonSslVhosts []*entity.VirtualHost
var sslVostsAddresses []string
for _, vhost := range vhosts {
if vhost.ModMacro {
ac.logger.Warn(fmt.Sprintf("virtual host '%s' has mod macro enabled. Skip it.", vhost.FilePath))
continue
}
// Prefer virtual host with ssl
if vhost.ServerName == serverName {
if vhost.Ssl {
suitableVhosts = append(suitableVhosts, vhost)
sslVostsAddresses = append(sslVostsAddresses, vhost.GetAddressesString(true))
} else {
suitableNonSslVhosts = append(suitableNonSslVhosts, vhost)
}
}
}
for _, vhost := range suitableNonSslVhosts {
// skip non ssl vhosts if there is already ssl vhost with the same address
if !com.IsSliceContainsStr(sslVostsAddresses, vhost.GetAddressesString(true)) {
suitableVhosts = append(suitableVhosts, vhost)
}
}
return suitableVhosts, nil
}
// makeSslVhosts makes an ssl virtual host version of a nonssl virtual host
func (ac *apacheConfigurator) makeSslVhosts(vhosts []*entity.VirtualHost) ([]*entity.VirtualHost, error) {
var totalVhosts []*entity.VirtualHost
var newSslVhosts []*entity.VirtualHost
var newMatches []string
for _, vhost := range vhosts {
if vhost.Ssl {
totalVhosts = append(totalVhosts, vhost)
continue
}
noSslFilePath := vhost.FilePath
sslFilePath, err := ac.getSslVhostFilePath(noSslFilePath)
if err != nil {
return nil, fmt.Errorf("could not get config file path for ssl virtual host: %v", err)
}
originMatches, err := ac.parser.Augeas.Match(fmt.Sprintf("/files%s//*[label()=~regexp('VirtualHost', 'i')]", escape(sslFilePath)))
if err != nil {
return nil, err
}
if err = ac.copyCreateSslVhostSkeleton(vhost, sslFilePath); err != nil {
return nil, fmt.Errorf("could not create config for ssl virtual host: %v", err)
}
// Reload augeas to take into account the new vhost
ac.parser.Augeas.Load()
newMatches, err = ac.parser.Augeas.Match(fmt.Sprintf("/files%s//*[label()=~regexp('VirtualHost', 'i')]", escape(sslFilePath)))
if err != nil {
return nil, err
}
sslVhostPath := getNewVhostPathFromAugesMatches(originMatches, newMatches)
if sslVhostPath == "" {
newMatches, err = ac.parser.Augeas.Match(fmt.Sprintf("/files%s//*[label()=~regexp('VirtualHost', 'i')]", escape(sslFilePath)))
if err != nil {
return nil, err
}
sslVhostPath = getNewVhostPathFromAugesMatches(originMatches, newMatches)
if sslVhostPath == "" {
return nil, errors.New("could not reverse map the HTTPS VirtualHost to the original")
}
}
ac.updateSslVhostAddresses(sslVhostPath)
if err := ac.Save(); err != nil {
return nil, err
}
sslVhost, err := ac.createVhost(sslVhostPath)
if err != nil {
return nil, err
}
sslVhost.Ancestor = vhost
newSslVhosts = append(newSslVhosts, sslVhost)
}
updateVhostsAugPath(newSslVhosts, newMatches)
totalVhosts = append(totalVhosts, newSslVhosts...)
return totalVhosts, nil
}
// CheckConfiguration checks if apache configuration is correct
func (ac *apacheConfigurator) CheckConfiguration() bool {
if err := ac.ctl.TestConfiguration(); err != nil {
return false
}
return true
}
// RestartWebServer restarts apache web server
func (ac *apacheConfigurator) RestartWebServer() error {
return ac.ctl.Restart()
}
func (ac *apacheConfigurator) copyCreateSslVhostSkeleton(noSslVhost *entity.VirtualHost, sslVhostFilePath string) error {
_, err := os.Stat(sslVhostFilePath)
if os.IsNotExist(err) {
ac.reverter.AddFileToDeletion(sslVhostFilePath)
} else if err == nil {
ac.reverter.BackupFile(sslVhostFilePath)
} else {
return err
}
noSslVhostContents, err := ac.getVhostBlockContent(noSslVhost)
if err != nil {
return err
}
sslVhostContent, _ := disableDangerousForSslRewriteRules(noSslVhostContents)
sslVhostFile, err := os.OpenFile(sslVhostFilePath, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0644)
if err != nil {
return err
}
defer sslVhostFile.Close()
sslContent := []string{
"<IfModule mod_ssl.c>\n",
strings.Join(sslVhostContent, "\n"),
"</VirtualHost>\n",
"</IfModule>\n",
}
for _, line := range sslContent {
_, err = sslVhostFile.WriteString(line)
if err != nil {
return fmt.Errorf("could not write to ssl virtual host file '%s': %v", sslVhostFilePath, err)
}
}
if !ac.parser.IsFilenameExistInCurrentPaths(sslVhostFilePath) {
err = ac.parser.ParseFile(sslVhostFilePath)
if err != nil {
return fmt.Errorf("could not parse ssl virtual host file '%s': %v", sslVhostFilePath, err)
}
}
ac.parser.Augeas.Set(fmt.Sprintf("/augeas/files%s/mtime", escape(sslVhostFilePath)), "0")
ac.parser.Augeas.Set(fmt.Sprintf("/augeas/files%s/mtime", escape(noSslVhost.FilePath)), "0")
return nil
}
func (ac *apacheConfigurator) getVhostBlockContent(vhost *entity.VirtualHost) ([]string, error) {
span, err := ac.parser.Augeas.Span(vhost.AugPath)
if err != nil {
return nil, fmt.Errorf("could not get VirtualHost '%s' from the file %s: %v", vhost.ServerName, vhost.FilePath, err)
}
file, err := os.Open(span.Filename)
if err != nil {
return nil, err
}
defer file.Close()
_, err = file.Seek(int64(span.SpanStart), 0)
if err != nil {
return nil, err
}
bContent := make([]byte, span.SpanEnd-span.SpanStart)
_, err = file.Read(bContent)
if err != nil {
return nil, err
}
content := string(bContent)
lines := strings.Split(content, "\n")
removeClosingVhostTag(lines)
return lines, nil
}
func (ac *apacheConfigurator) getSslVhostFilePath(noSslVhostFilePath string) (string, error) {
vhostRoot := opts.GetOption(opts.VhostRoot, ac.options)
var filePath string
var err error
if vhostRoot != "" {
_, err = os.Stat(vhostRoot)
if err == nil {
eVhostRoot, err := filepath.EvalSymlinks(vhostRoot)
if err != nil {
return "", err
}
filePath = filepath.Join(eVhostRoot, filepath.Base(noSslVhostFilePath))
}
} else {
filePath, err = filepath.EvalSymlinks(noSslVhostFilePath)
if err != nil {
return "", err
}
}
sslVhostExt := opts.GetOption(opts.SslVhostlExt, ac.options)
if strings.HasSuffix(filePath, ".conf") {
return filePath[:len(filePath)-len("conf.")] + sslVhostExt, nil
}
return filePath + sslVhostExt, nil
}
func (ac *apacheConfigurator) updateSslVhostAddresses(sslVhostPath string) ([]*entity.Address, error) {
var sslAddresses []*entity.Address
sslAddrMatches, err := ac.parser.Augeas.Match(sslVhostPath + "/arg")
if err != nil {
return nil, err
}
for _, sslAddrMatch := range sslAddrMatches {
addrString, err := ac.parser.GetArg(sslAddrMatch)
if err != nil {
return nil, err
}
oldAddress := entity.CreateVhostAddressFromString(addrString)
sslAddress := oldAddress.GetAddressWithNewPort("443") // TODO: it should be passed in an external code
err = ac.parser.Augeas.Set(sslAddrMatch, sslAddress.ToString())
if err != nil {
return nil, err
}
var exists bool
for _, addr := range sslAddresses {
if sslAddress.IsEqual(addr) {
exists = true
break
}
}
if !exists {
sslAddresses = append(sslAddresses, sslAddress)
}
}
return sslAddresses, nil
}
func (ac *apacheConfigurator) createVhost(path string) (*entity.VirtualHost, error) {
args, err := ac.parser.Augeas.Match(fmt.Sprintf("%s/arg", path))
if err != nil {
return nil, err
}
addrs := make(map[string]entity.Address)
for _, arg := range args {
arg, err = ac.parser.GetArg(arg)
if err != nil {
return nil, err
}
addr := entity.CreateVhostAddressFromString(arg)
addrs[addr.GetHash()] = addr
}
var ssl bool
sslDirectiveMatches, err := ac.parser.FindDirective("SslEngine", "on", path, false)
if err != nil {
return nil, err
}
if len(sslDirectiveMatches) > 0 {
ssl = true
}
for _, addr := range addrs {
if addr.Port == "443" {
ssl = true
break
}
}
fPath, err := ac.parser.Augeas.Get(fmt.Sprintf("/augeas/files%s/path", utils.GetFilePathFromAugPath(path)))
if err != nil {
return nil, err
}
filename := utils.GetFilePathFromAugPath(fPath)
if filename == "" {
return nil, nil
}
var macro bool
if strings.Contains(strings.ToLower(path), "/macro/") {
macro = true
}
vhostEnabled := ac.parser.IsFilenameExistInOriginalPaths(filename)
docRoot, err := ac.getDocumentRoot(path)
if err != nil {
return nil, err
}
virtualhost := entity.VirtualHost{
FilePath: filename,
AugPath: path,
DocRoot: docRoot,
Ssl: ssl,
ModMacro: macro,
Enabled: vhostEnabled,
Addresses: addrs,
}
ac.addServerNames(&virtualhost)
return &virtualhost, err
}
func (ac *apacheConfigurator) addServerNames(vhost *entity.VirtualHost) error {
vhostNames, err := ac.getVhostNames(vhost.AugPath)
if err != nil {
return err
}
for _, alias := range vhostNames.ServerAliases {
if !vhost.ModMacro {
vhost.Aliases = append(vhost.Aliases, alias)
}
}
if !vhost.ModMacro {
vhost.ServerName = vhostNames.ServerName
}
return nil
}
func (ac *apacheConfigurator) getVhostNames(path string) (*vhsotNames, error) {
serverNameMatch, err := ac.parser.FindDirective("ServerName", "", path, false)
if err != nil {
return nil, fmt.Errorf("failed searching ServerName directive: %v", err)
}
serverAliasMatch, err := ac.parser.FindDirective("ServerAlias", "", path, false)
if err != nil {
return nil, fmt.Errorf("failed searching ServerAlias directive: %v", err)
}
var serverAliases []string
var serverName string
for _, alias := range serverAliasMatch {
serverAlias, err := ac.parser.GetArg(alias)
if err != nil {
return nil, err
}
serverAliases = append(serverAliases, serverAlias)
}
if len(serverNameMatch) > 0 {
serverName, err = ac.parser.GetArg(serverNameMatch[len(serverNameMatch)-1])
if err != nil {
return nil, err
}
}
return &vhsotNames{serverName, serverAliases}, nil
}
func (ac *apacheConfigurator) getDocumentRoot(path string) (string, error) {
var docRoot string
docRootMatch, err := ac.parser.FindDirective("DocumentRoot", "", path, false)
if err != nil {
return "", fmt.Errorf("could not get vhost document root: %v", err)
}
if len(docRootMatch) > 0 {
docRoot, err = ac.parser.GetArg(docRootMatch[len(docRootMatch)-1])
if err != nil {
return "", fmt.Errorf("could not get vhost document root: %v", err)
}
// If the directory-path is not absolute then it is assumed to be relative to the ServerRoot.
if !strings.HasPrefix(docRoot, string(filepath.Separator)) {
docRoot = filepath.Join(ac.parser.ServerRoot, docRoot)
}
}
return docRoot, nil
}
// GetApacheConfigurator returns ApacheConfigurator instance
func GetApacheConfigurator(options map[string]string) (ApacheConfigurator, error) {
ctl, err := getApacheCtl(options)
if err != nil {
return nil, err
}
version, err := ctl.GetVersion()
if err != nil {
return nil, err
}
isVersionSupported, err := utils.CheckMinVersion(version, minApacheVersion)
if err != nil {
return nil, err
}
if !isVersionSupported {
return nil, fmt.Errorf("current apache version '%s' is not supported. Minimal supported version is '%s'", version, minApacheVersion)
}
// Test apache configuration before creating ApacheConfigurator
if err = ctl.TestConfiguration(); err != nil {
return nil, err
}
log := logger.NilLogger{}
parser, err := createParser(ctl, version, options)
if err != nil {
return nil, err
}
configurator := apacheConfigurator{
parser: parser,
reverter: &Reverter{apacheSite: apache.GetApacheSite(options), logger: &log},
ctl: ctl,
site: &apache.Site{},
logger: &log,
options: options,
version: version,
}
return &configurator, nil
}