// NewSession creates a Rets session from the given config
506560
func NewSession(c Config) (rets.Requester, io.Closer, error) {
	// start with the default Dialer from http.DefaultTransport
	transport := wirelog.NewHTTPTransport()
	// if there is a need to proxy
	if c.Proxy != "" {
		log.Printf("Using proxy %s", c.Proxy)
		d, err := proxy.SOCKS5("tcp", c.Proxy, nil, proxy.Direct)
		if err != nil {
			return nil, nil, fmt.Errorf("rets proxy: '%s'", c.Proxy)
		}
		transport.Dial = d.Dial
	}
	var closer io.Closer
	var err error
	// wire logging
	logFile := fmt.Sprintf("/tmp/rets/wirelog/%s-%s.log", c.Service, c.User)
	closer, err = wirelog.LogToFile(transport, logFile, true, true)
	if err != nil {
		return nil, nil, fmt.Errorf("wirelog setup")
	}
	log.Printf("wire logging enabled %s", logFile)

	// should we throw an err here too?
	sess, err := rets.DefaultSession(
		c.User,
		c.Password,
		c.UserAgent,
		c.UserAgentPassword,
		c.Version,
		transport,
	)
	return sess, closer, err
}
316324
func NewSession(connection net.Conn) Session {
	s := session{
		connection: connection,
	}

	return &s
}
50432
func NewSessionBindHandle(parser *parser.Parser) *SessionHandle {
	sessionHandle := &SessionHandle{parser: parser}
	sessionHandle.ch = make(cache)
	return sessionHandle
}
469403
func NewSession(username, password, organization, url string) (*bambou.Session, *Me) {

	root := NewMe()
	url += urlpostfix

	session := bambou.NewSession(username, password, organization, url, root)

	return session, root
}
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
}
1131794
func (sp *statePersistence) NewStorage() storage.Storage {
	modelUUID := sp.st.ModelUUID()
	// TODO(ericsnow) Copy the session?
	session := sp.st.session
	store := storage.NewStorage(modelUUID, session)
	return store
}
1159142
func NewSession(opts ...Option) *Session {
	var s Session
	s.buffers = &sync.Pool{
		New: func() interface{} {
			return make([]byte, 65536)
		},
	}

	for _, opt := range opts {
		opt(&s)
	}

	if s.withIDAliasing {
		s.signatures = make(map[[sha1.Size]byte]uint16)
		s.aliases = make(map[uint16]uint16)
		s.nextID = 256
	}

	s.specifiers = make(map[uint16][]TemplateFieldSpecifier)
	s.minRecord = make(map[uint16]uint16)

	return &s
}
1308476
func NewServer(addr string, opts ...ServerOption) *Server {
	sopts := &serverOptions{}
	for _, opt := range opts {
		opt(sopts)
	}
	sopts.adjust()

	s := &Server{
		addr:        addr,
		sessionMaps: make(map[int]*sessionMap, sopts.sessionBucketSize),
		opts:        sopts,

		stopOnce: &sync.Once{},
		startCh:  make(chan struct{}, 1),
	}

	for i := 0; i < sopts.sessionBucketSize; i++ {
		s.sessionMaps[i] = &sessionMap{
			sessions: make(map[interface{}]IOSession),
		}
	}

	return s
}
839605
func NewSessionKeyPK(private *ecdsa.PrivateKey, public *ecdsa.PublicKey, salt []byte) ([]byte, error) {
	granteePubEcies := ecies.ImportECDSAPublic(public)
	privateKey := ecies.ImportECDSA(private)

	bytes, err := privateKey.GenerateShared(granteePubEcies, 16, 16)
	if err != nil {
		return nil, err
	}
	bytes = append(salt, bytes...)
	sessionKey := crypto.Keccak256(bytes)
	return sessionKey, nil
}
239390
func NewServer(cfg Config) (Server, error) {
	if err := cfg.CheckAndSetDefaults(); err != nil {
		return nil, trace.Wrap(err)
	}
	ctx, cancel := context.WithCancel(cfg.Context)
	srv := &server{
		Config:           cfg,
		localSites:       []*localSite{},
		remoteSites:      []*remoteSite{},
		localAuthClient:  cfg.LocalAuthClient,
		localAccessPoint: cfg.LocalAccessPoint,
		newAccessPoint:   cfg.NewCachingAccessPoint,
		limiter:          cfg.Limiter,
		ctx:              ctx,
		cancel:           cancel,
		clusterPeers:     make(map[string]*clusterPeers),
		Entry: log.WithFields(log.Fields{
			trace.Component: cfg.Component,
		}),
	}

	for _, clusterInfo := range cfg.DirectClusters {
		cluster, err := newlocalSite(srv, clusterInfo.Name, clusterInfo.Client)
		if err != nil {
			return nil, trace.Wrap(err)
		}

		srv.localSites = append(srv.localSites, cluster)
	}

	var err error
	s, err := sshutils.NewServer(
		teleport.ComponentReverseTunnelServer,
		// TODO(klizhentas): improve interface, use struct instead of parameter list
		// this address is not used
		utils.NetAddr{Addr: "127.0.0.1:1", AddrNetwork: "tcp"},
		srv,
		cfg.HostSigners,
		sshutils.AuthMethods{
			PublicKey: srv.keyAuth,
		},
		sshutils.SetLimiter(cfg.Limiter),
		sshutils.SetCiphers(cfg.Ciphers),
		sshutils.SetKEXAlgorithms(cfg.KEXAlgorithms),
		sshutils.SetMACAlgorithms(cfg.MACAlgorithms),
	)
	if err != nil {
		return nil, err
	}
	srv.srv = s
	go srv.periodicFunctions()
	return srv, nil
}
1092864
func newSyncServer(e *Engine) *syncServer {
	return &syncServer{
		engine:            e,
		heartbeatInterval: syncHeartbeatInterval,
		sessions:          make(map[SyncSessionID]*syncSession),
	}
}
586406
func NewSessionCipher(identityStore IdentityStore, preKeyStore PreKeyStore, signedPreKeyStore SignedPreKeyStore, sessionStore SessionStore, recipientID string, deviceID uint32) *SessionCipher {
	return &SessionCipher{
		RecipientID:  recipientID,
		DeviceID:     deviceID,
		SessionStore: sessionStore,
		PreKeyStore:  preKeyStore,
		Builder:      NewSessionBuilder(identityStore, preKeyStore, signedPreKeyStore, sessionStore, recipientID, deviceID),
	}
}
983197
func NewSessionOptions(o *SessOptions) Session {
	now := time.Now()
	idLength := o.IDLength
	if idLength <= 0 {
		idLength = 18
	}
	timeout := o.Timeout
	if timeout == 0 {
		timeout = 30 * time.Minute
	}

	sess := sessionImpl{
		IDF:       genID(idLength),
		CreatedF:  now,
		AccessedF: now,
		AttrsF:    make(map[string]interface{}),
		TimeoutF:  timeout,
		mux:       &sync.RWMutex{},
	}

	if len(o.CAttrs) > 0 {
		sess.CAttrsF = make(map[string]interface{}, len(o.CAttrs))
		for k, v := range o.CAttrs {
			sess.CAttrsF[k] = v
		}
	}

	for k, v := range o.Attrs {
		sess.AttrsF[k] = v
	}

	return &sess
}
1122628
func (c *Crowd) NewSession(user string, pass string, address string) (Session, error) {
	s := Session{}

	svf := sessionValidationFactor{Name: "remote_address", Value: address}
	sar := sessionAuthReq{Username: user, Password: pass}
	sar.ValidationFactors = append(sar.ValidationFactors, svf)

	sarEncoded, err := xml.Marshal(sar)
	if err != nil {
		return s, err
	}
	sarBuf := bytes.NewBuffer(sarEncoded)

	url := c.url + "rest/usermanagement/1/session"

	c.Client.Jar = c.cookies
	req, err := http.NewRequest("POST", url, sarBuf)
	if err != nil {
		return s, err
	}
	req.SetBasicAuth(c.user, c.passwd)
	req.Header.Set("Accept", "application/xml")
	req.Header.Set("Content-Type", "application/xml")
	resp, err := c.Client.Do(req)
	if err != nil {
		return s, err
	}
	defer resp.Body.Close()
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return s, err
	}

	switch resp.StatusCode {
	case 400:
		er := Error{}
		err = xml.Unmarshal(body, &er)
		if err != nil {
			return s, err
		}

		return s, fmt.Errorf("%s", er.Reason)
	case 201:
		err = xml.Unmarshal(body, &s)
		if err != nil {
			return s, err
		}
	default:
		return s, fmt.Errorf("request failed: %s", resp.Status)
	}

	return s, nil
}
807516
func newSyncSession(node net.IP, id SyncSessionID) *syncSession {
	return &syncSession{
		id:         id,
		node:       node,
		desync:     true,
		startTime:  time.Now(),
		expiryTime: time.Now().Add(sessionDeadtime),
		notes:      make(chan *SyncNote, sessionNotesQueueSize),
	}
}
43941
func Server(conn io.ReadWriteCloser, config *Config) (*Session, error) {
	if config == nil {
		config = DefaultConfig()
	}
	if err := VerifyConfig(config); err != nil {
		return nil, err
	}
	return newSession(config, conn, false), nil
}
712692
func (t *Tokbox) NewSession(location string, mm MediaMode, ctx ...context.Context) (*Session, error) {
	params := url.Values{}

	if len(location) > 0 {
		params.Add("location", location)
	}

	params.Add("p2p.preference", string(mm))

	var endpoint string
	if t.BetaUrl == "" {
		endpoint = apiHost
	} else {
		endpoint = t.BetaUrl
	}
	req, err := http.NewRequest("POST", endpoint+apiSession, strings.NewReader(params.Encode()))
	if err != nil {
		return nil, err
	}

	//Create jwt token
	jwt, err := t.jwtToken()
	if err != nil {
		return nil, err
	}

	req.Header.Add("Accept", "application/json")
	req.Header.Add("X-OPENTOK-AUTH", jwt)

	if len(ctx) == 0 {
		ctx = append(ctx, nil)
	}
	res, err := client(ctx[0]).Do(req)
	if err != nil {
		return nil, err
	}
	defer res.Body.Close()

	if res.StatusCode != 200 {
		return nil, fmt.Errorf("Tokbox returns error code: %v", res.StatusCode)
	}

	var s []Session
	if err = json.NewDecoder(res.Body).Decode(&s); err != nil {
		return nil, err
	}

	if len(s) < 1 {
		return nil, fmt.Errorf("Tokbox did not return a session")
	}

	o := s[0]
	o.T = t
	return &o, nil
}