Browse code

Add key migration to daemon

Signed-off-by: Derek McGowan <derek@mcgstyle.net> (github: dmcgowan)

Derek McGowan authored on 2015/01/22 09:55:05
Showing 2 changed files
... ...
@@ -3,6 +3,11 @@
3 3
 package main
4 4
 
5 5
 import (
6
+	"fmt"
7
+	"io"
8
+	"os"
9
+	"path/filepath"
10
+
6 11
 	log "github.com/Sirupsen/logrus"
7 12
 	"github.com/docker/docker/builder"
8 13
 	"github.com/docker/docker/builtins"
... ...
@@ -14,6 +19,7 @@ import (
14 14
 	flag "github.com/docker/docker/pkg/mflag"
15 15
 	"github.com/docker/docker/pkg/signal"
16 16
 	"github.com/docker/docker/registry"
17
+	"github.com/docker/docker/utils"
17 18
 )
18 19
 
19 20
 const CanDaemon = true
... ...
@@ -28,6 +34,38 @@ func init() {
28 28
 	registryCfg.InstallFlags()
29 29
 }
30 30
 
31
+func migrateKey() error {
32
+	// Migrate trust key if exists at ~/.docker/key.json and owned by current user
33
+	oldPath := filepath.Join(getHomeDir(), ".docker", defaultTrustKeyFile)
34
+	newPath := filepath.Join(getDaemonConfDir(), defaultTrustKeyFile)
35
+	if _, err := os.Stat(newPath); os.IsNotExist(err) && utils.IsFileOwner(oldPath) {
36
+		if err := os.MkdirAll(getDaemonConfDir(), os.FileMode(0644)); err != nil {
37
+			return fmt.Errorf("Unable to create daemon configuraiton directory: %s", err)
38
+		}
39
+
40
+		newFile, err := os.OpenFile(newPath, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0600)
41
+		if err != nil {
42
+			return fmt.Errorf("error creating key file %q: %s", newPath, err)
43
+		}
44
+		defer newFile.Close()
45
+
46
+		oldFile, err := os.Open(oldPath)
47
+		if err != nil {
48
+			return fmt.Errorf("error opening open key file %q: %s", oldPath, err)
49
+		}
50
+
51
+		if _, err := io.Copy(newFile, oldFile); err != nil {
52
+			return fmt.Errorf("error copying key: %s", err)
53
+		}
54
+
55
+		oldFile.Close()
56
+		log.Debugf("Migrated key from %s to %s", oldPath, newPath)
57
+		return os.Remove(oldPath)
58
+	}
59
+
60
+	return nil
61
+}
62
+
31 63
 func mainDaemon() {
32 64
 	if flag.NArg() != 0 {
33 65
 		flag.Usage()
... ...
@@ -36,6 +74,9 @@ func mainDaemon() {
36 36
 	eng := engine.New()
37 37
 	signal.Trap(eng.Shutdown)
38 38
 
39
+	if err := migrateKey(); err != nil {
40
+		log.Fatal(err)
41
+	}
39 42
 	daemonCfg.TrustKeyPath = *flTrustKey
40 43
 
41 44
 	// Load builtins
... ...
@@ -37,3 +37,13 @@ func TreeSize(dir string) (size int64, err error) {
37 37
 	})
38 38
 	return
39 39
 }
40
+
41
+// IsFileOwner checks whether the current user is the owner of the given file.
42
+func IsFileOwner(f string) bool {
43
+	if fileInfo, err := os.Stat(f); err == nil && fileInfo != nil {
44
+		if stat, ok := fileInfo.Sys().(*syscall.Stat_t); ok && int(stat.Uid) == os.Getuid() {
45
+			return true
46
+		}
47
+	}
48
+	return false
49
+}