// serveFromDiskOrStatic matches rx against req's path and serves the match either from disk (if non-nil) or from static (embedded in the binary).
483521
func (ui *UIHandler) serveFromDiskOrStatic(rw http.ResponseWriter, req *http.Request, rx *regexp.Regexp, disk http.Handler, static *fileembed.Files) {
	suffix := httputil.PathSuffix(req)
	m := rx.FindStringSubmatch(suffix)
	if m == nil {
		panic("Caller should verify that rx matches")
	}
	file := m[1]
	if disk != nil {
		req.URL.Path = "/" + file
		disk.ServeHTTP(rw, req)
	} else {
		ServeStaticFile(rw, req, static, file)
	}

}
76086
func (srv *Server) Serve(l net.Listener) error {
	// 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)
	shadow.ConnState = connState(shadow.ConnState).Wrap

	l = gracefulServer{l, &shadow}
	wrap := listener.Wrap(l, listener.Automatic)
	appendListener(wrap)

	err := shadow.Serve(wrap)
	return peacefulError(err)
}
1071042
func (s *Server) serve(ctx context.Context, l net.Listener, wg *sync.WaitGroup, secret []byte) error {
	if s.testingServeHook != nil {
		s.testingServeHook()
	}
	srv := http.Server{
		Handler: &protocolHandler{
			ctx:    ctx,
			wg:     wg,
			secret: secret,
			tokens: s.TokenGenerators,
		},
	}
	return srv.Serve(l)
}
924763
func (srv *Server) Serve() error {
	if srv.Protocol == 1 {
		return Serve1(srv.Host, srv.router(), srv.Timeout)
	}
	return Serve(srv.Host, srv.router(), srv.Timeout)
}
429431
func Static(opts ...StaticOptions) HandlerFunc {
	return func(ctx *Context) {
		if ctx.Req().Method != "GET" && ctx.Req().Method != "HEAD" {
			ctx.Next()
			return
		}

		opt := prepareStaticOptions(opts)

		var rPath = ctx.Req().URL.Path
		// if defined prefix, then only check prefix
		if opt.Prefix != "" {
			if !strings.HasPrefix(ctx.Req().URL.Path, opt.Prefix) {
				ctx.Next()
				return
			}

			if len(opt.Prefix) == len(ctx.Req().URL.Path) {
				rPath = ""
			} else {
				rPath = ctx.Req().URL.Path[len(opt.Prefix):]
			}
		}

		f, err := opt.FileSystem.Open(strings.TrimLeft(rPath, "/"))
		if err != nil {
			if os.IsNotExist(err) {
				if opt.Prefix != "" {
					ctx.Result = NotFound()
				} else {
					ctx.Next()
					return
				}
			} else {
				ctx.Result = InternalServerError(err.Error())
			}
			ctx.HandleError()
			return
		}
		defer f.Close()

		finfo, err := f.Stat()
		if err != nil {
			ctx.Result = InternalServerError(err.Error())
			ctx.HandleError()
			return
		}

		if !finfo.IsDir() {
			if len(opt.FilterExts) > 0 && !opt.IsFilterExt(rPath) {
				ctx.Next()
				return
			}

			http.ServeContent(ctx, ctx.Req(), finfo.Name(), finfo.ModTime(), f)
			return
		}

		// try serving index.html or index.htm
		if len(opt.IndexFiles) > 0 {
			for _, index := range opt.IndexFiles {
				fi, err := opt.FileSystem.Open(strings.TrimLeft(path.Join(rPath, index), "/"))
				if err != nil {
					if !os.IsNotExist(err) {
						ctx.Result = InternalServerError(err.Error())
						ctx.HandleError()
						return
					}
				} else {
					finfo, err = fi.Stat()
					if err != nil {
						fi.Close()
						ctx.Result = InternalServerError(err.Error())
						ctx.HandleError()
						return
					}
					if !finfo.IsDir() {
						http.ServeContent(ctx, ctx.Req(), finfo.Name(), finfo.ModTime(), fi)
						fi.Close()
						return
					}
					fi.Close()
				}
			}
		}

		// list dir files
		if opt.ListDir {
			ctx.Header().Set("Content-Type", "text/html; charset=UTF-8")
			ctx.WriteString(`<ul style="list-style-type:none;line-height:32px;">`)
			if rPath != "/" {
				ctx.WriteString(`<li>&nbsp; &nbsp; <a href="` + path.Join("/", opt.Prefix, filepath.Dir(rPath)) + `">..</a></li>`)
			}

			fs, err := f.Readdir(0)
			if err != nil {
				ctx.Result = InternalServerError(err.Error())
				ctx.HandleError()
				return
			}

			for _, fi := range fs {
				if fi.IsDir() {
					ctx.WriteString(`<li>┖ <a href="` + path.Join("/", opt.Prefix, rPath, fi.Name()) + `">` + path.Base(fi.Name()) + `</a></li>`)
				} else {
					if len(opt.FilterExts) > 0 && !opt.IsFilterExt(fi.Name()) {
						continue
					}

					ctx.WriteString(`<li>&nbsp; &nbsp; <a href="` + path.Join("/", opt.Prefix, rPath, fi.Name()) + `">` + filepath.Base(fi.Name()) + `</a></li>`)
				}
			}
			ctx.WriteString("</ul>")
			return
		}

		ctx.Next()
	}
}
57349
func (c *conn) serve() {
	// Attempt to parse a Request from a raw packet, providing a nicer
	// API for callers to implement their own DHCP request handlers.
	r, err := ParseRequest(c.buf, c.remoteAddr)
	if err != nil {
		// Malformed packets get no response
		if err == dhcp6.ErrInvalidPacket {
			return
		}

		// BUG(mdlayher): decide to log or handle other request errors
		c.server.logf("%s: error parsing request: %s", c.remoteAddr.String(), err.Error())
		return
	}

	// Filter out unknown/invalid message types, using the lowest and highest
	// numbered types
	if r.MessageType < dhcp6.MessageTypeSolicit || r.MessageType > dhcp6.MessageTypeDHCPv4Response {
		c.server.logf("%s: unrecognized message type: %d", c.remoteAddr.String(), r.MessageType)
		return
	}

	// Set up response to send responses back to the original requester
	w := &response{
		remoteAddr: c.remoteAddr,
		conn:       c.conn,
		req:        r,
		options:    make(dhcp6.Options),
	}

	// Add server ID to response
	if sID := c.server.ServerID; sID != nil {
		_ = w.options.Add(dhcp6.OptionServerID, sID)
	}

	// If available in request, add client ID to response
	if cID, err := dhcp6opts.GetClientID(r.Options); err == nil {
		w.options.Add(dhcp6.OptionClientID, cID)
	}

	// Enforce a valid Handler.
	handler := c.server.Handler
	if handler == nil {
		panic("nil DHCPv6 handler for server")
	}

	handler.ServeDHCP(w, r)
}
1294512
func (srv *Server) Serve(l net.Listener) error {

	srv.configureDefaults()

	defer l.Close()

	var limiter chan struct{}

	if srv.MaxConnections > 0 {
		limiter = make(chan struct{}, srv.MaxConnections)
	} else {
		limiter = nil
	}

	for {

		conn, e := l.Accept()
		if e != nil {
			if ne, ok := e.(net.Error); ok && ne.Temporary() {
				time.Sleep(time.Second)
				continue
			}
			return e
		}

		session := srv.newSession(conn)

		if limiter != nil {
			go func() {
				select {
				case limiter <- struct{}{}:
					session.serve()
					<-limiter
				default:
					session.reject()
				}
			}()
		} else {
			go session.serve()
		}

	}

}
1119271
func (s *Server) Serve(addr string) error {
	ln, err := net.Listen("tcp", addr)
	if err != nil {
		return fmt.Errorf("failed to bind the import server to '%s': %v",
			addr, err)
	}

	return s.Server.Serve(ln)
}
412868
func serve(c Static, prefix, filepath string, allowDir bool) revel.Result {
	var basePath string
	if !fpath.IsAbs(prefix) {
		basePath = revel.BasePath
	}

	basePathPrefix := fpath.Join(basePath, fpath.FromSlash(prefix))
	fname := fpath.Join(basePathPrefix, fpath.FromSlash(filepath))

	// Verify the request file path is within the application's scope of access
	if !strings.HasPrefix(fname, basePathPrefix) {
		c.Log.Warn("Attempted to read file outside of base path", "path", fname, "basePath", basePathPrefix)
		return c.NotFound("")
	}

	// Normalize filepath and verify that the suffix is the same
	if !strings.Contains(fpath.ToSlash(fpath.Clean(fname)), fpath.ToSlash(filepath)) {
		c.Log.Warnf("Attempted to read path structure outside of base path: %s %s", fname, fpath.Clean(filepath))
		return c.NotFound("")
	}

	// Verify file path is accessible
	finfo, err := os.Stat(fname)
	if err != nil {
		if os.IsNotExist(err) || err.(*os.PathError).Err == syscall.ENOTDIR {
			c.Log.Warnf("File not found (%s): %s ", fname, err)
			return c.NotFound("File not found")
		}
		c.Log.Errorf("Error trying to get fileinfo for '%s': %s", fname, err)
		return c.RenderError(err)
	}
	isDir := finfo.Mode().IsDir()
	// Disallow directory listing
	if isDir && !allowDir {
		c.Log.Warn("Attempted directory listing of %s", fname)
		return c.Forbidden("Directory listing not allowed")
	}

	if isDir {
		if c.Request.URL.Path[len(c.Request.URL.Path)-1] != '/' {
			c.Response.Out.Header().Set("Location", c.Request.URL.Path+"/")
			c.Response.WriteHeader(http.StatusFound, "")
			// Send redirection
			c.RenderText("Redirecting")
		}

		viewArgs, err := c.processDir(fname, fpath.Join(basePath, prefix))
		if err != nil {
			viewArgs["message"] = fmt.Sprintf("An error occured %s", err.Error())
		}
		c.ViewArgs["details"] = viewArgs
		return c.RenderTemplate("static/folder-view.html")
	}

	// Open request file path
	file, err := os.Open(fname)
	if err != nil {
		if os.IsNotExist(err) {
			c.Log.Warnf("File not found (%s): %s ", fname, err)
			return c.NotFound("File not found")
		}
		c.Log.Errorf("Error opening '%s': %s", fname, err)
		return c.RenderError(err)
	}
	return c.RenderFile(file, revel.Inline)
}
465632
func serve() {
	lis, err := net.Listen("tcp", ":50053")
	if err != nil {
		log.Fatalf("failed to listen: %v", err)
	}
	s := grpc.NewServer()
	pb.RegisterEchoServer(s, &server{})

	if err := s.Serve(lis); err != nil {
		log.Fatalf("failed to serve: %v", err)
	}
}
1199528
func (s *Server) Serve() (err error) {
	if !s.hasListeners {
		if err = s.Listen(); err != nil {
			return err
		}
	}

	// set default handler, if none is set
	if s.handler == nil {
		if s.api == nil {
			return errors.New("can't create the default handler, as no api is set")
		}

		s.SetHandler(s.api.Serve(nil))
	}

	wg := new(sync.WaitGroup)
	once := new(sync.Once)
	signalNotify(s.interrupt)
	go handleInterrupt(once, s)

	servers := []*http.Server{}
	wg.Add(1)
	go s.handleShutdown(wg, &servers)

	if s.hasScheme(schemeUnix) {
		domainSocket := new(http.Server)
		domainSocket.MaxHeaderBytes = int(s.MaxHeaderSize)
		domainSocket.Handler = s.handler
		if int64(s.CleanupTimeout) > 0 {
			domainSocket.IdleTimeout = s.CleanupTimeout
		}

		configureServer(domainSocket, "unix", string(s.SocketPath))

		servers = append(servers, domainSocket)
		wg.Add(1)
		s.Logf("Serving todo list at unix://%s", s.SocketPath)
		go func(l net.Listener) {
			defer wg.Done()
			if err := domainSocket.Serve(l); err != nil && err != http.ErrServerClosed {
				s.Fatalf("%v", err)
			}
			s.Logf("Stopped serving todo list at unix://%s", s.SocketPath)
		}(s.domainSocketL)
	}

	if s.hasScheme(schemeHTTP) {
		httpServer := new(http.Server)
		httpServer.MaxHeaderBytes = int(s.MaxHeaderSize)
		httpServer.ReadTimeout = s.ReadTimeout
		httpServer.WriteTimeout = s.WriteTimeout
		httpServer.SetKeepAlivesEnabled(int64(s.KeepAlive) > 0)
		if s.ListenLimit > 0 {
			s.httpServerL = netutil.LimitListener(s.httpServerL, s.ListenLimit)
		}

		if int64(s.CleanupTimeout) > 0 {
			httpServer.IdleTimeout = s.CleanupTimeout
		}

		httpServer.Handler = s.handler

		configureServer(httpServer, "http", s.httpServerL.Addr().String())

		servers = append(servers, httpServer)
		wg.Add(1)
		s.Logf("Serving todo list at http://%s", s.httpServerL.Addr())
		go func(l net.Listener) {
			defer wg.Done()
			if err := httpServer.Serve(l); err != nil && err != http.ErrServerClosed {
				s.Fatalf("%v", err)
			}
			s.Logf("Stopped serving todo list at http://%s", l.Addr())
		}(s.httpServerL)
	}

	if s.hasScheme(schemeHTTPS) {
		httpsServer := new(http.Server)
		httpsServer.MaxHeaderBytes = int(s.MaxHeaderSize)
		httpsServer.ReadTimeout = s.TLSReadTimeout
		httpsServer.WriteTimeout = s.TLSWriteTimeout
		httpsServer.SetKeepAlivesEnabled(int64(s.TLSKeepAlive) > 0)
		if s.TLSListenLimit > 0 {
			s.httpsServerL = netutil.LimitListener(s.httpsServerL, s.TLSListenLimit)
		}
		if int64(s.CleanupTimeout) > 0 {
			httpsServer.IdleTimeout = s.CleanupTimeout
		}
		httpsServer.Handler = s.handler

		// Inspired by https://blog.bracebin.com/achieving-perfect-ssl-labs-score-with-go
		httpsServer.TLSConfig = &tls.Config{
			// Causes servers to use Go's default ciphersuite preferences,
			// which are tuned to avoid attacks. Does nothing on clients.
			PreferServerCipherSuites: true,
			// Only use curves which have assembly implementations
			// https://github.com/golang/go/tree/master/src/crypto/elliptic
			CurvePreferences: []tls.CurveID{tls.CurveP256},
			// Use modern tls mode https://wiki.mozilla.org/Security/Server_Side_TLS#Modern_compatibility
			NextProtos: []string{"http/1.1", "h2"},
			// https://www.owasp.org/index.php/Transport_Layer_Protection_Cheat_Sheet#Rule_-_Only_Support_Strong_Protocols
			MinVersion: tls.VersionTLS12,
			// These ciphersuites support Forward Secrecy: https://en.wikipedia.org/wiki/Forward_secrecy
			CipherSuites: []uint16{
				tls.TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,
				tls.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,
				tls.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
				tls.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
				tls.TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305,
				tls.TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305,
			},
		}

		// build standard config from server options
		if s.TLSCertificate != "" && s.TLSCertificateKey != "" {
			httpsServer.TLSConfig.Certificates = make([]tls.Certificate, 1)
			httpsServer.TLSConfig.Certificates[0], err = tls.LoadX509KeyPair(s.TLSCertificate, s.TLSCertificateKey)
			if err != nil {
				return err
			}
		}

		if s.TLSCACertificate != "" {
			// include specified CA certificate
			caCert, caCertErr := ioutil.ReadFile(s.TLSCACertificate)
			if caCertErr != nil {
				return caCertErr
			}
			caCertPool := x509.NewCertPool()
			ok := caCertPool.AppendCertsFromPEM(caCert)
			if !ok {
				return fmt.Errorf("cannot parse CA certificate")
			}
			httpsServer.TLSConfig.ClientCAs = caCertPool
			httpsServer.TLSConfig.ClientAuth = tls.RequireAndVerifyClientCert
		}

		// call custom TLS configurator
		configureTLS(httpsServer.TLSConfig)

		if len(httpsServer.TLSConfig.Certificates) == 0 {
			// after standard and custom config are passed, this ends up with no certificate
			if s.TLSCertificate == "" {
				if s.TLSCertificateKey == "" {
					s.Fatalf("the required flags `--tls-certificate` and `--tls-key` were not specified")
				}
				s.Fatalf("the required flag `--tls-certificate` was not specified")
			}
			if s.TLSCertificateKey == "" {
				s.Fatalf("the required flag `--tls-key` was not specified")
			}
			// this happens with a wrong custom TLS configurator
			s.Fatalf("no certificate was configured for TLS")
		}

		// must have at least one certificate or panics
		httpsServer.TLSConfig.BuildNameToCertificate()

		configureServer(httpsServer, "https", s.httpsServerL.Addr().String())

		servers = append(servers, httpsServer)
		wg.Add(1)
		s.Logf("Serving todo list at https://%s", s.httpsServerL.Addr())
		go func(l net.Listener) {
			defer wg.Done()
			if err := httpsServer.Serve(l); err != nil && err != http.ErrServerClosed {
				s.Fatalf("%v", err)
			}
			s.Logf("Stopped serving todo list at https://%s", l.Addr())
		}(tls.NewListener(s.httpsServerL, httpsServer.TLSConfig))
	}

	wg.Wait()
	return nil
}
666399
func Serve(c *fuse.Conn, fs FS) error {
	server := New(c, nil)
	return server.Serve(fs)
}
1235671
func (c *Conn) Serve(fs FS) error {
	if c.req != nil {
		panic("fuse: Serve called twice")
	}
	c.req = map[RequestID]*serveRequest{}

	root, err := fs.Root()
	if err != nil {
		return fmt.Errorf("cannot obtain root node: %v", syscall.Errno(err.(Errno)).Error())
	}
	c.node = append(c.node, nil, &serveNode{name: "/", node: root})
	c.handle = append(c.handle, nil)

	for {
		req, err := c.ReadRequest()
		if err != nil {
			if err == io.EOF {
				break
			}
			return err
		}

		go c.serve(fs, req)
	}
	return nil
}
733530
func (s *Server) serve(lis net.Listener) {
	s.wg.Add(1)
	go func() {
		log.Infof("Listening on %s", lis.Addr())
		err := s.httpServer.Serve(lis)
		log.Tracef("Finished serving RPC: %v", err)
		s.wg.Done()
	}()
}
70035
func Serve() {
	http.HandleFunc("/goad", serveResults)
	http.HandleFunc("/_health", health)
	err := http.ListenAndServe(*addr, nil)
	if err != nil {
		log.Fatal("ListenAndServe: ", err)
	}
}
400156
func (s *TrapServer) Serve(listener TrapListener) error {
	if listener == nil {
		return &ArgumentError{Message: "listener is nil"}
	}
	s.servingMu.Lock()
	s.serving = true
	s.servingMu.Unlock()
	size := s.args.MessageMaxSize
	if size < recvBufferSize {
		size = recvBufferSize
	}

	for {
		conn, err := s.transport.Listen()
		s.servingMu.RLock()
		serving := s.serving
		s.servingMu.RUnlock()
		if !serving {
			return nil
		}
		if err != nil {
			if e, ok := err.(net.Error); ok && e.Temporary() {
				continue
			}
			return err
		}

		go func(conn interface{}) {
			defer s.transport.Close(conn)
			buf := make([]byte, size)
			for {
				_, src, msg, err := s.transport.Read(conn, buf)
				if _, ok := err.(net.Error); ok {
					s.servingMu.RLock()
					serving := s.serving
					s.servingMu.RUnlock()
					if serving {
						s.logf("trap: failed to read packet: %v", err)
					}
					return
				}

				go s.handle(listener, conn, msg, src, err)
			}
		}(conn)
	}
}
459576
func (s *Server) Serve() {
	done := make(chan struct{})

	if s.HTTPAddr != "" {
		go func() {
			s.HTTPServe()
			done <- struct{}{}
		}()
	}

	if s.grpcListenAddress != "" {
		go func() {
			s.gRPCServe()
			done <- struct{}{}
		}()
	}

	// wait until at least one of the servers has shut down
	<-done
	graceful.Shutdown()
	s.gRPCStop()
}