2020-10-24 19:15:32 +00:00
|
|
|
package gemini
|
2020-09-25 23:06:56 +00:00
|
|
|
|
|
|
|
import (
|
|
|
|
"bufio"
|
|
|
|
"crypto/tls"
|
2020-11-05 20:27:12 +00:00
|
|
|
"errors"
|
2021-01-07 22:08:50 +00:00
|
|
|
"fmt"
|
2020-12-18 06:47:29 +00:00
|
|
|
"io"
|
2020-09-25 23:06:56 +00:00
|
|
|
"log"
|
|
|
|
"net"
|
|
|
|
"strings"
|
|
|
|
"time"
|
|
|
|
)
|
|
|
|
|
|
|
|
// 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
|
|
|
|
|
2020-11-01 01:07:02 +00:00
|
|
|
// 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-11-01 04:05:00 +00:00
|
|
|
// Certificates contains the certificates used by the server.
|
2020-11-23 17:17:54 +00:00
|
|
|
Certificates CertificateDir
|
2020-11-01 04:05:00 +00:00
|
|
|
|
2020-10-28 18:59:45 +00:00
|
|
|
// CreateCertificate, if not nil, will be called to create a new certificate
|
2020-10-31 19:38:39 +00:00
|
|
|
// if the current one is expired or missing.
|
2020-10-28 18:59:45 +00:00
|
|
|
CreateCertificate func(hostname string) (tls.Certificate, error)
|
2020-09-25 23:06:56 +00:00
|
|
|
|
2020-11-03 21:11:31 +00: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 20:28:50 +00:00
|
|
|
// registered responders
|
|
|
|
responders map[responderKey]Responder
|
2020-10-31 19:38:39 +00:00
|
|
|
hosts map[string]bool
|
2020-10-11 21:53:22 +00:00
|
|
|
}
|
|
|
|
|
2020-10-21 20:28:50 +00:00
|
|
|
type responderKey struct {
|
2020-10-21 17:22:26 +00:00
|
|
|
scheme string
|
|
|
|
hostname string
|
2020-10-12 17:50:07 +00:00
|
|
|
}
|
|
|
|
|
2020-10-21 20:28:50 +00:00
|
|
|
// Register registers a responder for the given pattern.
|
2020-10-28 20:02:04 +00:00
|
|
|
//
|
2020-11-01 00:32:38 +00:00
|
|
|
// Patterns must be in the form of "hostname" or "scheme://hostname".
|
|
|
|
// If no scheme is specified, a scheme of "gemini://" is implied.
|
|
|
|
// Wildcard patterns are supported (e.g. "*.example.com").
|
2020-10-21 20:28:50 +00:00
|
|
|
func (s *Server) Register(pattern string, responder Responder) {
|
2020-10-21 17:22:26 +00:00
|
|
|
if pattern == "" {
|
2020-10-24 19:15:32 +00:00
|
|
|
panic("gemini: invalid pattern")
|
2020-10-11 22:57:04 +00:00
|
|
|
}
|
2020-10-21 20:28:50 +00:00
|
|
|
if responder == nil {
|
2020-10-24 19:15:32 +00:00
|
|
|
panic("gemini: nil responder")
|
2020-10-11 22:57:04 +00:00
|
|
|
}
|
2020-10-21 20:28:50 +00:00
|
|
|
if s.responders == nil {
|
|
|
|
s.responders = map[responderKey]Responder{}
|
2020-10-31 19:38:39 +00:00
|
|
|
s.hosts = map[string]bool{}
|
2020-10-12 17:50:07 +00:00
|
|
|
}
|
|
|
|
|
2020-10-21 17:22:26 +00:00
|
|
|
split := strings.SplitN(pattern, "://", 2)
|
2020-10-21 20:28:50 +00:00
|
|
|
var key responderKey
|
2020-10-21 17:22:26 +00:00
|
|
|
if len(split) == 2 {
|
|
|
|
key.scheme = split[0]
|
|
|
|
key.hostname = split[1]
|
|
|
|
} else {
|
|
|
|
key.scheme = "gemini"
|
|
|
|
key.hostname = split[0]
|
|
|
|
}
|
2020-10-11 21:53:22 +00:00
|
|
|
|
2020-10-28 18:59:45 +00:00
|
|
|
if _, ok := s.responders[key]; ok {
|
|
|
|
panic("gemini: multiple registrations for " + pattern)
|
|
|
|
}
|
2020-10-21 20:28:50 +00:00
|
|
|
s.responders[key] = responder
|
2020-10-31 19:38:39 +00:00
|
|
|
s.hosts[key.hostname] = true
|
2020-10-11 21:53:22 +00:00
|
|
|
}
|
|
|
|
|
2020-10-21 20:28:50 +00:00
|
|
|
// RegisterFunc registers a responder function for the given pattern.
|
|
|
|
func (s *Server) RegisterFunc(pattern string, responder func(*ResponseWriter, *Request)) {
|
|
|
|
s.Register(pattern, ResponderFunc(responder))
|
2020-09-25 23:06:56 +00: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 18:59:45 +00:00
|
|
|
return s.Serve(tls.NewListener(ln, &tls.Config{
|
|
|
|
ClientAuth: tls.RequestClientCert,
|
|
|
|
MinVersion: tls.VersionTLS12,
|
|
|
|
GetCertificate: s.getCertificate,
|
|
|
|
}))
|
2020-09-25 23:06:56 +00: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 21:11:31 +00:00
|
|
|
s.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
|
|
|
|
go s.respond(rw)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-10-28 18:59:45 +00:00
|
|
|
func (s *Server) getCertificate(h *tls.ClientHelloInfo) (*tls.Certificate, error) {
|
2020-10-31 20:33:56 +00:00
|
|
|
cert, err := s.getCertificateFor(h.ServerName)
|
|
|
|
if err != nil {
|
|
|
|
// Try wildcard
|
2020-10-31 19:11:05 +00:00
|
|
|
wildcard := strings.SplitN(h.ServerName, ".", 2)
|
|
|
|
if len(wildcard) == 2 {
|
2020-10-31 20:33:56 +00:00
|
|
|
cert, err = s.getCertificateFor("*." + wildcard[1])
|
2020-10-31 19:11:05 +00:00
|
|
|
}
|
|
|
|
}
|
2020-10-31 20:33:56 +00:00
|
|
|
return cert, err
|
|
|
|
}
|
2020-10-31 19:11:05 +00:00
|
|
|
|
2020-10-31 20:33:56 +00:00
|
|
|
func (s *Server) getCertificateFor(hostname string) (*tls.Certificate, error) {
|
|
|
|
if _, ok := s.hosts[hostname]; !ok {
|
2020-11-05 20:27:12 +00:00
|
|
|
return nil, errors.New("hostname not registered")
|
2020-10-31 20:33:56 +00:00
|
|
|
}
|
2020-10-31 19:38:39 +00:00
|
|
|
|
2020-11-05 20:27:12 +00:00
|
|
|
// Generate a new certificate if it is missing or expired
|
|
|
|
cert, ok := s.Certificates.Lookup(hostname)
|
2020-11-06 03:30:13 +00:00
|
|
|
if !ok || cert.Leaf != nil && cert.Leaf.NotAfter.Before(time.Now()) {
|
2020-10-28 18:59:45 +00:00
|
|
|
if s.CreateCertificate != nil {
|
2020-10-31 20:33:56 +00:00
|
|
|
cert, err := s.CreateCertificate(hostname)
|
2020-10-28 18:59:45 +00:00
|
|
|
if err == nil {
|
2020-11-09 18:54:15 +00:00
|
|
|
s.Certificates.Add(hostname, cert)
|
|
|
|
if err := s.Certificates.Write(hostname, cert); err != nil {
|
|
|
|
s.logf("gemini: Failed to write new certificate for %s: %s", hostname, err)
|
2020-11-03 21:11:31 +00:00
|
|
|
}
|
2020-10-28 18:59:45 +00:00
|
|
|
}
|
|
|
|
return &cert, err
|
|
|
|
}
|
2020-11-05 20:27:12 +00:00
|
|
|
return nil, errors.New("no certificate")
|
2020-10-28 18:59:45 +00:00
|
|
|
}
|
2020-11-05 20:27:12 +00:00
|
|
|
return &cert, nil
|
2020-10-28 18:59:45 +00:00
|
|
|
}
|
|
|
|
|
2020-10-21 20:28:50 +00:00
|
|
|
// respond responds to a connection.
|
|
|
|
func (s *Server) respond(conn net.Conn) {
|
2020-12-18 06:41:14 +00:00
|
|
|
defer conn.Close()
|
2020-11-01 01:07:02 +00:00
|
|
|
if d := s.ReadTimeout; d != 0 {
|
2021-01-07 22:08:50 +00:00
|
|
|
_ = conn.SetReadDeadline(time.Now().Add(d))
|
2020-11-01 01:07:02 +00:00
|
|
|
}
|
|
|
|
if d := s.WriteTimeout; d != 0 {
|
2021-01-07 22:08:50 +00:00
|
|
|
_ = conn.SetWriteDeadline(time.Now().Add(d))
|
2020-11-01 01:07:02 +00:00
|
|
|
}
|
|
|
|
|
2020-12-18 06:14:06 +00:00
|
|
|
w := NewResponseWriter(conn)
|
2021-01-07 22:08:50 +00:00
|
|
|
defer func() {
|
|
|
|
_ = w.Flush()
|
|
|
|
}()
|
2020-12-18 06:41:14 +00:00
|
|
|
|
|
|
|
req, err := ReadRequest(conn)
|
2020-10-21 20:28:50 +00:00
|
|
|
if err != nil {
|
2021-01-07 22:08:50 +00:00
|
|
|
w.Status(StatusBadRequest)
|
2021-01-05 19:16:33 +00:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
// Store information about the TLS connection
|
|
|
|
if tlsConn, ok := conn.(*tls.Conn); ok {
|
|
|
|
req.TLS = tlsConn.ConnectionState()
|
|
|
|
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,
|
2020-11-01 21:25:59 +00:00
|
|
|
}
|
|
|
|
}
|
2020-12-18 06:41:14 +00:00
|
|
|
}
|
2020-11-01 21:25:59 +00:00
|
|
|
|
2020-12-18 06:41:14 +00:00
|
|
|
resp := s.responder(req)
|
2021-01-05 19:16:33 +00:00
|
|
|
if resp == nil {
|
2021-01-07 22:08:50 +00:00
|
|
|
w.Status(StatusNotFound)
|
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
|
|
|
|
|
|
|
resp.Respond(w, req)
|
2020-10-21 20:28:50 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func (s *Server) responder(r *Request) Responder {
|
2020-10-31 19:11:05 +00:00
|
|
|
if h, ok := s.responders[responderKey{r.URL.Scheme, r.URL.Hostname()}]; ok {
|
2020-10-21 20:28:50 +00:00
|
|
|
return h
|
|
|
|
}
|
|
|
|
wildcard := strings.SplitN(r.URL.Hostname(), ".", 2)
|
|
|
|
if len(wildcard) == 2 {
|
2020-10-31 19:11:05 +00:00
|
|
|
if h, ok := s.responders[responderKey{r.URL.Scheme, "*." + wildcard[1]}]; ok {
|
2020-10-21 20:28:50 +00:00
|
|
|
return h
|
|
|
|
}
|
|
|
|
}
|
2020-10-27 17:30:35 +00:00
|
|
|
return nil
|
2020-10-21 20:28:50 +00:00
|
|
|
}
|
|
|
|
|
2020-11-03 21:11:31 +00:00
|
|
|
func (s *Server) logf(format string, args ...interface{}) {
|
|
|
|
if s.ErrorLog != nil {
|
|
|
|
s.ErrorLog.Printf(format, args...)
|
|
|
|
} else {
|
|
|
|
log.Printf(format, args...)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-09-25 23:06:56 +00:00
|
|
|
// ResponseWriter is used by a Gemini handler to construct a Gemini response.
|
|
|
|
type ResponseWriter struct {
|
2021-01-07 22:08:50 +00:00
|
|
|
status Status
|
|
|
|
meta string
|
2020-10-14 01:00:07 +00:00
|
|
|
b *bufio.Writer
|
2020-09-25 23:06:56 +00:00
|
|
|
bodyAllowed bool
|
2020-09-28 01:53:58 +00:00
|
|
|
wroteHeader bool
|
2020-11-09 18:54:15 +00:00
|
|
|
mediatype string
|
2020-09-25 23:06:56 +00:00
|
|
|
}
|
|
|
|
|
2020-12-18 06:47:29 +00:00
|
|
|
// NewResponseWriter returns a ResponseWriter that uses the provided io.Writer.
|
|
|
|
func NewResponseWriter(w io.Writer) *ResponseWriter {
|
2020-09-25 23:06:56 +00:00
|
|
|
return &ResponseWriter{
|
2020-12-18 06:47:29 +00:00
|
|
|
b: bufio.NewWriter(w),
|
2020-09-25 23:06:56 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-01-07 22:08:50 +00:00
|
|
|
// Header sets the response header.
|
2020-09-25 23:06:56 +00:00
|
|
|
//
|
|
|
|
// Meta contains more information related to the response status.
|
|
|
|
// For successful responses, Meta should contain the mimetype of the response.
|
|
|
|
// For failure responses, Meta should contain a short description of the failure.
|
|
|
|
// Meta should not be longer than 1024 bytes.
|
2021-01-07 22:08:50 +00:00
|
|
|
func (w *ResponseWriter) Header(status Status, meta string) {
|
|
|
|
w.status = status
|
|
|
|
w.meta = meta
|
|
|
|
}
|
|
|
|
|
|
|
|
// Status sets the response header to the given status code.
|
|
|
|
//
|
|
|
|
// Status is equivalent to Header(status, status.Message())
|
|
|
|
func (w *ResponseWriter) Status(status Status) {
|
|
|
|
meta := status.Message()
|
2020-09-25 23:06:56 +00:00
|
|
|
|
2020-10-27 17:30:35 +00:00
|
|
|
if status.Class() == StatusClassSuccess {
|
2021-01-07 22:08:50 +00:00
|
|
|
meta = w.mediatype
|
2020-09-25 23:06:56 +00:00
|
|
|
}
|
2020-09-28 01:53:58 +00:00
|
|
|
|
2021-01-07 22:08:50 +00:00
|
|
|
w.Header(status, meta)
|
2020-10-27 17:30:35 +00:00
|
|
|
}
|
|
|
|
|
2020-11-09 18:44:42 +00:00
|
|
|
// SetMediaType sets the media type that will be written for a successful response.
|
2020-09-28 01:53:58 +00:00
|
|
|
// If the mimetype is not set, it will default to "text/gemini".
|
2020-11-09 18:44:42 +00:00
|
|
|
func (w *ResponseWriter) SetMediaType(mediatype string) {
|
|
|
|
w.mediatype = mediatype
|
2020-09-25 23:06:56 +00:00
|
|
|
}
|
|
|
|
|
2020-12-18 18:15:17 +00:00
|
|
|
// Write writes data to the connection as part of the response body.
|
2020-09-25 23:06:56 +00:00
|
|
|
// If the response status does not allow for a response body, Write returns
|
|
|
|
// ErrBodyNotAllowed.
|
2020-09-28 01:53:58 +00:00
|
|
|
//
|
2020-11-01 00:32:38 +00:00
|
|
|
// If the response header has not yet been written, Write calls WriteHeader
|
|
|
|
// with StatusSuccess and the mimetype set in SetMimetype.
|
2020-10-14 01:00:07 +00:00
|
|
|
func (w *ResponseWriter) Write(b []byte) (int, error) {
|
|
|
|
if !w.wroteHeader {
|
2021-01-07 22:08:50 +00:00
|
|
|
err := w.writeHeader()
|
|
|
|
if err != nil {
|
|
|
|
return 0, err
|
2020-09-28 01:53:58 +00:00
|
|
|
}
|
|
|
|
}
|
2021-01-07 22:08:50 +00:00
|
|
|
|
2020-10-14 01:00:07 +00:00
|
|
|
if !w.bodyAllowed {
|
2020-09-25 23:06:56 +00:00
|
|
|
return 0, ErrBodyNotAllowed
|
|
|
|
}
|
2021-01-07 22:08:50 +00:00
|
|
|
|
2020-10-14 01:00:07 +00:00
|
|
|
return w.b.Write(b)
|
2020-09-25 23:06:56 +00:00
|
|
|
}
|
|
|
|
|
2021-01-07 22:08:50 +00:00
|
|
|
func (w *ResponseWriter) writeHeader() error {
|
|
|
|
status := w.status
|
|
|
|
if status == 0 {
|
|
|
|
status = StatusSuccess
|
|
|
|
}
|
|
|
|
|
|
|
|
meta := w.meta
|
|
|
|
|
|
|
|
if status.Class() == StatusClassSuccess {
|
|
|
|
w.bodyAllowed = true
|
|
|
|
|
|
|
|
if meta == "" {
|
|
|
|
meta = w.mediatype
|
|
|
|
}
|
|
|
|
|
|
|
|
if meta == "" {
|
|
|
|
meta = "text/gemini"
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
_, err := fmt.Fprintf(w.b, "%d %s\r\n", int(status), meta)
|
|
|
|
if err != nil {
|
|
|
|
return fmt.Errorf("failed to write response header: %w", err)
|
|
|
|
}
|
|
|
|
|
|
|
|
w.wroteHeader = true
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2020-12-18 18:15:17 +00:00
|
|
|
// Flush writes any buffered data to the underlying io.Writer.
|
|
|
|
func (w *ResponseWriter) Flush() error {
|
2021-01-07 22:08:50 +00:00
|
|
|
if !w.wroteHeader {
|
|
|
|
err := w.writeHeader()
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-12-18 18:15:17 +00:00
|
|
|
return w.b.Flush()
|
|
|
|
}
|
|
|
|
|
2020-10-21 20:28:50 +00:00
|
|
|
// A Responder responds to a Gemini request.
|
|
|
|
type Responder interface {
|
|
|
|
// Respond accepts a Request and constructs a Response.
|
|
|
|
Respond(*ResponseWriter, *Request)
|
2020-09-25 23:06:56 +00:00
|
|
|
}
|
|
|
|
|
2020-11-01 19:35:03 +00:00
|
|
|
// ResponderFunc is a wrapper around a bare function that implements Responder.
|
|
|
|
type ResponderFunc func(*ResponseWriter, *Request)
|
|
|
|
|
|
|
|
func (f ResponderFunc) Respond(w *ResponseWriter, r *Request) {
|
|
|
|
f(w, r)
|
2020-09-28 06:05:37 +00:00
|
|
|
}
|