Tizen_4.0 base
[platform/upstream/docker-engine.git] / api / common.go
1 package api
2
3 import (
4         "encoding/json"
5         "encoding/pem"
6         "fmt"
7         "os"
8         "path/filepath"
9
10         "github.com/docker/docker/pkg/ioutils"
11         "github.com/docker/docker/pkg/system"
12         "github.com/docker/libtrust"
13 )
14
15 // Common constants for daemon and client.
16 const (
17         // DefaultVersion of Current REST API
18         DefaultVersion string = "1.31"
19
20         // NoBaseImageSpecifier is the symbol used by the FROM
21         // command to specify that no base image is to be used.
22         NoBaseImageSpecifier string = "scratch"
23 )
24
25 // LoadOrCreateTrustKey attempts to load the libtrust key at the given path,
26 // otherwise generates a new one
27 func LoadOrCreateTrustKey(trustKeyPath string) (libtrust.PrivateKey, error) {
28         err := system.MkdirAll(filepath.Dir(trustKeyPath), 0700, "")
29         if err != nil {
30                 return nil, err
31         }
32         trustKey, err := libtrust.LoadKeyFile(trustKeyPath)
33         if err == libtrust.ErrKeyFileDoesNotExist {
34                 trustKey, err = libtrust.GenerateECP256PrivateKey()
35                 if err != nil {
36                         return nil, fmt.Errorf("Error generating key: %s", err)
37                 }
38                 encodedKey, err := serializePrivateKey(trustKey, filepath.Ext(trustKeyPath))
39                 if err != nil {
40                         return nil, fmt.Errorf("Error serializing key: %s", err)
41                 }
42                 if err := ioutils.AtomicWriteFile(trustKeyPath, encodedKey, os.FileMode(0600)); err != nil {
43                         return nil, fmt.Errorf("Error saving key file: %s", err)
44                 }
45         } else if err != nil {
46                 return nil, fmt.Errorf("Error loading key file %s: %s", trustKeyPath, err)
47         }
48         return trustKey, nil
49 }
50
51 func serializePrivateKey(key libtrust.PrivateKey, ext string) (encoded []byte, err error) {
52         if ext == ".json" || ext == ".jwk" {
53                 encoded, err = json.Marshal(key)
54                 if err != nil {
55                         return nil, fmt.Errorf("unable to encode private key JWK: %s", err)
56                 }
57         } else {
58                 pemBlock, err := key.PEMBlock()
59                 if err != nil {
60                         return nil, fmt.Errorf("unable to encode private key PEM: %s", err)
61                 }
62                 encoded = pem.EncodeToMemory(pemBlock)
63         }
64         return
65 }