Exemple #1
1
func (s *Server) listenAndServeScgi(addr string) error {

	var l net.Listener
	var err error

	//if the path begins with a "/", assume it's a unix address
	if strings.HasPrefix(addr, "/") {
		l, err = net.Listen("unix", addr)
	} else {
		l, err = net.Listen("tcp", addr)
	}

	//save the listener so it can be closed
	s.l = l

	if err != nil {
		s.Logger.Println("SCGI listen error", err.Error())
		return err
	}

	for {
		fd, err := l.Accept()
		if err != nil {
			s.Logger.Println("SCGI accept error", err.Error())
			return err
		}
		go s.handleScgiRequest(fd)
	}
	return nil
}
Exemple #2
0
// Serve starts a secure echo server on the given listener.
func Serve(l net.Listener) error {
	defer l.Close()
	pub, priv, err := box.GenerateKey(rand.Reader)
	if err != nil {
		return err
	}

	for {
		rawConn, err := l.Accept()
		if err != nil {
			return err
		}
		conn := &Conn{rawConn: rawConn, pub: pub, priv: priv}
		go func(c *Conn) {
			defer c.Close()
			buf := make([]byte, 1024*32)
			n, err := c.Read(buf)
			if err != nil {
				fmt.Println(err)
			}
			got := string(buf[:n])
			log.Print(got)
			// echo the message
			n, err = c.Write([]byte(got))
			if err != nil {
				fmt.Println(err)
			}
		}(conn)
	}

}
Exemple #3
0
func (srv *Server) Serve(l net.Listener) error {
	defer l.Close()
	var tempDelay time.Duration // how long to sleep on accept failure
	for {
		rw, e := l.Accept()
		if e != nil {
			if ne, ok := e.(net.Error); ok && ne.Temporary() {
				if tempDelay == 0 {
					tempDelay = 5 * time.Millisecond
				} else {
					tempDelay *= 2
				}
				if max := 1 * time.Second; tempDelay > max {
					tempDelay = max
				}
//				srv.logf("http: Accept error: %v; retrying in %v", e, tempDelay)
				time.Sleep(tempDelay)
				continue
			}
			return e
		}
		tempDelay = 0
		c, err := srv.newConn(rw)
		if err != nil {
			continue
		}
//		c.setState(c.rwc, StateNew) // before Serve can return
		go c.serve()
	}
}
func (c *controller) acceptClientConnections(sock string, l net.Listener) {
	for {
		conn, err := l.Accept()
		if err != nil {
			if _, err1 := os.Stat(sock); os.IsNotExist(err1) {
				logrus.Debugf("Unix socket %s doesn't exist. cannot accept client connections", sock)
				return
			}
			logrus.Errorf("Error accepting connection %v", err)
			continue
		}
		go func() {
			defer conn.Close()

			err := c.processExternalKey(conn)
			ret := success
			if err != nil {
				ret = err.Error()
			}

			_, err = conn.Write([]byte(ret))
			if err != nil {
				logrus.Errorf("Error returning to the client %v", err)
			}
		}()
	}
}
func runBackendInstance(ln net.Listener, handler connHandler) {
	var tempDelay time.Duration // how long to sleep on accept failure
	for {
		conn, err := ln.Accept()
		if err != nil {
			if ne, ok := err.(net.Error); ok && ne.Temporary() {
				if tempDelay == 0 {
					tempDelay = 5 * time.Millisecond
				} else {
					tempDelay *= 2
				}
				if max := 1 * time.Second; tempDelay > max {
					tempDelay = max
				}
				fmt.Printf("http: Accept error: %v; retrying in %v\n", err, tempDelay)
				time.Sleep(tempDelay)
				continue
			}
			break
		}
		go func() {
			defer GinkgoRecover()
			handler(test_util.NewHttpConn(conn))
		}()
	}
}
Exemple #6
0
func RunServer(cfg Config) {
	memoryStore := NewStore()

	var ln net.Listener
	var err error

	if cfg.TLSEnabled() {
		ln, err = tls.Listen("tcp", ":"+cfg.Port, cfg.TLSConfig())
	} else {
		ln, err = net.Listen("tcp", ":"+cfg.Port)
	}
	if err != nil {
		log.Println("Failed to start server:", err.Error())
	}

	for {
		conn, err := ln.Accept()
		if err != nil {
			log.Println("Client failed to open new connection:", err.Error())
		}

		id, err := newUUID()
		if err != nil {
			log.Println("Failed to create unique ID for new client")
			conn.Close()
			continue
		}

		log.Printf("New connection opened clientId=%s", id)

		c := NewClient(id, conn, memoryStore)
		go c.Handle()
	}
}
Exemple #7
0
// Serve accepts incoming connections on the Listener l, creating a
// new service thread for each.  The service threads read requests and
// then call srv.Handler to reply to them.
func (srv *Server) Serve(l net.Listener) error {
	defer l.Close()
	handler := srv.Handler
	if handler == nil {
		handler = DefaultServeMux
	}

	for {
		rw, e := l.Accept()
		if e != nil {
			if ne, ok := e.(net.Error); ok && ne.Temporary() {
				log.Printf("icap: Accept error: %v", e)
				continue
			}
			return e
		}
		if srv.ReadTimeout != 0 {
			rw.SetReadDeadline(time.Now().Add(srv.ReadTimeout))
		}
		if srv.WriteTimeout != 0 {
			rw.SetWriteDeadline(time.Now().Add(srv.WriteTimeout))
		}
		c, err := newConn(rw, handler)
		if err != nil {
			continue
		}
		go c.serve()
	}
	panic("not reached")
}
func (mockLive *MockLivestatus) StartMockLivestatus() {
	var listener net.Listener
	var err error
	switch mockLive.ConnectionType {
	case "tcp":
		listener, err = net.Listen("tcp", mockLive.LivestatusAddress)
	case "file":
		listener, err = net.Listen("unix", mockLive.LivestatusAddress)
	default:
		log.Panic("ConnectionType undefined")
		return
	}

	if err != nil {
		log.Panic(err)
	}

	isRunning := true
	for isRunning {
		conn, err := listener.Accept()
		if err != nil {
			//log.Println(err)
			continue
		}
		go mockLive.handle(conn)

		mutex.Lock()
		isRunning = mockLive.isRunning
		mutex.Unlock()
	}
}
func (this *TcpServer) doAcceptTcpClients(hServer net.Listener) {
	for {
		conn, err := hServer.Accept()
		if this.beNotifiedToShutDown {
			break
		}

		this.initClientWithConnection(conn)

		if err != nil {
			//回调accept失败
			if nil != this.delegate {
				_, implemented := this.delegate.(ITcpServerDelegate)
				if implemented {
					this.delegate.TcpServerAcceptClientError(this.getClientInfoMapClient(conn), err.Error())
					break
				}
			}
		} else {

			handlerThread := this.createHandlerThread(conn)
			this.addHandlerThreadToQueue(handlerThread)
			this.setClientInfoMapConnectionThread(conn, handlerThread)

			if nil != this.delegate {
				_, implemented := this.delegate.(ITcpServerDelegate)
				if implemented {
					this.delegate.TcpServerClientConnected(this.getClientInfoMapClient(conn))
				}
			}
		}
	}
}
Exemple #10
0
// ListenAndServe services SPDY requests using the given listener.
// If the handler is nil, then http.DefaultServeMux is used.
func (srv *Server) Serve(l net.Listener) error {
	defer l.Close()
	handler := srv.Handler
	if handler == nil {
		handler = http.DefaultServeMux
	}
	for {
		fmt.Println("Spdy waiting for connections...")
		conn, err := l.Accept()
		fmt.Println("...Spdy accepted connection... %v->%v", conn.RemoteAddr(), conn.LocalAddr())
		if err != nil {
			return err
		}
		go func(c net.Conn) {
			// Echo all incoming data.
			fmt.Println("echoing data...")
			bb := new(bytes.Buffer)
			io.Copy(bb, c)
			// Shut down the connection.
			fmt.Println("spdyrequest: %s", bb.String())
			fmt.Println("closing conn...")
			c.Close()
		}(conn)
		// s, err := newSession(c, handler)
		// if err != nil {
		// return err
		// }
		// go s.serve()
	}
	/*
	 */
	return nil
}
Exemple #11
0
func dataAccept(l net.Listener, f *FtpConn) {

	conn, err := l.Accept()
	if err != nil {
		log.Fatal(err)
	}

	switch <-f.pasvChan {
	case 1: //send
		f.getFileList(conn)
		f.pasvChan <- -1
	case 2: //store
		fout, err := os.Create(filepath.Join(getRealPath(f.wd), f.fileName))
		defer fout.Close()
		if err != nil {
			log.Println(err)
			f.pasvChan <- 0
			return
		}
		io.Copy(fout, conn)
		f.pasvChan <- -2
	case 3: //retr
		fout, err := os.Open(filepath.Join(getRealPath(f.wd), f.fileName))
		defer fout.Close()
		if err != nil {
			log.Println(err)
			f.pasvChan <- 0
			return
		}
		io.Copy(conn, fout)
		f.pasvChan <- -3
	}
	conn.Close()
	l.Close()
}
Exemple #12
0
// Serve starts a secure echo server on the given listener. Sending an empty
// message will quit the server.
func Serve(l net.Listener) error {

	for {
		conn, err := l.Accept()
		if err != nil {
			return err
		}
		defer conn.Close()

		pub, priv, err := box.GenerateKey(rand.Reader)
		if err != nil {
			return err
		}

		peer, err := exchangeKeys(conn, pub)
		if err != nil {
			return err
		}
		secure := NewSecureConn(conn, priv, peer)

		// If nothing is copied then the server will end. This allows the client to
		// send an empty message to kill the server.
		if n, err := io.Copy(secure, secure); n == 0 {
			if err != nil {
				return err
			}
			return fmt.Errorf("Server ending.")
		}
	}
}
Exemple #13
0
func server(t *testing.T, listener net.Listener, connHandler ConnectionHandler, stopCh chan bool, acceptDelay time.Duration) {
	defer listener.Close()

	connCh := make(chan net.Conn, 0)
	errCh := make(chan error, 0)
	go func() {
		for {
			time.Sleep(acceptDelay)
			conn, err := listener.Accept()
			if err == nil {
				connCh <- conn
			} else {
				errCh <- err
			}
		}
	}()
AcceptLoop:
	for {
		select {
		case <-stopCh:
			break AcceptLoop
		case conn := <-connCh:
			go connHandler(t, conn)
		case err := <-errCh:
			if _, ok := <-stopCh; !ok {
				t.Error("Accept:", err.Error())
			} else {
				break AcceptLoop
			}
		}
	}
}
Exemple #14
0
/*
	Yields all accepted connections to the net.Listener on the returned Channel.
*/
func Chan(ln net.Listener, backlog int) *Netchan {
	c := &Netchan{}
	c.Accept = make(chan net.Conn, backlog)
	c.Quit = make(chan bool, 1)
	c.Listener = ln

	go func() {
		select {
		case <-c.Quit:
			close(c.Accept)

			if err := ln.Close(); err != nil {
				panic(err)
			}

			c.Quit <- true
		}
	}()

	go func() {
		for {
			conn, err := ln.Accept()

			// An error means that the listener was closed, or another event
			// happened where we can't continue listening for connections.
			if err != nil {
				return
			}

			c.Accept <- conn
		}
	}()

	return c
}
Exemple #15
0
// Serve handles connections from ln and multiplexes then across registered listener.
func (mux *Mux) Serve(ln net.Listener) error {
	mux.mu.Lock()
	mux.ln = ln
	mux.mu.Unlock()
	for {
		// Wait for the next connection.
		// If it returns a temporary error then simply retry.
		// If it returns any other error then exit immediately.
		conn, err := ln.Accept()
		if err, ok := err.(interface {
			Temporary() bool
		}); ok && err.Temporary() {
			continue
		}
		if err != nil {
			// Wait for all connections to be demux
			mux.wg.Wait()
			for _, ln := range mux.m {
				close(ln.c)
			}
			return err
		}

		// Demux in a goroutine to
		mux.wg.Add(1)
		go mux.handleConn(conn)
	}
}
func asyncAcceptTCP(serverfd net.Listener, timeout time.Duration) (net.Conn, error) {
	t := time.NewTimer(timeout)
	defer t.Stop()

	if asynctcpconn == nil {
		asynctcpconn = make(chan tcpconn, 1)
		go func() {
			connfd, err := serverfd.Accept()
			if err != nil {
				asynctcpconn <- tcpconn{err, nil}
			} else {
				asynctcpconn <- tcpconn{nil, connfd}
			}
		}()
	}

	select {
	case p := <-asynctcpconn:
		asynctcpconn = nil
		return p.fd, p.err
	case <-t.C:
		return nil, ErrTimeout
	}
	panic("Oops, unreachable")
}
Exemple #17
0
func (s *server) Run(ready chan struct{}, externalListener chan error) (err error) {
	var listener net.Listener
	o := SimpleLogOutput{}
	lf := NewSimpleLogFactory(o, nil)
	o.Info(fmt.Sprintf("Listening on port %d...", s.port))
	if listener, err = net.Listen("tcp", fmt.Sprintf("127.0.0.1:%d", s.port)); err != nil {
		return
	}
	closeListener := make(chan error)
	go func() {
		<-closeListener
		listener.Close()
	}()
	close(ready)
	for {
		var c net.Conn
		if c, err = listener.Accept(); err != nil {
			externalListener <- io.EOF
			return
		}
		xp := NewTransport(c, lf, nil)
		srv := NewServer(xp, nil)
		srv.Register(createTestProtocol(newTestProtocol(c)))
		srv.AddCloseListener(closeListener)
		srv.Run(true)
	}
	return nil
}
Exemple #18
0
func serveSingleCopy(name string, l net.Listener, dst io.Writer, src io.Reader) {
	defer l.Close()

	conn, err := l.Accept()
	if err != nil {
		log.Printf("'%s' accept error: %s", name, err)
		return
	}

	// Be sure to close the connection after we're done copying so
	// that an EOF will successfully be sent to the remote side
	defer conn.Close()

	// The connection is the destination/source that is nil
	if dst == nil {
		dst = conn
	} else {
		src = conn
	}

	written, err := io.Copy(dst, src)
	log.Printf("%d bytes written for '%s'", written, name)
	if err != nil {
		log.Printf("'%s' copy error: %s", name, err)
	}
}
Exemple #19
0
func AcceptConns(listener net.Listener, socketChan chan net.Conn, errChan chan error) {
	defer close(socketChan)
	defer close(errChan)

	var acceptDelay time.Duration
	maxDelay := 1 * time.Second

	for ok := true; ok; {
		socket, err := listener.Accept()
		if err == nil {
			acceptDelay = 0
			socketChan <- socket
			continue
		}
		if netErr, ok := err.(net.Error); ok && netErr.Temporary() {
			// Sleep on `Accept()` failures. Taken from `net/http/server.go`,
			// Copyright 2009, The Go Authors.
			if acceptDelay == 0 {
				acceptDelay = 5 * time.Millisecond
			} else {
				acceptDelay *= 2
			}
			if acceptDelay > maxDelay {
				acceptDelay = maxDelay
			}
			time.Sleep(acceptDelay)
			continue
		}
		ok = false
		errChan <- err
	}
}
Exemple #20
0
// server accepts incoming connections
func (s *ServerState) Serve(ln net.Listener) {
	// Start sending worker updates at 1Hz
	go s.sendWorkState(1)

	// Start up our auto discover server
	var a *discoveryServer
	addr := ln.Addr()
	if taddr, ok := addr.(*net.TCPAddr); ok {
		var err error

		a, err = newDiscoveryServer(taddr.Port)

		if err != nil {
			log.Print("Error starting auto-discovery", err)
			return
		}
		defer a.stop()
	}

	// Incoming connections
	for {
		DebugPrint("Server accepting...")
		conn, err := ln.Accept()
		if err != nil {
			log.Print(err)
			continue
		}

		// Turn into a message conn
		mc := NewMessageConn(conn, time.Duration(10)*time.Second)

		// Spin off thread to handle the new connection
		go s.handleConnection(mc)
	}
}
Exemple #21
0
func serve(listener net.Listener) {
	certificate, err := tls.LoadX509KeyPair("server.crt", "server.key")
	if err != nil {
		panic(err)
	}

	for {
		c, err := listener.Accept()
		if err != nil {
			log.Printf("accept: %s", err)
		}

		tlsConn := tls.Server(c, &tls.Config{
			Certificates: []tls.Certificate{certificate},
		})
		if err := tlsConn.Handshake(); err != nil {
			log.Printf("tls: %s", err)
		}

		go func() {
			io.Copy(os.Stdout, tlsConn)
			c.Close()
		}()

		go func() {
			io.Copy(tlsConn, os.Stdin)
			c.Close()
		}()
	}
}
Exemple #22
0
func (proc *requestProcessor) Listen(l net.Listener) {
	config := newConfig(proc.server)
	timeout := time.Duration(0) // how long to sleep on accept failure
	for {
		rw, err := l.Accept()
		if err != nil {
			if netErr, ok := err.(net.Error); ok && netErr.Temporary() {
				if timeout == 0 {
					timeout = 5 * time.Millisecond
				} else {
					timeout *= 2
				}
				if max := 5 * time.Second; timeout > max {
					timeout = max
				}
				log.Printf("stomp: Accept error: %v; retrying in %v", err, timeout)
				time.Sleep(timeout)
				continue
			}
			return
		}
		timeout = 0
		// TODO: need to pass Server to connection so it has access to
		// configuration parameters.
		_ = client.NewConn(config, rw, proc.ch)
	}
	// This is no longer required for go 1.1
	panic("not reached")
}
Exemple #23
0
// ListenAndServe listens on l, accepts network connections, and
// handles requests according to the doozer protocol.
func ListenAndServe(l net.Listener, canWrite chan bool, st *store.Store, p consensus.Proposer, rwsk, rosk string, self string) {
	var w bool
	for {
		c, err := l.Accept()
		if err != nil {
			if err == syscall.EINVAL {
				break
			}
			if e, ok := err.(*net.OpError); ok && !e.Temporary() {
				break
			}
			log.Println(err)
			continue
		}

		// has this server become writable?
		select {
		case w = <-canWrite:
			canWrite = nil
		default:
		}

		go serve(c, st, p, w, rwsk, rosk, self)
	}
}
Exemple #24
0
func (cl *Client) acceptConnections(l net.Listener, utp bool) {
	for {
		cl.waitAccept()
		conn, err := l.Accept()
		conn = pproffd.WrapNetConn(conn)
		if cl.closed.IsSet() {
			if conn != nil {
				conn.Close()
			}
			return
		}
		if err != nil {
			log.Print(err)
			// I think something harsher should happen here? Our accept
			// routine just f****d off.
			return
		}
		if utp {
			acceptUTP.Add(1)
		} else {
			acceptTCP.Add(1)
		}
		cl.mu.RLock()
		reject := cl.badPeerIPPort(
			missinggo.AddrIP(conn.RemoteAddr()),
			missinggo.AddrPort(conn.RemoteAddr()))
		cl.mu.RUnlock()
		if reject {
			acceptReject.Add(1)
			conn.Close()
			continue
		}
		go cl.incomingConnection(conn, utp)
	}
}
Exemple #25
0
func transponder(t *testing.T, ln net.Listener, done chan<- int) {
	defer func() { done <- 1 }()

	c, err := ln.Accept()
	if err != nil {
		t.Errorf("net.Listener.Accept failed: %v", err)
		return
	}
	c.LocalAddr()
	c.RemoteAddr()
	c.SetDeadline(time.Now().Add(100 * time.Millisecond))
	c.SetReadDeadline(time.Now().Add(100 * time.Millisecond))
	c.SetWriteDeadline(time.Now().Add(100 * time.Millisecond))
	defer c.Close()

	b := make([]byte, 128)
	n, err := c.Read(b)
	if err != nil {
		t.Errorf("net.Conn.Read failed: %v", err)
		return
	}
	if _, err := c.Write(b[:n]); err != nil {
		t.Errorf("net.Conn.Write failed: %v", err)
		return
	}
}
Exemple #26
0
// serve connections on this listener until it is closed.
func (s *Server) serve(ln net.Listener) {
	for {
		conn, err := ln.Accept()
		if err != nil {
			if !s.isClosing() {
				log.Error(err)
			}
			return
		}

		s.mu.Lock()
		s.conns[conn] = struct{}{}
		s.mu.Unlock()

		go func() {
			defer func() {
				s.mu.Lock()
				delete(s.conns, conn)
				s.mu.Unlock()
				conn.Close()
			}()

			if err := s.serveConn(conn); err != nil {
				if err != io.EOF && !s.isClosing() {
					log.Error(err)
				}
			}
		}()
	}
}
Exemple #27
0
func (srv *Server) Serve(l net.Listener) error {
	defer l.Close()
	var tempDelay time.Duration
	for {
		rw, e := l.Accept()
		if e != nil {
			if ne, ok := e.(net.Error); ok && ne.Temporary() {
				if tempDelay == 0 {
					tempDelay = 5 * time.Millisecond
				} else {
					tempDelay *= 2
				}
				if max := 1 * time.Second; tempDelay > max {
					tempDelay = max
				}
				srv.logf("smtp: Accept error: %v; retrying in %v", e, tempDelay)
				time.Sleep(tempDelay)
				continue
			}
			return e
		}
		tempDelay = 0
		c, err := srv.newConn(rw)
		if err != nil {
			continue
		}
		go c.serve()
	}
}
Exemple #28
0
func GoServe(t *testing.T, tr smux.Transport, l net.Listener) (done func()) {
	closed := make(chan struct{}, 1)

	go func() {
		for {
			c1, err := l.Accept()
			if err != nil {
				select {
				case <-closed:
					return // closed naturally.
				default:
					checkErr(t, err)
				}
			}

			log("accepted connection")
			sc1, err := tr.NewConn(c1, true)
			checkErr(t, err)
			go sc1.Serve(echoStream)
		}
	}()

	return func() {
		closed <- struct{}{}
	}
}
Exemple #29
0
// Serve accepts incoming connections on the listener lis, creating a new
// ServerTransport and service goroutine for each. The service goroutines
// read gRPC requests and then call the registered handlers to reply to them.
// Service returns when lis.Accept fails.
func (s *Server) Serve(lis net.Listener) error {
	s.mu.Lock()
	s.printf("serving")
	if s.lis == nil {
		s.mu.Unlock()
		return ErrServerStopped
	}
	s.lis[lis] = true
	s.mu.Unlock()
	defer func() {
		lis.Close()
		s.mu.Lock()
		delete(s.lis, lis)
		s.mu.Unlock()
	}()
	for {
		rawConn, err := lis.Accept()
		if err != nil {
			s.mu.Lock()
			s.printf("done serving; Accept = %v", err)
			s.mu.Unlock()
			return err
		}
		// Start a new goroutine to deal with rawConn
		// so we don't stall this Accept loop goroutine.
		go s.handleRawConn(rawConn)
	}
}
Exemple #30
0
func LoopListen(bind string, chanConn chan net.Conn) {
	var listener net.Listener
	var err error
	for {
		logf("Listen on %s", bind)
		listener, err = net.Listen("tcp", bind)
		if err != nil {
			logf(err.Error())
			time.Sleep(time.Second)
			continue
		}

		for {
			conn, err := listener.Accept()
			if err != nil {
				logf(err.Error())
				continue
			}
			go func(conn net.Conn) {
				logf("Got Connection on %s", bind)
				chanConn <- conn
			}(conn)
		}
	}

}