// GetNotaryRepository returns a NotaryRepository which stores all the
// information needed to operate on a notary repository.
// It creates an HTTP transport providing authentication support.
11306
func GetNotaryRepository(in io.Reader, out io.Writer, userAgent string, repoInfo *registry.RepositoryInfo, authConfig *types.AuthConfig, actions ...string) (client.Repository, error) {
	server, err := Server(repoInfo.Index)
	if err != nil {
		return nil, err
	}

	var cfg = tlsconfig.ClientDefault()
	cfg.InsecureSkipVerify = !repoInfo.Index.Secure

	// Get certificate base directory
	certDir, err := certificateDirectory(server)
	if err != nil {
		return nil, err
	}
	logrus.Debugf("reading certificate directory: %s", certDir)

	if err := registry.ReadCertsDirectory(cfg, certDir); err != nil {
		return nil, err
	}

	base := &http.Transport{
		Proxy: http.ProxyFromEnvironment,
		Dial: (&net.Dialer{
			Timeout:   30 * time.Second,
			KeepAlive: 30 * time.Second,
			DualStack: true,
		}).Dial,
		TLSHandshakeTimeout: 10 * time.Second,
		TLSClientConfig:     cfg,
		DisableKeepAlives:   true,
	}

	// Skip configuration headers since request is not going to Docker daemon
	modifiers := registry.Headers(userAgent, http.Header{})
	authTransport := transport.NewTransport(base, modifiers...)
	pingClient := &http.Client{
		Transport: authTransport,
		Timeout:   5 * time.Second,
	}
	endpointStr := server + "/v2/"
	req, err := http.NewRequest("GET", endpointStr, nil)
	if err != nil {
		return nil, err
	}

	challengeManager := challenge.NewSimpleManager()

	resp, err := pingClient.Do(req)
	if err != nil {
		// Ignore error on ping to operate in offline mode
		logrus.Debugf("Error pinging notary server %q: %s", endpointStr, err)
	} else {
		defer resp.Body.Close()

		// Add response to the challenge manager to parse out
		// authentication header and register authentication method
		if err := challengeManager.AddResponse(resp); err != nil {
			return nil, err
		}
	}

	scope := auth.RepositoryScope{
		Repository: repoInfo.Name.Name(),
		Actions:    actions,
		Class:      repoInfo.Class,
	}
	creds := simpleCredentialStore{auth: *authConfig}
	tokenHandlerOptions := auth.TokenHandlerOptions{
		Transport:   authTransport,
		Credentials: creds,
		Scopes:      []auth.Scope{scope},
		ClientID:    registry.AuthClientID,
	}
	tokenHandler := auth.NewTokenHandlerWithOptions(tokenHandlerOptions)
	basicHandler := auth.NewBasicHandler(creds)
	modifiers = append(modifiers, auth.NewAuthorizer(challengeManager, tokenHandler, basicHandler))
	tr := transport.NewTransport(base, modifiers...)

	return client.NewFileCachedRepository(
		GetTrustDirectory(),
		data.GUN(repoInfo.Name.Name()),
		server,
		tr,
		GetPassphraseRetriever(in, out),
		trustpinning.TrustPinConfig{})
}
944861
func (c *connection) getCachedRepository(name string) (repository, error) {
	if cached, ok := c.cached[name]; ok {
		return cached, nil
	}

	if c.isV2 == nil {
		v2, err := c.checkV2()
		if err != nil {
			return nil, err
		}
		c.isV2 = &v2
	}
	if *c.isV2 {
		base := c.url
		base.Host = normalizeDockerHubHost(base.Host, true)
		repo := &v2repository{
			name:     name,
			endpoint: base,
			token:    c.token,
		}
		c.cached[name] = repo
		return repo, nil
	}

	repo, err := c.getRepositoryV1(name)
	if err != nil {
		return nil, err
	}
	c.cached[name] = repo
	return repo, nil
}
628707
func (client Client) GetRepository(projectKey, repositorySlug string) (Repository, error) {
	retry := retry.New(3, retry.DefaultBackoffFunc)

	var r Repository
	work := func() error {
		req, err := http.NewRequest("GET", fmt.Sprintf("%s/rest/api/1.0/projects/%s/repos/%s", client.baseURL.String(), projectKey, repositorySlug), nil)
		if err != nil {
			return err
		}
		req.Header.Set("Accept", "application/json")
		// use credentials if we have them.  If not, the repository must be public.
		if client.userName != "" && client.password != "" {
			req.SetBasicAuth(client.userName, client.password)
		}

		responseCode, data, err := client.consumeResponse(req)
		if err != nil {
			return err
		}

		if responseCode != http.StatusOK {
			reason := "unhandled reason"
			switch {
			case responseCode == http.StatusNotFound:
				reason = "Not found"
			case responseCode == http.StatusUnauthorized:
				reason = "Unauthorized"
			}
			return errorResponse{StatusCode: responseCode, Reason: reason}
		}

		err = json.Unmarshal(data, &r)
		if err != nil {
			return err
		}
		return nil
	}

	return r, retry.Try(work)
}
493316
func (c *Client) NewRepository(name string, users []string, isPublic bool) (repository, error) {
	r := repository{Name: name, Users: users, IsPublic: isPublic}
	if err := c.post(r, "/repository"); err != nil {
		return repository{}, err
	}
	return r, nil
}
723252
func (c *Client) SnapshotGetRepository(repositories ...string) *SnapshotGetRepositoryService {
	return NewSnapshotGetRepositoryService(c).Repository(repositories...)
}
624104
func (s *SnapshotCreateRepositoryService) Repository(repository string) *SnapshotCreateRepositoryService {
	s.repository = repository
	return s
}
1062483
func (client NexusClient) CreateSnapshotRepository(repositoryID RepositoryID) (int, error) {
	repo := createrepo{
		Data: CreateRepoData{
			Id:                 repositoryID,
			Name:               string(repositoryID),
			Provider:           "maven2",
			RepoType:           "hosted",
			RepoPolicy:         "SNAPSHOT",
			ProviderRole:       "org.sonatype.nexus.proxy.repository.Repository",
			ContentResourceURI: client.BaseURL + "/content/repositories/" + string(repositoryID),
			Format:             "maven2",
			Browseable:         true,
			Indexable:          true,
			Exposed:            true,
			WritePolicy:        "ALLOW_WRITE",
			NotFoundCacheTTL:   1440,
		}}

	data, err := xml.Marshal(&repo)
	if err != nil {
		return 0, err
	}

	req, err := http.NewRequest("POST", client.BaseURL+"/service/local/repositories", bytes.NewBuffer(data))
	if err != nil {
		return 0, err
	}
	req.SetBasicAuth(client.Username, client.Password)
	req.Header.Add("Content-type", "application/xml")
	req.Header.Add("Accept", "application/json")

	resp, err := client.HttpClient.Do(req)
	if err != nil {
		return 0, err
	}
	defer resp.Body.Close()

	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return 0, err
	}

	if resp.StatusCode != 201 {
		return resp.StatusCode, fmt.Errorf("Client.CreateSnapshotRepository(): unexpected response status: %d (%s)\n", resp.StatusCode, string(body))
	}

	return resp.StatusCode, nil
}
328268
func Get(ctx context.Context, name string, options map[string]interface{}, repository distribution.Repository) (distribution.Repository, error) {
	if middlewares != nil {
		if initFunc, exists := middlewares[name]; exists {
			return initFunc(ctx, repository, options)
		}
	}

	return nil, fmt.Errorf("no repository middleware registered with name: %s", name)
}
782526
func (d *Deployment) GetRepositoryURL() string {
	if d == nil || d.RepositoryURL == nil {
		return ""
	}
	return *d.RepositoryURL
}
1063299
func (user *User) GetAccessibleRepositories(limit int) (repos []*Repository, _ error) {
	sess := x.Where("owner_id !=? ", user.ID).Desc("updated_unix")
	if limit > 0 {
		sess.Limit(limit)
		repos = make([]*Repository, 0, limit)
	} else {
		repos = make([]*Repository, 0, 10)
	}
	return repos, sess.Join("INNER", "access", "access.user_id = ? AND access.repo_id = repository.id", user.ID).Find(&repos)
}
258292
func (client Client) GetRepositories() (map[int]Repository, error) {
	start := 0
	repositories := make(map[int]Repository)
	morePages := true
	for morePages {
		retry := retry.New(3, retry.DefaultBackoffFunc)
		var data []byte
		work := func() error {
			req, err := http.NewRequest("GET", fmt.Sprintf("%s/rest/api/1.0/repos?start=%d&limit=%d", client.baseURL.String(), start, stashPageLimit), nil)
			if err != nil {
				return err
			}
			req.Header.Set("Accept", "application/json")
			// use credentials if we have them.  If not, the repository must be public.
			if client.userName != "" && client.password != "" {
				req.SetBasicAuth(client.userName, client.password)
			}

			var responseCode int
			responseCode, data, err = client.consumeResponse(req)
			if err != nil {
				return err
			}
			if responseCode != http.StatusOK {
				reason := "unhandled reason"
				switch {
				case responseCode == http.StatusBadRequest:
					reason = "Bad request."
				}
				return errorResponse{StatusCode: responseCode, Reason: reason}
			}
			return nil
		}
		if err := retry.Try(work); err != nil {
			return nil, err
		}

		var r Repositories
		err := json.Unmarshal(data, &r)
		if err != nil {
			return nil, err
		}
		for _, repo := range r.Repository {
			repositories[repo.ID] = repo
		}
		morePages = !r.IsLastPage
		start = r.NextPageStart
	}
	return repositories, nil
}
1362416
func (s *SnapshotDeleteRepositoryService) Repository(repositories ...string) *SnapshotDeleteRepositoryService {
	s.repository = append(s.repository, repositories...)
	return s
}
573348
func (ssa *SQLStorageAuthority) GetCertificate(ctx context.Context, serial string) (core.Certificate, error) {
	if !core.ValidSerial(serial) {
		err := fmt.Errorf("Invalid certificate serial %s", serial)
		return core.Certificate{}, err
	}

	cert, err := SelectCertificate(ssa.dbMap.WithContext(ctx), "WHERE serial = ?", serial)
	if err == sql.ErrNoRows {
		return core.Certificate{}, berrors.NotFoundError("certificate with serial %q not found", serial)
	}
	if err != nil {
		return core.Certificate{}, err
	}
	return cert, err
}
690469
func (s *DefaultService) ResolveRepository(name reference.Named) (*RepositoryInfo, error) {
	s.mu.Lock()
	defer s.mu.Unlock()
	return newRepositoryInfo(s.config, name)
}
71930
func (c *Client) GetCertAuthority(id services.CertAuthID, loadSigningKeys bool, opts ...services.MarshalOption) (services.CertAuthority, error) {
	if err := id.Check(); err != nil {
		return nil, trace.Wrap(err)
	}
	out, err := c.Get(c.Endpoint("authorities", string(id.Type), id.DomainName), url.Values{
		"load_keys": []string{fmt.Sprintf("%t", loadSigningKeys)},
	})
	if err != nil {
		return nil, trace.Wrap(err)
	}
	return services.GetCertAuthorityMarshaler().UnmarshalCertAuthority(
		out.Bytes(), services.SkipValidation())
}
381471
func (i *Installation) GetRepositorySelection() string {
	if i == nil || i.RepositorySelection == nil {
		return ""
	}
	return *i.RepositorySelection
}
927253
func getImageManifestByIDFromRegistry(registry *url.URL, repositoryName, imageID, username, password string, insecure bool) ([]byte, error) {
	ctx := context.Background()

	credentials := registryclient.NewBasicCredentials()
	credentials.Add(registry, username, password)

	insecureRT, err := rest.TransportFor(&rest.Config{TLSClientConfig: rest.TLSClientConfig{Insecure: true}})
	if err != nil {
		return nil, err
	}

	repo, err := registryclient.NewContext(http.DefaultTransport, insecureRT).
		WithCredentials(credentials).
		Repository(ctx, registry, repositoryName, insecure)
	if err != nil {
		return nil, err
	}

	manifests, err := repo.Manifests(ctx, nil)
	if err != nil {
		return nil, err
	}

	manifest, err := manifests.Get(ctx, godigest.Digest(imageID))
	if err != nil {
		return nil, err
	}
	_, manifestPayload, err := manifest.Payload()
	if err != nil {
		return nil, err
	}

	return manifestPayload, nil
}