// NewSecureChannelSession creates a new secure channel for the given card and public key.
542095
func NewSecureChannelSession(card *pcsc.Card, keyData []byte) (*SecureChannelSession, error) {
	// Generate an ECDSA keypair for ourselves
	gen := ecdh.NewEllipticECDH(crypto.S256())
	private, public, err := gen.GenerateKey(rand.Reader)
	if err != nil {
		return nil, err
	}

	cardPublic, ok := gen.Unmarshal(keyData)
	if !ok {
		return nil, fmt.Errorf("Could not unmarshal public key from card")
	}

	secret, err := gen.GenerateSharedSecret(private, cardPublic)
	if err != nil {
		return nil, err
	}

	return &SecureChannelSession{
		card:      card,
		secret:    secret,
		publicKey: gen.Marshal(public),
	}, nil
}
104482
func (e *sessionMessages) SessionMessageChannel(topics ...string) chan SessionMessage {
	e.mutex.Lock()
	defer e.mutex.Unlock()
	channelEntry := &sessionMessageChannelEntry{topics: topics, channel: make(chan SessionMessage, 16+len(e.history))}
	e.channels[channelEntry] = true
	for _, oldEvent := range e.history {
		channelEntry.emitSessionEvent(oldEvent)
	}
	return channelEntry.channel
}
925709
func (g *gossipServiceImpl) SelfChannelInfo(chain common.ChainID) *proto.SignedGossipMessage {
	ch := g.chanState.getGossipChannelByChainID(chain)
	if ch == nil {
		return nil
	}
	return ch.Self()
}
456355
func (mgr *MemorySessionManager) NewSession() (Session, error) {
	sid, err := mgr.sessionID()
	if err != nil {
		return nil, err
	}
	s := MemorySession{sid: sid, data: make(map[string]interface{}), createdAt: time.Now()}
	mgr.lock.Lock()
	mgr.sessions[sid] = &s
	mgr.lock.Unlock()
	return &s, nil
}
395431
func NewSession(config *Config) (*Session, error) {
	session := &Session{
		shutdown: make(chan struct{}),

		// Event channels, same order as api.h
		loggedIn:  make(chan error, 1),
		loggedOut: make(chan struct{}, 1),

		metadataUpdates: make(map[updatesListener]struct{}),

		connectionErrors: make(chan error, 1),
		messagesToUser:   make(chan string, 1),
		notifyMainThread: make(chan struct{}, 1),
		playTokenLost:    make(chan struct{}, 1),

		rawLogMessages: make(chan string, 128),
		logMessages:    make(chan *LogMessage, 128),

		endOfTrack:      make(chan struct{}, 1),
		streamingErrors: make(chan error, 1),

		userInfoUpdates: make(map[updatesListener]struct{}),

		offlineStatusUpdates: make(chan struct{}, 1),
		offlineErrors:        make(chan error, 1),
		credentialsBlobs:     make(chan []byte, 1),
		connectionStates:     make(chan struct{}, 1),

		scrobbleErrors:        make(chan error, 1),
		privateSessionChanges: make(chan bool, 1),

		audioConsumer: config.AudioConsumer,
	}

	if err := session.setupConfig(config); err != nil {
		return nil, err
	}

	// libspotify expects certain methods to be called from the same thread as was
	// used when the sp_session_create was called. Hence we do lock down one
	// thread to only process events and some of these special calls.
	//
	// AFAIK this is the only way we can decide which thread a given goroutine
	// executes on.
	errc := make(chan error, 1)
	go func() {
		// TODO make sure we have enough threads available
		runtime.LockOSThread()

		err := spError(C.sp_session_create(&session.config, &session.sp_session))
		errc <- err
		if err != nil {
			return
		}
		session.processEvents()
	}()

	if err := <-errc; err != nil {
		return nil, err
	}

	go session.processBackground()

	return session, nil
}
68313
func newSessionCache(proxyClient auth.ClientI, servers []utils.NetAddr, cipherSuites []uint16) (*sessionCache, error) {
	clusterName, err := proxyClient.GetClusterName()
	if err != nil {
		return nil, trace.Wrap(err)
	}
	m, err := ttlmap.New(1024, ttlmap.CallOnExpire(closeContext))
	if err != nil {
		return nil, trace.Wrap(err)
	}
	cache := &sessionCache{
		clusterName:  clusterName.GetClusterName(),
		proxyClient:  proxyClient,
		contexts:     m,
		authServers:  servers,
		closer:       utils.NewCloseBroadcaster(),
		cipherSuites: cipherSuites,
	}
	// periodically close expired and unused sessions
	go cache.expireSessions()
	return cache, nil
}
105688
func (e *sessionMessages) CloseSessionMessageChannel(channel chan SessionMessage) {
	e.mutex.Lock()
	defer e.mutex.Unlock()
	for channelEntry := range e.channels {
		if channelEntry.channel == channel {
			close(channelEntry.channel)
			delete(e.channels, channelEntry)
			break
		}
	}
}
102010
func (rootCA *RootCA) NewServerTLSCredentials(cert *tls.Certificate) (*MutableTLSCreds, error) {
	tlsConfig, err := NewServerTLSConfig([]tls.Certificate{*cert}, rootCA.Pool)
	if err != nil {
		return nil, err
	}

	mtls, err := NewMutableTLS(tlsConfig)

	return mtls, err
}
636228
func newSessionQueue(cfg *sessionQueueConfig) *sessionQueue {
	localInit := wtwire.NewInitMessage(
		lnwire.NewRawFeatureVector(wtwire.WtSessionsRequired),
		cfg.ChainHash,
	)

	towerAddr := &lnwire.NetAddress{
		IdentityKey: cfg.ClientSession.Tower.IdentityKey,
		Address:     cfg.ClientSession.Tower.Addresses[0],
	}

	sq := &sessionQueue{
		cfg:          cfg,
		commitQueue:  list.New(),
		pendingQueue: list.New(),
		localInit:    localInit,
		towerAddr:    towerAddr,
		seqNum:       cfg.ClientSession.SeqNum,
		retryBackoff: cfg.MinBackoff,
		quit:         make(chan struct{}),
		forceQuit:    make(chan struct{}),
		shutdown:     make(chan struct{}),
	}
	sq.queueCond = sync.NewCond(&sq.queueMtx)

	sq.restoreCommittedUpdates()

	return sq
}
1183674
func (sam *SAM) NewStreamSession(id string, keys I2PKeys, options []string) (*StreamSession, error) {
	conn, err := sam.newGenericSession("STREAM", id, keys, options, []string{})
	if err != nil {
		return nil, err
	}
	return &StreamSession{sam.address, id, conn, keys}, nil
}
919568
func (c *Client) NewServiceClient(path string, namespace string) *Client {
	vc := c.URL()
	u, err := url.Parse(path)
	if err != nil {
		log.Panicf("url.Parse(%q): %s", path, err)
	}
	if u.Host == "" {
		u.Scheme = vc.Scheme
		u.Host = vc.Host
	}

	client := NewClient(u, c.k)
	client.Namespace = "urn:" + namespace
	if cert := c.Certificate(); cert != nil {
		client.SetCertificate(*cert)
	}

	// Copy the trusted thumbprints
	c.hostsMu.Lock()
	for k, v := range c.hosts {
		client.hosts[k] = v
	}
	c.hostsMu.Unlock()

	// Copy the cookies
	client.Client.Jar.SetCookies(u, c.Client.Jar.Cookies(u))

	// Set SOAP Header cookie
	for _, cookie := range client.Jar.Cookies(u) {
		if cookie.Name == SessionCookieName {
			client.cookie = cookie.Value
			break
		}
	}

	// Copy any query params (e.g. GOVMOMI_TUNNEL_PROXY_PORT used in testing)
	client.u.RawQuery = vc.RawQuery

	client.UserAgent = c.UserAgent

	return client
}
962763
func NewSession(client *http.Client, authConfig *types.AuthConfig, endpoint *V1Endpoint) (*Session, error) {
	if err := authorizeClient(client, authConfig, endpoint); err != nil {
		return nil, err
	}

	return newSession(client, authConfig, endpoint), nil
}
1186192
func (p *peer) ChannelSnapshots() []*channeldb.ChannelSnapshot {
	p.activeChanMtx.RLock()
	defer p.activeChanMtx.RUnlock()

	snapshots := make([]*channeldb.ChannelSnapshot, 0, len(p.activeChannels))
	for _, activeChan := range p.activeChannels {
		// We'll only return a snapshot for channels that are
		// *immedately* available for routing payments over.
		if activeChan.RemoteNextRevocation() == nil {
			continue
		}

		snapshot := activeChan.StateSnapshot()
		snapshots = append(snapshots, snapshot)
	}

	return snapshots
}
1035355
func NewSession(host, user, passwd string, configOptions *ConfigOptions) *BigIP {
	var url string
	if !strings.HasPrefix(host, "http") {
		url = fmt.Sprintf("https://%s", host)
	} else {
		url = host
	}
	if configOptions == nil {
		configOptions = defaultConfigOptions
	}
	return &BigIP{
		Host:     url,
		User:     user,
		Password: passwd,
		Transport: &http.Transport{
			TLSClientConfig: &tls.Config{
				InsecureSkipVerify: true,
			},
		},
		ConfigOptions: configOptions,
	}
}
702438
func NewAutocommitSession(sessn *vtgatepb.Session) *SafeSession {
	newSession := proto.Clone(sessn).(*vtgatepb.Session)
	newSession.InTransaction = false
	newSession.ShardSessions = nil
	newSession.Autocommit = true
	return NewSafeSession(newSession)
}
1225018
func NewStream(source OpusReader, vc *discordgo.VoiceConnection, done chan error) *StreamingSession {
	session := &StreamingSession{
		source: source,
		vc:     vc,
		done:   done,
	}

	go session.stream()

	return session
}
875095
func newSession(maxAge int) *Session {
	uid, err := uuid.NewV4()
	if err != nil {
		panic(ErrNoSessionID)
	}
	return &Session{
		true, // is new
		internalSession{
			make(map[string]interface{}),
			uid.String(),
			time.Now(),
			time.Duration(maxAge) * time.Second,
		},
	}
}