common.go 1.9 KB

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