2015-01-30 14:52:18 +08:00
|
|
|
// Package server implements a configurable, general-purpose web server.
|
|
|
|
// It relies on configurations obtained from the adjacent config package
|
|
|
|
// and can execute middleware as defined by the adjacent middleware package.
|
2015-01-14 03:43:45 +08:00
|
|
|
package server
|
|
|
|
|
|
|
|
import (
|
2016-04-13 00:09:45 +08:00
|
|
|
"crypto/rand"
|
2015-04-16 04:11:32 +08:00
|
|
|
"crypto/tls"
|
2015-06-02 13:22:11 +08:00
|
|
|
"crypto/x509"
|
2015-03-30 12:01:42 +08:00
|
|
|
"fmt"
|
2016-04-13 00:09:45 +08:00
|
|
|
"io"
|
2015-06-02 13:22:11 +08:00
|
|
|
"io/ioutil"
|
2016-01-12 00:07:14 +08:00
|
|
|
"log"
|
2015-04-16 04:11:32 +08:00
|
|
|
"net"
|
2015-01-14 03:43:45 +08:00
|
|
|
"net/http"
|
2015-03-26 23:52:03 +08:00
|
|
|
"os"
|
2015-10-26 08:45:55 +08:00
|
|
|
"runtime"
|
2016-04-07 05:36:46 +08:00
|
|
|
"strings"
|
2015-10-26 08:45:55 +08:00
|
|
|
"sync"
|
|
|
|
"time"
|
2015-01-14 03:43:45 +08:00
|
|
|
)
|
|
|
|
|
2016-04-13 00:09:45 +08:00
|
|
|
const (
|
|
|
|
tlsNewTicketEvery = time.Hour * 10 // generate a new ticket for TLS PFS encryption every so often
|
|
|
|
tlsNumTickets = 4 // hold and consider that many tickets to decrypt TLS sessions
|
|
|
|
)
|
|
|
|
|
2015-01-14 03:43:45 +08:00
|
|
|
// Server represents an instance of a server, which serves
|
2015-10-26 08:45:55 +08:00
|
|
|
// HTTP requests at a particular address (host and port). A
|
|
|
|
// server is capable of serving numerous virtual hosts on
|
|
|
|
// the same address and the listener may be stopped for
|
|
|
|
// graceful termination (POSIX only).
|
2015-01-14 03:43:45 +08:00
|
|
|
type Server struct {
|
2015-10-26 08:45:55 +08:00
|
|
|
*http.Server
|
2016-02-11 15:06:05 +08:00
|
|
|
HTTP2 bool // whether to enable HTTP/2
|
2015-11-15 09:00:18 +08:00
|
|
|
tls bool // whether this server is serving all HTTPS hosts or not
|
2016-02-11 15:06:05 +08:00
|
|
|
OnDemandTLS bool // whether this server supports on-demand TLS (load certs at handshake-time)
|
2016-04-13 00:09:45 +08:00
|
|
|
tlsGovChan chan struct{} // close to stop the TLS maintenance goroutine
|
2015-11-15 09:00:18 +08:00
|
|
|
vhosts map[string]virtualHost // virtual hosts keyed by their address
|
|
|
|
listener ListenerFile // the listener which is bound to the socket
|
|
|
|
listenerMu sync.Mutex // protects listener
|
|
|
|
httpWg sync.WaitGroup // used to wait on outstanding connections
|
|
|
|
startChan chan struct{} // used to block until server is finished starting
|
|
|
|
connTimeout time.Duration // the maximum duration of a graceful shutdown
|
2016-01-04 08:05:10 +08:00
|
|
|
ReqCallback OptionalCallback // if non-nil, is executed at the beginning of every request
|
2016-01-13 15:32:46 +08:00
|
|
|
SNICallback func(clientHello *tls.ClientHelloInfo) (*tls.Certificate, error)
|
2015-10-26 08:45:55 +08:00
|
|
|
}
|
|
|
|
|
2015-11-03 03:28:50 +08:00
|
|
|
// ListenerFile represents a listener.
|
2015-10-26 08:45:55 +08:00
|
|
|
type ListenerFile interface {
|
|
|
|
net.Listener
|
|
|
|
File() (*os.File, error)
|
2015-01-14 03:43:45 +08:00
|
|
|
}
|
|
|
|
|
2016-01-04 08:05:10 +08:00
|
|
|
// OptionalCallback is a function that may or may not handle a request.
|
|
|
|
// It returns whether or not it handled the request. If it handled the
|
|
|
|
// request, it is presumed that no further request handling should occur.
|
|
|
|
type OptionalCallback func(http.ResponseWriter, *http.Request) bool
|
|
|
|
|
2015-04-16 04:11:32 +08:00
|
|
|
// New creates a new Server which will bind to addr and serve
|
2015-11-15 09:00:18 +08:00
|
|
|
// the sites/hosts configured in configs. Its listener will
|
|
|
|
// gracefully close when the server is stopped which will take
|
|
|
|
// no longer than gracefulTimeout.
|
|
|
|
//
|
|
|
|
// This function does not start serving.
|
2015-10-30 14:19:43 +08:00
|
|
|
//
|
|
|
|
// Do not re-use a server (start, stop, then start again). We
|
|
|
|
// could probably add more locking to make this possible, but
|
|
|
|
// as it stands, you should dispose of a server after stopping it.
|
|
|
|
// The behavior of serving with a spent server is undefined.
|
2015-11-15 09:00:18 +08:00
|
|
|
func New(addr string, configs []Config, gracefulTimeout time.Duration) (*Server, error) {
|
2016-02-11 15:06:05 +08:00
|
|
|
var useTLS, useOnDemandTLS bool
|
2015-07-12 02:00:11 +08:00
|
|
|
if len(configs) > 0 {
|
2016-02-11 15:06:05 +08:00
|
|
|
useTLS = configs[0].TLS.Enabled
|
2016-02-16 14:39:04 +08:00
|
|
|
useOnDemandTLS = configs[0].TLS.OnDemand
|
2015-07-12 02:00:11 +08:00
|
|
|
}
|
|
|
|
|
2015-04-16 04:11:32 +08:00
|
|
|
s := &Server{
|
2015-10-26 08:45:55 +08:00
|
|
|
Server: &http.Server{
|
2016-02-11 15:06:05 +08:00
|
|
|
Addr: addr,
|
|
|
|
TLSConfig: new(tls.Config),
|
2015-10-26 08:45:55 +08:00
|
|
|
// TODO: Make these values configurable?
|
|
|
|
// ReadTimeout: 2 * time.Minute,
|
|
|
|
// WriteTimeout: 2 * time.Minute,
|
|
|
|
// MaxHeaderBytes: 1 << 16,
|
|
|
|
},
|
2016-02-11 15:06:05 +08:00
|
|
|
tls: useTLS,
|
|
|
|
OnDemandTLS: useOnDemandTLS,
|
2015-11-15 09:00:18 +08:00
|
|
|
vhosts: make(map[string]virtualHost),
|
|
|
|
startChan: make(chan struct{}),
|
|
|
|
connTimeout: gracefulTimeout,
|
2015-01-14 03:43:45 +08:00
|
|
|
}
|
2015-10-27 03:34:31 +08:00
|
|
|
s.Handler = s // this is weird, but whatever
|
2015-10-26 08:45:55 +08:00
|
|
|
|
|
|
|
// We have to bound our wg with one increment
|
|
|
|
// to prevent a "race condition" that is hard-coded
|
|
|
|
// into sync.WaitGroup.Wait() - basically, an add
|
|
|
|
// with a positive delta must be guaranteed to
|
|
|
|
// occur before Wait() is called on the wg.
|
2015-10-29 12:54:27 +08:00
|
|
|
// In a way, this kind of acts as a safety barrier.
|
2015-10-26 08:45:55 +08:00
|
|
|
s.httpWg.Add(1)
|
2015-01-14 03:43:45 +08:00
|
|
|
|
2015-10-26 08:45:55 +08:00
|
|
|
// Set up each virtualhost
|
2015-04-16 04:11:32 +08:00
|
|
|
for _, conf := range configs {
|
|
|
|
if _, exists := s.vhosts[conf.Host]; exists {
|
2015-10-26 08:45:55 +08:00
|
|
|
return nil, fmt.Errorf("cannot serve %s - host already defined for address %s", conf.Address(), s.Addr)
|
2015-04-16 04:11:32 +08:00
|
|
|
}
|
2015-01-22 05:10:52 +08:00
|
|
|
|
2015-04-16 04:11:32 +08:00
|
|
|
vh := virtualHost{config: conf}
|
2015-01-14 03:43:45 +08:00
|
|
|
|
2015-04-16 04:11:32 +08:00
|
|
|
// Build middleware stack
|
|
|
|
err := vh.buildStack()
|
2015-03-29 06:37:37 +08:00
|
|
|
if err != nil {
|
2015-04-16 04:11:32 +08:00
|
|
|
return nil, err
|
2015-03-29 06:37:37 +08:00
|
|
|
}
|
|
|
|
|
2015-04-16 04:11:32 +08:00
|
|
|
s.vhosts[conf.Host] = vh
|
2015-01-14 03:43:45 +08:00
|
|
|
}
|
|
|
|
|
2015-04-16 04:11:32 +08:00
|
|
|
return s, nil
|
|
|
|
}
|
2015-01-22 05:10:52 +08:00
|
|
|
|
2015-10-26 08:45:55 +08:00
|
|
|
// Serve starts the server with an existing listener. It blocks until the
|
|
|
|
// server stops.
|
|
|
|
func (s *Server) Serve(ln ListenerFile) error {
|
|
|
|
err := s.setup()
|
|
|
|
if err != nil {
|
2015-11-06 06:21:13 +08:00
|
|
|
defer close(s.startChan) // MUST defer so error is properly reported, same with all cases in this file
|
2015-10-26 08:45:55 +08:00
|
|
|
return err
|
2015-03-17 01:44:54 +08:00
|
|
|
}
|
2015-10-26 08:45:55 +08:00
|
|
|
return s.serve(ln)
|
|
|
|
}
|
2015-03-17 01:44:54 +08:00
|
|
|
|
2015-10-26 08:45:55 +08:00
|
|
|
// ListenAndServe starts the server with a new listener. It blocks until the server stops.
|
|
|
|
func (s *Server) ListenAndServe() error {
|
|
|
|
err := s.setup()
|
|
|
|
if err != nil {
|
2015-11-06 06:21:13 +08:00
|
|
|
defer close(s.startChan)
|
2015-10-26 08:45:55 +08:00
|
|
|
return err
|
2015-04-10 00:08:22 +08:00
|
|
|
}
|
2015-03-17 01:44:54 +08:00
|
|
|
|
2015-10-26 08:45:55 +08:00
|
|
|
ln, err := net.Listen("tcp", s.Addr)
|
|
|
|
if err != nil {
|
2015-11-01 03:22:23 +08:00
|
|
|
var succeeded bool
|
|
|
|
if runtime.GOOS == "windows" { // TODO: Limit this to Windows only? (it keeps sockets open after closing listeners)
|
|
|
|
for i := 0; i < 20; i++ {
|
|
|
|
time.Sleep(100 * time.Millisecond)
|
|
|
|
ln, err = net.Listen("tcp", s.Addr)
|
|
|
|
if err == nil {
|
|
|
|
succeeded = true
|
|
|
|
break
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
if !succeeded {
|
2015-11-06 06:21:13 +08:00
|
|
|
defer close(s.startChan)
|
2015-11-01 03:22:23 +08:00
|
|
|
return err
|
|
|
|
}
|
2015-10-26 08:45:55 +08:00
|
|
|
}
|
2015-03-26 23:52:03 +08:00
|
|
|
|
2015-10-26 08:45:55 +08:00
|
|
|
return s.serve(ln.(*net.TCPListener))
|
|
|
|
}
|
|
|
|
|
|
|
|
// serve prepares s to listen on ln by wrapping ln in a
|
|
|
|
// tcpKeepAliveListener (if ln is a *net.TCPListener) and
|
|
|
|
// then in a gracefulListener, so that keep-alive is supported
|
|
|
|
// as well as graceful shutdown/restart. It also configures
|
|
|
|
// TLS listener on top of that if applicable.
|
|
|
|
func (s *Server) serve(ln ListenerFile) error {
|
|
|
|
if tcpLn, ok := ln.(*net.TCPListener); ok {
|
|
|
|
ln = tcpKeepAliveListener{TCPListener: tcpLn}
|
2015-04-16 04:11:32 +08:00
|
|
|
}
|
|
|
|
|
2015-10-26 08:45:55 +08:00
|
|
|
s.listenerMu.Lock()
|
|
|
|
s.listener = newGracefulListener(ln, &s.httpWg)
|
|
|
|
s.listenerMu.Unlock()
|
|
|
|
|
2015-04-16 04:11:32 +08:00
|
|
|
if s.tls {
|
2015-05-04 20:53:54 +08:00
|
|
|
var tlsConfigs []TLSConfig
|
2015-04-16 04:11:32 +08:00
|
|
|
for _, vh := range s.vhosts {
|
|
|
|
tlsConfigs = append(tlsConfigs, vh.config.TLS)
|
|
|
|
}
|
2016-02-11 15:06:05 +08:00
|
|
|
return serveTLS(s, s.listener, tlsConfigs)
|
2015-01-14 03:43:45 +08:00
|
|
|
}
|
2015-10-26 08:45:55 +08:00
|
|
|
|
2015-10-30 14:19:43 +08:00
|
|
|
close(s.startChan) // unblock anyone waiting for this to start listening
|
2015-10-26 08:45:55 +08:00
|
|
|
return s.Server.Serve(s.listener)
|
2015-01-14 03:43:45 +08:00
|
|
|
}
|
|
|
|
|
2015-10-26 08:45:55 +08:00
|
|
|
// setup prepares the server s to begin listening; it should be
|
|
|
|
// called just before the listener announces itself on the network
|
|
|
|
// and should only be called when the server is just starting up.
|
|
|
|
func (s *Server) setup() error {
|
2016-01-13 15:29:22 +08:00
|
|
|
if !s.HTTP2 {
|
|
|
|
s.TLSNextProto = make(map[string]func(*http.Server, *tls.Conn, http.Handler))
|
2015-09-11 11:52:49 +08:00
|
|
|
}
|
2015-10-26 08:45:55 +08:00
|
|
|
|
|
|
|
// Execute startup functions now
|
|
|
|
for _, vh := range s.vhosts {
|
|
|
|
for _, startupFunc := range vh.config.Startup {
|
|
|
|
err := startupFunc()
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
}
|
2015-09-11 11:52:49 +08:00
|
|
|
}
|
2015-10-26 08:45:55 +08:00
|
|
|
|
|
|
|
return nil
|
2015-09-11 11:52:49 +08:00
|
|
|
}
|
|
|
|
|
2016-02-11 15:06:05 +08:00
|
|
|
// serveTLS serves TLS with SNI and client auth support if s has them enabled. It
|
|
|
|
// blocks until s quits.
|
|
|
|
func serveTLS(s *Server, ln net.Listener, tlsConfigs []TLSConfig) error {
|
2015-05-21 14:06:53 +08:00
|
|
|
// Customize our TLS configuration
|
2016-02-11 15:06:05 +08:00
|
|
|
s.TLSConfig.MinVersion = tlsConfigs[0].ProtocolMinVersion
|
|
|
|
s.TLSConfig.MaxVersion = tlsConfigs[0].ProtocolMaxVersion
|
|
|
|
s.TLSConfig.CipherSuites = tlsConfigs[0].Ciphers
|
|
|
|
s.TLSConfig.PreferServerCipherSuites = tlsConfigs[0].PreferServerCipherSuites
|
2015-05-05 11:25:29 +08:00
|
|
|
|
2015-06-02 13:22:11 +08:00
|
|
|
// TLS client authentication, if user enabled it
|
2016-02-11 15:06:05 +08:00
|
|
|
err := setupClientAuth(tlsConfigs, s.TLSConfig)
|
2015-04-16 04:11:32 +08:00
|
|
|
if err != nil {
|
2015-11-06 06:21:13 +08:00
|
|
|
defer close(s.startChan)
|
2015-04-16 04:11:32 +08:00
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2016-04-13 00:09:45 +08:00
|
|
|
// Setup any goroutines governing over TLS settings
|
|
|
|
s.tlsGovChan = make(chan struct{})
|
|
|
|
timer := time.NewTicker(tlsNewTicketEvery)
|
|
|
|
go runTLSTicketKeyRotation(s.TLSConfig, timer, s.tlsGovChan)
|
|
|
|
|
2015-10-26 08:45:55 +08:00
|
|
|
// Create TLS listener - note that we do not replace s.listener
|
|
|
|
// with this TLS listener; tls.listener is unexported and does
|
|
|
|
// not implement the File() method we need for graceful restarts
|
|
|
|
// on POSIX systems.
|
2016-02-11 15:06:05 +08:00
|
|
|
ln = tls.NewListener(ln, s.TLSConfig)
|
2015-06-02 13:22:11 +08:00
|
|
|
|
2015-10-30 14:19:43 +08:00
|
|
|
close(s.startChan) // unblock anyone waiting for this to start listening
|
2015-10-26 08:45:55 +08:00
|
|
|
return s.Server.Serve(ln)
|
2015-04-16 04:11:32 +08:00
|
|
|
}
|
|
|
|
|
2015-10-26 08:45:55 +08:00
|
|
|
// Stop stops the server. It blocks until the server is
|
|
|
|
// totally stopped. On POSIX systems, it will wait for
|
|
|
|
// connections to close (up to a max timeout of a few
|
|
|
|
// seconds); on Windows it will close the listener
|
|
|
|
// immediately.
|
2015-11-15 09:00:18 +08:00
|
|
|
func (s *Server) Stop() (err error) {
|
2015-10-30 14:19:43 +08:00
|
|
|
s.Server.SetKeepAlivesEnabled(false)
|
2015-10-26 08:45:55 +08:00
|
|
|
|
|
|
|
if runtime.GOOS != "windows" {
|
|
|
|
// force connections to close after timeout
|
|
|
|
done := make(chan struct{})
|
|
|
|
go func() {
|
|
|
|
s.httpWg.Done() // decrement our initial increment used as a barrier
|
|
|
|
s.httpWg.Wait()
|
|
|
|
close(done)
|
|
|
|
}()
|
|
|
|
|
|
|
|
// Wait for remaining connections to finish or
|
|
|
|
// force them all to close after timeout
|
|
|
|
select {
|
2015-11-15 09:00:18 +08:00
|
|
|
case <-time.After(s.connTimeout):
|
2015-10-26 08:45:55 +08:00
|
|
|
case <-done:
|
2015-06-02 13:22:11 +08:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2015-10-29 12:54:27 +08:00
|
|
|
// Close the listener now; this stops the server without delay
|
2015-10-26 08:45:55 +08:00
|
|
|
s.listenerMu.Lock()
|
2015-11-15 09:00:18 +08:00
|
|
|
if s.listener != nil {
|
|
|
|
err = s.listener.Close()
|
2015-06-02 13:22:11 +08:00
|
|
|
}
|
2015-11-15 09:00:18 +08:00
|
|
|
s.listenerMu.Unlock()
|
2015-06-02 13:22:11 +08:00
|
|
|
|
2016-04-13 00:09:45 +08:00
|
|
|
// Closing this signals any TLS governor goroutines to exit
|
|
|
|
if s.tlsGovChan != nil {
|
|
|
|
close(s.tlsGovChan)
|
|
|
|
}
|
|
|
|
|
2015-11-15 09:00:18 +08:00
|
|
|
return
|
2015-10-26 08:45:55 +08:00
|
|
|
}
|
|
|
|
|
2015-10-30 14:19:43 +08:00
|
|
|
// WaitUntilStarted blocks until the server s is started, meaning
|
|
|
|
// that practically the next instruction is to start the server loop.
|
|
|
|
// It also unblocks if the server encounters an error during startup.
|
|
|
|
func (s *Server) WaitUntilStarted() {
|
|
|
|
<-s.startChan
|
|
|
|
}
|
|
|
|
|
2015-11-15 09:00:18 +08:00
|
|
|
// ListenerFd gets a dup'ed file of the listener. If there
|
|
|
|
// is no underlying file, the return value will be nil. It
|
|
|
|
// is the caller's responsibility to close the file.
|
2015-11-13 14:54:42 +08:00
|
|
|
func (s *Server) ListenerFd() *os.File {
|
2015-10-26 08:45:55 +08:00
|
|
|
s.listenerMu.Lock()
|
|
|
|
defer s.listenerMu.Unlock()
|
2015-11-15 09:00:18 +08:00
|
|
|
if s.listener != nil {
|
|
|
|
file, _ := s.listener.File()
|
|
|
|
return file
|
|
|
|
}
|
|
|
|
return nil
|
2015-06-02 13:22:11 +08:00
|
|
|
}
|
|
|
|
|
2015-04-16 04:11:32 +08:00
|
|
|
// ServeHTTP is the entry point for every request to the address that s
|
|
|
|
// is bound to. It acts as a multiplexer for the requests hostname as
|
|
|
|
// defined in the Host header so that the correct virtualhost
|
|
|
|
// (configuration and middleware stack) will handle the request.
|
2015-01-14 03:43:45 +08:00
|
|
|
func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
2015-03-27 12:52:27 +08:00
|
|
|
defer func() {
|
2015-03-29 06:37:37 +08:00
|
|
|
// In case the user doesn't enable error middleware, we still
|
|
|
|
// need to make sure that we stay alive up here
|
2015-03-27 12:52:27 +08:00
|
|
|
if rec := recover(); rec != nil {
|
2015-03-29 06:37:37 +08:00
|
|
|
http.Error(w, http.StatusText(http.StatusInternalServerError),
|
|
|
|
http.StatusInternalServerError)
|
2015-03-27 12:52:27 +08:00
|
|
|
}
|
|
|
|
}()
|
2015-03-30 12:01:42 +08:00
|
|
|
|
2016-01-04 08:05:10 +08:00
|
|
|
w.Header().Set("Server", "Caddy")
|
|
|
|
|
2015-04-16 04:11:32 +08:00
|
|
|
host, _, err := net.SplitHostPort(r.Host)
|
|
|
|
if err != nil {
|
|
|
|
host = r.Host // oh well
|
2015-03-30 12:01:42 +08:00
|
|
|
}
|
2015-01-14 03:43:45 +08:00
|
|
|
|
2016-04-07 05:36:46 +08:00
|
|
|
// "The host subcomponent is case-insensitive." (RFC 3986)
|
|
|
|
host = strings.ToLower(host)
|
|
|
|
|
2015-04-29 05:31:42 +08:00
|
|
|
// Try the host as given, or try falling back to 0.0.0.0 (wildcard)
|
|
|
|
if _, ok := s.vhosts[host]; !ok {
|
|
|
|
if _, ok2 := s.vhosts["0.0.0.0"]; ok2 {
|
|
|
|
host = "0.0.0.0"
|
2015-06-10 13:07:32 +08:00
|
|
|
} else if _, ok2 := s.vhosts[""]; ok2 {
|
|
|
|
host = ""
|
2015-04-29 05:31:42 +08:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2016-03-12 14:37:54 +08:00
|
|
|
// Execute the optional request callback if it exists and it's not disabled
|
|
|
|
if s.ReqCallback != nil && !s.vhosts[host].config.TLS.Manual && s.ReqCallback(w, r) {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2015-04-16 04:11:32 +08:00
|
|
|
if vh, ok := s.vhosts[host]; ok {
|
|
|
|
status, _ := vh.stack.ServeHTTP(w, r)
|
2015-01-14 03:43:45 +08:00
|
|
|
|
2015-04-16 04:11:32 +08:00
|
|
|
// Fallback error response in case error handling wasn't chained in
|
2016-03-03 02:33:40 +08:00
|
|
|
if status >= 400 {
|
2015-06-16 00:17:09 +08:00
|
|
|
DefaultErrorFunc(w, r, status)
|
2015-04-16 04:11:32 +08:00
|
|
|
}
|
|
|
|
} else {
|
2016-02-04 16:17:10 +08:00
|
|
|
// Get the remote host
|
|
|
|
remoteHost, _, err := net.SplitHostPort(r.RemoteAddr)
|
|
|
|
if err != nil {
|
|
|
|
remoteHost = r.RemoteAddr
|
|
|
|
}
|
2016-02-14 15:10:57 +08:00
|
|
|
|
2015-04-16 04:11:32 +08:00
|
|
|
w.WriteHeader(http.StatusNotFound)
|
2015-10-26 08:45:55 +08:00
|
|
|
fmt.Fprintf(w, "No such host at %s", s.Server.Addr)
|
2016-02-20 04:34:54 +08:00
|
|
|
log.Printf("[INFO] %s - No such host at %s (Remote: %s, Referer: %s)",
|
|
|
|
host, s.Server.Addr, remoteHost, r.Header.Get("Referer"))
|
2015-01-14 03:43:45 +08:00
|
|
|
}
|
|
|
|
}
|
2015-06-16 00:17:09 +08:00
|
|
|
|
2015-10-10 06:35:34 +08:00
|
|
|
// DefaultErrorFunc responds to an HTTP request with a simple description
|
|
|
|
// of the specified HTTP status code.
|
2015-06-16 00:17:09 +08:00
|
|
|
func DefaultErrorFunc(w http.ResponseWriter, r *http.Request, status int) {
|
|
|
|
w.WriteHeader(status)
|
|
|
|
fmt.Fprintf(w, "%d %s", status, http.StatusText(status))
|
|
|
|
}
|
2015-10-26 08:45:55 +08:00
|
|
|
|
|
|
|
// setupClientAuth sets up TLS client authentication only if
|
|
|
|
// any of the TLS configs specified at least one cert file.
|
|
|
|
func setupClientAuth(tlsConfigs []TLSConfig, config *tls.Config) error {
|
|
|
|
var clientAuth bool
|
|
|
|
for _, cfg := range tlsConfigs {
|
|
|
|
if len(cfg.ClientCerts) > 0 {
|
|
|
|
clientAuth = true
|
|
|
|
break
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
if clientAuth {
|
|
|
|
pool := x509.NewCertPool()
|
|
|
|
for _, cfg := range tlsConfigs {
|
|
|
|
for _, caFile := range cfg.ClientCerts {
|
|
|
|
caCrt, err := ioutil.ReadFile(caFile) // Anyone that gets a cert from this CA can connect
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
if !pool.AppendCertsFromPEM(caCrt) {
|
|
|
|
return fmt.Errorf("error loading client certificate '%s': no certificates were successfully parsed", caFile)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
config.ClientCAs = pool
|
|
|
|
config.ClientAuth = tls.RequireAndVerifyClientCert
|
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2016-04-13 00:09:45 +08:00
|
|
|
var runTLSTicketKeyRotation = standaloneTLSTicketKeyRotation
|
|
|
|
|
|
|
|
var setSessionTicketKeysTestHook = func(keys [][32]byte) [][32]byte {
|
|
|
|
return keys
|
|
|
|
}
|
|
|
|
|
|
|
|
// standaloneTLSTicketKeyRotation governs over the array of TLS ticket keys used to de/crypt TLS tickets.
|
|
|
|
// It periodically sets a new ticket key as the first one, used to encrypt (and decrypt),
|
|
|
|
// pushing any old ticket keys to the back, where they are considered for decryption only.
|
|
|
|
//
|
|
|
|
// Lack of entropy for the very first ticket key results in the feature being disabled (as does Go),
|
|
|
|
// later lack of entropy temporarily disables ticket key rotation.
|
|
|
|
// Old ticket keys are still phased out, though.
|
|
|
|
//
|
|
|
|
// Stops the timer when returning.
|
|
|
|
func standaloneTLSTicketKeyRotation(c *tls.Config, timer *time.Ticker, exitChan chan struct{}) {
|
|
|
|
defer timer.Stop()
|
|
|
|
// The entire page should be marked as sticky, but Go cannot do that
|
|
|
|
// without resorting to syscall#Mlock. And, we don't have madvise (for NODUMP), too. ☹
|
|
|
|
keys := make([][32]byte, 1, tlsNumTickets)
|
|
|
|
|
|
|
|
rng := c.Rand
|
|
|
|
if rng == nil {
|
|
|
|
rng = rand.Reader
|
|
|
|
}
|
|
|
|
if _, err := io.ReadFull(rng, keys[0][:]); err != nil {
|
|
|
|
c.SessionTicketsDisabled = true // bail if we don't have the entropy for the first one
|
|
|
|
return
|
|
|
|
}
|
|
|
|
c.SetSessionTicketKeys(setSessionTicketKeysTestHook(keys))
|
|
|
|
|
|
|
|
for {
|
|
|
|
select {
|
|
|
|
case _, isOpen := <-exitChan:
|
|
|
|
if !isOpen {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
case <-timer.C:
|
|
|
|
rng = c.Rand // could've changed since the start
|
|
|
|
if rng == nil {
|
|
|
|
rng = rand.Reader
|
|
|
|
}
|
|
|
|
var newTicketKey [32]byte
|
|
|
|
_, err := io.ReadFull(rng, newTicketKey[:])
|
|
|
|
|
|
|
|
if len(keys) < tlsNumTickets {
|
|
|
|
keys = append(keys, keys[0]) // manipulates the internal length
|
|
|
|
}
|
|
|
|
for idx := len(keys) - 1; idx >= 1; idx-- {
|
|
|
|
keys[idx] = keys[idx-1] // yes, this makes copies
|
|
|
|
}
|
|
|
|
|
|
|
|
if err == nil {
|
|
|
|
keys[0] = newTicketKey
|
|
|
|
}
|
|
|
|
// pushes the last key out, doesn't matter that we don't have a new one
|
|
|
|
c.SetSessionTicketKeys(setSessionTicketKeysTestHook(keys))
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2015-11-11 10:46:18 +08:00
|
|
|
// RunFirstStartupFuncs runs all of the server's FirstStartup
|
|
|
|
// callback functions unless one of them returns an error first.
|
2015-11-15 09:00:18 +08:00
|
|
|
// It is the caller's responsibility to call this only once and
|
2015-11-11 10:46:18 +08:00
|
|
|
// at the correct time. The functions here should not be executed
|
|
|
|
// at restarts or where the user does not explicitly start a new
|
|
|
|
// instance of the server.
|
|
|
|
func (s *Server) RunFirstStartupFuncs() error {
|
|
|
|
for _, vh := range s.vhosts {
|
|
|
|
for _, f := range vh.config.FirstStartup {
|
|
|
|
if err := f(); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2015-10-26 08:45:55 +08:00
|
|
|
// tcpKeepAliveListener sets TCP keep-alive timeouts on accepted
|
|
|
|
// connections. It's used by ListenAndServe and ListenAndServeTLS so
|
|
|
|
// dead TCP connections (e.g. closing laptop mid-download) eventually
|
|
|
|
// go away.
|
|
|
|
//
|
|
|
|
// Borrowed from the Go standard library.
|
|
|
|
type tcpKeepAliveListener struct {
|
|
|
|
*net.TCPListener
|
|
|
|
}
|
|
|
|
|
|
|
|
// Accept accepts the connection with a keep-alive enabled.
|
|
|
|
func (ln tcpKeepAliveListener) Accept() (c net.Conn, err error) {
|
|
|
|
tc, err := ln.AcceptTCP()
|
|
|
|
if err != nil {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
tc.SetKeepAlive(true)
|
|
|
|
tc.SetKeepAlivePeriod(3 * time.Minute)
|
|
|
|
return tc, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// File implements ListenerFile; returns the underlying file of the listener.
|
|
|
|
func (ln tcpKeepAliveListener) File() (*os.File, error) {
|
|
|
|
return ln.TCPListener.File()
|
|
|
|
}
|
|
|
|
|
|
|
|
// ShutdownCallbacks executes all the shutdown callbacks
|
|
|
|
// for all the virtualhosts in servers, and returns all the
|
|
|
|
// errors generated during their execution. In other words,
|
|
|
|
// an error executing one shutdown callback does not stop
|
|
|
|
// execution of others. Only one shutdown callback is executed
|
|
|
|
// at a time. You must protect the servers that are passed in
|
|
|
|
// if they are shared across threads.
|
|
|
|
func ShutdownCallbacks(servers []*Server) []error {
|
|
|
|
var errs []error
|
|
|
|
for _, s := range servers {
|
|
|
|
for _, vhost := range s.vhosts {
|
|
|
|
for _, shutdownFunc := range vhost.config.Shutdown {
|
|
|
|
err := shutdownFunc()
|
|
|
|
if err != nil {
|
|
|
|
errs = append(errs, err)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return errs
|
|
|
|
}
|