config.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382
  1. package registry
  2. import (
  3. "encoding/json"
  4. "errors"
  5. "fmt"
  6. "net"
  7. "net/url"
  8. "regexp"
  9. "strings"
  10. "github.com/docker/docker/opts"
  11. flag "github.com/docker/docker/pkg/mflag"
  12. "github.com/docker/docker/utils"
  13. )
  14. // Options holds command line options.
  15. type Options struct {
  16. Mirrors opts.ListOpts
  17. InsecureRegistries opts.ListOpts
  18. }
  19. const (
  20. // Only used for user auth + account creation
  21. INDEXSERVER = "https://index.docker.io/v1/"
  22. REGISTRYSERVER = "https://registry-1.docker.io/v1/"
  23. INDEXNAME = "docker.io"
  24. // INDEXSERVER = "https://registry-stage.hub.docker.com/v1/"
  25. )
  26. var (
  27. ErrInvalidRepositoryName = errors.New("Invalid repository name (ex: \"registry.domain.tld/myrepos\")")
  28. emptyServiceConfig = NewServiceConfig(nil)
  29. validNamespaceChars = regexp.MustCompile(`^([a-z0-9-_]*)$`)
  30. validRepo = regexp.MustCompile(`^([a-z0-9-_.]+)$`)
  31. )
  32. func IndexServerAddress() string {
  33. return INDEXSERVER
  34. }
  35. func IndexServerName() string {
  36. return INDEXNAME
  37. }
  38. // InstallFlags adds command-line options to the top-level flag parser for
  39. // the current process.
  40. func (options *Options) InstallFlags() {
  41. options.Mirrors = opts.NewListOpts(ValidateMirror)
  42. flag.Var(&options.Mirrors, []string{"-registry-mirror"}, "Specify a preferred Docker registry mirror")
  43. options.InsecureRegistries = opts.NewListOpts(ValidateIndexName)
  44. flag.Var(&options.InsecureRegistries, []string{"-insecure-registry"}, "Enable insecure communication with specified registries (no certificate verification for HTTPS and enable HTTP fallback) (e.g., localhost:5000 or 10.20.0.0/16)")
  45. }
  46. type netIPNet net.IPNet
  47. func (ipnet *netIPNet) MarshalJSON() ([]byte, error) {
  48. return json.Marshal((*net.IPNet)(ipnet).String())
  49. }
  50. func (ipnet *netIPNet) UnmarshalJSON(b []byte) (err error) {
  51. var ipnet_str string
  52. if err = json.Unmarshal(b, &ipnet_str); err == nil {
  53. var cidr *net.IPNet
  54. if _, cidr, err = net.ParseCIDR(ipnet_str); err == nil {
  55. *ipnet = netIPNet(*cidr)
  56. }
  57. }
  58. return
  59. }
  60. // ServiceConfig stores daemon registry services configuration.
  61. type ServiceConfig struct {
  62. InsecureRegistryCIDRs []*netIPNet `json:"InsecureRegistryCIDRs"`
  63. IndexConfigs map[string]*IndexInfo `json:"IndexConfigs"`
  64. }
  65. // NewServiceConfig returns a new instance of ServiceConfig
  66. func NewServiceConfig(options *Options) *ServiceConfig {
  67. if options == nil {
  68. options = &Options{
  69. Mirrors: opts.NewListOpts(nil),
  70. InsecureRegistries: opts.NewListOpts(nil),
  71. }
  72. }
  73. // Localhost is by default considered as an insecure registry
  74. // This is a stop-gap for people who are running a private registry on localhost (especially on Boot2docker).
  75. //
  76. // TODO: should we deprecate this once it is easier for people to set up a TLS registry or change
  77. // daemon flags on boot2docker?
  78. options.InsecureRegistries.Set("127.0.0.0/8")
  79. config := &ServiceConfig{
  80. InsecureRegistryCIDRs: make([]*netIPNet, 0),
  81. IndexConfigs: make(map[string]*IndexInfo, 0),
  82. }
  83. // Split --insecure-registry into CIDR and registry-specific settings.
  84. for _, r := range options.InsecureRegistries.GetAll() {
  85. // Check if CIDR was passed to --insecure-registry
  86. _, ipnet, err := net.ParseCIDR(r)
  87. if err == nil {
  88. // Valid CIDR.
  89. config.InsecureRegistryCIDRs = append(config.InsecureRegistryCIDRs, (*netIPNet)(ipnet))
  90. } else {
  91. // Assume `host:port` if not CIDR.
  92. config.IndexConfigs[r] = &IndexInfo{
  93. Name: r,
  94. Mirrors: make([]string, 0),
  95. Secure: false,
  96. Official: false,
  97. }
  98. }
  99. }
  100. // Configure public registry.
  101. config.IndexConfigs[IndexServerName()] = &IndexInfo{
  102. Name: IndexServerName(),
  103. Mirrors: options.Mirrors.GetAll(),
  104. Secure: true,
  105. Official: true,
  106. }
  107. return config
  108. }
  109. // isSecureIndex returns false if the provided indexName is part of the list of insecure registries
  110. // Insecure registries accept HTTP and/or accept HTTPS with certificates from unknown CAs.
  111. //
  112. // The list of insecure registries can contain an element with CIDR notation to specify a whole subnet.
  113. // If the subnet contains one of the IPs of the registry specified by indexName, the latter is considered
  114. // insecure.
  115. //
  116. // indexName should be a URL.Host (`host:port` or `host`) where the `host` part can be either a domain name
  117. // or an IP address. If it is a domain name, then it will be resolved in order to check if the IP is contained
  118. // in a subnet. If the resolving is not successful, isSecureIndex will only try to match hostname to any element
  119. // of insecureRegistries.
  120. func (config *ServiceConfig) isSecureIndex(indexName string) bool {
  121. // Check for configured index, first. This is needed in case isSecureIndex
  122. // is called from anything besides NewIndexInfo, in order to honor per-index configurations.
  123. if index, ok := config.IndexConfigs[indexName]; ok {
  124. return index.Secure
  125. }
  126. host, _, err := net.SplitHostPort(indexName)
  127. if err != nil {
  128. // assume indexName is of the form `host` without the port and go on.
  129. host = indexName
  130. }
  131. addrs, err := lookupIP(host)
  132. if err != nil {
  133. ip := net.ParseIP(host)
  134. if ip != nil {
  135. addrs = []net.IP{ip}
  136. }
  137. // if ip == nil, then `host` is neither an IP nor it could be looked up,
  138. // either because the index is unreachable, or because the index is behind an HTTP proxy.
  139. // So, len(addrs) == 0 and we're not aborting.
  140. }
  141. // Try CIDR notation only if addrs has any elements, i.e. if `host`'s IP could be determined.
  142. for _, addr := range addrs {
  143. for _, ipnet := range config.InsecureRegistryCIDRs {
  144. // check if the addr falls in the subnet
  145. if (*net.IPNet)(ipnet).Contains(addr) {
  146. return false
  147. }
  148. }
  149. }
  150. return true
  151. }
  152. // ValidateMirror validates an HTTP(S) registry mirror
  153. func ValidateMirror(val string) (string, error) {
  154. uri, err := url.Parse(val)
  155. if err != nil {
  156. return "", fmt.Errorf("%s is not a valid URI", val)
  157. }
  158. if uri.Scheme != "http" && uri.Scheme != "https" {
  159. return "", fmt.Errorf("Unsupported scheme %s", uri.Scheme)
  160. }
  161. if uri.Path != "" || uri.RawQuery != "" || uri.Fragment != "" {
  162. return "", fmt.Errorf("Unsupported path/query/fragment at end of the URI")
  163. }
  164. return fmt.Sprintf("%s://%s/v1/", uri.Scheme, uri.Host), nil
  165. }
  166. // ValidateIndexName validates an index name.
  167. func ValidateIndexName(val string) (string, error) {
  168. // 'index.docker.io' => 'docker.io'
  169. if val == "index."+IndexServerName() {
  170. val = IndexServerName()
  171. }
  172. // *TODO: Check if valid hostname[:port]/ip[:port]?
  173. return val, nil
  174. }
  175. func validateRemoteName(remoteName string) error {
  176. var (
  177. namespace string
  178. name string
  179. )
  180. nameParts := strings.SplitN(remoteName, "/", 2)
  181. if len(nameParts) < 2 {
  182. namespace = "library"
  183. name = nameParts[0]
  184. // the repository name must not be a valid image ID
  185. if err := utils.ValidateID(name); err == nil {
  186. return fmt.Errorf("Invalid repository name (%s), cannot specify 64-byte hexadecimal strings", name)
  187. }
  188. } else {
  189. namespace = nameParts[0]
  190. name = nameParts[1]
  191. }
  192. if !validNamespaceChars.MatchString(namespace) {
  193. return fmt.Errorf("Invalid namespace name (%s). Only [a-z0-9-_] are allowed.", namespace)
  194. }
  195. if len(namespace) < 4 || len(namespace) > 30 {
  196. return fmt.Errorf("Invalid namespace name (%s). Cannot be fewer than 4 or more than 30 characters.", namespace)
  197. }
  198. if strings.HasPrefix(namespace, "-") || strings.HasSuffix(namespace, "-") {
  199. return fmt.Errorf("Invalid namespace name (%s). Cannot begin or end with a hyphen.", namespace)
  200. }
  201. if strings.Contains(namespace, "--") {
  202. return fmt.Errorf("Invalid namespace name (%s). Cannot contain consecutive hyphens.", namespace)
  203. }
  204. if !validRepo.MatchString(name) {
  205. return fmt.Errorf("Invalid repository name (%s), only [a-z0-9-_.] are allowed", name)
  206. }
  207. return nil
  208. }
  209. func validateNoSchema(reposName string) error {
  210. if strings.Contains(reposName, "://") {
  211. // It cannot contain a scheme!
  212. return ErrInvalidRepositoryName
  213. }
  214. return nil
  215. }
  216. // ValidateRepositoryName validates a repository name
  217. func ValidateRepositoryName(reposName string) error {
  218. var err error
  219. if err = validateNoSchema(reposName); err != nil {
  220. return err
  221. }
  222. indexName, remoteName := splitReposName(reposName)
  223. if _, err = ValidateIndexName(indexName); err != nil {
  224. return err
  225. }
  226. return validateRemoteName(remoteName)
  227. }
  228. // NewIndexInfo returns IndexInfo configuration from indexName
  229. func (config *ServiceConfig) NewIndexInfo(indexName string) (*IndexInfo, error) {
  230. var err error
  231. indexName, err = ValidateIndexName(indexName)
  232. if err != nil {
  233. return nil, err
  234. }
  235. // Return any configured index info, first.
  236. if index, ok := config.IndexConfigs[indexName]; ok {
  237. return index, nil
  238. }
  239. // Construct a non-configured index info.
  240. index := &IndexInfo{
  241. Name: indexName,
  242. Mirrors: make([]string, 0),
  243. Official: false,
  244. }
  245. index.Secure = config.isSecureIndex(indexName)
  246. return index, nil
  247. }
  248. // GetAuthConfigKey special-cases using the full index address of the official
  249. // index as the AuthConfig key, and uses the (host)name[:port] for private indexes.
  250. func (index *IndexInfo) GetAuthConfigKey() string {
  251. if index.Official {
  252. return IndexServerAddress()
  253. }
  254. return index.Name
  255. }
  256. // splitReposName breaks a reposName into an index name and remote name
  257. func splitReposName(reposName string) (string, string) {
  258. nameParts := strings.SplitN(reposName, "/", 2)
  259. var indexName, remoteName string
  260. if len(nameParts) == 1 || (!strings.Contains(nameParts[0], ".") &&
  261. !strings.Contains(nameParts[0], ":") && nameParts[0] != "localhost") {
  262. // This is a Docker Index repos (ex: samalba/hipache or ubuntu)
  263. // 'docker.io'
  264. indexName = IndexServerName()
  265. remoteName = reposName
  266. } else {
  267. indexName = nameParts[0]
  268. remoteName = nameParts[1]
  269. }
  270. return indexName, remoteName
  271. }
  272. // NewRepositoryInfo validates and breaks down a repository name into a RepositoryInfo
  273. func (config *ServiceConfig) NewRepositoryInfo(reposName string) (*RepositoryInfo, error) {
  274. if err := validateNoSchema(reposName); err != nil {
  275. return nil, err
  276. }
  277. indexName, remoteName := splitReposName(reposName)
  278. if err := validateRemoteName(remoteName); err != nil {
  279. return nil, err
  280. }
  281. repoInfo := &RepositoryInfo{
  282. RemoteName: remoteName,
  283. }
  284. var err error
  285. repoInfo.Index, err = config.NewIndexInfo(indexName)
  286. if err != nil {
  287. return nil, err
  288. }
  289. if repoInfo.Index.Official {
  290. normalizedName := repoInfo.RemoteName
  291. if strings.HasPrefix(normalizedName, "library/") {
  292. // If pull "library/foo", it's stored locally under "foo"
  293. normalizedName = strings.SplitN(normalizedName, "/", 2)[1]
  294. }
  295. repoInfo.LocalName = normalizedName
  296. repoInfo.RemoteName = normalizedName
  297. // If the normalized name does not contain a '/' (e.g. "foo")
  298. // then it is an official repo.
  299. if strings.IndexRune(normalizedName, '/') == -1 {
  300. repoInfo.Official = true
  301. // Fix up remote name for official repos.
  302. repoInfo.RemoteName = "library/" + normalizedName
  303. }
  304. // *TODO: Prefix this with 'docker.io/'.
  305. repoInfo.CanonicalName = repoInfo.LocalName
  306. } else {
  307. // *TODO: Decouple index name from hostname (via registry configuration?)
  308. repoInfo.LocalName = repoInfo.Index.Name + "/" + repoInfo.RemoteName
  309. repoInfo.CanonicalName = repoInfo.LocalName
  310. }
  311. return repoInfo, nil
  312. }
  313. // GetSearchTerm special-cases using local name for official index, and
  314. // remote name for private indexes.
  315. func (repoInfo *RepositoryInfo) GetSearchTerm() string {
  316. if repoInfo.Index.Official {
  317. return repoInfo.LocalName
  318. }
  319. return repoInfo.RemoteName
  320. }
  321. // ParseRepositoryInfo performs the breakdown of a repository name into a RepositoryInfo, but
  322. // lacks registry configuration.
  323. func ParseRepositoryInfo(reposName string) (*RepositoryInfo, error) {
  324. return emptyServiceConfig.NewRepositoryInfo(reposName)
  325. }
  326. // NormalizeLocalName transforms a repository name into a normalize LocalName
  327. // Passes through the name without transformation on error (image id, etc)
  328. func NormalizeLocalName(name string) string {
  329. repoInfo, err := ParseRepositoryInfo(name)
  330. if err != nil {
  331. return name
  332. }
  333. return repoInfo.LocalName
  334. }