func nextproto3(s *Server, c *tls.Conn, h Handler) {
	z := new(http.Server)
	z.Addr = s.Addr
	z.Handler = s.inner_h
	z.ReadTimeout = s.ReadTimeout
	z.WriteTimeout = s.WriteTimeout
	z.MaxHeaderBytes = s.MaxHeaderBytes
	if z.Handler == nil {
		z.Handler = http.DefaultServeMux
	}
	server_session := spdy.NewServerSession(c, z)
	server_session.Serve()
}
Ejemplo n.º 2
0
func (c *conn) handleConnection(outchan chan *Session) {
	hserve := new(http.Server)
	if c.srv.Handler == nil {
		hserve.Handler = http.DefaultServeMux
	} else {
		hserve.Handler = c.srv.Handler
	}
	hserve.Addr = c.srv.Addr
	c.ss = NewServerSession(c.cn, hserve)
	if outchan != nil {
		outchan <- c.ss
	}
	c.ss.Serve()
}
Ejemplo n.º 3
0
func main() {
	port := 8080

	var srv http.Server

	router := mux.NewRouter()

	router.HandleFunc("/hello", hello)
	router.HandleFunc("/welcome", welcome)
	router.PathPrefix("/").Handler(http.FileServer(http.Dir(".")))

	srv.Addr = Sprintf(":%d", port)

	/* set the http handler */
	srv.Handler = &gpp.Handler{EnableProxy: true, Handler: router}

	/* initial http2 support */
	http2.ConfigureServer(&srv, nil)

	log.Print("Listen on: ", Sprintf("https://0.0.0.0:%d", port))
	srv.ListenAndServeTLS("server.crt", "server.key")
	if err != nil {
		log.Fatal(err)
	}
}
Ejemplo n.º 4
0
func (e *endpoint) Serve() error {
	// TODO: Currently only support single server per endpoint
	if len(e.OriginServers) > 1 {
		return errors.New("Currently only 1 origin server per endpoint is supported.")
	}

	// Create http2 server
	var srv http.Server

	// Set Port
	srv.Addr = e.Address

	// Mux setup
	router := http.NewServeMux()

	// Set mux
	srv.Handler = router

	// Set handlers
	setHandlers(router, e)

	err := http2.ConfigureServer(&srv, &http2.Server{})
	if err != nil {
		return err
	}

	log.Printf("Listening on %s", srv.Addr)
	srv.ListenAndServeTLS(e.Certs.CertFile, e.Certs.KeyFile)

	return nil
}
Ejemplo n.º 5
0
// Run the http server on a given host and port.
func (m *Martini) RunOnAddr(addr string) {
	// TODO: Should probably be implemented using a new instance of http.Server in place of
	// calling http.ListenAndServer directly, so that it could be stored in the martini struct for later use.
	// This would also allow to improve testing when a custom host and port are passed.

	logger := m.Injector.Get(reflect.TypeOf(m.logger)).Interface().(*log.Logger)
	logger.Printf("listening on %s (%s)\n", addr, Env)
	l, err := net.Listen("tcp", addr)
	if err != nil {
		logger.Fatalln(err.Error())
		return
	}
	var server http.Server
	server.Handler = m
	server.ConnState = m.connectStateChange
	m.server.l = l

	go func() {
		channel := m.server.stateChannel
		for input := range channel {
			switch input.state {
			case http.StateNew, http.StateActive, http.StateIdle:
				m.server.connsLock.Lock()
				m.server.stateMap[input.conn] = input.state
				m.server.connsLock.Unlock()
			case http.StateHijacked, http.StateClosed:
				m.server.connsLock.Lock()
				delete(m.server.stateMap, input.conn)
				m.server.connsLock.Unlock()
			}
		}
	}()
	server.Serve(l)
}
Ejemplo n.º 6
0
func (s *fakeServer) Start(readyErrCh chan error) {
	var err error
	s.Listener, err = net.Listen("tcp", s.endpoint)
	if err != nil {
		readyErrCh <- err
		return
	}

	readyErrCh <- nil

	httpServer := http.Server{}
	httpServer.SetKeepAlivesEnabled(false)
	mux := http.NewServeMux()
	httpServer.Handler = mux

	mux.HandleFunc("/fake-path", func(w http.ResponseWriter, r *http.Request) {
		w.WriteHeader(s.responseStatus)

		requestBody, _ := ioutil.ReadAll(r.Body)
		defer r.Body.Close()

		receivedRequest := receivedRequest{
			Body:   requestBody,
			Method: r.Method,
		}

		s.ReceivedRequests = append(s.ReceivedRequests, receivedRequest)
		w.Write([]byte(s.responseBody))
	})

	httpServer.Serve(s.Listener)
}
func (c *conn) serveSmart() {
	defer func() {
		if err := recover(); err != nil {
			const size = 4096
			buf := make([]byte, size)
			buf = buf[:runtime.Stack(buf, false)]
			log.Printf("http: panic serving %v: %v\n%s", c.remoteAddr, err, buf)
		}
		if !c.hijacked() {
			c.close()
		}
	}()

	if tlsConn, ok := c.rwc.(*tls.Conn); ok {
		if d := c.server.ReadTimeout; d != 0 {
			c.rwc.SetReadDeadline(time.Now().Add(d))
		}
		if d := c.server.WriteTimeout; d != 0 {
			c.rwc.SetWriteDeadline(time.Now().Add(d))
		}
		if err := tlsConn.Handshake(); err != nil {
			return
		}
		c.tlsState = new(tls.ConnectionState)
		*c.tlsState = tlsConn.ConnectionState()
		if proto := c.tlsState.NegotiatedProtocol; validNPN(proto) {
			if fn := c.server.TLSNextProto[proto]; fn != nil {
				h := initNPNRequest{tlsConn, serverHandler{c.server}}
				fn(c.server, tlsConn, h)
			}
			return
		}
	}
	initial_bytes := make([]byte, start_bytes)
	// add smart detection
	n, err := c.rwc.Read(initial_bytes)
	if err != nil || n != start_bytes {
		return
	}

	if checkspdy(initial_bytes) {
		s := c.server
		z := new(http.Server)
		z.Addr = s.Addr
		z.Handler = s.inner_h
		z.ReadTimeout = s.ReadTimeout
		z.WriteTimeout = s.WriteTimeout
		z.MaxHeaderBytes = s.MaxHeaderBytes
		server_session := spdy.NewServerSession(NewSmartConn(c.rwc, initial_bytes), z)
		server_session.Serve()
		return
	}

	c2, err := c.server.newConn(NewSmartConn(c.rwc, initial_bytes))
	if err != nil {
		return
	}
	c2.serve()
}
Ejemplo n.º 8
0
func (t *WSTunnelServer) Start(listener net.Listener) {
	t.Log.Info(VV)
	if t.serverRegistry != nil {
		return // already started...
	}
	t.serverRegistry = make(map[token]*remoteServer)
	go t.idleTunnelReaper()

	//===== HTTP Server =====

	var httpServer http.Server

	// Convert a handler that takes a tunnel as first arg to a std http handler
	wrap := func(h func(t *WSTunnelServer, w http.ResponseWriter, r *http.Request)) func(http.ResponseWriter, *http.Request) {
		return func(w http.ResponseWriter, r *http.Request) {
			h(t, w, r)
		}
	}

	// Reqister handlers with default mux
	httpMux := http.NewServeMux()
	httpMux.HandleFunc("/", wrap(payloadHeaderHandler))
	httpMux.HandleFunc("/_token/", wrap(payloadPrefixHandler))
	httpMux.HandleFunc("/_tunnel", wrap(tunnelHandler))
	httpMux.HandleFunc("/_health_check", wrap(checkHandler))
	httpMux.HandleFunc("/_stats", wrap(statsHandler))
	httpServer.Handler = httpMux
	//httpServer.ErrorLog = log15Logger // would like to set this somehow...

	// Read/Write timeouts disabled for now due to bug:
	// https://code.google.com/p/go/issues/detail?id=6410
	// https://groups.google.com/forum/#!topic/golang-nuts/oBIh_R7-pJQ
	//ReadTimeout: time.Duration(cliTout) * time.Second, // read and idle timeout
	//WriteTimeout: time.Duration(cliTout) * time.Second, // timeout while writing response

	// Now create the listener and hook it all up
	if listener == nil {
		t.Log.Info("Listening", "port", t.Port)
		laddr := fmt.Sprintf(":%d", t.Port)
		var err error
		listener, err = net.Listen("tcp", laddr)
		if err != nil {
			t.Log.Crit("Cannot listen", "addr", laddr)
			os.Exit(1)
		}
	} else {
		t.Log.Info("Listener", "addr", listener.Addr().String())
	}
	go func() {
		t.Log.Debug("Server started")
		httpServer.Serve(listener)
		t.Log.Debug("Server ended")
	}()

	go func() {
		<-t.exitChan
		listener.Close()
	}()
}
Ejemplo n.º 9
0
func NewHostRouter(httpServer *http.Server) *HostRouter {
	r := &HostRouter{
		Scheme: "http",
	}
	httpServer.Handler = r
	r.server = httpServer
	return r
}
Ejemplo n.º 10
0
func main() {

	root := flag.String("r", "./testdata", "root of the directory to serve")
	spdy_debug := flag.Bool("s", false, "enable SPDY debug output")
	flag.Parse()

	if *spdy_debug {
		// enable spdy debug messages
		spdy.EnableDebug()
	}

	for {
		const SLEEP_RETRY = 5
		var conn *tls.Conn
		var err error
		for i := 0; i < 10; i++ {
			// connect to P.
			conn, err = tls.Dial("tcp", HOST_PORT, &tls.Config{InsecureSkipVerify: true})
			if err != nil {
				time.Sleep(100 * time.Millisecond)
			} else {
				break
			}
		}
		if conn == nil {
			log.Println("Failed to connect. Waiting", SLEEP_RETRY, "seconds.")
			time.Sleep(SLEEP_RETRY * time.Second)
			continue
		}

		// build the request
		buf := new(bytes.Buffer)
		_, err = buf.WriteString("Hello from C")
		handle(err)
		req, err := http.NewRequest("PUT", "https://"+HOST_PORT, buf)
		handle(err)

		// make the client connection
		client := httputil.NewClientConn(conn, nil)
		res, err := client.Do(req)
		if err != nil {
			log.Println("Error: Failed to make connection to P:", err)
			continue
		}
		buf.Reset()
		_, err = io.Copy(buf, res.Body)
		handle(err)
		fmt.Printf("%q from P: %q.\n", res.Status, buf.String())

		c, _ := client.Hijack()
		conn = c.(*tls.Conn)
		server := new(http.Server)
		server.Handler = &handler{data: nil, rt: *root}
		//http.FileServer(http.Dir(*root))
		session := spdy.NewServerSession(conn, server)
		session.Serve()
	}
}
Ejemplo n.º 11
0
// newServeWaiter wraps srv in a serveWaiter.
func newServeWaiter(srv *http.Server) (t *serveWaiter) {
	handler := srv.Handler
	if handler == nil {
		handler = http.DefaultServeMux
	}
	t = &serveWaiter{ServeCloser: NewServeCloser(srv)}
	srv.Handler = &waitGroupHandler{srv: t, handler: handler}
	return
}
Ejemplo n.º 12
0
func (e *Echo) run(s *http.Server, files ...string) {
	s.Handler = e
	if len(files) == 0 {
		e.logger.Fatal(s.ListenAndServe())
	} else if len(files) == 2 {
		e.logger.Fatal(s.ListenAndServeTLS(files[0], files[1]))
	} else {
		e.logger.Fatal("invalid TLS configuration")
	}
}
Ejemplo n.º 13
0
/*
NewServer returns an intialized endlessServer Object. Calling Serve on it will
actually "start" the server.
*/
func NewServer(addr string, handler http.Handler) *endlessServer {
	var srv http.Server

	srv.Addr = addr
	srv.ReadTimeout = DefaultReadTimeOut
	srv.WriteTimeout = DefaultWriteTimeOut
	srv.MaxHeaderBytes = DefaultMaxHeaderBytes
	srv.Handler = handler

	return New(srv)
}
Ejemplo n.º 14
0
func (s *Http2Server) ListenAndServeTLS(config *tls.Config) error {
	srv := http.Server{
		Addr:      s.Base.Node.Addr,
		Handler:   s.Handler,
		TLSConfig: config,
	}
	if srv.Handler == nil {
		srv.Handler = http.HandlerFunc(s.HandleRequest)
	}
	http2.ConfigureServer(&srv, nil)
	return srv.ListenAndServeTLS("", "")
}
Ejemplo n.º 15
0
func (context *Context) ListenAndServeTLS(port string, certFile string, keyFile string) {
	var httpServer http.Server
	httpServer.Addr = ":" + port
	httpServer.Handler = http.HandlerFunc(serverHandler)

	go func() {
		err := httpServer.ListenAndServeTLS(certFile, keyFile)
		if err != nil {
			log.Printf("Listen error: %s", err)
		}
	}()
}
Ejemplo n.º 16
0
func (e *Echo) run(s *http.Server, files ...string) {
	s.Handler = e
	if e.http2 {
		http2.ConfigureServer(s, nil)
	}
	if len(files) == 0 {
		log.Fatal(s.ListenAndServe())
	} else if len(files) == 2 {
		log.Fatal(s.ListenAndServeTLS(files[0], files[1]))
	} else {
		log.Fatal("echo => invalid TLS configuration")
	}
}
Ejemplo n.º 17
0
func Attach(server *http.Server, opts Options) *Server {
	mux := http.NewServeMux()
	srv := NewServer(opts)
	path := getPath(opts)
	debug(fmt.Sprintf("intercepting request for path \"%s\"", path))
	mux.Handle(path, srv)
	if path != "/" {
		mux.Handle("/", server.Handler)
	}

	server.Handler = mux
	return srv
}
Ejemplo n.º 18
0
func (e *Echo) run(s *http.Server, files ...string) {
	s.Handler = e
	// TODO: Remove in Go 1.6+
	if e.http2 {
		http2.ConfigureServer(s, nil)
	}
	if len(files) == 0 {
		e.logger.Fatal(s.ListenAndServe())
	} else if len(files) == 2 {
		e.logger.Fatal(s.ListenAndServeTLS(files[0], files[1]))
	} else {
		e.logger.Fatal("invalid TLS configuration")
	}
}
func testHttpServer(t *testing.T) net.Listener {
	ln, err := net.Listen("tcp", "127.0.0.1:0")
	if err != nil {
		t.Fatalf("err: %s", err)
	}

	mux := http.NewServeMux()
	mux.HandleFunc("/header", testHttpHandlerHeader)

	var server http.Server
	server.Handler = mux
	go server.Serve(ln)

	return ln
}
Ejemplo n.º 20
0
// NewHTTPEntry returns a new HTTPEntry server
func NewHTTPEntry(host string, port int, messageQueue queue.MessageQueue) (*HTTPEntry, error) {
	h := new(HTTPEntry)

	addr := utils.Addrcat(host, port)
	server := new(http.Server)
	server.Addr = addr
	server.Handler = h

	h.host = host
	h.port = port
	h.server = server
	h.messageQueue = messageQueue

	return h, nil
}
Ejemplo n.º 21
0
func makeWebInterface(relatedNode *node) *http.Server {
	newServer := new(http.Server)
	mux := http.NewServeMux()
	mux.HandleFunc("/storage/", relatedNode.webstorage)
	mux.HandleFunc("/exit/", relatedNode.exit)
	mux.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) {
		if req.URL.Path != "/" {
			http.NotFound(w, req)
			return
		}
		fmt.Fprintf(w, "")
	})
	newServer.Addr = relatedNode.Address().IP.String() + ":" + strconv.Itoa(relatedNode.Address().Port+80)
	newServer.Handler = mux
	return newServer
}
Ejemplo n.º 22
0
// StartProxy - starts proxy with current configuration, this method is non blocking.
func (hf *Hoverfly) StartProxy() error {

	rebuildHashes(hf.RequestCache, hf.Cfg.Webserver)

	if hf.Cfg.ProxyPort == "" {
		return fmt.Errorf("Proxy port is not set!")
	}

	if hf.Cfg.Webserver {
		hf.Proxy = NewWebserverProxy(hf)
	} else {
		hf.Proxy = NewProxy(hf)
	}

	log.WithFields(log.Fields{
		"destination": hf.Cfg.Destination,
		"port":        hf.Cfg.ProxyPort,
		"mode":        hf.Cfg.GetMode(),
	}).Info("current proxy configuration")

	// creating TCP listener
	listener, err := net.Listen("tcp", fmt.Sprintf(":%s", hf.Cfg.ProxyPort))
	if err != nil {
		return err
	}

	sl, err := NewStoppableListener(listener)
	if err != nil {
		return err
	}
	hf.SL = sl
	server := http.Server{}

	hf.Cfg.ProxyControlWG.Add(1)

	go func() {
		defer func() {
			log.Info("sending done signal")
			hf.Cfg.ProxyControlWG.Done()
		}()
		log.Info("serving proxy")
		server.Handler = hf.Proxy
		log.Warn(server.Serve(sl))
	}()

	return nil
}
Ejemplo n.º 23
0
func main() {
	flag.Parse()
	docroot, err := filepath.Abs("./html")
	HandleErr(err)
	hServe := new(http.Server)
	mux := http.NewServeMux()
	mux.HandleFunc("/mapi/", proxy)
	mux.Handle("/", http.StripPrefix("/", http.FileServer(http.Dir(docroot))))
	hServe.Handler = mux
	hServe.Addr = ":" + strconv.Itoa(*port)

	//":"+strconv.Itoa(*port),http.FileServer(http.Dir(docroot)) )
	log.Notice("server running at %s:%d. CTRL + C to shutdown\n", "http://localhost", *port)
	err = hServe.ListenAndServe()
	HandleErr(err)

}
Ejemplo n.º 24
0
func main() {

	err := database.Connect()
	if err != nil {
		log.Fatal(err)
	}

	addr := os.Getenv("LISTEN")
	if addr == "" {
		addr = "0.0.0.0:8443"
	}

	if os.Getenv("DEBUG") == "true" {
		log.SetLevel(log.DebugLevel)
	}

	var cert tls.Certificate

	if certName == "" {
		log.Info("Generating self-signed certificate")
		cert, err = GenCert()
	} else {
		log.Info("Using certificate from vault")
		cert, err = GetNutcrackerCert()
	}
	if err != nil {
		log.Fatal(err)
	}

	sock, err := Socket(addr, cert)
	if err != nil {
		log.Fatal(err)
	}

	r := mux.NewRouter()
	addRoutes(r)

	server := new(http.Server)
	server.ErrorLog = new(stdLog.Logger)
	server.ErrorLog.SetOutput(ioutil.Discard)
	server.Addr = addr
	server.Handler = context.ClearHandler(r)
	log.Infof("HTTPS server listening on: %s", addr)
	server.Serve(sock)
}
Ejemplo n.º 25
0
func (s *stat) Run(addr string) {
	if len(addr) == 0 {
		return
	}
	log.Infof("run status http server %s", addr)
	var err error
	s.l, err = net.Listen("tcp", addr)
	if err != nil {
		log.Errorf("listen stat addr %s err %v", addr, err)
		return
	}

	srv := http.Server{}
	mux := http.NewServeMux()
	mux.Handle("/stat", s)
	srv.Handler = mux

	srv.Serve(s.l)
}
Ejemplo n.º 26
0
// Test network updates, very similar to TestMockRootfs, but using network as
// the transport for the image.
func TestNetworkRootfs(t *testing.T) {
	prepareMockDevices(t)
	defer cleanupMockDevices()

	var server http.Server

	server.Handler = http.FileServer(http.Dir("."))
	addr := ":" + testPortString
	listen, err := net.Listen("tcp", addr)
	mt.AssertNoError(t, err)

	defer listen.Close()
	go server.Serve(listen)

	// Do this test twice, once with a valid update, and once with a too
	// short/broken update.
	for _, mode := range []int{0, os.O_TRUNC}[:] {
		executeNetworkTest(t, mode)
	}
}
Ejemplo n.º 27
0
func (s *server) start(username string, password string, host string, port int, readyErrCh chan error) error {
	s.logger.Debug(s.logTag, "Starting registry server at %s:%d", host, port)
	var err error
	s.listener, err = net.Listen("tcp", fmt.Sprintf("%s:%d", host, port))
	if err != nil {
		readyErrCh <- bosherr.WrapError(err, "Starting registry listener")
		return nil
	}

	readyErrCh <- nil

	httpServer := http.Server{}
	mux := http.NewServeMux()
	httpServer.Handler = mux

	registry := NewRegistry()
	instanceHandler := newInstanceHandler(username, password, registry, s.logger)
	mux.HandleFunc("/instances/", instanceHandler.HandleFunc)

	return httpServer.Serve(s.listener)
}
Ejemplo n.º 28
0
// NewUnitedAdmin returns a UnitedAdmin
func NewUnitedAdmin(host string, port int, messageQueue queue.MessageQueue) (*UnitedAdmin, error) {
	s := new(UnitedAdmin)

	s.adminMux = map[string]func(http.ResponseWriter, *http.Request, string){
		"/stat":  s.statHandler,
		"/empty": s.emptyHandler,
		"/rm":    s.rmHandler,
	}

	addr := utils.Addrcat(host, port)
	server := new(http.Server)
	server.Addr = addr
	server.Handler = s

	s.host = host
	s.port = port
	s.server = server
	s.messageQueue = messageQueue

	return s, nil
}
Ejemplo n.º 29
0
// UpgradeServer operates similarly to ConfigureServer() with the exception that
// it returns a clone copy of the original server that will be used to
// exclusively serve HTTP/1.1 and HTTP/1.0 requests. The "HTTP/2 Configured"
// server passed to UpgradeServer() should not be modified once this call has
// been made, nor should it actively be listening for new connections.
//
// When an existing HTTP/1.1 connection requests an upgrade to h2c or h2c-14 mode,
// the connection will be hijacked from the "clone server" (as returned by
// UpgradeServer() and handed off to the internal http2 configured server.
//
// Ex usage:
//
// http.HandleFunc("/", func(rw http.ResponseWriter, r *http.Request) {
// 				rw.Header().Set("Content-Type", "text/plain")
// 				fmt.Fprintf(rw, "response to %v\n", r)
// })
//
// s := http2.UpgradeServer(&http.Server{Addr:":8080"},nil)
// s.ListenAndServe()
//
// NB: Do *not* alter the returned server's Handler, as it is hooked in order to
// perform the protocol switch. Any changes to uri handling must be made in the
// "inner" server *before* it is passed to UpgradeServer(). The standard
// http.DefaultServeMux will always be used as a last resort.
//
// NB: Note that HTTP/1.1 requests with bodies (i.e. HTTP POST) are not
// supported in the initial Upgrade request but will work once the connection
// is fully HTTP/2. Requests that have content entities will automatically
// fallback to HTTP/1.1 (the upgrade silently fails but the normal handler
// is invoked).
func UpgradeServer(s *http.Server, conf *Server) *http.Server {
	if conf == nil {
		conf = new(Server)
	}

	handler := s.Handler
	if handler == nil {
		handler = http.DefaultServeMux
	}

	h1s := new(http.Server)
	*h1s = *s
	h1s.TLSConfig = nil
	h1s.TLSNextProto = nil
	h1s.Handler = &upgradeMux{
		handler: handler,
		srv:     s,
		conf:    conf,
	}

	ConfigureServer(s, conf)
	return h1s
}
Ejemplo n.º 30
0
func newTestAtlasServer(t *testing.T) *atlasServer {
	hs := &atlasServer{t: t}

	ln, err := net.Listen("tcp", ":0")
	if err != nil {
		t.Fatal(err)
	}
	hs.ln = ln

	hs.URL = &url.URL{
		Scheme: "http",
		Host:   ln.Addr().String(),
	}

	mux := http.NewServeMux()
	hs.setupRoutes(mux)

	var server http.Server
	server.Handler = mux
	hs.server = server
	go server.Serve(ln)

	return hs
}