2020-10-24 19:15:32 +00:00
|
|
|
package gemini
|
2020-09-25 23:06:56 +00:00
|
|
|
|
|
|
|
import (
|
2021-02-15 04:58:28 +00:00
|
|
|
"context"
|
2020-09-25 23:06:56 +00:00
|
|
|
"crypto/tls"
|
2020-11-05 20:27:12 +00:00
|
|
|
"errors"
|
2020-09-25 23:06:56 +00:00
|
|
|
"log"
|
|
|
|
"net"
|
2021-02-15 05:36:08 +00:00
|
|
|
"runtime"
|
2021-02-15 04:58:28 +00:00
|
|
|
"sync"
|
|
|
|
"sync/atomic"
|
2020-09-25 23:06:56 +00:00
|
|
|
"time"
|
|
|
|
)
|
|
|
|
|
2021-02-14 20:50:41 +00:00
|
|
|
// A Server defines parameters for running a Gemini server. The zero value for
|
|
|
|
// Server is a valid configuration.
|
2020-09-25 23:06:56 +00:00
|
|
|
type Server struct {
|
2021-02-14 20:50:41 +00:00
|
|
|
// Addr optionally specifies the TCP address for the server to listen on,
|
|
|
|
// in the form "host:port". If empty, ":1965" (port 1965) is used.
|
|
|
|
// See net.Dial for details of the address format.
|
2020-09-25 23:06:56 +00:00
|
|
|
Addr string
|
|
|
|
|
2021-02-18 01:30:59 +00:00
|
|
|
// The Handler to invoke.
|
|
|
|
Handler Handler
|
|
|
|
|
2021-02-14 20:50:41 +00:00
|
|
|
// ReadTimeout is the maximum duration for reading the entire
|
|
|
|
// request.
|
|
|
|
//
|
|
|
|
// A ReadTimeout of zero means no timeout.
|
2020-11-01 01:07:02 +00:00
|
|
|
ReadTimeout time.Duration
|
|
|
|
|
|
|
|
// WriteTimeout is the maximum duration before timing out
|
|
|
|
// writes of the response.
|
2021-02-14 20:50:41 +00:00
|
|
|
//
|
|
|
|
// A WriteTimeout of zero means no timeout.
|
2020-11-01 01:07:02 +00:00
|
|
|
WriteTimeout time.Duration
|
|
|
|
|
2021-02-19 23:53:06 +00:00
|
|
|
// GetCertificate returns a TLS certificate based on the given
|
|
|
|
// hostname.
|
|
|
|
//
|
|
|
|
// If GetCertificate is nil or returns nil, then no certificate
|
|
|
|
// will be used and the connection will be aborted.
|
2021-02-19 03:22:17 +00:00
|
|
|
GetCertificate func(hostname string) (*tls.Certificate, error)
|
2020-09-25 23:06:56 +00:00
|
|
|
|
2021-02-14 20:50:41 +00:00
|
|
|
// ErrorLog specifies an optional logger for errors accepting connections,
|
|
|
|
// unexpected behavior from handlers, and underlying file system errors.
|
2020-11-03 21:11:31 +00:00
|
|
|
// If nil, logging is done via the log package's standard logger.
|
|
|
|
ErrorLog *log.Logger
|
|
|
|
|
2021-02-15 04:58:28 +00:00
|
|
|
listeners map[*net.Listener]struct{}
|
|
|
|
conns map[*net.Conn]struct{}
|
|
|
|
done int32
|
|
|
|
mu sync.Mutex
|
2020-10-11 21:53:22 +00:00
|
|
|
}
|
|
|
|
|
2020-09-25 23:06:56 +00:00
|
|
|
// ListenAndServe listens for requests at the server's configured address.
|
2021-02-14 20:50:41 +00:00
|
|
|
// ListenAndServe listens on the TCP network address srv.Addr and then calls
|
|
|
|
// Serve to handle requests on incoming connections.
|
|
|
|
//
|
|
|
|
// If srv.Addr is blank, ":1965" is used.
|
|
|
|
//
|
|
|
|
// ListenAndServe always returns a non-nil error. After Shutdown or Close, the
|
|
|
|
// returned error is ErrServerClosed.
|
|
|
|
func (srv *Server) ListenAndServe() error {
|
2021-02-16 01:16:32 +00:00
|
|
|
if atomic.LoadInt32(&srv.done) == 1 {
|
|
|
|
return ErrServerClosed
|
|
|
|
}
|
|
|
|
|
2021-02-14 20:50:41 +00:00
|
|
|
addr := srv.Addr
|
2020-09-25 23:06:56 +00:00
|
|
|
if addr == "" {
|
|
|
|
addr = ":1965"
|
|
|
|
}
|
|
|
|
|
|
|
|
ln, err := net.Listen("tcp", addr)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
defer ln.Close()
|
|
|
|
|
2021-02-14 20:50:41 +00:00
|
|
|
return srv.Serve(tls.NewListener(ln, &tls.Config{
|
2020-10-28 18:59:45 +00:00
|
|
|
ClientAuth: tls.RequestClientCert,
|
|
|
|
MinVersion: tls.VersionTLS12,
|
2021-02-14 20:50:41 +00:00
|
|
|
GetCertificate: srv.getCertificate,
|
2020-10-28 18:59:45 +00:00
|
|
|
}))
|
2020-09-25 23:06:56 +00:00
|
|
|
}
|
|
|
|
|
2021-02-15 04:58:28 +00:00
|
|
|
func (srv *Server) trackListener(l *net.Listener) {
|
|
|
|
srv.mu.Lock()
|
|
|
|
defer srv.mu.Unlock()
|
|
|
|
if srv.listeners == nil {
|
|
|
|
srv.listeners = make(map[*net.Listener]struct{})
|
|
|
|
}
|
|
|
|
srv.listeners[l] = struct{}{}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (srv *Server) deleteListener(l *net.Listener) {
|
|
|
|
srv.mu.Lock()
|
|
|
|
defer srv.mu.Unlock()
|
|
|
|
delete(srv.listeners, l)
|
|
|
|
}
|
|
|
|
|
2021-02-14 20:50:41 +00:00
|
|
|
// Serve accepts incoming connections on the Listener l, creating a new
|
|
|
|
// service goroutine for each. The service goroutines read requests and
|
|
|
|
// then calls the appropriate Handler to reply to them.
|
|
|
|
//
|
|
|
|
// Serve always returns a non-nil error and closes l. After Shutdown or Close,
|
|
|
|
// the returned error is ErrServerClosed.
|
|
|
|
func (srv *Server) Serve(l net.Listener) error {
|
2021-02-15 04:58:28 +00:00
|
|
|
defer l.Close()
|
|
|
|
|
2021-02-16 01:18:08 +00:00
|
|
|
srv.trackListener(&l)
|
|
|
|
defer srv.deleteListener(&l)
|
|
|
|
|
2021-02-15 04:58:28 +00:00
|
|
|
if atomic.LoadInt32(&srv.done) == 1 {
|
|
|
|
return ErrServerClosed
|
|
|
|
}
|
|
|
|
|
2020-09-25 23:06:56 +00:00
|
|
|
var tempDelay time.Duration // how long to sleep on accept failure
|
|
|
|
|
|
|
|
for {
|
|
|
|
rw, err := l.Accept()
|
|
|
|
if err != nil {
|
2021-02-15 04:58:28 +00:00
|
|
|
if atomic.LoadInt32(&srv.done) == 1 {
|
|
|
|
return ErrServerClosed
|
|
|
|
}
|
2020-09-25 23:06:56 +00:00
|
|
|
// If this is a temporary error, sleep
|
|
|
|
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
|
|
|
|
}
|
2021-02-14 20:50:41 +00:00
|
|
|
srv.logf("gemini: Accept error: %v; retrying in %v", err, tempDelay)
|
2020-09-25 23:06:56 +00:00
|
|
|
time.Sleep(tempDelay)
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
|
|
|
// Otherwise, return the error
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
tempDelay = 0
|
2021-02-14 20:50:41 +00:00
|
|
|
go srv.respond(rw)
|
2020-09-25 23:06:56 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-02-15 04:58:28 +00:00
|
|
|
func (srv *Server) closeListenersLocked() error {
|
|
|
|
var err error
|
|
|
|
for ln := range srv.listeners {
|
|
|
|
if cerr := (*ln).Close(); cerr != nil && err == nil {
|
|
|
|
err = cerr
|
|
|
|
}
|
|
|
|
delete(srv.listeners, ln)
|
|
|
|
}
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
// Close immediately closes all active net.Listeners and connections.
|
|
|
|
// For a graceful shutdown, use Shutdown.
|
|
|
|
//
|
|
|
|
// Close returns any error returned from closing the Server's
|
|
|
|
// underlying Listener(s).
|
|
|
|
func (srv *Server) Close() error {
|
|
|
|
srv.mu.Lock()
|
|
|
|
defer srv.mu.Unlock()
|
|
|
|
if !atomic.CompareAndSwapInt32(&srv.done, 0, 1) {
|
|
|
|
return ErrServerClosed
|
|
|
|
}
|
|
|
|
err := srv.closeListenersLocked()
|
|
|
|
|
|
|
|
// Close active connections
|
|
|
|
for conn := range srv.conns {
|
|
|
|
(*conn).Close()
|
|
|
|
delete(srv.conns, conn)
|
|
|
|
}
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
func (srv *Server) numConns() int {
|
|
|
|
srv.mu.Lock()
|
|
|
|
defer srv.mu.Unlock()
|
|
|
|
return len(srv.conns)
|
|
|
|
}
|
|
|
|
|
|
|
|
// shutdownPollInterval is how often we poll for quiescence
|
|
|
|
// during Server.Shutdown. This is lower during tests, to
|
|
|
|
// speed up tests.
|
|
|
|
// Ideally we could find a solution that doesn't involve polling,
|
|
|
|
// but which also doesn't have a high runtime cost (and doesn't
|
|
|
|
// involve any contentious mutexes), but that is left as an
|
|
|
|
// exercise for the reader.
|
|
|
|
var shutdownPollInterval = 500 * time.Millisecond
|
|
|
|
|
|
|
|
// Shutdown gracefully shuts down the server without interrupting any
|
|
|
|
// active connections. Shutdown works by first closing all open
|
|
|
|
// listeners and then waiting indefinitely for connections
|
|
|
|
// to close and then shut down.
|
|
|
|
// If the provided context expires before the shutdown is complete,
|
|
|
|
// Shutdown returns the context's error, otherwise it returns any
|
|
|
|
// error returned from closing the Server's underlying Listener(s).
|
|
|
|
//
|
|
|
|
// When Shutdown is called, Serve, ListenAndServe, and
|
|
|
|
// ListenAndServeTLS immediately return ErrServerClosed. Make sure the
|
|
|
|
// program doesn't exit and waits instead for Shutdown to return.
|
|
|
|
//
|
|
|
|
// Once Shutdown has been called on a server, it may not be reused;
|
|
|
|
// future calls to methods such as Serve will return ErrServerClosed.
|
|
|
|
func (srv *Server) Shutdown(ctx context.Context) error {
|
|
|
|
if !atomic.CompareAndSwapInt32(&srv.done, 0, 1) {
|
|
|
|
return ErrServerClosed
|
|
|
|
}
|
|
|
|
|
|
|
|
srv.mu.Lock()
|
|
|
|
err := srv.closeListenersLocked()
|
|
|
|
srv.mu.Unlock()
|
|
|
|
|
|
|
|
// Wait for active connections to close
|
|
|
|
ticker := time.NewTicker(shutdownPollInterval)
|
|
|
|
defer ticker.Stop()
|
|
|
|
for {
|
|
|
|
if srv.numConns() == 0 {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
select {
|
|
|
|
case <-ctx.Done():
|
|
|
|
return ctx.Err()
|
|
|
|
case <-ticker.C:
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-02-14 20:50:41 +00:00
|
|
|
func (srv *Server) getCertificate(h *tls.ClientHelloInfo) (*tls.Certificate, error) {
|
2021-02-19 03:22:17 +00:00
|
|
|
if srv.GetCertificate == nil {
|
|
|
|
return nil, errors.New("gemini: GetCertificate is nil")
|
2020-10-31 19:11:05 +00:00
|
|
|
}
|
2021-02-19 03:22:17 +00:00
|
|
|
return srv.GetCertificate(h.ServerName)
|
2020-10-28 18:59:45 +00:00
|
|
|
}
|
|
|
|
|
2021-02-15 04:58:28 +00:00
|
|
|
func (srv *Server) trackConn(conn *net.Conn) {
|
|
|
|
srv.mu.Lock()
|
|
|
|
defer srv.mu.Unlock()
|
|
|
|
if srv.conns == nil {
|
|
|
|
srv.conns = make(map[*net.Conn]struct{})
|
|
|
|
}
|
|
|
|
srv.conns[conn] = struct{}{}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (srv *Server) deleteConn(conn *net.Conn) {
|
|
|
|
srv.mu.Lock()
|
|
|
|
defer srv.mu.Unlock()
|
|
|
|
delete(srv.conns, conn)
|
|
|
|
}
|
|
|
|
|
2020-10-21 20:28:50 +00:00
|
|
|
// respond responds to a connection.
|
2021-02-14 20:50:41 +00:00
|
|
|
func (srv *Server) respond(conn net.Conn) {
|
2020-12-18 06:41:14 +00:00
|
|
|
defer conn.Close()
|
2021-02-15 04:58:28 +00:00
|
|
|
|
2021-02-15 05:36:08 +00:00
|
|
|
defer func() {
|
|
|
|
if err := recover(); err != nil && err != ErrAbortHandler {
|
|
|
|
const size = 64 << 10
|
|
|
|
buf := make([]byte, size)
|
|
|
|
buf = buf[:runtime.Stack(buf, false)]
|
|
|
|
srv.logf("gemini: panic serving %v: %v\n%s", conn.RemoteAddr(), err, buf)
|
|
|
|
}
|
|
|
|
}()
|
|
|
|
|
2021-02-15 04:58:28 +00:00
|
|
|
srv.trackConn(&conn)
|
|
|
|
defer srv.deleteConn(&conn)
|
|
|
|
|
2021-02-14 20:50:41 +00:00
|
|
|
if d := srv.ReadTimeout; d != 0 {
|
|
|
|
conn.SetReadDeadline(time.Now().Add(d))
|
2020-11-01 01:07:02 +00:00
|
|
|
}
|
2021-02-14 20:50:41 +00:00
|
|
|
if d := srv.WriteTimeout; d != 0 {
|
|
|
|
conn.SetWriteDeadline(time.Now().Add(d))
|
2020-11-01 01:07:02 +00:00
|
|
|
}
|
|
|
|
|
2021-02-17 16:44:11 +00:00
|
|
|
w := newResponseWriter(conn)
|
2020-12-18 06:41:14 +00:00
|
|
|
|
|
|
|
req, err := ReadRequest(conn)
|
2020-10-21 20:28:50 +00:00
|
|
|
if err != nil {
|
2021-02-17 18:36:16 +00:00
|
|
|
w.WriteHeader(StatusBadRequest, "Bad request")
|
2021-02-15 05:36:08 +00:00
|
|
|
w.Flush()
|
2021-01-05 19:16:33 +00:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
// Store information about the TLS connection
|
|
|
|
if tlsConn, ok := conn.(*tls.Conn); ok {
|
2021-02-08 17:32:47 +00:00
|
|
|
state := tlsConn.ConnectionState()
|
|
|
|
req.TLS = &state
|
2021-02-20 23:12:51 +00:00
|
|
|
req.Host = state.ServerName
|
2020-12-18 06:41:14 +00:00
|
|
|
}
|
2020-11-01 21:25:59 +00:00
|
|
|
|
2021-02-14 02:10:19 +00:00
|
|
|
// Store remote address
|
2021-02-20 21:27:33 +00:00
|
|
|
req.RemoteAddr = conn.RemoteAddr()
|
2021-02-14 02:10:19 +00:00
|
|
|
|
2021-02-18 01:30:59 +00:00
|
|
|
h := srv.Handler
|
2021-02-15 06:15:23 +00:00
|
|
|
if h == nil {
|
2021-02-17 18:36:16 +00:00
|
|
|
w.WriteHeader(StatusNotFound, "Not found")
|
2021-02-15 05:36:08 +00:00
|
|
|
w.Flush()
|
2021-01-05 19:16:33 +00:00
|
|
|
return
|
2020-10-21 20:28:50 +00:00
|
|
|
}
|
2021-01-05 19:16:33 +00:00
|
|
|
|
2021-02-20 20:49:07 +00:00
|
|
|
// TODO: Allow configuring the server context
|
|
|
|
ctx := context.Background()
|
|
|
|
h.ServeGemini(ctx, w, req)
|
2021-02-15 05:36:08 +00:00
|
|
|
w.Flush()
|
2020-10-21 20:28:50 +00:00
|
|
|
}
|
|
|
|
|
2021-02-14 20:50:41 +00:00
|
|
|
func (srv *Server) logf(format string, args ...interface{}) {
|
|
|
|
if srv.ErrorLog != nil {
|
|
|
|
srv.ErrorLog.Printf(format, args...)
|
2020-11-03 21:11:31 +00:00
|
|
|
} else {
|
|
|
|
log.Printf(format, args...)
|
|
|
|
}
|
|
|
|
}
|