go-gemini/server.go

273 lines
7.0 KiB
Go
Raw Normal View History

2020-10-24 13:15:32 -06:00
package gemini
2020-09-25 17:06:56 -06:00
import (
"crypto/tls"
2020-11-05 13:27:12 -07:00
"errors"
2020-09-25 17:06:56 -06:00
"log"
"net"
"strings"
"time"
2021-01-14 18:42:12 -07:00
"git.sr.ht/~adnano/go-gemini/certificate"
2020-09-25 17:06:56 -06:00
)
// Server is a Gemini server.
type Server struct {
// Addr specifies the address that the server should listen on.
// If Addr is empty, the server will listen on the address ":1965".
Addr string
// ReadTimeout is the maximum duration for reading a request.
ReadTimeout time.Duration
// WriteTimeout is the maximum duration before timing out
// writes of the response.
WriteTimeout time.Duration
2020-10-31 22:05:00 -06:00
// Certificates contains the certificates used by the server.
2021-01-14 18:42:12 -07:00
Certificates certificate.Dir
2020-10-31 22:05:00 -06:00
// GetCertificate, if not nil, will be called to retrieve a new certificate
// if the current one is expired or missing.
GetCertificate func(hostname string) (tls.Certificate, error)
2020-09-25 17:06:56 -06:00
2020-11-03 14:11:31 -07:00
// ErrorLog specifies an optional logger for errors accepting connections
// and file system errors.
// If nil, logging is done via the log package's standard logger.
ErrorLog *log.Logger
2020-10-21 14:28:50 -06:00
// registered responders
2021-02-08 10:50:50 -07:00
responders map[handlerKey]Handler
hosts map[string]bool
}
2021-02-08 10:50:50 -07:00
type handlerKey struct {
2020-10-21 11:22:26 -06:00
scheme string
hostname string
}
2021-02-08 10:50:50 -07:00
// Handle registers the handler for the given pattern.
// If a handler already exists for pattern, Handle panics.
2020-10-28 14:02:04 -06:00
//
2021-01-14 20:12:07 -07:00
// The pattern must be in the form of "hostname" or "scheme://hostname".
2020-10-31 18:32:38 -06:00
// If no scheme is specified, a scheme of "gemini://" is implied.
// Wildcard patterns are supported (e.g. "*.example.com").
// To handle any hostname, use the wildcard pattern "*".
2021-02-08 10:50:50 -07:00
func (s *Server) Handle(pattern string, handler Handler) {
2020-10-21 11:22:26 -06:00
if pattern == "" {
2020-10-24 13:15:32 -06:00
panic("gemini: invalid pattern")
2020-10-11 16:57:04 -06:00
}
2021-02-08 10:50:50 -07:00
if handler == nil {
2020-10-24 13:15:32 -06:00
panic("gemini: nil responder")
2020-10-11 16:57:04 -06:00
}
2020-10-21 14:28:50 -06:00
if s.responders == nil {
2021-02-08 10:50:50 -07:00
s.responders = map[handlerKey]Handler{}
s.hosts = map[string]bool{}
}
2020-10-21 11:22:26 -06:00
split := strings.SplitN(pattern, "://", 2)
2021-02-08 10:50:50 -07:00
var key handlerKey
2020-10-21 11:22:26 -06:00
if len(split) == 2 {
key.scheme = split[0]
key.hostname = split[1]
} else {
key.scheme = "gemini"
key.hostname = split[0]
}
2020-10-28 12:59:45 -06:00
if _, ok := s.responders[key]; ok {
panic("gemini: multiple registrations for " + pattern)
}
2021-02-08 10:50:50 -07:00
s.responders[key] = handler
s.hosts[key.hostname] = true
}
2021-02-08 10:50:50 -07:00
// HandleFunc registers the handler function for the given pattern.
2021-02-09 07:45:10 -07:00
func (s *Server) HandleFunc(pattern string, handler func(ResponseWriter, *Request)) {
2021-02-08 10:50:50 -07:00
s.Handle(pattern, HandlerFunc(handler))
2020-09-25 17:06:56 -06:00
}
// ListenAndServe listens for requests at the server's configured address.
func (s *Server) ListenAndServe() error {
addr := s.Addr
if addr == "" {
addr = ":1965"
}
ln, err := net.Listen("tcp", addr)
if err != nil {
return err
}
defer ln.Close()
2020-10-28 12:59:45 -06:00
return s.Serve(tls.NewListener(ln, &tls.Config{
ClientAuth: tls.RequestClientCert,
MinVersion: tls.VersionTLS12,
GetCertificate: s.getCertificate,
}))
2020-09-25 17:06:56 -06:00
}
// Serve listens for requests on the provided listener.
func (s *Server) Serve(l net.Listener) error {
var tempDelay time.Duration // how long to sleep on accept failure
for {
rw, err := l.Accept()
if err != nil {
// 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
}
2020-11-03 14:11:31 -07:00
s.logf("gemini: Accept error: %v; retrying in %v", err, tempDelay)
2020-09-25 17:06:56 -06:00
time.Sleep(tempDelay)
continue
}
// Otherwise, return the error
return err
}
tempDelay = 0
go s.respond(rw)
}
}
// getCertificate retrieves a certificate for the given client hello.
2020-10-28 12:59:45 -06:00
func (s *Server) getCertificate(h *tls.ClientHelloInfo) (*tls.Certificate, error) {
cert, err := s.lookupCertificate(h.ServerName, h.ServerName)
if err != nil {
// Try wildcard
2020-10-31 13:11:05 -06:00
wildcard := strings.SplitN(h.ServerName, ".", 2)
if len(wildcard) == 2 {
// Use the wildcard pattern as the hostname.
hostname := "*." + wildcard[1]
cert, err = s.lookupCertificate(hostname, hostname)
}
// Try "*" wildcard
if err != nil {
// Use the server name as the hostname
// since "*" is not a valid hostname.
cert, err = s.lookupCertificate("*", h.ServerName)
2020-10-31 13:11:05 -06:00
}
}
return cert, err
}
2020-10-31 13:11:05 -06:00
// lookupCertificate retrieves the certificate for the given hostname,
// if and only if the provided pattern is registered.
// If no certificate is found in the certificate store or the certificate
// is expired, it calls GetCertificate to retrieve a new certificate.
func (s *Server) lookupCertificate(pattern, hostname string) (*tls.Certificate, error) {
if _, ok := s.hosts[pattern]; !ok {
2020-11-05 13:27:12 -07:00
return nil, errors.New("hostname not registered")
}
2020-11-05 13:27:12 -07:00
cert, ok := s.Certificates.Lookup(hostname)
2020-11-05 20:30:13 -07:00
if !ok || cert.Leaf != nil && cert.Leaf.NotAfter.Before(time.Now()) {
if s.GetCertificate != nil {
cert, err := s.GetCertificate(hostname)
2020-10-28 12:59:45 -06:00
if err == nil {
2021-01-14 18:42:12 -07:00
if err := s.Certificates.Add(hostname, cert); err != nil {
2020-11-09 11:54:15 -07:00
s.logf("gemini: Failed to write new certificate for %s: %s", hostname, err)
2020-11-03 14:11:31 -07:00
}
2020-10-28 12:59:45 -06:00
}
return &cert, err
}
2020-11-05 13:27:12 -07:00
return nil, errors.New("no certificate")
2020-10-28 12:59:45 -06:00
}
2020-11-05 13:27:12 -07:00
return &cert, nil
2020-10-28 12:59:45 -06:00
}
2020-10-21 14:28:50 -06:00
// respond responds to a connection.
func (s *Server) respond(conn net.Conn) {
defer conn.Close()
if d := s.ReadTimeout; d != 0 {
_ = conn.SetReadDeadline(time.Now().Add(d))
}
if d := s.WriteTimeout; d != 0 {
_ = conn.SetWriteDeadline(time.Now().Add(d))
}
w := NewResponseWriter(conn)
defer func() {
_ = w.Flush()
}()
req, err := ReadRequest(conn)
2020-10-21 14:28:50 -06:00
if err != nil {
w.Status(StatusBadRequest)
return
}
// Store information about the TLS connection
if tlsConn, ok := conn.(*tls.Conn); ok {
state := tlsConn.ConnectionState()
req.TLS = &state
if len(req.TLS.PeerCertificates) > 0 {
peerCert := req.TLS.PeerCertificates[0]
// Store the TLS certificate
req.Certificate = &tls.Certificate{
Certificate: [][]byte{peerCert.Raw},
Leaf: peerCert,
}
}
}
resp := s.responder(req)
if resp == nil {
w.Status(StatusNotFound)
return
2020-10-21 14:28:50 -06:00
}
2021-02-08 10:50:50 -07:00
resp.ServeGemini(w, req)
2020-10-21 14:28:50 -06:00
}
2021-02-08 10:50:50 -07:00
func (s *Server) responder(r *Request) Handler {
if h, ok := s.responders[handlerKey{r.URL.Scheme, r.URL.Hostname()}]; ok {
2020-10-21 14:28:50 -06:00
return h
}
wildcard := strings.SplitN(r.URL.Hostname(), ".", 2)
if len(wildcard) == 2 {
2021-02-08 10:50:50 -07:00
if h, ok := s.responders[handlerKey{r.URL.Scheme, "*." + wildcard[1]}]; ok {
2020-10-21 14:28:50 -06:00
return h
}
}
2021-02-08 10:50:50 -07:00
if h, ok := s.responders[handlerKey{r.URL.Scheme, "*"}]; ok {
return h
}
return nil
2020-10-21 14:28:50 -06:00
}
2020-11-03 14:11:31 -07:00
func (s *Server) logf(format string, args ...interface{}) {
if s.ErrorLog != nil {
s.ErrorLog.Printf(format, args...)
} else {
log.Printf(format, args...)
}
}
2021-02-08 10:50:50 -07:00
// A Handler responds to a Gemini request.
//
// ServeGemini should write the response header and data to the ResponseWriter
// and then return.
type Handler interface {
2021-02-09 07:45:10 -07:00
ServeGemini(ResponseWriter, *Request)
2020-09-25 17:06:56 -06:00
}
2021-02-08 10:50:50 -07:00
// The HandlerFunc type is an adapter to allow the use of ordinary functions
// as Gemini handlers. If f is a function with the appropriate signature,
// HandlerFunc(f) is a Handler that calls f.
2021-02-09 07:45:10 -07:00
type HandlerFunc func(ResponseWriter, *Request)
2021-02-08 10:50:50 -07:00
// ServeGemini calls f(w, r).
2021-02-09 07:45:10 -07:00
func (f HandlerFunc) ServeGemini(w ResponseWriter, r *Request) {
f(w, r)
2020-09-28 00:05:37 -06:00
}