// LogTLSState logs information about the TLS connection and remote peers
542442
func LogTLSState(ctx context.Context, tlsState *tls.ConnectionState) {
	if tlsState == nil {
		log.G(ctx).Debugf("no TLS Chains found")
		return
	}

	peerCerts := []string{}
	verifiedChain := []string{}
	for _, cert := range tlsState.PeerCertificates {
		peerCerts = append(peerCerts, cert.Subject.CommonName)
	}
	for _, chain := range tlsState.VerifiedChains {
		subjects := []string{}
		for _, cert := range chain {
			subjects = append(subjects, cert.Subject.CommonName)
		}
		verifiedChain = append(verifiedChain, strings.Join(subjects, ","))
	}

	log.G(ctx).WithFields(logrus.Fields{
		"peer.peerCert": peerCerts,
		// "peer.verifiedChain": verifiedChain},
	}).Debugf("")
}
1296632
func (ftp *FTP) AuthTLS(config *tls.Config) error {
	if _, err := ftp.cmd("234", "AUTH TLS"); err != nil {
		return err
	}

	// wrap tls on existing connection
	ftp.tlsconfig = config

	ftp.conn = tls.Client(ftp.conn, config)
	ftp.writer = bufio.NewWriter(ftp.conn)
	ftp.reader = bufio.NewReader(ftp.conn)

	if _, err := ftp.cmd(StatusOK, "PBSZ 0"); err != nil {
		return err
	}

	if _, err := ftp.cmd(StatusOK, "PROT P"); err != nil {
		return err
	}

	return nil
}
96715
func (b *Backend) updateState(taskState *tasks.TaskState) error {
	conn := b.open()
	defer conn.Close()

	encoded, err := json.Marshal(taskState)
	if err != nil {
		return err
	}

	_, err = conn.Do("SET", taskState.TaskUUID, encoded)
	if err != nil {
		return err
	}

	return b.setExpirationTime(taskState.TaskUUID)
}
997895
func (n *Network) PeerUserTLSDir(p *Peer, user string) string {
	return n.peerUserCryptoDir(p, user, "tls")
}
273032
func (tr *Transport) TLSClientAuthServerConfig() (*tls.Config, error) {
	cert, err := tr.getCertificate()
	if err != nil {
		return nil, err
	}

	return &tls.Config{
		Certificates: []tls.Certificate{cert},
		RootCAs:      tr.TrustStore.Pool(),
		ClientCAs:    tr.ClientTrustStore.Pool(),
		ClientAuth:   tls.RequireAndVerifyClientCert,
		CipherSuites: core.CipherSuites,
		MinVersion:   tls.VersionTLS12,
	}, nil
}
624911
func NewLogStreamState(c context.Context, id HashID) *LogStreamState {
	return &LogStreamState{Parent: ds.NewKey(c, "LogStream", string(id), 0, nil)}
}
345422
func NewTSSLSocket(hostPort string, cfg *tls.Config) (*TSSLSocket, error) {
	return NewTSSLSocketTimeout(hostPort, cfg, 0)
}
1179829
func DialWithTLSCert(network, raddr string, priority Priority, tag string, serverCert []byte) (*Writer, error) {
	pool := x509.NewCertPool()
	pool.AppendCertsFromPEM(serverCert)
	config := tls.Config{
		RootCAs: pool,
	}

	return DialWithTLSConfig(network, raddr, priority, tag, &config)
}
993623
func (set RoleSet) CheckLoginDuration(ttl time.Duration) ([]string, error) {
	logins := make(map[string]bool)
	var matchedTTL bool
	for _, role := range set {
		maxSessionTTL := role.GetOptions().MaxSessionTTL.Value()
		if ttl <= maxSessionTTL && maxSessionTTL != 0 {
			matchedTTL = true

			for _, login := range role.GetLogins(Allow) {
				logins[login] = true
			}
		}
	}
	if !matchedTTL {
		return nil, trace.AccessDenied("this user cannot request a certificate for %v", ttl)
	}
	if len(logins) == 0 {
		return nil, trace.AccessDenied("this user cannot create SSH sessions, has no allowed logins")
	}
	out := make([]string, 0, len(logins))
	for login := range logins {
		out = append(out, login)
	}
	return out, nil
}
729756
func (d *Daemon) CheckServiceTasksInState(service string, state swarm.TaskState, message string) func(*check.C) (interface{}, check.CommentInterface) {
	return func(c *check.C) (interface{}, check.CommentInterface) {
		tasks := d.GetServiceTasks(c, service)
		var count int
		for _, task := range tasks {
			if task.Status.State == state {
				if message == "" || strings.Contains(task.Status.Message, message) {
					count++
				}
			}
		}
		return count, nil
	}
}
1023361
func TLSClient(opts TLSClientOptions) (*http.Client, error) {
	transport, err := TLSTransport(opts)
	if err != nil {
		return nil, err
	}
	return &http.Client{Transport: transport}, nil
}
966421
func NewState(opts ...Options) *LState {
	var ls *LState
	if len(opts) == 0 {
		ls = newLState(Options{
			CallStackSize: CallStackSize,
			RegistrySize:  RegistrySize,
		})
		ls.OpenLibs()
	} else {
		if opts[0].CallStackSize < 1 {
			opts[0].CallStackSize = CallStackSize
		}
		if opts[0].RegistrySize < 128 {
			opts[0].RegistrySize = RegistrySize
		}
		ls = newLState(opts[0])
		if !opts[0].SkipOpenLibs {
			ls.OpenLibs()
		}
	}
	return ls
}
1266987
func WithLoginTLS(server string, name string, user string, password string, tlsConfig *tls.Config) *Bot {
	if tlsConfig == nil {
		tlsConfig = &tls.Config{}
	}
	cfg := Config{
		TLSConfig: tlsConfig,
		User:      user,
		Password:  password,
	}
	return New(server, name, cfg)
}
1121472
func NewState(c Config, lg *log.Logger, tokens *token.Store) *State {
	l := &State{
		config:               c,
		logger:               lg,
		services:             make(map[string]*ServiceState),
		checks:               make(map[types.CheckID]*CheckState),
		checkAliases:         make(map[string]map[types.CheckID]chan<- struct{}),
		metadata:             make(map[string]string),
		tokens:               tokens,
		notifyHandlers:       make(map[chan<- struct{}]struct{}),
		managedProxies:       make(map[string]*ManagedProxy),
		managedProxyHandlers: make(map[chan<- struct{}]struct{}),
	}
	l.SetDiscardCheckOutput(c.DiscardCheckOutput)
	return l
}
1095261
func (e *endpoint) completeState() stack.TCPEndpointState {
	var s stack.TCPEndpointState
	s.SegTime = time.Now()

	// Copy EndpointID.
	e.mu.Lock()
	s.ID = stack.TCPEndpointID(e.id)
	e.mu.Unlock()

	// Copy endpoint rcv state.
	e.rcvListMu.Lock()
	s.RcvBufSize = e.rcvBufSize
	s.RcvBufUsed = e.rcvBufUsed
	s.RcvClosed = e.rcvClosed
	e.rcvListMu.Unlock()

	// Endpoint TCP Option state.
	s.SendTSOk = e.sendTSOk
	s.RecentTS = e.recentTS
	s.TSOffset = e.tsOffset
	s.SACKPermitted = e.sackPermitted
	s.SACK.Blocks = make([]header.SACKBlock, e.sack.NumBlocks)
	copy(s.SACK.Blocks, e.sack.Blocks[:e.sack.NumBlocks])
	s.SACK.ReceivedBlocks, s.SACK.MaxSACKED = e.scoreboard.Copy()

	// Copy endpoint send state.
	e.sndBufMu.Lock()
	s.SndBufSize = e.sndBufSize
	s.SndBufUsed = e.sndBufUsed
	s.SndClosed = e.sndClosed
	s.SndBufInQueue = e.sndBufInQueue
	s.PacketTooBigCount = e.packetTooBigCount
	s.SndMTU = e.sndMTU
	e.sndBufMu.Unlock()

	// Copy receiver state.
	s.Receiver = stack.TCPReceiverState{
		RcvNxt:         e.rcv.rcvNxt,
		RcvAcc:         e.rcv.rcvAcc,
		RcvWndScale:    e.rcv.rcvWndScale,
		PendingBufUsed: e.rcv.pendingBufUsed,
		PendingBufSize: e.rcv.pendingBufSize,
	}

	// Copy sender state.
	s.Sender = stack.TCPSenderState{
		LastSendTime: e.snd.lastSendTime,
		DupAckCount:  e.snd.dupAckCount,
		FastRecovery: stack.TCPFastRecoveryState{
			Active:  e.snd.fr.active,
			First:   e.snd.fr.first,
			Last:    e.snd.fr.last,
			MaxCwnd: e.snd.fr.maxCwnd,
		},
		SndCwnd:          e.snd.sndCwnd,
		Ssthresh:         e.snd.sndSsthresh,
		SndCAAckCount:    e.snd.sndCAAckCount,
		Outstanding:      e.snd.outstanding,
		SndWnd:           e.snd.sndWnd,
		SndUna:           e.snd.sndUna,
		SndNxt:           e.snd.sndNxt,
		RTTMeasureSeqNum: e.snd.rttMeasureSeqNum,
		RTTMeasureTime:   e.snd.rttMeasureTime,
		Closed:           e.snd.closed,
		RTO:              e.snd.rto,
		SRTTInited:       e.snd.srttInited,
		MaxPayloadSize:   e.snd.maxPayloadSize,
		SndWndScale:      e.snd.sndWndScale,
		MaxSentAck:       e.snd.maxSentAck,
	}
	e.snd.rtt.Lock()
	s.Sender.SRTT = e.snd.rtt.srtt
	e.snd.rtt.Unlock()

	if cubic, ok := e.snd.cc.(*cubicState); ok {
		s.Sender.Cubic = stack.TCPCubicState{
			WMax:                    cubic.wMax,
			WLastMax:                cubic.wLastMax,
			T:                       cubic.t,
			TimeSinceLastCongestion: time.Since(cubic.t),
			C:                       cubic.c,
			K:                       cubic.k,
			Beta:                    cubic.beta,
			WC:                      cubic.wC,
			WEst:                    cubic.wEst,
		}
	}
	return s
}
571603
func IsInState(ctx context.Context, client client.APIClient, containerID string, state ...string) func(log poll.LogT) poll.Result {
	return func(log poll.LogT) poll.Result {
		inspect, err := client.ContainerInspect(ctx, containerID)
		if err != nil {
			return poll.Error(err)
		}
		for _, v := range state {
			if inspect.State.Status == v {
				return poll.Success()
			}
		}
		return poll.Continue("waiting for container to be one of (%s), currently %s", strings.Join(state, ", "), inspect.State.Status)
	}
}
1268957
func MonitorState(cancel <-chan struct{}, conn client.Connection, req StateRequest, check func(s *State, exists bool) bool) (*State, error) {
	logger := plog.WithFields(log.Fields{
		"hostid":     req.HostID,
		"serviceid":  req.ServiceID,
		"instanceid": req.InstanceID,
	})

	basepth := "/"
	if req.PoolID != "" {
		basepth = path.Join("/pools", req.PoolID)
	}

	// Monitor the state of the object
	done := make(chan struct{})
	defer func() { close(done) }()
	for {
		// Get the current host state and set the watch
		hspth := path.Join(basepth, "/hosts", req.HostID, "instances", req.StateID())
		hsok := true
		hsdat := &HostState{}
		hsev, err := conn.GetW(hspth, hsdat, done)
		if err == client.ErrNoNode {
			hsok = false
		} else if err != nil {
			logger.WithError(err).Debug("Could not watch host state")
			return nil, &StateError{
				Request:   req,
				Operation: "watch",
				Message:   "could not watch host state",
			}
		}

		// Get the current service state and set the watch
		sspth := path.Join(basepth, "/services", req.ServiceID, req.StateID())
		ssok := true
		ssdat := &ServiceState{}
		ssev, err := conn.GetW(sspth, ssdat, done)
		if err == client.ErrNoNode {
			ssok = false
		} else if err != nil {
			logger.WithError(err).Debug("Could not watch service state")
			return nil, &StateError{
				Request:   req,
				Operation: "watch",
				Message:   "could not watch service state",
			}
		}

		cspth := path.Join(sspth, "current")
		csok := true
		cstate := &CurrentStateContainer{}
		csev, err := conn.GetW(cspth, cstate, done)
		if err == client.ErrNoNode {
			csok = false
		} else if err != nil {
			logger.WithError(err).Debug("Could not watch service status")
			return nil, &StateError{
				Request:   req,
				Operation: "watch",
				Message:   "could not watch service status",
			}
		}

		// Ensure the nodes are compatible
		if hsok != ssok || ssok != csok {
			logger.WithFields(log.Fields{
				"hoststateexists":     hsok,
				"servicestateexists":  ssok,
				"servicestatusexists": csok,
			}).Debug("Incongruent state")
			return nil, &StateError{
				Request:   req,
				Operation: "watch",
				Message:   "incongruent state",
			}
		}
		exists := hsok && ssok && csok

		// Does the state statisfy the requirements?
		state := &State{
			HostState:             *hsdat,
			ServiceState:          *ssdat,
			CurrentStateContainer: *cstate,
			HostID:                req.HostID,
			ServiceID:             req.ServiceID,
			InstanceID:            req.InstanceID,
		}

		// Only return the state if the value is true.  Return an error if the
		// state has been deleted.
		if check(state, exists) {
			return state, nil
		} else if !exists {
			logger.Debug("State does not exist")
			return nil, &StateError{
				Request:   req,
				Operation: "watch",
				Message:   "state does not exist",
			}
		}

		// Wait for something to happen
		select {
		case <-hsev:
		case <-ssev:
		case <-csev:
		case <-cancel:
			logger.Debug("Aborted state monitor")
			return nil, nil
		}

		close(done)
		done = make(chan struct{})
	}
}