package main import ( "errors" "io/ioutil" "os/user" "path" "strings" "time" "dim13.org/acme" "gopkg.in/yaml.v2" ) const ( defKeySize = 2048 day = time.Hour * 24 week = day * 7 defGrace = week keyPath = "private" crtPath = "certs" ) type Config struct { Gracetime time.Duration Listen string ListenTLS string BaseDir string KeySize int Directory string Account []account Hook map[string]string } type account struct { Mail string Phone string KeySize int KeyFile string Domain []domain } type domain struct { Gracetime time.Duration Altnames []string KeySize int KeyFile string CrtFile string Webroot string Hook []string } var ( errNoKey = errors.New("no key file specified") errNoAltNames = errors.New("no altnames specified") errNoMail = errors.New("no mail specified") ) func expandHome(p string) (string, error) { if strings.HasPrefix(p, "~") { usr, err := user.Current() if err != nil { return p, err } return path.Join(usr.HomeDir, p[1:]), nil } return p, nil } func LoadConfig(fname string) (*Config, error) { conf, err := ioutil.ReadFile(fname) if err != nil { return nil, err } c := new(Config) err = yaml.Unmarshal(conf, c) if err != nil { return nil, err } c.BaseDir, err = expandHome(c.BaseDir) if err != nil { return nil, err } // apply defaults if c.Gracetime == 0 { c.Gracetime = defGrace } if c.KeySize == 0 { c.KeySize = defKeySize } if c.Directory == "" { c.Directory = acme.LE1 } for i, acc := range c.Account { if acc.KeySize == 0 { acc.KeySize = c.KeySize } if acc.Mail == "" { return nil, errNoMail } if acc.KeyFile == "" { acc.KeyFile = path.Join(keyPath, acc.Mail+".key") } if c.BaseDir != "" { acc.KeyFile = path.Join(c.BaseDir, acc.KeyFile) } c.Account[i] = acc for i, dom := range acc.Domain { if dom.Gracetime != 0 { dom.Gracetime = c.Gracetime } if dom.KeySize == 0 { dom.KeySize = c.KeySize } if len(dom.Altnames) == 0 { return nil, errNoAltNames } dom.Altnames = checkWWW(dom.Altnames) d := dom.Altnames[0] if dom.KeyFile == "" { dom.KeyFile = path.Join(keyPath, d+".key") } if dom.CrtFile == "" { dom.CrtFile = path.Join(crtPath, d+".pem") } if c.BaseDir != "" { dom.KeyFile = path.Join(c.BaseDir, dom.KeyFile) dom.CrtFile = path.Join(c.BaseDir, dom.CrtFile) } acc.Domain[i] = dom } } return c, nil } func checkWWW(altnames []string) []string { ch := make(chan string) go func(ch chan string, s []string) { for _, an := range s { if strings.HasPrefix(an, "www.") { ch <- an[4:] } } close(ch) }(ch, altnames) has := func(s string) bool { for _, an := range altnames { if an == s { return true } } return false } for d := range ch { if !has(d) { altnames = append(altnames, d) } } return altnames }