1// Copyright 2017 VMware, Inc. All Rights Reserved.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//    http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15package common
16
17import (
18	"io/ioutil"
19
20	"gopkg.in/urfave/cli.v1"
21
22	"github.com/vmware/vic/pkg/errors"
23	"github.com/vmware/vic/pkg/trace"
24)
25
26// Registries contains metadata used to create/configure registry CA data
27type Registries struct {
28	RegistryCAsArg         cli.StringSlice `arg:"registry-ca"`
29	InsecureRegistriesArg  cli.StringSlice `arg:"insecure-registry"`
30	WhitelistRegistriesArg cli.StringSlice `arg:"whitelist-registry"`
31
32	RegistryCAs []byte
33
34	InsecureRegistries  []string `cmd:"insecure-registry"`
35	WhitelistRegistries []string `cmd:"whitelist-registry"`
36}
37
38// Flags generates command line flags
39func (r *Registries) Flags() []cli.Flag {
40	return []cli.Flag{
41		cli.StringSliceFlag{
42			Name:  "registry-ca, rc",
43			Usage: "Specify a list of additional certificate authority files to use to verify secure registry servers",
44			Value: &r.RegistryCAsArg,
45		},
46	}
47}
48
49// LoadRegistryCAs loads additional CA certs for docker registry usage
50func (r *Registries) loadRegistryCAs(op trace.Operation) ([]byte, error) {
51	defer trace.End(trace.Begin("", op))
52
53	var registryCerts []byte
54	for _, f := range r.RegistryCAsArg {
55		b, err := ioutil.ReadFile(f)
56		if err != nil {
57			err = errors.Errorf("Failed to load authority from file %s: %s", f, err)
58			return nil, err
59		}
60
61		registryCerts = append(registryCerts, b...)
62		op.Infof("Loaded registry CA from %s", f)
63	}
64
65	return registryCerts, nil
66}
67
68func (r *Registries) ProcessRegistries(op trace.Operation) error {
69	// load additional certificate authorities for use with registries
70	if len(r.RegistryCAsArg) > 0 {
71		registryCAs, err := r.loadRegistryCAs(op)
72		if err != nil {
73			return errors.Errorf("Unable to load CA certificates for registry logins: %s", err)
74		}
75
76		r.RegistryCAs = registryCAs
77	}
78
79	r.InsecureRegistries = r.InsecureRegistriesArg.Value()
80	r.WhitelistRegistries = r.WhitelistRegistriesArg.Value()
81	return nil
82}
83