// NewTCPListener returns a listener that accepts authenticated encrypted connections
// using the given secretConnKey and the default timeout values.
340761
func NewTCPListener(ln net.Listener, secretConnKey ed25519.PrivKeyEd25519) *tcpListener {
	return &tcpListener{
		TCPListener:      ln.(*net.TCPListener),
		secretConnKey:    secretConnKey,
		timeoutAccept:    time.Second * defaultTimeoutAcceptSeconds,
		timeoutReadWrite: time.Second * defaultTimeoutReadWriteSeconds,
	}
}
441774
func NewListenerAddr(l net.Listener, addr string, pkfile, certfile string) (net.Listener, error) {
	cfg, err := BuildListenerConfig(addr, pkfile, certfile)
	if err != nil {
		return nil, err
	}
	return tls.NewListener(l, cfg), nil
}
935401
func (n *Net) ListenTCP(nett string, laddr *net.TCPAddr) (*net.TCPListener, error) {
	if err := n.inherit(); err != nil {
		return nil, err
	}

	n.mutex.Lock()
	defer n.mutex.Unlock()

	// look for an inherited listener
	for i, l := range n.inherited {
		if l == nil { // we nil used inherited listeners
			continue
		}
		if isSameAddr(l.Addr(), laddr) {
			n.inherited[i] = nil
			n.active = append(n.active, l)
			return l.(*net.TCPListener), nil
		}
	}

	// make a fresh listener
	l, err := net.ListenTCP(nett, laddr)
	if err != nil {
		return nil, err
	}
	n.active = append(n.active, l)
	return l, nil
}
449954
func NewTSocketFromConnTimeout(conn net.Conn, timeout time.Duration) *TSocket {
	return &TSocket{conn: conn, addr: conn.RemoteAddr(), timeout: timeout}
}
471098
func (k *KeybaseDaemonRPC) OnConnect(ctx context.Context,
	conn *rpc.Connection, rawClient rpc.GenericClient,
	server *rpc.Server) (err error) {
	k.lock.Lock()
	defer k.lock.Unlock()

	for _, p := range k.protocols {
		if err = k.registerProtocol(server, p); err != nil {
			return err
		}
	}

	// Using conn.GetClient() here would cause problematic
	// recursion.
	c := keybase1.NotifyCtlClient{Cli: rawClient}
	err = c.SetNotifications(ctx, keybase1.NotificationChannels{
		Session:       true,
		Paperkeys:     true,
		Keyfamily:     true,
		Kbfsrequest:   true,
		Reachability:  true,
		Service:       true,
		Team:          true,
		Chatkbfsedits: true,
		Favorites:     true,
	})
	if err != nil {
		return err
	}

	// Introduce ourselves. TODO: move this to SharedKeybaseConnection
	// somehow?
	configClient := keybase1.ConfigClient{Cli: rawClient}
	err = configClient.HelloIAm(ctx, keybase1.ClientDetails{
		Pid:        os.Getpid(),
		ClientType: k.config.Mode().ClientType(),
		Argv:       os.Args,
		Version:    VersionString(),
	})
	if err != nil {
		return err
	}

	// Set k.server only if err == nil.
	k.server = server

	return nil
}
355104
func SSHTunnelListener(addr string, config *SSHConfig) (Listener, error) {
	ln, err := net.Listen("tcp", addr)
	if err != nil {
		return nil, err
	}

	if config == nil {
		config = &SSHConfig{}
	}

	sshConfig := &ssh.ServerConfig{}
	sshConfig.PasswordCallback = defaultSSHPasswordCallback(config.Authenticator)
	if config.Authenticator == nil {
		sshConfig.NoClientAuth = true
	}
	tlsConfig := config.TLSConfig
	if tlsConfig == nil {
		tlsConfig = DefaultTLSConfig
	}

	signer, err := ssh.NewSignerFromKey(tlsConfig.Certificates[0].PrivateKey)
	if err != nil {
		ln.Close()
		return nil, err

	}
	sshConfig.AddHostKey(signer)

	l := &sshTunnelListener{
		Listener: tcpKeepAliveListener{ln.(*net.TCPListener)},
		config:   sshConfig,
		connChan: make(chan net.Conn, 1024),
		errChan:  make(chan error, 1),
	}

	go l.listenLoop()

	return l, nil
}
418356
func TLSListeners(tlsConfig *tls.Config) ([]net.Listener, error) {
	listeners, err := Listeners()

	if listeners == nil || err != nil {
		return nil, err
	}

	if tlsConfig != nil && err == nil {
		for i, l := range listeners {
			// Activate TLS only for TCP sockets
			if l.Addr().Network() == "tcp" {
				listeners[i] = tls.NewListener(l, tlsConfig)
			}
		}
	}

	return listeners, err
}
253802
func setupRPCListeners() ([]net.Listener, error) {
	// Setup TLS if not disabled.
	listenFunc := net.Listen
	if !cfg.DisableTLS {
		// Generate the TLS cert and key file if both don't already
		// exist.
		if !fileExists(cfg.RPCKey) && !fileExists(cfg.RPCCert) {
			err := genCertPair(cfg.RPCCert, cfg.RPCKey)
			if err != nil {
				return nil, err
			}
		}
		keypair, err := tls.LoadX509KeyPair(cfg.RPCCert, cfg.RPCKey)
		if err != nil {
			return nil, err
		}

		tlsConfig := tls.Config{
			Certificates: []tls.Certificate{keypair},
			MinVersion:   tls.VersionTLS12,
		}

		// Change the standard net.Listen function to the tls one.
		listenFunc = func(net string, laddr string) (net.Listener, error) {
			return tls.Listen(net, laddr, &tlsConfig)
		}
	}

	netAddrs, err := parseListeners(cfg.RPCListeners)
	if err != nil {
		return nil, err
	}

	listeners := make([]net.Listener, 0, len(netAddrs))
	for _, addr := range netAddrs {
		listener, err := listenFunc(addr.Network(), addr.String())
		if err != nil {
			rpcsLog.Warnf("Can't listen on %s: %v", addr, err)
			continue
		}
		listeners = append(listeners, listener)
	}

	return listeners, nil
}
781959
func H2Listener(addr string, config *tls.Config) (Listener, error) {
	ln, err := net.Listen("tcp", addr)
	if err != nil {
		return nil, err
	}
	if config == nil {
		config = DefaultTLSConfig
	}

	l := &h2Listener{
		Listener: tcpKeepAliveListener{ln.(*net.TCPListener)},
		server: &http2.Server{
			// MaxConcurrentStreams:         1000,
			PermitProhibitedCipherSuites: true,
			IdleTimeout:                  5 * time.Minute,
		},
		tlsConfig: config,
		connChan:  make(chan net.Conn, 1024),
		errChan:   make(chan error, 1),
	}
	go l.listenLoop()

	return l, nil
}
855196
func NewToken() (*Token, error) {
	id, err := utils.RandomBytes(tokenIDBytes)
	if err != nil {
		return nil, err
	}

	secret, err := utils.RandomBytes(tokenSecretBytes)
	if err != nil {
		return nil, err
	}

	return &Token{ID: id, Secret: secret}, nil
}
746940
func (process *TeleportProcess) createListener(listenerType, address string) (net.Listener, error) {
	listener, err := net.Listen("tcp", address)
	if err != nil {
		return nil, trace.Wrap(err)
	}
	process.Lock()
	defer process.Unlock()
	r := RegisteredListener{Type: listenerType, Address: address, Listener: listener}
	process.registeredListeners = append(process.registeredListeners, r)
	return listener, nil
}
345250
func NewTCPClient(uri ...string) (client *TCPClient) {
	client = new(TCPClient)
	client.initSocketClient()
	client.Linger = -1
	client.NoDelay = true
	client.KeepAlive = true
	client.setCreateConn(client.createTCPConn)
	client.SetURIList(uri)
	return
}
577367
func (s *DefaultCookieProtector) NewToken(data []byte) ([]byte, error) {
	nonce := make([]byte, cookieNonceSize)
	if _, err := rand.Read(nonce); err != nil {
		return nil, err
	}
	aead, aeadNonce, err := s.createAEAD(nonce)
	if err != nil {
		return nil, err
	}
	return append(nonce, aead.Seal(nil, aeadNonce, data, nil)...), nil
}
923010
func NewTCPMux(listener net.Listener) (mux *TCPMux, err error) {
	log.Debug("Starting TCP multiplexer")
	if listener == nil {
		return nil, fmt.Errorf("listener can not be nil")
	}
	mux = &TCPMux{
		listener:    listener,
		connections: make(chan net.Conn),
		closing:     make(chan chan error),
		log: log.WithFields(logrus.Fields{
			"address": listener.Addr(),
		}),
	}
	go mux.loop()
	mux.log.Info("Started TCP multiplexer")
	return mux, nil
}
241719
func NewToken() (*Token, error) {
	byteSecret, err := generateRandomBytes(tokenLength)
	secret := base32.StdEncoding.EncodeToString(byteSecret)
	return &Token{
		Provider: provider,
		User:     "",
		Secret:   secret,
	}, err
}
953866
func (p *Packet) NewTCPPayload(newPayload string) error {

	if p.tcpLayer.Payload != nil {
		return errors.New("payload already exists")
	}

	p.tcpLayer.Payload = []byte(newPayload)

	return nil
}
39729
func NewPublicListener(svc *connect.Service, cfg PublicListenerConfig,
	logger *log.Logger) *Listener {
	bindAddr := fmt.Sprintf("%s:%d", cfg.BindAddress, cfg.BindPort)
	return &Listener{
		Service: svc,
		listenFunc: func() (net.Listener, error) {
			return tls.Listen("tcp", bindAddr, svc.ServerTLSConfig())
		},
		dialFunc: func() (net.Conn, error) {
			return net.DialTimeout("tcp", cfg.LocalServiceAddress,
				time.Duration(cfg.LocalConnectTimeoutMs)*time.Millisecond)
		},
		bindAddr:      bindAddr,
		stopChan:      make(chan struct{}),
		listeningChan: make(chan struct{}),
		logger:        logger,
		metricPrefix:  publicListenerMetricPrefix,
		// For now we only label ourselves as source - we could fetch the src
		// service from cert on each connection and label metrics differently but it
		// significaly complicates the active connection tracking here and it's not
		// clear that it's very valuable - on aggregate looking at all _outbound_
		// connections across all proxies gets you a full picture of src->dst
		// traffic. We might expand this later for better debugging of which clients
		// are abusing a particular service instance but we'll see how valuable that
		// seems for the extra complication of tracking many gauges here.
		metricLabels: []metrics.Label{{Name: "dst", Value: svc.Name()}},
	}
}