diff --git a/cmd/syncthing/main.go b/cmd/syncthing/main.go index 81fc8a139..ad241bab2 100644 --- a/cmd/syncthing/main.go +++ b/cmd/syncthing/main.go @@ -135,12 +135,14 @@ func main() { var showVersion bool var doUpgrade bool var doUpgradeCheck bool + var generateDir string flag.StringVar(&confDir, "home", getDefaultConfDir(), "Set configuration directory") flag.BoolVar(&reset, "reset", false, "Prepare to resync from cluster") flag.BoolVar(&showVersion, "version", false, "Show version") flag.BoolVar(&doUpgrade, "upgrade", false, "Perform upgrade") flag.BoolVar(&doUpgradeCheck, "upgrade-check", false, "Check for available upgrade") flag.IntVar(&logFlags, "logflags", logFlags, "Set log flags") + flag.StringVar(&generateDir, "generate", "", "Generate key in specified dir") flag.Usage = usageFor(flag.CommandLine, usage, extraUsage) flag.Parse() @@ -151,10 +153,29 @@ func main() { l.SetFlags(logFlags) - var err error - lockPort, err = getLockPort() - if err != nil { - l.Fatalln("Opening lock port:", err) + if generateDir != "" { + dir := expandTilde(generateDir) + + info, err := os.Stat(dir) + l.FatalErr(err) + if !info.IsDir() { + l.Fatalln(dir, "is not a directory") + } + + cert, err := loadCert(dir, "") + if err == nil { + l.Warnln("Key exists; will not overwrite.") + l.Infoln("Node ID:", protocol.NewNodeID(cert.Certificate[0])) + return + } + + newCertificate(dir, "") + cert, err = loadCert(dir, "") + l.FatalErr(err) + if err == nil { + l.Infoln("Node ID:", protocol.NewNodeID(cert.Certificate[0])) + } + return } if doUpgrade || doUpgradeCheck { @@ -182,6 +203,12 @@ func main() { } } + var err error + lockPort, err = getLockPort() + if err != nil { + l.Fatalln("Opening lock port:", err) + } + if len(os.Getenv("GOGC")) == 0 { debug.SetGCPercent(25) } diff --git a/cmd/syncthing/tls.go b/cmd/syncthing/tls.go index bef52f812..e46e8079e 100644 --- a/cmd/syncthing/tls.go +++ b/cmd/syncthing/tls.go @@ -39,7 +39,7 @@ func certSeed(bs []byte) int64 { } func newCertificate(dir string, prefix string) { - l.Infoln("Generating RSA certificate and key...") + l.Infoln("Generating RSA key and certificate...") priv, err := rsa.GenerateKey(rand.Reader, tlsRSABits) l.FatalErr(err) @@ -67,11 +67,9 @@ func newCertificate(dir string, prefix string) { l.FatalErr(err) pem.Encode(certOut, &pem.Block{Type: "CERTIFICATE", Bytes: derBytes}) certOut.Close() - l.Okln("Created RSA certificate file") keyOut, err := os.OpenFile(filepath.Join(dir, prefix+"key.pem"), os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0600) l.FatalErr(err) pem.Encode(keyOut, &pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(priv)}) keyOut.Close() - l.Okln("Created RSA key file") }