// SSHTunnelListener creates a Listener for SSH tunnel server.
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
}
1298810
func NewTunnel(client rest.Interface, config *rest.Config, namespace, podName string, remote int) *Tunnel {
	return &Tunnel{
		config:    config,
		client:    client,
		Namespace: namespace,
		PodName:   podName,
		Remote:    remote,
		stopChan:  make(chan struct{}, 1),
		readyChan: make(chan struct{}, 1),
		Out:       ioutil.Discard,
	}
}
481810
func (t *TcpListener) tcpListen() error {
	defer t.wg.Done()

	for {
		select {
		case <-t.done:
			return nil
		default:
			// Accept connection:
			conn, err := t.listener.AcceptTCP()
			if err != nil {
				return err
			}

			select {
			case <-t.accept:
				// not over connection limit, handle the connection properly.
				t.wg.Add(1)
				// generate a random id for this TCPConn
				id := internal.RandomString(6)
				t.remember(id, conn)
				go t.handler(conn, id)
			default:
				// We are over the connection limit, refuse & close.
				t.refuser(conn)
			}
		}
	}
}
39245
func (s *reliableSender) spawnPeerHandler(peerPubKey [33]byte) (peerManager, bool) {
	s.activePeersMtx.Lock()
	defer s.activePeersMtx.Unlock()

	msgHandler, ok := s.activePeers[peerPubKey]
	if !ok {
		msgHandler = peerManager{
			msgs: make(chan lnwire.Message),
			done: make(chan struct{}),
		}
		s.activePeers[peerPubKey] = msgHandler

		s.wg.Add(1)
		go s.peerHandler(msgHandler, peerPubKey)
	}

	return msgHandler, ok
}
848669
func NewTunnelIpv4SrcField(tunnelIpSrc net.IP, tunnelIpSrcMask *net.IP) *MatchField {
	f := new(MatchField)
	f.Class = OXM_CLASS_NXM_1
	f.Field = NXM_NX_TUN_IPV4_SRC
	f.HasMask = false

	tunnelIpSrcField := new(TunnelIpv4SrcField)
	tunnelIpSrcField.TunnelIpv4Src = tunnelIpSrc
	f.Value = tunnelIpSrcField
	f.Length = uint8(tunnelIpSrcField.Len())

	// Add the mask
	if tunnelIpSrcMask != nil {
		mask := new(TunnelIpv4SrcField)
		mask.TunnelIpv4Src = *tunnelIpSrcMask
		f.Mask = mask
		f.HasMask = true
		f.Length += uint8(mask.Len())
	}

	return f
}
1266116
func NewUpdateStatusTimer() remotestate.UpdateStatusTimerFunc {
	r := rand.New(rand.NewSource(time.Now().Unix()))
	return func(wait time.Duration) remotestate.Waiter {
		// Actual time to wait is randomised to be +/-20%
		// of the nominal value.
		lower := 0.8 * float64(wait)
		window := 0.4 * float64(wait)
		offset := float64(r.Int63n(int64(window)))
		wait = time.Duration(lower + offset)

		return waitDuration(wait)
	}
}
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
}
562564
func OptEnableRunnerTLS(grpcSecurity client.GRPCSecurity) pluginRunnerOpt {
	return func(r *runner) {
		r.grpcSecurity = grpcSecurity
	}
}
1067633
func TCPListener(port int) ListenConst {
	return func() (Listener, error) {
		listener, err := net.Listen("tcp", fmt.Sprintf(":%d", port))
		if err != nil {
			return nil, fmt.Errorf("Error binding to port %d: %v", port, err.Error())
		}
		return &tcpListener{listener: listener}, nil
	}
}
535227
func TunnelAuthDialer(proxyAddr string, sshConfig *ssh.ClientConfig) auth.DialContext {
	return func(ctx context.Context, network string, addr string) (net.Conn, error) {
		// Connect to the reverse tunnel server.
		dialer := proxy.DialerFromEnvironment(proxyAddr)
		sconn, err := dialer.Dial("tcp", proxyAddr, sshConfig)
		if err != nil {
			return nil, trace.Wrap(err)
		}

		conn, err := connectProxyTransport(sconn.Conn, RemoteAuthServer)
		if err != nil {
			return nil, trace.Wrap(err)
		}
		return conn, nil
	}
}
51747
func (c *SSHTunneler) nodesSyncLoop() {
	// TODO (cjcullen) make this watch.
	go wait.Until(func() {
		addrs, err := c.getAddresses()
		klog.V(4).Infof("Calling update w/ addrs: %v", addrs)
		if err != nil {
			klog.Errorf("Failed to getAddresses: %v", err)
		}
		c.tunnels.Update(addrs)
		atomic.StoreInt64(&c.lastSync, c.clock.Now().Unix())
	}, 15*time.Second, c.stopChan)
}
235592
func NewStopListener(address string) (*StopListener, error) {
	listen, err := net.Listen("tcp", address)
	if err != nil {
		return nil, err // ### return, could not connect ###
	}

	return &StopListener{
		TCPListener: listen.(*net.TCPListener),
		active:      true,
	}, nil
}
146006
func MTLSListener(addr string, config *tls.Config) (Listener, error) {
	if config == nil {
		config = DefaultTLSConfig
	}
	ln, err := net.Listen("tcp", addr)
	if err != nil {
		return nil, err
	}

	l := &mtlsListener{
		ln:       tls.NewListener(tcpKeepAliveListener{ln.(*net.TCPListener)}, config),
		connChan: make(chan net.Conn, 1024),
		errChan:  make(chan error, 1),
	}
	go l.listenLoop()

	return l, nil
}
515732
func (s *Server) AcceptLoop(clr chan struct{}) {
	// If we were to exit before the listener is setup properly,
	// make sure we close the channel.
	defer func() {
		if clr != nil {
			close(clr)
		}
	}()

	// Snapshot server options.
	opts := s.getOpts()

	hp := net.JoinHostPort(opts.Host, strconv.Itoa(opts.Port))
	l, e := net.Listen("tcp", hp)
	if e != nil {
		s.Fatalf("Error listening on port: %s, %q", hp, e)
		return
	}
	s.Noticef("Listening for client connections on %s",
		net.JoinHostPort(opts.Host, strconv.Itoa(l.Addr().(*net.TCPAddr).Port)))

	// Alert of TLS enabled.
	if opts.TLSConfig != nil {
		s.Noticef("TLS required for client connections")
	}

	s.Noticef("Server id is %s", s.info.ID)
	s.Noticef("Server is ready")

	// Setup state that can enable shutdown
	s.mu.Lock()
	s.listener = l

	// If server was started with RANDOM_PORT (-1), opts.Port would be equal
	// to 0 at the beginning this function. So we need to get the actual port
	if opts.Port == 0 {
		// Write resolved port back to options.
		opts.Port = l.Addr().(*net.TCPAddr).Port
	}

	// Now that port has been set (if it was set to RANDOM), set the
	// server's info Host/Port with either values from Options or
	// ClientAdvertise. Also generate the JSON byte array.
	if err := s.setInfoHostPortAndGenerateJSON(); err != nil {
		s.Fatalf("Error setting server INFO with ClientAdvertise value of %s, err=%v", s.opts.ClientAdvertise, err)
		s.mu.Unlock()
		return
	}
	// Keep track of client connect URLs. We may need them later.
	s.clientConnectURLs = s.getClientConnectURLs()
	s.mu.Unlock()

	// Let the caller know that we are ready
	close(clr)
	clr = nil

	tmpDelay := ACCEPT_MIN_SLEEP

	for s.isRunning() {
		conn, err := l.Accept()
		if err != nil {
			if s.isLameDuckMode() {
				// Signal that we are not accepting new clients
				s.ldmCh <- true
				// Now wait for the Shutdown...
				<-s.quitCh
				return
			}
			tmpDelay = s.acceptError("Client", err, tmpDelay)
			continue
		}
		tmpDelay = ACCEPT_MIN_SLEEP
		s.startGoRoutine(func() {
			s.createClient(conn)
			s.grWG.Done()
		})
	}
	s.done <- true
}
918624
func CreateListener(endpoint string) (net.Listener, error) {
	protocol, addr, err := parseEndpoint(endpoint)
	if err != nil {
		return nil, err
	}

	switch protocol {
	case tcpProtocol:
		return net.Listen(tcpProtocol, addr)

	case npipeProtocol:
		return winio.ListenPipe(addr, nil)

	default:
		return nil, fmt.Errorf("only support tcp and npipe endpoint")
	}
}
838297
func newListenerUDP(port int) (*net.UDPConn, error) {
	addr := JoinHostPort("127.0.0.1", port)
	udpAddr, err := net.ResolveUDPAddr(udp, addr)
	if err != nil {
		return nil, err
	}

	ln, err := net.ListenUDP(udp, udpAddr)
	if err != nil {
		return nil, err
	}

	return ln, nil
}
409112
func (c *Client) ListenTCP(laddr *net.TCPAddr) (net.Listener, error) {
	if laddr.Port == 0 && isBrokenOpenSSHVersion(string(c.ServerVersion())) {
		return c.autoPortListenWorkaround(laddr)
	}

	m := channelForwardMsg{
		laddr.IP.String(),
		uint32(laddr.Port),
	}
	// send message
	ok, resp, err := c.SendRequest("tcpip-forward", true, Marshal(&m))
	if err != nil {
		return nil, err
	}
	if !ok {
		return nil, errors.New("ssh: tcpip-forward request denied by peer")
	}

	// If the original port was 0, then the remote side will
	// supply a real port number in the response.
	if laddr.Port == 0 {
		var p struct {
			Port uint32
		}
		if err := Unmarshal(resp, &p); err != nil {
			return nil, err
		}
		laddr.Port = int(p.Port)
	}

	// Register this forward, using the port number we obtained.
	ch := c.forwards.add(*laddr)

	return &tcpListener{laddr, c, ch}, nil
}