// Listen starts listening on the given host:port addr.
495814
func (s *Server) Listen(addr string) error {
	if s.listener != nil {
		return nil
	}

	if addr == "" {
		return fmt.Errorf("<host>:<port> needs to be provided to start listening")
	}

	var err error
	s.listener, err = listen.Listen(addr)
	if err != nil {
		return fmt.Errorf("Failed to listen on %s: %v", addr, err)
	}
	base := s.ListenURL()
	s.printf("Starting to listen on %s\n", base)

	doEnableTLS := func() error {
		config := &tls.Config{
			Rand:       rand.Reader,
			Time:       time.Now,
			NextProtos: []string{http2.NextProtoTLS, "http/1.1"},
			MinVersion: tls.VersionTLS12,
		}
		if s.tlsCertFile == "" && s.certManager != nil {
			config.GetCertificate = s.certManager
			// TODO(mpl): see if we can instead use
			// https://godoc.org/golang.org/x/crypto/acme/autocert#Manager.TLSConfig
			config.NextProtos = append(config.NextProtos, alpnProto)
			s.listener = tls.NewListener(s.listener, config)
			return nil
		}

		config.Certificates = make([]tls.Certificate, 1)
		config.Certificates[0], err = loadX509KeyPair(s.tlsCertFile, s.tlsKeyFile)
		if err != nil {
			return fmt.Errorf("Failed to load TLS cert: %v", err)
		}
		s.listener = tls.NewListener(s.listener, config)
		return nil
	}
	if s.enableTLS {
		if err := doEnableTLS(); err != nil {
			return err
		}
	}

	if strings.HasSuffix(base, ":0") {
		s.printf("Now listening on %s\n", s.ListenURL())
	}

	return nil
}
883262
func Listen(host string, port int, ciphers []string) {
	config := &ssh.ServerConfig{
		Config: ssh.Config{
			Ciphers: ciphers,
		},
		PublicKeyCallback: func(conn ssh.ConnMetadata, key ssh.PublicKey) (*ssh.Permissions, error) {
			pkey, err := models.SearchPublicKeyByContent(strings.TrimSpace(string(ssh.MarshalAuthorizedKey(key))))
			if err != nil {
				log.Error(3, "SearchPublicKeyByContent: %v", err)
				return nil, err
			}
			return &ssh.Permissions{Extensions: map[string]string{"key-id": com.ToStr(pkey.ID)}}, nil
		},
	}

	keyPath := filepath.Join(setting.AppDataPath, "ssh/gogs.rsa")
	if !com.IsExist(keyPath) {
		os.MkdirAll(filepath.Dir(keyPath), os.ModePerm)
		_, stderr, err := com.ExecCmd(setting.SSH.KeygenPath, "-f", keyPath, "-t", "rsa", "-m", "PEM", "-N", "")
		if err != nil {
			panic(fmt.Sprintf("Fail to generate private key: %v - %s", err, stderr))
		}
		log.Trace("SSH: New private key is generateed: %s", keyPath)
	}

	privateBytes, err := ioutil.ReadFile(keyPath)
	if err != nil {
		panic("SSH: Fail to load private key: " + err.Error())
	}
	private, err := ssh.ParsePrivateKey(privateBytes)
	if err != nil {
		panic("SSH: Fail to parse private key: " + err.Error())
	}
	config.AddHostKey(private)

	go listen(config, host, port)
}
977479
func (l TCPListener) Listen() (net.Listener, error) {
	return net.FileListener(os.NewFile(l.Fd(), fmt.Sprintf("%s:%d", l.Addr, l.Port)))
}
962276
func (a *App) Listen() error {
	a.prepareStatic()

	http.Handle("/", a.router)

	// Starts listening.
	return http.ListenAndServe(a.Config.ListenAddr, nil)
}
1182484
func (c *Config) Listener(proto, addr string, port int) (net.Listener, error) {
	if addr == "" {
		addr = c.BindAddr
	}

	// Do our own range check to avoid bugs in package net.
	//
	//   golang.org/issue/11715
	//   golang.org/issue/13447
	//
	// Both of the above bugs were fixed by golang.org/cl/12447 which will be
	// included in Go 1.6. The error returned below is the same as what Go 1.6
	// will return.
	if 0 > port || port > 65535 {
		return nil, &net.OpError{
			Op:  "listen",
			Net: proto,
			Err: &net.AddrError{Err: "invalid port", Addr: fmt.Sprint(port)},
		}
	}
	return net.Listen(proto, net.JoinHostPort(addr, strconv.Itoa(port)))
}
859127
func (p *AuthProxy) Listen() error {
	mux := bone.New()
	proxy := &httputil.ReverseProxy{
		Transport: p.t,
		Director: func(r *http.Request) {
			r.URL.Scheme = p.u.Scheme
			r.URL.Host = p.u.Host
			r.Host = p.u.Host
			r.URL.Path = r.URL.Path[6:]

			if p.sess.HasToken() {
				tok := string(p.sess.Token())
				r.Header["Authorization"] = []string{"Bearer " + tok}
			}

			r.Header["User-Agent"] = []string{"Torus-Daemon/" + p.c.Version}
			r.Header["X-Registry-Version"] = []string{p.c.APIVersion}
		},
	}

	go p.o.Start()

	mux.HandleFunc("/proxy/", proxyCanceler(proxy))
	mux.SubRoute("/v1", routes.NewRouteMux(p.c, p.sess, p.db, p.t, p.o, p.client, p.logic, p.updates))

	h := httpdown.HTTP{}
	p.s = h.Serve(&http.Server{Handler: requestIDHandler(loggingHandler(mux))}, p.l)

	return p.s.Wait()
}
861643
func (s *Server) listen(listener net.Listener) {
	for {
		// Accept a connection
		conn, err := listener.Accept()
		if err != nil {
			if s.shutdown {
				return
			}
			s.logger.Printf("[ERR] consul.rpc: failed to accept RPC conn: %v", err)
			continue
		}

		go s.handleConn(conn, false)
		metrics.IncrCounter([]string{"rpc", "accept_conn"}, 1)
	}
}
699161
func Listen(c chan<- Operation) {
	dummy.mu.Lock()
	defer dummy.mu.Unlock()
	if c == nil {
		c = discardOperations
	}
	dummy.ops = c
	for _, st := range dummy.state {
		st.mu.Lock()
		st.ops = c
		st.mu.Unlock()
	}
}
286644
func (s *HTTPScaffold) Listen(baseHandler http.Handler) error {
	err := s.StartListen(baseHandler)
	if err != nil {
		return err
	}

	return s.WaitForShutdown()
}
757329
func (s *ServerHTTPS) Listen() (net.Listener, error) {

	l, err := net.Listen("tcp", s.Addr[len(transport.HTTPS+"://"):])
	if err != nil {
		return nil, err
	}
	return l, nil
}
803546
func (client *Client) Listen(socketDefinition protocol.SocketDefinition) (net.Listener, error) {
	// connect to the socket master
	conn, err := net.Dial("tcp", client.socketMasterAddress)
	if err != nil {
		return nil, err
	}

	// bind to a port
	err = protocol.WriteHandshakeRequest(conn, protocol.HandshakeRequest{
		SocketDefinition: socketDefinition,
	})
	if err != nil {
		conn.Close()
		return nil, err
	}

	// see if that worked
	res, err := protocol.ReadHandshakeResponse(conn)
	if err != nil {
		conn.Close()
		return nil, err
	}
	if res.Status != "OK" {
		conn.Close()
		return nil, fmt.Errorf("%s", res.Status)
	}

	// start a new session
	session, err := yamux.Server(conn, yamux.DefaultConfig())
	if err != nil {
		conn.Close()
		return nil, err
	}

	return session, nil
}
1072372
func (pf *PortForwarder) listenOnPort(port *ForwardedPort) error {
	errTcp4 := pf.listenOnPortAndAddress(port, "tcp4", "127.0.0.1")
	errTcp6 := pf.listenOnPortAndAddress(port, "tcp6", "[::1]")
	if errTcp4 != nil && errTcp6 != nil {
		return fmt.Errorf("All listeners failed to create with the following errors: %s, %s", errTcp4, errTcp6)
	}
	return nil
}
1116596
func (m *Mux) Listen(a string, statefns ...func(net.Conn, http.ConnState)) error {
	l, err := net.Listen("tcp", a)
	if err != nil {
		return err
	}

	listener := ninjaListener{
		Listener: l,
	}

	m.listener = listener
	m.Port = listener.Addr().(*net.TCPAddr).Port

	//state := make(chan http.ConnState)

	srv := &http.Server{
		Handler: m,
		Addr:    a,
		ConnState: func(conn net.Conn, state http.ConnState) {
			switch state {
			case http.StateNew:
				m.activeConnection(conn)
			case http.StateActive:
				m.activeConnection(conn)
			case http.StateIdle:
				m.idleConnection(conn)
			case http.StateClosed, http.StateHijacked:
				m.removeConnection(conn)
			}
			for _, connstate := range statefns {
				connstate(conn, state)
			}
		},
	}

	m.Opened(m)

	err = srv.Serve(listener)

	return err
}
519066
func (c *Collector) Listen(port int) error {
	var err error
	c.ln, err = net.Listen("tcp", ":"+strconv.Itoa(port))
	return err
}
353294
func (db *DB) Listen(channels ...string) *Listener {
	ln := &Listener{
		db: db,
	}
	ln.init()
	_ = ln.Listen(channels...)
	return ln
}
885423
func Listen() {
	//we're listening on all interfaces on chosen port
	connString := ":" + Me().GetPortString()
	udpAddress, err := net.ResolveUDPAddr("udp", connString)
	if err != nil {
		Logln("Incorrect connection string", err)
		panic(err)
	}
	conn, err := net.ListenUDP("udp", udpAddress)
	conn.SetReadBuffer(8192)
	if err != nil {
		Logln("Cannot start listening", err)
		panic(err)
	}
	Logln("Starting listening on port", Me().GetPortString())
	for i := 0; i < MAX_MESSAGE_HANDLERS; i++ {
		go messageHandler()
	}
	for i := 0; i < MAX_MESSAGE_SENDERS; i++ {
		go messageSender()
	}
	Me().SetState(STATE_READY)
	for {
		buffer := make([]byte, 4096)
		count, addr, err := conn.ReadFromUDP(buffer)
		if err != nil {
			Logln("Connection error", err)
		}
		if count > 0 {
			messagesIn <- netData{
				addr: addr,
				data: buffer[0:count],
			}
		}
		//time.Sleep(1 * time.Second)
	}
	conn.Close()
}
919236
func (s *Swarm) Listen(addrs ...ma.Multiaddr) error {
	errs := make([]error, len(addrs))
	var succeeded int
	for i, a := range addrs {
		if err := s.AddListenAddr(a); err != nil {
			errs[i] = err
		} else {
			succeeded++
		}
	}

	for i, e := range errs {
		if e != nil {
			log.Warningf("listen on %s failed: %s", addrs[i], errs[i])
		}
	}

	if succeeded == 0 && len(addrs) > 0 {
		return fmt.Errorf("failed to listen on any addresses: %s", errs)
	}

	return nil
}