github.com/hoffie/larasync@v0.0.0-20151025221940-0384d2bddcef/config/server.go (about) 1 package config 2 3 import ( 4 "encoding/hex" 5 "fmt" 6 "io/ioutil" 7 "time" 8 9 apicommon "github.com/hoffie/larasync/api/common" 10 "github.com/hoffie/larasync/api/server" 11 ) 12 13 // ServerConfig contains all settings for our server mode. 14 type ServerConfig struct { 15 Server struct { 16 Listen string 17 } 18 Signatures struct { 19 AdminPubkey string 20 AdminPubkeyBinary *[apicommon.PublicKeySize]byte 21 MaxAge time.Duration 22 } 23 Repository struct { 24 BasePath string 25 } 26 } 27 28 // Sanitize populates all zero values with sane defaults and ensures that any 29 // required options are set to sane values. 30 func (c *ServerConfig) Sanitize() error { 31 if c.Server.Listen == "" { 32 c.Server.Listen = fmt.Sprintf("127.0.0.1:%d", server.DefaultPort) 33 } 34 err := c.decodeAdminPubkey() 35 if err != nil { 36 Log.Error("no valid admin pubkey configured; refusing to run") 37 return err 38 } 39 if len(c.Repository.BasePath) == 0 { 40 Log.Error("no repository base path configured; refusing to run") 41 return ErrMissingBasePath 42 } 43 _, err = ioutil.ReadDir(c.Repository.BasePath) 44 if err != nil { 45 Log.Error(fmt.Sprintf("unable to open repository base path configured; "+ 46 "refusing to run (%s)", err)) 47 return ErrBadBasePath 48 } 49 if c.Signatures.MaxAge == 0 { 50 c.Signatures.MaxAge = 10 * time.Second 51 } 52 return nil 53 } 54 55 // decodeAdminPubkey reads AdminPubkey, hex-decodes it and performs validation steps. 56 func (c *ServerConfig) decodeAdminPubkey() error { 57 if c.Signatures.AdminPubkey == "" { 58 return ErrAdminPubkeyMissing 59 } 60 dec, err := hex.DecodeString(c.Signatures.AdminPubkey) 61 if err != nil { 62 return ErrInvalidAdminPubkey 63 } 64 if len(dec) != apicommon.PublicKeySize { 65 return ErrTruncatedAdminPubkey 66 } 67 c.Signatures.AdminPubkeyBinary = new([apicommon.PublicKeySize]byte) 68 copy(c.Signatures.AdminPubkeyBinary[:], dec) 69 return nil 70 }