2020-10-24 13:15:32 -06:00
|
|
|
package gemini
|
2020-09-25 17:06:56 -06:00
|
|
|
|
|
|
|
import (
|
|
|
|
"bufio"
|
|
|
|
"crypto/tls"
|
2020-09-27 23:10:36 -06:00
|
|
|
"crypto/x509"
|
2020-09-25 17:06:56 -06:00
|
|
|
"log"
|
|
|
|
"net"
|
|
|
|
"net/url"
|
|
|
|
"strconv"
|
|
|
|
"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-10-28 12:59:45 -06:00
|
|
|
// Certificates contains the certificates used by the server.
|
|
|
|
Certificates CertificateStore
|
2020-10-11 21:48:18 -06:00
|
|
|
|
2020-10-28 12:59:45 -06:00
|
|
|
// CreateCertificate, if not nil, will be called to create a new certificate
|
2020-10-31 13:38:39 -06:00
|
|
|
// if the current one is expired or missing.
|
2020-10-28 12:59:45 -06:00
|
|
|
CreateCertificate func(hostname string) (tls.Certificate, error)
|
2020-09-25 17:06:56 -06:00
|
|
|
|
2020-10-21 14:28:50 -06:00
|
|
|
// registered responders
|
|
|
|
responders map[responderKey]Responder
|
2020-10-31 13:38:39 -06:00
|
|
|
hosts map[string]bool
|
2020-10-11 15:53:22 -06:00
|
|
|
}
|
|
|
|
|
2020-10-21 14:28:50 -06:00
|
|
|
type responderKey struct {
|
2020-10-21 11:22:26 -06:00
|
|
|
scheme string
|
|
|
|
hostname string
|
2020-10-12 11:50:07 -06:00
|
|
|
}
|
|
|
|
|
2020-10-21 14:28:50 -06:00
|
|
|
// Register registers a responder for the given pattern.
|
2020-10-28 14:02:04 -06:00
|
|
|
//
|
|
|
|
// Patterns must be in the form of hostname or scheme://hostname
|
|
|
|
// (e.g. gemini://example.com).
|
2020-10-21 11:22:26 -06:00
|
|
|
// If no scheme is specified, a default scheme of gemini:// is assumed.
|
2020-10-28 14:02:04 -06:00
|
|
|
//
|
2020-10-21 11:22:26 -06:00
|
|
|
// Wildcard patterns are supported (e.g. *.example.com).
|
2020-10-28 14:50:17 -06:00
|
|
|
// To register a certificate for a wildcard hostname, call Certificates.Add:
|
2020-10-28 14:02:04 -06:00
|
|
|
//
|
|
|
|
// var s gemini.Server
|
|
|
|
// s.Certificates.Add("*.example.com", cert)
|
2020-10-21 14:28:50 -06:00
|
|
|
func (s *Server) Register(pattern string, responder Responder) {
|
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
|
|
|
}
|
2020-10-21 14:28:50 -06:00
|
|
|
if responder == 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 {
|
|
|
|
s.responders = map[responderKey]Responder{}
|
2020-10-31 13:38:39 -06:00
|
|
|
s.hosts = map[string]bool{}
|
2020-10-12 11:50:07 -06:00
|
|
|
}
|
|
|
|
|
2020-10-21 11:22:26 -06:00
|
|
|
split := strings.SplitN(pattern, "://", 2)
|
2020-10-21 14:28:50 -06:00
|
|
|
var key responderKey
|
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-11 15:53:22 -06:00
|
|
|
|
2020-10-28 12:59:45 -06:00
|
|
|
if _, ok := s.responders[key]; ok {
|
|
|
|
panic("gemini: multiple registrations for " + pattern)
|
|
|
|
}
|
2020-10-21 14:28:50 -06:00
|
|
|
s.responders[key] = responder
|
2020-10-31 13:38:39 -06:00
|
|
|
s.hosts[key.hostname] = true
|
2020-10-11 15:53:22 -06:00
|
|
|
}
|
|
|
|
|
2020-10-21 14:28:50 -06: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 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-10-24 13:15:32 -06:00
|
|
|
log.Printf("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)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-10-28 12:59:45 -06:00
|
|
|
func (s *Server) getCertificate(h *tls.ClientHelloInfo) (*tls.Certificate, error) {
|
2020-10-31 13:38:39 -06:00
|
|
|
hostname := h.ServerName
|
|
|
|
cert, err := s.Certificates.Lookup(hostname)
|
2020-10-31 13:11:05 -06:00
|
|
|
if err == ErrCertificateUnknown {
|
|
|
|
wildcard := strings.SplitN(h.ServerName, ".", 2)
|
|
|
|
if len(wildcard) == 2 {
|
|
|
|
cert, err = s.Certificates.Lookup("*." + wildcard[1])
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-10-31 13:38:39 -06:00
|
|
|
switch err {
|
|
|
|
case ErrCertificateUnknown:
|
|
|
|
if _, ok := s.hosts[hostname]; !ok {
|
|
|
|
break
|
|
|
|
}
|
|
|
|
fallthrough
|
|
|
|
|
|
|
|
case ErrCertificateExpired:
|
2020-10-28 12:59:45 -06:00
|
|
|
if s.CreateCertificate != nil {
|
|
|
|
cert, err := s.CreateCertificate(h.ServerName)
|
|
|
|
if err == nil {
|
|
|
|
s.Certificates.Add(h.ServerName, cert)
|
|
|
|
}
|
|
|
|
return &cert, err
|
|
|
|
}
|
|
|
|
}
|
2020-10-31 13:11:05 -06:00
|
|
|
|
2020-10-28 12:59:45 -06:00
|
|
|
return cert, err
|
|
|
|
}
|
|
|
|
|
2020-10-21 14:28:50 -06:00
|
|
|
// respond responds to a connection.
|
|
|
|
func (s *Server) respond(conn net.Conn) {
|
|
|
|
r := bufio.NewReader(conn)
|
|
|
|
w := newResponseWriter(conn)
|
|
|
|
// Read requested URL
|
|
|
|
rawurl, err := r.ReadString('\r')
|
|
|
|
if err != nil {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
// Read terminating line feed
|
|
|
|
if b, err := r.ReadByte(); err != nil {
|
|
|
|
return
|
|
|
|
} else if b != '\n' {
|
|
|
|
w.WriteHeader(StatusBadRequest, "Bad request")
|
|
|
|
}
|
|
|
|
// Trim carriage return
|
|
|
|
rawurl = rawurl[:len(rawurl)-1]
|
|
|
|
// Ensure URL is valid
|
|
|
|
if len(rawurl) > 1024 {
|
|
|
|
w.WriteHeader(StatusBadRequest, "Bad request")
|
|
|
|
} else if url, err := url.Parse(rawurl); err != nil || url.User != nil {
|
|
|
|
// Note that we return an error status if User is specified in the URL
|
|
|
|
w.WriteHeader(StatusBadRequest, "Bad request")
|
|
|
|
} else {
|
|
|
|
// If no scheme is specified, assume a default scheme of gemini://
|
|
|
|
if url.Scheme == "" {
|
|
|
|
url.Scheme = "gemini"
|
|
|
|
}
|
|
|
|
req := &Request{
|
|
|
|
URL: url,
|
|
|
|
RemoteAddr: conn.RemoteAddr(),
|
|
|
|
TLS: conn.(*tls.Conn).ConnectionState(),
|
|
|
|
}
|
2020-10-27 11:30:35 -06:00
|
|
|
resp := s.responder(req)
|
|
|
|
if resp != nil {
|
|
|
|
resp.Respond(w, req)
|
|
|
|
} else {
|
|
|
|
w.WriteStatus(StatusNotFound)
|
|
|
|
}
|
2020-10-21 14:28:50 -06:00
|
|
|
}
|
|
|
|
w.b.Flush()
|
|
|
|
conn.Close()
|
|
|
|
}
|
|
|
|
|
|
|
|
func (s *Server) responder(r *Request) Responder {
|
2020-10-31 13:11:05 -06:00
|
|
|
if h, ok := s.responders[responderKey{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 {
|
2020-10-31 13:11:05 -06:00
|
|
|
if h, ok := s.responders[responderKey{r.URL.Scheme, "*." + wildcard[1]}]; ok {
|
2020-10-21 14:28:50 -06:00
|
|
|
return h
|
|
|
|
}
|
|
|
|
}
|
2020-10-27 11:30:35 -06:00
|
|
|
return nil
|
2020-10-21 14:28:50 -06:00
|
|
|
}
|
|
|
|
|
2020-09-25 17:06:56 -06:00
|
|
|
// ResponseWriter is used by a Gemini handler to construct a Gemini response.
|
|
|
|
type ResponseWriter struct {
|
2020-10-13 19:00:07 -06:00
|
|
|
b *bufio.Writer
|
2020-09-25 17:06:56 -06:00
|
|
|
bodyAllowed bool
|
2020-09-27 19:53:58 -06:00
|
|
|
wroteHeader bool
|
|
|
|
mimetype string
|
2020-09-25 17:06:56 -06:00
|
|
|
}
|
|
|
|
|
|
|
|
func newResponseWriter(conn net.Conn) *ResponseWriter {
|
|
|
|
return &ResponseWriter{
|
2020-10-13 19:00:07 -06:00
|
|
|
b: bufio.NewWriter(conn),
|
2020-09-25 17:06:56 -06:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// WriteHeader writes the response header.
|
2020-09-27 19:53:58 -06:00
|
|
|
// If the header has already been written, WriteHeader does nothing.
|
2020-09-25 17:06:56 -06: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.
|
2020-10-27 11:30:35 -06:00
|
|
|
func (w *ResponseWriter) WriteHeader(status Status, meta string) {
|
2020-10-13 19:00:07 -06:00
|
|
|
if w.wroteHeader {
|
2020-09-27 19:53:58 -06:00
|
|
|
return
|
|
|
|
}
|
2020-10-27 11:30:35 -06:00
|
|
|
w.b.WriteString(strconv.Itoa(int(status)))
|
2020-10-13 19:00:07 -06:00
|
|
|
w.b.WriteByte(' ')
|
|
|
|
w.b.WriteString(meta)
|
|
|
|
w.b.Write(crlf)
|
2020-09-25 17:06:56 -06:00
|
|
|
|
|
|
|
// Only allow body to be written on successful status codes.
|
2020-10-27 11:30:35 -06:00
|
|
|
if status.Class() == StatusClassSuccess {
|
2020-10-13 19:00:07 -06:00
|
|
|
w.bodyAllowed = true
|
2020-09-25 17:06:56 -06:00
|
|
|
}
|
2020-10-13 19:00:07 -06:00
|
|
|
w.wroteHeader = true
|
2020-09-27 19:53:58 -06:00
|
|
|
}
|
|
|
|
|
2020-10-27 11:30:35 -06:00
|
|
|
// WriteStatus writes the response header with the given status code.
|
|
|
|
func (w *ResponseWriter) WriteStatus(status Status) {
|
|
|
|
w.WriteHeader(status, status.Message())
|
|
|
|
}
|
|
|
|
|
2020-09-27 19:53:58 -06:00
|
|
|
// SetMimetype sets the mimetype that will be written for a successful response.
|
|
|
|
// The provided mimetype will only be used if Write is called without calling
|
|
|
|
// WriteHeader.
|
|
|
|
// If the mimetype is not set, it will default to "text/gemini".
|
2020-10-13 19:00:07 -06:00
|
|
|
func (w *ResponseWriter) SetMimetype(mimetype string) {
|
|
|
|
w.mimetype = mimetype
|
2020-09-25 17:06:56 -06:00
|
|
|
}
|
|
|
|
|
|
|
|
// Write writes the response body.
|
|
|
|
// If the response status does not allow for a response body, Write returns
|
|
|
|
// ErrBodyNotAllowed.
|
2020-09-27 19:53:58 -06:00
|
|
|
//
|
|
|
|
// If WriteHeader has not yet been called, Write calls
|
|
|
|
// WriteHeader(StatusSuccess, mimetype) where mimetype is the mimetype set in
|
|
|
|
// SetMimetype. If no mimetype is set, a default of "text/gemini" will be used.
|
2020-10-13 19:00:07 -06:00
|
|
|
func (w *ResponseWriter) Write(b []byte) (int, error) {
|
|
|
|
if !w.wroteHeader {
|
|
|
|
mimetype := w.mimetype
|
2020-09-27 20:03:09 -06:00
|
|
|
if mimetype == "" {
|
|
|
|
mimetype = "text/gemini"
|
2020-09-27 19:53:58 -06:00
|
|
|
}
|
2020-10-13 19:00:07 -06:00
|
|
|
w.WriteHeader(StatusSuccess, mimetype)
|
2020-09-27 19:53:58 -06:00
|
|
|
}
|
2020-10-13 19:00:07 -06:00
|
|
|
if !w.bodyAllowed {
|
2020-09-25 17:06:56 -06:00
|
|
|
return 0, ErrBodyNotAllowed
|
|
|
|
}
|
2020-10-13 19:00:07 -06:00
|
|
|
return w.b.Write(b)
|
2020-09-25 17:06:56 -06:00
|
|
|
}
|
|
|
|
|
2020-10-21 14:28:50 -06: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 17:06:56 -06:00
|
|
|
}
|
|
|
|
|
2020-10-21 15:34:07 -06:00
|
|
|
// Input returns the request query.
|
|
|
|
// If no input is provided, it responds with StatusInput.
|
|
|
|
func Input(w *ResponseWriter, r *Request, prompt string) (string, bool) {
|
|
|
|
if r.URL.ForceQuery || r.URL.RawQuery != "" {
|
2020-10-27 21:35:22 -06:00
|
|
|
query, err := url.QueryUnescape(r.URL.RawQuery)
|
|
|
|
return query, err == nil
|
2020-09-28 00:05:37 -06:00
|
|
|
}
|
2020-10-21 15:34:07 -06:00
|
|
|
w.WriteHeader(StatusInput, prompt)
|
|
|
|
return "", false
|
2020-09-28 00:05:37 -06:00
|
|
|
}
|
|
|
|
|
2020-10-21 15:34:07 -06:00
|
|
|
// SensitiveInput returns the request query.
|
|
|
|
// If no input is provided, it responds with StatusSensitiveInput.
|
|
|
|
func SensitiveInput(w *ResponseWriter, r *Request, prompt string) (string, bool) {
|
|
|
|
if r.URL.ForceQuery || r.URL.RawQuery != "" {
|
2020-10-27 21:35:22 -06:00
|
|
|
query, err := url.QueryUnescape(r.URL.RawQuery)
|
|
|
|
return query, err == nil
|
2020-09-28 00:05:37 -06:00
|
|
|
}
|
2020-10-24 13:15:32 -06:00
|
|
|
w.WriteHeader(StatusSensitiveInput, prompt)
|
2020-10-21 15:34:07 -06:00
|
|
|
return "", false
|
2020-09-28 00:05:37 -06:00
|
|
|
}
|
|
|
|
|
2020-09-27 20:13:50 -06:00
|
|
|
// Redirect replies to the request with a redirect to the given URL.
|
2020-10-27 11:30:35 -06:00
|
|
|
func Redirect(w *ResponseWriter, url string) {
|
2020-10-13 18:22:12 -06:00
|
|
|
w.WriteHeader(StatusRedirect, url)
|
2020-09-27 18:52:24 -06:00
|
|
|
}
|
|
|
|
|
2020-09-27 20:06:08 -06:00
|
|
|
// PermanentRedirect replies to the request with a permanent redirect to the given URL.
|
2020-10-27 11:30:35 -06:00
|
|
|
func PermanentRedirect(w *ResponseWriter, url string) {
|
2020-10-13 18:22:12 -06:00
|
|
|
w.WriteHeader(StatusRedirectPermanent, url)
|
2020-09-27 18:52:24 -06:00
|
|
|
}
|
|
|
|
|
2020-10-21 15:47:34 -06:00
|
|
|
// Certificate returns the request certificate. If one is not provided,
|
|
|
|
// it returns nil and responds with StatusCertificateRequired.
|
|
|
|
func Certificate(w *ResponseWriter, r *Request) (*x509.Certificate, bool) {
|
2020-10-13 18:22:12 -06:00
|
|
|
if len(r.TLS.PeerCertificates) == 0 {
|
2020-10-27 11:30:35 -06:00
|
|
|
w.WriteStatus(StatusCertificateRequired)
|
2020-10-21 15:47:34 -06:00
|
|
|
return nil, false
|
2020-09-27 23:10:36 -06:00
|
|
|
}
|
2020-10-21 15:47:34 -06:00
|
|
|
return r.TLS.PeerCertificates[0], true
|
2020-09-27 23:10:36 -06:00
|
|
|
}
|
|
|
|
|
2020-10-24 13:29:12 -06:00
|
|
|
// ResponderFunc is a wrapper around a bare function that implements Responder.
|
2020-10-21 14:28:50 -06:00
|
|
|
type ResponderFunc func(*ResponseWriter, *Request)
|
2020-09-25 17:06:56 -06:00
|
|
|
|
2020-10-21 14:28:50 -06:00
|
|
|
func (f ResponderFunc) Respond(w *ResponseWriter, r *Request) {
|
2020-10-13 18:22:12 -06:00
|
|
|
f(w, r)
|
2020-09-25 17:06:56 -06:00
|
|
|
}
|