Ejemplo n.º 1
0
func Serve(log *logging.Logger, addr string, ssl *ini.File) {
	var cmd []byte
	var ln net.Listener

	if ssl != nil {
		certificate := ssl.Section("ssl").Key("certificate").String()
		key := ssl.Section("ssl").Key("key").String()

		ln = tlsServe(log, addr, certificate, key)
		log.Debug("Opened SSL socket")
	} else {
		ln = plainServe(log, addr)
		log.Debug("Opened plain socket")
	}
	defer ln.Close()

	for {
		conn, err := ln.Accept()
		buff := bufio.NewReader(conn)

		if err != nil {
			// handle error
			log.Error("Error: %v\n", err)
		}
		log.Debug("Connection from " + conn.RemoteAddr().String() + " accepted")

		cmd, err = buff.ReadBytes('\n')
		log.Debug("Remote data readed")
		Parse(log, cmd, conn)
		conn.Close()
	}
}
Ejemplo n.º 2
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")
}
Ejemplo n.º 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()
	}
}
Ejemplo n.º 4
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)
	}
}
Ejemplo n.º 5
0
func (srv *Server) handleInterrupt(interrupt chan os.Signal, quitting chan struct{}, listener net.Listener) {
	for _ = range interrupt {
		if srv.Interrupted {
			srv.logf("already shutting down")
			continue
		}
		srv.logf("shutdown initiated")
		srv.Interrupted = true
		if srv.BeforeShutdown != nil {
			if !srv.BeforeShutdown() {
				srv.Interrupted = false
				continue
			}
		}

		close(quitting)
		srv.SetKeepAlivesEnabled(false)
		if err := listener.Close(); err != nil {
			srv.logf("[ERROR] %s", err)
		}

		if srv.ShutdownInitiated != nil {
			srv.ShutdownInitiated()
		}
	}
}
Ejemplo n.º 6
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
}
Ejemplo n.º 7
0
Archivo: server.go Proyecto: lpgo/ftp
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()
}
Ejemplo n.º 8
0
// Start network server
func (s *Server) Listen() error {
	tlsConfig, err := crypto.GetServerTlsConfig()
	if err != nil {
		return err
	}

	var listener net.Listener
	if tlsConfig != nil {
		listener, err = tls.Listen("tcp", s.address, tlsConfig)
	} else {
		listener, err = net.Listen("tcp", s.address)
		log.Println("Warning: creating a non-TLS insecure server")
	}
	if err != nil {
		return err
	}

	defer listener.Close()

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

		s.newClient(conn)
	}

	return nil
}
Ejemplo n.º 9
0
func (srv *Server) loop(l net.Listener) error {
	defer l.Close()
	var tempDelay time.Duration // how long to sleep on accept failure
	for {
		grw, 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
				}
				log.Errorf("rtmp: Accept error: %v; retrying in %v", e, tempDelay)
				time.Sleep(tempDelay)
				continue
			}
			return e
		}
		tempDelay = 0
		go serve(srv, grw)
	}
}
Ejemplo n.º 10
0
// Serve принимает входящее соединение и запускает в отдельном потоке его обработку.
func (srv *Server) Serve(l net.Listener) error {
	log.Printf("Listen %s...", srv.Addr)
	if srv.connections == nil {
		srv.connections = NewList() // инициализируем хранилище информации о соединениях
	}
	var tempDelay time.Duration // задержка до возврата ошибки
	for {
		conn, err := l.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
				}
				log.Printf("Accept error: %v; retrying in %v", err, tempDelay)
				time.Sleep(tempDelay)
				continue
			}
			l.Close()
			return err
		}
		tempDelay = 0
		go srv.servConn(conn) // запускаем обработку соединения
	}
}
Ejemplo n.º 11
0
func serverMain() {
	var ln net.Listener
	var list_err error
	//fmt.Println("Starting server...")

	tcpAddr, err := net.ResolveTCPAddr("tcp", ":8080")
	if err != nil {
		log.Println(err)
	}

	for {
		ln, list_err = net.ListenTCP("tcp", tcpAddr)
		if list_err != nil {
			log.Println(list_err)
		} else {
			break
		}
	}
	defer ln.Close()
	for {
		// accept connection on port
		conn, con_err := ln.Accept()
		if con_err != nil {
			log.Println(con_err)
			continue
		}
		go handleConnection(conn)
	}
}
Ejemplo n.º 12
0
// Run accepts incoming `quiltctl` connections and responds to them.
func Run(conn db.Conn, listenAddr string) error {
	proto, addr, err := api.ParseListenAddress(listenAddr)
	if err != nil {
		return err
	}

	var sock net.Listener
	apiServer := server{conn}
	for {
		sock, err = net.Listen(proto, addr)

		if err == nil {
			break
		}
		log.WithError(err).Error("Failed to open socket.")

		time.Sleep(30 * time.Second)
	}

	// Cleanup the socket if we're interrupted.
	sigc := make(chan os.Signal, 1)
	signal.Notify(sigc, os.Interrupt, os.Kill, syscall.SIGTERM, syscall.SIGHUP)
	go func(c chan os.Signal) {
		sig := <-c
		log.Printf("Caught signal %s: shutting down.\n", sig)
		sock.Close()
		os.Exit(0)
	}(sigc)

	s := grpc.NewServer()
	pb.RegisterAPIServer(s, apiServer)
	s.Serve(sock)

	return nil
}
Ejemplo n.º 13
0
func (w *Worker) run(listener net.Listener) {
	defer close(w.wait)
	defer listener.Close()
	server := &http.Server{Handler: http.HandlerFunc(w.handleRequest)}
	go server.Serve(listener)
	<-w.quit
}
Ejemplo n.º 14
0
func TestShutdownWaitsForJobCompletion(t *testing.T) {
	var wg sync.WaitGroup
	name := "shutdown_worker"
	var listener net.Listener

	listener, _ = makeJobAssignServer(":1337", name, "")
	defer listener.Close()

	ranJob := false
	worker := NewWorker(name, func(job Job) ([]byte, error) {
		wg.Done()
		time.Sleep(time.Duration(10 * time.Millisecond))
		ranJob = true
		return []byte{}, nil
	})
	worker.sigtermHandler = getTestSigtermHandler()

	wg.Add(1)
	go worker.Listen("localhost", "1337")
	wg.Wait()
	worker.w.Shutdown()
	if !ranJob {
		t.Error("Didn't run job")
	}
}
Ejemplo n.º 15
0
// TestJobAssign tests that the worker runs the JOB_FUNC if the server sends a 'JOB_ASSIGN' packet.
func TestJobAssign(t *testing.T) {

	name := "worker_name"
	workload := "the_workload"

	var channel chan error
	var listener net.Listener

	listener, channel = makeJobAssignServer(":1337", name, workload)
	defer listener.Close()

	worker := NewWorker(name, func(job Job) ([]byte, error) {
		if string(job.Data()) != workload {
			close(channel)
			t.Fatalf("expected workload of '%s', received '%s'", workload, string(job.Data()))
		}
		close(channel)
		return []byte{}, nil
	})
	go worker.Listen("localhost", "1337")

	for err := range channel {
		t.Fatal(err)
	}
	worker.w.Shutdown()
}
Ejemplo n.º 16
0
// Serve accepts incoming connections on the Listener l, creating a
// new service goroutine for each.  The service goroutines read requests and
// then call srv.Handler to reply to them.
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.ErrorLog.Printf("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
		}

		srv.ErrorLog.Printf("accept a connection from %v\n", c.Conn.RemoteAddr())
		go c.serve()
	}
}
Ejemplo n.º 17
0
func (srv *Server) run(lis net.Listener) {
	defer srv.tomb.Done()
	defer srv.wg.Wait() // wait for any outstanding requests to complete.
	srv.wg.Add(1)
	go func() {
		<-srv.tomb.Dying()
		lis.Close()
		srv.wg.Done()
	}()
	handler := websocket.Handler(func(conn *websocket.Conn) {
		srv.wg.Add(1)
		defer srv.wg.Done()
		// If we've got to this stage and the tomb is still
		// alive, we know that any tomb.Kill must occur after we
		// have called wg.Add, so we avoid the possibility of a
		// handler goroutine running after Stop has returned.
		if srv.tomb.Err() != tomb.ErrStillAlive {
			return
		}
		if err := srv.serveConn(conn); err != nil {
			log.Errorf("state/api: error serving RPCs: %v", err)
		}
	})
	// The error from http.Serve is not interesting.
	http.Serve(lis, handler)
}
Ejemplo n.º 18
0
func server(listener net.Listener, connHandler ConnectionHandler) {
	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
			}
		}
	}()
	for {
		select {
		case conn := <-connCh:
			go connHandler(conn)
		case err := <-errCh:
			log.Fatalln("Accept:", err.Error())
		}
	}
}
Ejemplo n.º 19
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
			}
		}
	}
}
Ejemplo n.º 20
0
func (s *server) Start() error {
	var l net.Listener
	var err error

	if s.opts.EnableTLS && s.opts.TLSConfig != nil {
		l, err = tls.Listen("tcp", s.address, s.opts.TLSConfig)
	} else {
		l, err = net.Listen("tcp", s.address)
	}
	if err != nil {
		return err
	}

	log.Infof("Listening on %s", l.Addr().String())

	s.mtx.Lock()
	s.address = l.Addr().String()
	s.mtx.Unlock()

	go http.Serve(l, s.mux)

	go func() {
		ch := <-s.exit
		ch <- l.Close()
	}()

	return nil
}
Ejemplo n.º 21
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
}
Ejemplo n.º 22
0
func (srv *Server) run(lis net.Listener) {
	defer srv.tomb.Done()
	defer srv.wg.Wait() // wait for any outstanding requests to complete.
	srv.wg.Add(1)
	go func() {
		<-srv.tomb.Dying()
		lis.Close()
		srv.wg.Done()
	}()
	srv.wg.Add(1)
	go func() {
		err := srv.mongoPinger()
		srv.tomb.Kill(err)
		srv.wg.Done()
	}()
	mux := http.NewServeMux()
	mux.HandleFunc("/", srv.apiHandler)
	mux.Handle("/log",
		&debugLogHandler{
			httpHandler: httpHandler{state: srv.state},
			logDir:      srv.logDir})
	mux.Handle("/charms",
		&charmsHandler{
			httpHandler: httpHandler{state: srv.state},
			dataDir:     srv.dataDir})
	mux.Handle("/tools",
		&toolsHandler{httpHandler{state: srv.state}})
	// The error from http.Serve is not interesting.
	http.Serve(lis, mux)
}
Ejemplo n.º 23
0
func (srv *Server) Serve(l net.Listener) error {
	l = WrapListener(l)

	// Spawn a shadow http.Server to do the actual servering. We do this
	// because we need to sketch on some of the parameters you passed in,
	// and it's nice to keep our sketching to ourselves.
	shadow := *(*http.Server)(srv)

	if shadow.ReadTimeout == 0 {
		shadow.ReadTimeout = forever
	}

	go func() {
		<-kill
		shadow.SetKeepAlivesEnabled(false)
		l.Close()
	}()

	err := shadow.Serve(l)

	// We expect an error when we close the listener, so we indiscriminately
	// swallow Serve errors when we're in a shutdown state.
	select {
	case <-kill:
		return nil
	default:
		return err
	}
}
Ejemplo n.º 24
0
func (srv *Server) supervise(l net.Listener) error {
	p, err := srv.forkExec(l)
	if err != nil {
		return err
	}
	if ServerState != nil {
		ServerState(StateStart)
	}
	c := make(chan os.Signal)
	signal.Notify(c, syscall.SIGINT, ShutdownSignal, RestartSignal)
	for {
		switch sig := <-c; sig {
		case RestartSignal:
			child, err := srv.forkExec(l)
			if err != nil {
				return err
			}
			p.Signal(ShutdownSignal)
			p.Wait()
			p = child
			if ServerState != nil {
				ServerState(StateRestart)
			}
		case syscall.SIGINT, ShutdownSignal:
			signal.Stop(c)
			l.Close()
			p.Signal(ShutdownSignal)
			_, err := p.Wait()
			if ServerState != nil {
				ServerState(StateShutdown)
			}
			return err
		}
	}
}
Ejemplo n.º 25
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
}
Ejemplo n.º 26
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)
	}

}
Ejemplo n.º 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()
	}
}
Ejemplo n.º 28
0
// TestCanDo tests that Listen properly sends a 'CAN_DO worker_name' packet to the TCP server.
func TestCanDo(t *testing.T) {

	var channel chan error
	var listener net.Listener

	name := "worker_name"

	listener, channel = makeTCPServer(":1337", func(conn net.Conn) error {
		cmd, body, err := readGearmanCommand(conn)
		if err != nil {
			return err
		}
		// 1 = CAN_DO
		if cmd != 1 {
			return fmt.Errorf("expected command 1 (CAN_DO), received command %d", cmd)
		}
		if body != "worker_name" {
			return fmt.Errorf("expected '%s', received '%s'", name, body)
		}
		close(channel)
		return nil
	})
	defer listener.Close()

	worker := NewWorker(name, func(job Job) ([]byte, error) {
		return []byte{}, nil
	})
	go worker.Listen("localhost", "1337")

	for err := range channel {
		t.Fatal(err)
	}
	worker.w.Shutdown()
}
Ejemplo n.º 29
0
Archivo: server.go Proyecto: qband/down
// 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)
	}
}
Ejemplo n.º 30
0
func (srv *Server) ListenAndServe() error {

	tcpAddr, err := net.ResolveTCPAddr("tcp", srv.host)
	var listener net.Listener

	if err != nil {
		log.Printf("error resolving address %s: %s", srv.host, err)
	} else {
		listener, err = net.Listen(tcpAddr.Network(), tcpAddr.String())
		if err != nil {
			log.Printf("error listening: %s", err)
		}
	}

	if err == nil {

		srv.Logger.Printf(LOG_STARTUP,
			"Starting server run loop, listening on %s", srv.host)

		for {
			conn, err := listener.Accept()
			if err != nil {
				log.Printf("accept error: %v", err)
			} else {
				sc := NewServerConn(srv, conn)
				go sc.serve()
			}
		}

		listener.Close()
	}
	return err
}