From 8c40684989c8dd260705d6f5715f63863070d8a5 Mon Sep 17 00:00:00 2001 From: Nicola Murino Date: Fri, 2 Aug 2019 11:17:23 +0200 Subject: [PATCH] sftpd: simplify initialization code now gocyclo is happy again --- sftpd/server.go | 32 +++++++++++++++++++------------- 1 file changed, 19 insertions(+), 13 deletions(-) diff --git a/sftpd/server.go b/sftpd/server.go index 9fa60d2c..5b63d808 100644 --- a/sftpd/server.go +++ b/sftpd/server.go @@ -86,19 +86,9 @@ func (c Configuration) Initialize(configDir string) error { ServerVersion: "SSH-2.0-" + c.Banner, } - if len(c.Keys) == 0 { - autoFile := filepath.Join(configDir, defaultPrivateKeyName) - if _, err := os.Stat(autoFile); os.IsNotExist(err) { - logger.Info(logSender, "No host keys configured and %s does not exist; creating new private key for server", autoFile) - logger.InfoToConsole("No host keys configured and %s does not exist; creating new private key for server", autoFile) - if err := c.generatePrivateKey(autoFile); err != nil { - return err - } - } else if err != nil { - return err - } - - c.Keys = append(c.Keys, Key{PrivateKey: defaultPrivateKeyName}) + err = c.checkHostKeys(configDir) + if err != nil { + return err } for _, k := range c.Keys { @@ -275,6 +265,22 @@ func loginUser(user dataprovider.User) (*ssh.Permissions, error) { return p, nil } +// If no host keys are defined we try to use or generate the default one. +func (c *Configuration) checkHostKeys(configDir string) error { + var err error + if len(c.Keys) == 0 { + autoFile := filepath.Join(configDir, defaultPrivateKeyName) + if _, err = os.Stat(autoFile); os.IsNotExist(err) { + logger.Info(logSender, "No host keys configured and %s does not exist; creating new private key for server", autoFile) + logger.InfoToConsole("No host keys configured and %s does not exist; creating new private key for server", autoFile) + err = c.generatePrivateKey(autoFile) + } + + c.Keys = append(c.Keys, Key{PrivateKey: defaultPrivateKeyName}) + } + return err +} + func (c Configuration) validatePublicKeyCredentials(conn ssh.ConnMetadata, pubKey string) (*ssh.Permissions, error) { var err error var user dataprovider.User