40 Commits

Author SHA1 Message Date
Adnan Maolood
7fb1b6c6a4 Update documentation 2020-11-01 00:10:30 -04:00
Adnan Maolood
0d3230a7d5 Rename InsecureTrustAlways to InsecureSkipTrust 2020-10-31 23:41:30 -04:00
Adnan Maolood
79b3b22e69 Update documentation 2020-10-31 23:05:31 -04:00
Adnan Maolood
33c1dc435d Guarantee that (*Response).Body is non-nil 2020-10-31 23:04:47 -04:00
Adnan Maolood
dad8f38bfb Fix examples/client.go 2020-10-31 22:50:42 -04:00
Adnan Maolood
8181b86759 Add option to skip trust checks 2020-10-31 22:45:21 -04:00
Adnan Maolood
65a5065250 Refactor client.TrustCertificate workflow 2020-10-31 22:34:51 -04:00
Adnan Maolood
b9cb7fe71d Update log.Printf calls 2020-10-31 21:33:59 -04:00
Adnan Maolood
7d470c5fb1 Implement Server read and write timeouts 2020-10-31 21:07:02 -04:00
Adnan Maolood
42c95f8c8d Implement Client connection timeout 2020-10-31 20:55:56 -04:00
Adnan Maolood
a2fc1772bf Set default mimetype if META is empty 2020-10-31 20:32:38 -04:00
Adnan Maolood
63b9b484d1 Remove Redirect and PermanentRedirect functions
Use (*ResponseWriter).WriteHeader instead.
2020-10-31 16:51:10 -04:00
Adnan Maolood
ca8e0166fc Add ErrCertificateNotFound 2020-10-31 16:45:38 -04:00
Adnan Maolood
14ef3be6fe server: Automatically write new certificates to disk 2020-10-31 16:33:56 -04:00
Adnan Maolood
3aa254870a Call CreateCertificate for missing certificates 2020-10-31 15:38:39 -04:00
Adnan Maolood
a89065babb Fix handling of wildcard hostnames 2020-10-31 15:11:05 -04:00
Adnan Maolood
eb466ad02f Add ParseLines function 2020-10-29 09:42:53 -04:00
Adnan Maolood
66e4dc86d5 Add optional host argument in examples/client.go 2020-10-28 16:50:17 -04:00
Adnan Maolood
5e4a38dccb Fix documentation 2020-10-28 16:04:14 -04:00
Adnan Maolood
b5fbd197a1 Update documentation 2020-10-28 16:02:04 -04:00
Adnan Maolood
34ae2a9066 Use strings.Builder in Fingerprint 2020-10-28 15:14:24 -04:00
Adnan Maolood
7f0b1fa8a1 Refactor server certificates 2020-10-28 15:03:54 -04:00
Adnan Maolood
32f22a3e2c Fix examples/cert.go 2020-10-28 13:47:52 -04:00
Adnan Maolood
fbd97a62de Refactor client certificates 2020-10-28 13:41:24 -04:00
Adnan Maolood
768664e0c5 Add ErrInputRequired and ErrCertificateRequired 2020-10-28 01:06:08 -04:00
Adnan Maolood
7a1a33513a Store a reference to the Request in Response 2020-10-28 00:21:27 -04:00
Adnan Maolood
e6072d8bbc Ensure absolute paths in client certificate store 2020-10-27 23:47:13 -04:00
Adnan Maolood
4c5167f590 Add Client.GetInput field 2020-10-27 23:35:22 -04:00
Adnan Maolood
d1dcf070ff Restrict client certificates to certain paths 2020-10-27 23:34:06 -04:00
Adnan Maolood
fc72224ce9 client: Follow redirects 2020-10-27 22:12:10 -04:00
Adnan Maolood
b84811668c Reject schemes other than gemini:// in NewRequest 2020-10-27 21:18:05 -04:00
Adnan Maolood
239ec885f7 Add (*Client).Get function 2020-10-27 19:22:34 -04:00
Adnan Maolood
12a9deb1a6 Make (*Response).Body an io.ReadCloser 2020-10-27 19:16:55 -04:00
Adnan Maolood
860a33f5a2 Fix examples 2020-10-27 14:17:14 -04:00
Adnan Maolood
9079be9019 Add ServeFile function 2020-10-27 13:32:48 -04:00
Adnan Maolood
79165833de Add (*ResponseWriter).WriteStatus function 2020-10-27 13:30:35 -04:00
Adnan Maolood
8ab4064841 Add NewRequestFromURL function 2020-10-27 13:27:52 -04:00
Adnan Maolood
c44f011b15 Remove (Text).HTML function 2020-10-26 12:49:16 -04:00
Adnan Maolood
192065d0e6 Add contributing instructions to README.md 2020-10-24 21:55:58 -04:00
Adnan Maolood
255eef9e31 Add import path to README.md 2020-10-24 16:58:35 -04:00
18 changed files with 1058 additions and 907 deletions

View File

@@ -6,9 +6,19 @@ Package gemini implements the [Gemini protocol](https://gemini.circumlunar.space
It aims to provide an API similar to that of net/http to make it easy to develop Gemini clients and servers. It aims to provide an API similar to that of net/http to make it easy to develop Gemini clients and servers.
## Usage
import "git.sr.ht/~adnano/go-gemini"
## Examples ## Examples
There are a few examples provided in the `examples` directory. There are a few examples provided in the examples directory.
To run the examples: To run an example:
go run examples/server.go go run examples/server.go
## Contributing
Send patches and questions to [~adnano/go-gemini-devel](https://lists.sr.ht/~adnano/go-gemini-devel).
Subscribe to release announcements on [~adnano/go-gemini-announce](https://lists.sr.ht/~adnano/go-gemini-announce).

94
cert.go
View File

@@ -6,22 +6,27 @@ import (
"crypto/rand" "crypto/rand"
"crypto/tls" "crypto/tls"
"crypto/x509" "crypto/x509"
"encoding/pem"
"log"
"math/big" "math/big"
"net" "net"
"os"
"path/filepath" "path/filepath"
"strings" "strings"
"time" "time"
) )
// CertificateStore maps hostnames to certificates. // CertificateStore maps certificate scopes to certificates.
// The zero value of CertificateStore is an empty store ready to use. // The zero value of CertificateStore is an empty store ready to use.
type CertificateStore struct { type CertificateStore struct {
store map[string]tls.Certificate store map[string]tls.Certificate
dir bool
path string
} }
// Add adds a certificate for the given hostname to the store. // Add adds a certificate for the given scope to the store.
// It tries to parse the certificate if it is not already parsed. // It tries to parse the certificate if it is not already parsed.
func (c *CertificateStore) Add(hostname string, cert tls.Certificate) { func (c *CertificateStore) Add(scope string, cert tls.Certificate) {
if c.store == nil { if c.store == nil {
c.store = map[string]tls.Certificate{} c.store = map[string]tls.Certificate{}
} }
@@ -32,14 +37,23 @@ func (c *CertificateStore) Add(hostname string, cert tls.Certificate) {
cert.Leaf = parsed cert.Leaf = parsed
} }
} }
c.store[hostname] = cert if c.dir {
// Write certificates
log.Printf("gemini: Writing certificate for %s to %s", scope, c.path)
certPath := filepath.Join(c.path, scope+".crt")
keyPath := filepath.Join(c.path, scope+".key")
if err := WriteCertificate(cert, certPath, keyPath); err != nil {
log.Printf("gemini: Failed to write certificate for %s: %s", scope, err)
}
}
c.store[scope] = cert
} }
// Lookup returns the certificate for the given hostname. // Lookup returns the certificate for the given scope.
func (c *CertificateStore) Lookup(hostname string) (*tls.Certificate, error) { func (c *CertificateStore) Lookup(scope string) (*tls.Certificate, error) {
cert, ok := c.store[hostname] cert, ok := c.store[scope]
if !ok { if !ok {
return nil, ErrCertificateUnknown return nil, ErrCertificateNotFound
} }
// Ensure that the certificate is not expired // Ensure that the certificate is not expired
if cert.Leaf != nil && cert.Leaf.NotAfter.Before(time.Now()) { if cert.Leaf != nil && cert.Leaf.NotAfter.Before(time.Now()) {
@@ -50,9 +64,10 @@ func (c *CertificateStore) Lookup(hostname string) (*tls.Certificate, error) {
// Load loads certificates from the given path. // Load loads certificates from the given path.
// The path should lead to a directory containing certificates and private keys // The path should lead to a directory containing certificates and private keys
// in the form hostname.crt and hostname.key. // in the form scope.crt and scope.key.
// For example, the hostname "localhost" would have the corresponding files // For example, the hostname "localhost" would have the corresponding files
// localhost.crt (certificate) and localhost.key (private key). // localhost.crt (certificate) and localhost.key (private key).
// New certificates will be written to this directory.
func (c *CertificateStore) Load(path string) error { func (c *CertificateStore) Load(path string) error {
matches, err := filepath.Glob(filepath.Join(path, "*.crt")) matches, err := filepath.Glob(filepath.Join(path, "*.crt"))
if err != nil { if err != nil {
@@ -64,15 +79,24 @@ func (c *CertificateStore) Load(path string) error {
if err != nil { if err != nil {
continue continue
} }
hostname := strings.TrimSuffix(filepath.Base(crtPath), ".crt") scope := strings.TrimSuffix(filepath.Base(crtPath), ".crt")
c.Add(hostname, cert) c.Add(scope, cert)
} }
c.dir = true
c.path = path
return nil return nil
} }
// NewCertificate creates and returns a new parsed certificate. // CertificateOptions configures how a certificate is created.
func NewCertificate(host string, duration time.Duration) (tls.Certificate, error) { type CertificateOptions struct {
crt, priv, err := newX509KeyPair(host, duration) IPAddresses []net.IP
DNSNames []string
Duration time.Duration
}
// CreateCertificate creates a new TLS certificate.
func CreateCertificate(options CertificateOptions) (tls.Certificate, error) {
crt, priv, err := newX509KeyPair(options)
if err != nil { if err != nil {
return tls.Certificate{}, err return tls.Certificate{}, err
} }
@@ -84,7 +108,7 @@ func NewCertificate(host string, duration time.Duration) (tls.Certificate, error
} }
// newX509KeyPair creates and returns a new certificate and private key. // newX509KeyPair creates and returns a new certificate and private key.
func newX509KeyPair(host string, duration time.Duration) (*x509.Certificate, crypto.PrivateKey, error) { func newX509KeyPair(options CertificateOptions) (*x509.Certificate, crypto.PrivateKey, error) {
// Generate an ED25519 private key // Generate an ED25519 private key
_, priv, err := ed25519.GenerateKey(rand.Reader) _, priv, err := ed25519.GenerateKey(rand.Reader)
if err != nil { if err != nil {
@@ -103,7 +127,7 @@ func newX509KeyPair(host string, duration time.Duration) (*x509.Certificate, cry
} }
notBefore := time.Now() notBefore := time.Now()
notAfter := notBefore.Add(duration) notAfter := notBefore.Add(options.Duration)
template := x509.Certificate{ template := x509.Certificate{
SerialNumber: serialNumber, SerialNumber: serialNumber,
@@ -112,15 +136,8 @@ func newX509KeyPair(host string, duration time.Duration) (*x509.Certificate, cry
KeyUsage: keyUsage, KeyUsage: keyUsage,
ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth}, ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
BasicConstraintsValid: true, BasicConstraintsValid: true,
} IPAddresses: options.IPAddresses,
DNSNames: options.DNSNames,
hosts := strings.Split(host, ",")
for _, h := range hosts {
if ip := net.ParseIP(h); ip != nil {
template.IPAddresses = append(template.IPAddresses, ip)
} else {
template.DNSNames = append(template.DNSNames, h)
}
} }
crt, err := x509.CreateCertificate(rand.Reader, &template, &template, public, priv) crt, err := x509.CreateCertificate(rand.Reader, &template, &template, public, priv)
@@ -133,3 +150,30 @@ func newX509KeyPair(host string, duration time.Duration) (*x509.Certificate, cry
} }
return cert, priv, nil return cert, priv, nil
} }
// WriteCertificate writes the provided certificate and private key
// to certPath and keyPath respectively.
func WriteCertificate(cert tls.Certificate, certPath, keyPath string) error {
certOut, err := os.OpenFile(certPath, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0600)
if err != nil {
return err
}
defer certOut.Close()
if err := pem.Encode(certOut, &pem.Block{
Type: "CERTIFICATE",
Bytes: cert.Leaf.Raw,
}); err != nil {
return err
}
keyOut, err := os.OpenFile(keyPath, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0600)
if err != nil {
return err
}
defer keyOut.Close()
privBytes, err := x509.MarshalPKCS8PrivateKey(cert.PrivateKey)
if err != nil {
return err
}
return pem.Encode(keyOut, &pem.Block{Type: "PRIVATE KEY", Bytes: privBytes})
}

232
client.go
View File

@@ -4,69 +4,97 @@ import (
"bufio" "bufio"
"crypto/tls" "crypto/tls"
"crypto/x509" "crypto/x509"
"net"
"net/url"
"path"
"strings"
"time"
) )
// Client represents a Gemini client. // Client is a Gemini client.
type Client struct { type Client struct {
// KnownHosts is a list of known hosts that the client trusts. // KnownHosts is a list of known hosts.
KnownHosts KnownHosts KnownHosts KnownHosts
// CertificateStore maps hostnames to certificates. // Certificates stores client-side certificates.
// It is used to determine which certificate to use when the server requests Certificates CertificateStore
// a certificate.
CertificateStore CertificateStore
// GetCertificate, if not nil, will be called when a server requests a certificate. // Timeout specifies a time limit for requests made by this
// The returned certificate will be used when sending the request again. // Client. The timeout includes connection time and reading
// If the certificate is nil, the request will not be sent again and // the response body. The timer remains running after
// Get and Do return and will interrupt reading of the Response.Body.
//
// A Timeout of zero means no timeout.
Timeout time.Duration
// InsecureSkipTrust specifies whether the client should trust
// any certificate it receives without checking KnownHosts
// or calling TrustCertificate.
// Use with caution.
InsecureSkipTrust bool
// GetInput is called to retrieve input when the server requests it.
// If GetInput is nil or returns false, no input will be sent and
// the response will be returned. // the response will be returned.
GetCertificate func(hostname string, store *CertificateStore) *tls.Certificate GetInput func(prompt string, sensitive bool) (input string, ok bool)
// TrustCertificate, if not nil, will be called to determine whether the // CheckRedirect determines whether to follow a redirect.
// client should trust the given certificate. // If CheckRedirect is nil, a default policy of no more than 5 consecutive
// If error is not nil, the connection will be aborted. // redirects will be enforced.
TrustCertificate func(hostname string, cert *x509.Certificate, knownHosts *KnownHosts) error CheckRedirect func(req *Request, via []*Request) error
// CreateCertificate is called to generate a certificate upon
// the request of a server.
// If CreateCertificate is nil or the returned error is not nil,
// the request will not be sent again and the response will be returned.
CreateCertificate func(hostname, path string) (tls.Certificate, error)
// TrustCertificate is called to determine whether the client
// should trust a certificate it has not seen before.
// If TrustCertificate is nil, the certificate will not be trusted
// and the connection will be aborted.
//
// If TrustCertificate returns TrustOnce, the certificate will be added
// to the client's list of known hosts.
// If TrustCertificate returns TrustAlways, the certificate will also be
// written to the known hosts file.
TrustCertificate func(hostname string, cert *x509.Certificate) Trust
} }
// Send sends a Gemini request and returns a Gemini response. // Get performs a Gemini request for the given url.
func (c *Client) Send(req *Request) (*Response, error) { func (c *Client) Get(url string) (*Response, error) {
req, err := NewRequest(url)
if err != nil {
return nil, err
}
return c.Do(req)
}
// Do performs a Gemini request and returns a Gemini response.
func (c *Client) Do(req *Request) (*Response, error) {
return c.do(req, nil)
}
func (c *Client) do(req *Request, via []*Request) (*Response, error) {
// Connect to the host // Connect to the host
config := &tls.Config{ config := &tls.Config{
InsecureSkipVerify: true, InsecureSkipVerify: true,
MinVersion: tls.VersionTLS12, MinVersion: tls.VersionTLS12,
GetClientCertificate: func(info *tls.CertificateRequestInfo) (*tls.Certificate, error) { GetClientCertificate: func(_ *tls.CertificateRequestInfo) (*tls.Certificate, error) {
// Request certificates take precedence over client certificates return c.getClientCertificate(req)
if req.Certificate != nil {
return req.Certificate, nil
}
// If we have already stored the certificate, return it
if cert, err := c.CertificateStore.Lookup(hostname(req.Host)); err == nil {
return cert, nil
}
return &tls.Certificate{}, nil
}, },
VerifyConnection: func(cs tls.ConnectionState) error { VerifyConnection: func(cs tls.ConnectionState) error {
cert := cs.PeerCertificates[0] return c.verifyConnection(req, cs)
// Verify the hostname
if err := verifyHostname(cert, hostname(req.Host)); err != nil {
return err
}
// Check that the client trusts the certificate
if c.TrustCertificate == nil {
if err := c.KnownHosts.Lookup(hostname(req.Host), cert); err != nil {
return err
}
} else if err := c.TrustCertificate(hostname(req.Host), cert, &c.KnownHosts); err != nil {
return err
}
return nil
}, },
} }
conn, err := tls.Dial("tcp", req.Host, config) conn, err := tls.Dial("tcp", req.Host, config)
if err != nil { if err != nil {
return nil, err return nil, err
} }
defer conn.Close() // Set connection deadline
if d := c.Timeout; d != 0 {
conn.SetDeadline(time.Now().Add(d))
}
// Write the request // Write the request
w := bufio.NewWriter(conn) w := bufio.NewWriter(conn)
@@ -77,26 +105,128 @@ func (c *Client) Send(req *Request) (*Response, error) {
// Read the response // Read the response
resp := &Response{} resp := &Response{}
r := bufio.NewReader(conn) if err := resp.read(conn); err != nil {
if err := resp.read(r); err != nil {
return nil, err return nil, err
} }
// Store connection information // Store connection state
resp.TLS = conn.ConnectionState() resp.TLS = conn.ConnectionState()
// Resend the request with a certificate if the server responded switch {
// with CertificateRequired case resp.Status == StatusCertificateRequired:
if resp.Status == StatusCertificateRequired {
// Check to see if a certificate was already provided to prevent an infinite loop // Check to see if a certificate was already provided to prevent an infinite loop
if req.Certificate != nil { if req.Certificate != nil {
return resp, nil return resp, nil
} }
if c.GetCertificate != nil {
if cert := c.GetCertificate(hostname(req.Host), &c.CertificateStore); cert != nil { hostname, path := req.URL.Hostname(), strings.TrimSuffix(req.URL.Path, "/")
req.Certificate = cert if c.CreateCertificate != nil {
return c.Send(req) cert, err := c.CreateCertificate(hostname, path)
if err != nil {
return resp, err
}
c.Certificates.Add(hostname+path, cert)
return c.do(req, via)
}
return resp, ErrCertificateRequired
case resp.Status.Class() == StatusClassInput:
if c.GetInput != nil {
input, ok := c.GetInput(resp.Meta, resp.Status == StatusSensitiveInput)
if ok {
req.URL.ForceQuery = true
req.URL.RawQuery = url.QueryEscape(input)
return c.do(req, via)
} }
} }
return resp, ErrInputRequired
case resp.Status.Class() == StatusClassRedirect:
if via == nil {
via = []*Request{}
}
via = append(via, req)
target, err := url.Parse(resp.Meta)
if err != nil {
return resp, err
}
target = req.URL.ResolveReference(target)
redirect, err := NewRequestFromURL(target)
if err != nil {
return resp, err
}
if c.CheckRedirect != nil {
if err := c.CheckRedirect(redirect, via); err != nil {
return resp, err
}
} else if len(via) > 5 {
// Default policy of no more than 5 redirects
return resp, ErrTooManyRedirects
}
return c.do(redirect, via)
} }
resp.Request = req
return resp, nil return resp, nil
} }
func (c *Client) getClientCertificate(req *Request) (*tls.Certificate, error) {
// Request certificates have the highest precedence
if req.Certificate != nil {
return req.Certificate, nil
}
// Search recursively for the certificate
scope := req.URL.Hostname() + strings.TrimSuffix(req.URL.Path, "/")
for {
cert, err := c.Certificates.Lookup(scope)
if err == nil {
return cert, err
}
if err == ErrCertificateExpired {
break
}
scope = path.Dir(scope)
if scope == "." {
break
}
}
return &tls.Certificate{}, nil
}
func (c *Client) verifyConnection(req *Request, cs tls.ConnectionState) error {
// Verify the hostname
var hostname string
if host, _, err := net.SplitHostPort(req.Host); err == nil {
hostname = host
} else {
hostname = req.Host
}
cert := cs.PeerCertificates[0]
if err := verifyHostname(cert, hostname); err != nil {
return err
}
if c.InsecureSkipTrust {
return nil
}
// Check the known hosts
err := c.KnownHosts.Lookup(hostname, cert)
switch err {
case ErrCertificateExpired, ErrCertificateNotFound:
// See if the client trusts the certificate
if c.TrustCertificate != nil {
switch c.TrustCertificate(hostname, cert) {
case TrustOnce:
c.KnownHosts.AddTemporary(hostname, cert)
return nil
case TrustAlways:
c.KnownHosts.Add(hostname, cert)
return nil
}
}
return ErrCertificateNotTrusted
}
return err
}

65
doc.go
View File

@@ -1,63 +1,34 @@
/* /*
Package gemini implements the Gemini protocol. Package gemini implements the Gemini protocol.
Send makes a Gemini request with the default client: Get makes a Gemini request:
req := gemini.NewRequest("gemini://example.com") resp, err := gemini.Get("gemini://example.com")
resp, err := gemini.Send(req) if err != nil {
// handle error
}
defer resp.Body.Close()
// ...
For control over client behavior, create a Client:
client := &gemini.Client{}
resp, err := client.Get("gemini://example.com")
if err != nil { if err != nil {
// handle error // handle error
} }
// ... // ...
For control over client behavior, create a custom Client:
var client gemini.Client
resp, err := client.Send(req)
if err != nil {
// handle error
}
// ...
The default client loads known hosts from "$XDG_DATA_HOME/gemini/known_hosts".
Custom clients can load their own list of known hosts:
err := client.KnownHosts.Load("path/to/my/known_hosts")
if err != nil {
// handle error
}
Clients can control when to trust certificates with TrustCertificate:
client.TrustCertificate = func(hostname string, cert *x509.Certificate, knownHosts *gemini.KnownHosts) error {
return knownHosts.Lookup(hostname, cert)
}
If a server responds with StatusCertificateRequired, the default client will generate a certificate and resend the request with it. Custom clients can do so in GetCertificate:
client.GetCertificate = func(hostname string, store *gemini.CertificateStore) *tls.Certificate {
// If the certificate is in the store, return it
if cert, err := store.Lookup(hostname); err == nil {
return &cert
}
// Otherwise, generate a certificate
duration := time.Hour
cert, err := gemini.NewCertificate(hostname, duration)
if err != nil {
return nil
}
// Store and return the certificate
store.Add(hostname, cert)
return &cert
}
Server is a Gemini server. Server is a Gemini server.
var server gemini.Server server := &gemini.Server{
ReadTimeout: 10 * time.Second,
WriteTimeout: 10 * time.Second,
}
Servers must be configured with certificates: Servers should be configured with certificates:
err := server.CertificateStore.Load("/var/lib/gemini/certs") err := server.Certificates.Load("/var/lib/gemini/certs")
if err != nil { if err != nil {
// handle error // handle error
} }

View File

@@ -7,7 +7,7 @@ import (
"fmt" "fmt"
"log" "log"
gmi "git.sr.ht/~adnano/go-gemini" "git.sr.ht/~adnano/go-gemini"
) )
type user struct { type user struct {
@@ -33,16 +33,15 @@ var (
) )
func main() { func main() {
var mux gmi.ServeMux var mux gemini.ServeMux
mux.HandleFunc("/", welcome) mux.HandleFunc("/", login)
mux.HandleFunc("/login", login) mux.HandleFunc("/password", loginPassword)
mux.HandleFunc("/login/password", loginPassword)
mux.HandleFunc("/profile", profile) mux.HandleFunc("/profile", profile)
mux.HandleFunc("/admin", admin) mux.HandleFunc("/admin", admin)
mux.HandleFunc("/logout", logout) mux.HandleFunc("/logout", logout)
var server gmi.Server var server gemini.Server
if err := server.CertificateStore.Load("/var/lib/gemini/certs"); err != nil { if err := server.Certificates.Load("/var/lib/gemini/certs"); err != nil {
log.Fatal(err) log.Fatal(err)
} }
server.Register("localhost", &mux) server.Register("localhost", &mux)
@@ -53,74 +52,69 @@ func main() {
} }
func getSession(crt *x509.Certificate) (*session, bool) { func getSession(crt *x509.Certificate) (*session, bool) {
fingerprint := gmi.Fingerprint(crt) fingerprint := gemini.Fingerprint(crt)
session, ok := sessions[fingerprint] session, ok := sessions[fingerprint]
return session, ok return session, ok
} }
func welcome(w *gmi.ResponseWriter, r *gmi.Request) { func login(w *gemini.ResponseWriter, r *gemini.Request) {
fmt.Fprintln(w, "Welcome to this example.") cert, ok := gemini.Certificate(w, r)
fmt.Fprintln(w, "=> /login Login")
}
func login(w *gmi.ResponseWriter, r *gmi.Request) {
cert, ok := gmi.Certificate(w, r)
if !ok { if !ok {
return return
} }
username, ok := gmi.Input(w, r, "Username") username, ok := gemini.Input(w, r, "Username")
if !ok { if !ok {
return return
} }
fingerprint := gmi.Fingerprint(cert) fingerprint := gemini.Fingerprint(cert)
sessions[fingerprint] = &session{ sessions[fingerprint] = &session{
username: username, username: username,
} }
gmi.Redirect(w, r, "/login/password") w.WriteHeader(gemini.StatusRedirect, "/password")
} }
func loginPassword(w *gmi.ResponseWriter, r *gmi.Request) { func loginPassword(w *gemini.ResponseWriter, r *gemini.Request) {
cert, ok := gmi.Certificate(w, r) cert, ok := gemini.Certificate(w, r)
if !ok { if !ok {
return return
} }
session, ok := getSession(cert) session, ok := getSession(cert)
if !ok { if !ok {
gmi.CertificateNotAuthorized(w, r) w.WriteStatus(gemini.StatusCertificateNotAuthorized)
return return
} }
password, ok := gmi.SensitiveInput(w, r, "Password") password, ok := gemini.SensitiveInput(w, r, "Password")
if !ok { if !ok {
return return
} }
expected := logins[session.username].password expected := logins[session.username].password
if password == expected { if password == expected {
session.authorized = true session.authorized = true
gmi.Redirect(w, r, "/profile") w.WriteHeader(gemini.StatusRedirect, "/profile")
} else { } else {
gmi.SensitiveInput(w, r, "Wrong password. Try again") gemini.SensitiveInput(w, r, "Wrong password. Try again")
} }
} }
func logout(w *gmi.ResponseWriter, r *gmi.Request) { func logout(w *gemini.ResponseWriter, r *gemini.Request) {
cert, ok := gmi.Certificate(w, r) cert, ok := gemini.Certificate(w, r)
if !ok { if !ok {
return return
} }
fingerprint := gmi.Fingerprint(cert) fingerprint := gemini.Fingerprint(cert)
delete(sessions, fingerprint) delete(sessions, fingerprint)
fmt.Fprintln(w, "Successfully logged out.") fmt.Fprintln(w, "Successfully logged out.")
} }
func profile(w *gmi.ResponseWriter, r *gmi.Request) { func profile(w *gemini.ResponseWriter, r *gemini.Request) {
cert, ok := gmi.Certificate(w, r) cert, ok := gemini.Certificate(w, r)
if !ok { if !ok {
return return
} }
session, ok := getSession(cert) session, ok := getSession(cert)
if !ok { if !ok {
gmi.CertificateNotAuthorized(w, r) w.WriteStatus(gemini.StatusCertificateNotAuthorized)
return return
} }
user := logins[session.username] user := logins[session.username]
@@ -129,19 +123,19 @@ func profile(w *gmi.ResponseWriter, r *gmi.Request) {
fmt.Fprintln(w, "=> /logout Logout") fmt.Fprintln(w, "=> /logout Logout")
} }
func admin(w *gmi.ResponseWriter, r *gmi.Request) { func admin(w *gemini.ResponseWriter, r *gemini.Request) {
cert, ok := gmi.Certificate(w, r) cert, ok := gemini.Certificate(w, r)
if !ok { if !ok {
return return
} }
session, ok := getSession(cert) session, ok := getSession(cert)
if !ok { if !ok {
gmi.CertificateNotAuthorized(w, r) w.WriteStatus(gemini.StatusCertificateNotAuthorized)
return return
} }
user := logins[session.username] user := logins[session.username]
if !user.admin { if !user.admin {
gmi.CertificateNotAuthorized(w, r) w.WriteStatus(gemini.StatusCertificateNotAuthorized)
return return
} }
fmt.Fprintln(w, "Welcome to the admin portal.") fmt.Fprintln(w, "Welcome to the admin portal.")

View File

@@ -7,17 +7,29 @@ import (
"crypto/tls" "crypto/tls"
"crypto/x509" "crypto/x509"
"encoding/pem" "encoding/pem"
"fmt"
"log" "log"
"os" "os"
"time" "time"
gmi "git.sr.ht/~adnano/go-gemini" "git.sr.ht/~adnano/go-gemini"
) )
func main() { func main() {
host := "localhost" if len(os.Args) < 3 {
duration := 365 * 24 * time.Hour fmt.Printf("usage: %s [hostname] [duration]\n", os.Args[0])
cert, err := gmi.NewCertificate(host, duration) os.Exit(1)
}
host := os.Args[1]
duration, err := time.ParseDuration(os.Args[2])
if err != nil {
log.Fatal(err)
}
options := gemini.CertificateOptions{
DNSNames: []string{host},
Duration: duration,
}
cert, err := gemini.CreateCertificate(options)
if err != nil { if err != nil {
log.Fatal(err) log.Fatal(err)
} }

View File

@@ -7,112 +7,15 @@ import (
"crypto/tls" "crypto/tls"
"crypto/x509" "crypto/x509"
"fmt" "fmt"
"io/ioutil"
"log"
"os" "os"
"time" "time"
gmi "git.sr.ht/~adnano/go-gemini" "git.sr.ht/~adnano/go-gemini"
) )
var ( const trustPrompt = `The certificate offered by %s is of unknown trust. Its fingerprint is:
scanner = bufio.NewScanner(os.Stdin)
client = &gmi.Client{}
)
func init() {
// Initialize the client
client.KnownHosts.LoadDefault() // Load known hosts
client.TrustCertificate = func(hostname string, cert *x509.Certificate, knownHosts *gmi.KnownHosts) error {
err := knownHosts.Lookup(hostname, cert)
if err != nil {
switch err {
case gmi.ErrCertificateNotTrusted:
// Alert the user that the certificate is not trusted
fmt.Printf("Warning: Certificate for %s is not trusted!\n", hostname)
fmt.Println("This could indicate a Man-in-the-Middle attack.")
case gmi.ErrCertificateUnknown:
// Prompt the user to trust the certificate
trust := trustCertificate(cert)
switch trust {
case trustOnce:
// Temporarily trust the certificate
knownHosts.AddTemporary(hostname, cert)
return nil
case trustAlways:
// Add the certificate to the known hosts file
knownHosts.Add(hostname, cert)
return nil
}
}
}
return err
}
client.GetCertificate = func(hostname string, store *gmi.CertificateStore) *tls.Certificate {
// If the certificate is in the store, return it
if cert, err := store.Lookup(hostname); err == nil {
return cert
}
// Otherwise, generate a certificate
fmt.Println("Generating client certificate for", hostname)
duration := time.Hour
cert, err := gmi.NewCertificate(hostname, duration)
if err != nil {
return nil
}
// Store and return the certificate
store.Add(hostname, cert)
return &cert
}
}
// sendRequest sends a request to the given URL.
func sendRequest(req *gmi.Request) error {
resp, err := client.Send(req)
if err != nil {
return err
}
// TODO: More fine-grained analysis of the status code.
switch resp.Status / 10 {
case gmi.StatusClassInput:
fmt.Printf("%s: ", resp.Meta)
scanner.Scan()
req.URL.RawQuery = scanner.Text()
return sendRequest(req)
case gmi.StatusClassSuccess:
fmt.Print(string(resp.Body))
return nil
case gmi.StatusClassRedirect:
fmt.Println("Redirecting to", resp.Meta)
// Make the request to the same host
red, err := gmi.NewRequestTo(resp.Meta, req.Host)
if err != nil {
return err
}
// Handle relative redirects
red.URL = req.URL.ResolveReference(red.URL)
return sendRequest(red)
case gmi.StatusClassTemporaryFailure:
return fmt.Errorf("Temporary failure: %s", resp.Meta)
case gmi.StatusClassPermanentFailure:
return fmt.Errorf("Permanent failure: %s", resp.Meta)
case gmi.StatusClassCertificateRequired:
// Note that this should not happen unless the server responds with
// CertificateRequired even after we send a certificate.
// CertificateNotAuthorized and CertificateNotValid are handled here.
return fmt.Errorf("Certificate required: %s", resp.Meta)
}
panic("unreachable")
}
type trust int
const (
trustAbort trust = iota
trustOnce
trustAlways
)
const trustPrompt = `The certificate offered by this server is of unknown trust. Its fingerprint is:
%s %s
If you knew the fingerprint to expect in advance, verify that this matches. If you knew the fingerprint to expect in advance, verify that this matches.
@@ -121,45 +24,70 @@ Otherwise, this should be safe to trust.
[t]rust always; trust [o]nce; [a]bort [t]rust always; trust [o]nce; [a]bort
=> ` => `
func trustCertificate(cert *x509.Certificate) trust { var (
fmt.Printf(trustPrompt, gmi.Fingerprint(cert)) scanner = bufio.NewScanner(os.Stdin)
scanner.Scan() client = &gemini.Client{}
switch scanner.Text() { )
case "t":
return trustAlways func init() {
case "o": client.Timeout = 2 * time.Minute
return trustOnce client.KnownHosts.LoadDefault()
default: client.TrustCertificate = func(hostname string, cert *x509.Certificate) gemini.Trust {
return trustAbort fmt.Printf(trustPrompt, hostname, gemini.Fingerprint(cert))
scanner.Scan()
switch scanner.Text() {
case "t":
return gemini.TrustAlways
case "o":
return gemini.TrustOnce
default:
return gemini.TrustNone
}
}
client.CreateCertificate = func(hostname, path string) (tls.Certificate, error) {
fmt.Println("Generating client certificate for", hostname, path)
return gemini.CreateCertificate(gemini.CertificateOptions{
Duration: time.Hour,
})
}
client.GetInput = func(prompt string, sensitive bool) (string, bool) {
fmt.Printf("%s: ", prompt)
scanner.Scan()
return scanner.Text(), true
} }
} }
func main() { func main() {
if len(os.Args) < 2 { if len(os.Args) < 2 {
fmt.Printf("usage: %s gemini://...", os.Args[0]) fmt.Printf("usage: %s gemini://... [host]", os.Args[0])
os.Exit(1) os.Exit(1)
} }
var host string
if len(os.Args) >= 3 {
host = os.Args[2]
}
url := os.Args[1] url := os.Args[1]
var req *gmi.Request req, err := gemini.NewRequest(url)
var err error
if host != "" {
req, err = gmi.NewRequestTo(url, host)
} else {
req, err = gmi.NewRequest(url)
}
if err != nil { if err != nil {
fmt.Println(err) fmt.Println(err)
os.Exit(1) os.Exit(1)
} }
if len(os.Args) == 3 {
req.Host = os.Args[2]
}
if err := sendRequest(req); err != nil { resp, err := client.Do(req)
if err != nil {
fmt.Println(err) fmt.Println(err)
os.Exit(1) os.Exit(1)
} }
defer resp.Body.Close()
if resp.Status.Class() == gemini.StatusClassSuccess {
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
log.Fatal(err)
}
fmt.Print(string(body))
} else {
fmt.Printf("request failed: %d %s: %s", resp.Status, resp.Status.Message(), resp.Meta)
}
} }

90
examples/html.go Normal file
View File

@@ -0,0 +1,90 @@
// +build ignore
// This example illustrates a gemtext to HTML converter.
package main
import (
"fmt"
"html"
"strings"
"git.sr.ht/~adnano/go-gemini"
)
func main() {
text := gemini.Text{
gemini.LineHeading1("Hello, world!"),
gemini.LineText("This is a gemini text document."),
}
html := textToHTML(text)
fmt.Print(html)
}
// textToHTML returns the Gemini text response as HTML.
func textToHTML(text gemini.Text) string {
var b strings.Builder
var pre bool
var list bool
for _, l := range text {
if _, ok := l.(gemini.LineListItem); ok {
if !list {
list = true
fmt.Fprint(&b, "<ul>\n")
}
} else if list {
list = false
fmt.Fprint(&b, "</ul>\n")
}
switch l.(type) {
case gemini.LineLink:
link := l.(gemini.LineLink)
url := html.EscapeString(link.URL)
name := html.EscapeString(link.Name)
if name == "" {
name = url
}
fmt.Fprintf(&b, "<p><a href='%s'>%s</a></p>\n", url, name)
case gemini.LinePreformattingToggle:
pre = !pre
if pre {
fmt.Fprint(&b, "<pre>\n")
} else {
fmt.Fprint(&b, "</pre>\n")
}
case gemini.LinePreformattedText:
text := string(l.(gemini.LinePreformattedText))
fmt.Fprintf(&b, "%s\n", html.EscapeString(text))
case gemini.LineHeading1:
text := string(l.(gemini.LineHeading1))
fmt.Fprintf(&b, "<h1>%s</h1>\n", html.EscapeString(text))
case gemini.LineHeading2:
text := string(l.(gemini.LineHeading2))
fmt.Fprintf(&b, "<h2>%s</h2>\n", html.EscapeString(text))
case gemini.LineHeading3:
text := string(l.(gemini.LineHeading3))
fmt.Fprintf(&b, "<h3>%s</h3>\n", html.EscapeString(text))
case gemini.LineListItem:
text := string(l.(gemini.LineListItem))
fmt.Fprintf(&b, "<li>%s</li>\n", html.EscapeString(text))
case gemini.LineQuote:
text := string(l.(gemini.LineQuote))
fmt.Fprintf(&b, "<blockquote>%s</blockquote>\n", html.EscapeString(text))
case gemini.LineText:
text := string(l.(gemini.LineText))
if text == "" {
fmt.Fprint(&b, "<br>\n")
} else {
fmt.Fprintf(&b, "<p>%s</p>\n", html.EscapeString(text))
}
}
}
if pre {
fmt.Fprint(&b, "</pre>\n")
}
if list {
fmt.Fprint(&b, "</ul>\n")
}
return b.String()
}

View File

@@ -3,110 +3,32 @@
package main package main
import ( import (
"bytes"
"crypto/tls" "crypto/tls"
"crypto/x509"
"encoding/pem"
"log" "log"
"os"
"time" "time"
gmi "git.sr.ht/~adnano/go-gemini" "git.sr.ht/~adnano/go-gemini"
) )
func main() { func main() {
var server gmi.Server var server gemini.Server
if err := server.CertificateStore.Load("/var/lib/gemini/certs"); err != nil { server.ReadTimeout = 1 * time.Minute
server.WriteTimeout = 2 * time.Minute
if err := server.Certificates.Load("/var/lib/gemini/certs"); err != nil {
log.Fatal(err) log.Fatal(err)
} }
server.GetCertificate = func(hostname string, store *gmi.CertificateStore) *tls.Certificate { server.CreateCertificate = func(hostname string) (tls.Certificate, error) {
cert, err := store.Lookup(hostname) return gemini.CreateCertificate(gemini.CertificateOptions{
if err != nil { DNSNames: []string{hostname},
switch err { Duration: time.Minute, // for testing purposes
case gmi.ErrCertificateExpired: })
// Generate a new certificate if the current one is expired.
log.Print("Old certificate expired, creating new one")
fallthrough
case gmi.ErrCertificateUnknown:
// Generate a certificate if one does not exist.
cert, err := gmi.NewCertificate(hostname, time.Minute)
if err != nil {
// Failed to generate new certificate, abort
return nil
}
// Store and return the new certificate
err = writeCertificate("/var/lib/gemini/certs/"+hostname, cert)
if err != nil {
return nil
}
store.Add(hostname, cert)
return &cert
}
}
return cert
} }
var mux gmi.ServeMux var mux gemini.ServeMux
mux.Handle("/", gmi.FileServer(gmi.Dir("/var/www"))) mux.Handle("/", gemini.FileServer(gemini.Dir("/var/www")))
server.Register("localhost", &mux) server.Register("localhost", &mux)
if err := server.ListenAndServe(); err != nil { if err := server.ListenAndServe(); err != nil {
log.Fatal(err) log.Fatal(err)
} }
} }
// writeCertificate writes the provided certificate and private key
// to path.crt and path.key respectively.
func writeCertificate(path string, cert tls.Certificate) error {
crt, err := marshalX509Certificate(cert.Leaf.Raw)
if err != nil {
return err
}
key, err := marshalPrivateKey(cert.PrivateKey)
if err != nil {
return err
}
// Write the certificate
crtPath := path + ".crt"
crtOut, err := os.OpenFile(crtPath, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0600)
if err != nil {
return err
}
if _, err := crtOut.Write(crt); err != nil {
return err
}
// Write the private key
keyPath := path + ".key"
keyOut, err := os.OpenFile(keyPath, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0600)
if err != nil {
return err
}
if _, err := keyOut.Write(key); err != nil {
return err
}
return nil
}
// marshalX509Certificate returns a PEM-encoded version of the given raw certificate.
func marshalX509Certificate(cert []byte) ([]byte, error) {
var b bytes.Buffer
if err := pem.Encode(&b, &pem.Block{Type: "CERTIFICATE", Bytes: cert}); err != nil {
return nil, err
}
return b.Bytes(), nil
}
// marshalPrivateKey returns PEM encoded versions of the given certificate and private key.
func marshalPrivateKey(priv interface{}) ([]byte, error) {
var b bytes.Buffer
privBytes, err := x509.MarshalPKCS8PrivateKey(priv)
if err != nil {
return nil, err
}
if err := pem.Encode(&b, &pem.Block{Type: "PRIVATE KEY", Bytes: privBytes}); err != nil {
return nil, err
}
return b.Bytes(), nil
}

30
fs.go
View File

@@ -5,7 +5,6 @@ import (
"mime" "mime"
"os" "os"
"path" "path"
"path/filepath"
) )
func init() { func init() {
@@ -25,14 +24,14 @@ type fsHandler struct {
} }
func (fsh fsHandler) Respond(w *ResponseWriter, r *Request) { func (fsh fsHandler) Respond(w *ResponseWriter, r *Request) {
path := path.Clean(r.URL.Path) p := path.Clean(r.URL.Path)
f, err := fsh.Open(path) f, err := fsh.Open(p)
if err != nil { if err != nil {
NotFound(w, r) w.WriteStatus(StatusNotFound)
return return
} }
// Detect mimetype // Detect mimetype
ext := filepath.Ext(path) ext := path.Ext(p)
mimetype := mime.TypeByExtension(ext) mimetype := mime.TypeByExtension(ext)
w.SetMimetype(mimetype) w.SetMimetype(mimetype)
// Copy file to response writer // Copy file to response writer
@@ -58,6 +57,27 @@ type Dir string
// If the file is a directory, it tries to open the index file in that directory. // If the file is a directory, it tries to open the index file in that directory.
func (d Dir) Open(name string) (File, error) { func (d Dir) Open(name string) (File, error) {
p := path.Join(string(d), name) p := path.Join(string(d), name)
return openFile(p)
}
// ServeFile responds to the request with the contents of the named file
// or directory.
// TODO: Use io/fs.FS when available.
func ServeFile(w *ResponseWriter, fs FS, name string) {
f, err := fs.Open(name)
if err != nil {
w.WriteStatus(StatusNotFound)
return
}
// Detect mimetype
ext := path.Ext(name)
mimetype := mime.TypeByExtension(ext)
w.SetMimetype(mimetype)
// Copy file to response writer
io.Copy(w, f)
}
func openFile(p string) (File, error) {
f, err := os.OpenFile(p, os.O_RDONLY, 0644) f, err := os.OpenFile(p, os.O_RDONLY, 0644)
if err != nil { if err != nil {
return nil, err return nil, err

106
gemini.go
View File

@@ -1,98 +1,52 @@
package gemini package gemini
import ( import (
"crypto/tls"
"crypto/x509"
"errors" "errors"
"sync" "sync"
"time"
) )
// Status codes. var crlf = []byte("\r\n")
const (
StatusInput = 10
StatusSensitiveInput = 11
StatusSuccess = 20
StatusRedirect = 30
StatusRedirectPermanent = 31
StatusTemporaryFailure = 40
StatusServerUnavailable = 41
StatusCGIError = 42
StatusProxyError = 43
StatusSlowDown = 44
StatusPermanentFailure = 50
StatusNotFound = 51
StatusGone = 52
StatusProxyRequestRefused = 53
StatusBadRequest = 59
StatusCertificateRequired = 60
StatusCertificateNotAuthorized = 61
StatusCertificateNotValid = 62
)
// Status code categories.
const (
StatusClassInput = 1
StatusClassSuccess = 2
StatusClassRedirect = 3
StatusClassTemporaryFailure = 4
StatusClassPermanentFailure = 5
StatusClassCertificateRequired = 6
)
// Errors. // Errors.
var ( var (
ErrInvalidURL = errors.New("gemini: invalid URL") ErrInvalidURL = errors.New("gemini: invalid URL")
ErrInvalidResponse = errors.New("gemini: invalid response") ErrInvalidResponse = errors.New("gemini: invalid response")
ErrCertificateUnknown = errors.New("gemini: unknown certificate")
ErrCertificateExpired = errors.New("gemini: certificate expired") ErrCertificateExpired = errors.New("gemini: certificate expired")
ErrCertificateNotTrusted = errors.New("gemini: certificate is not trusted") ErrCertificateNotFound = errors.New("gemini: certificate not found")
ErrCertificateNotTrusted = errors.New("gemini: certificate not trusted")
ErrCertificateRequired = errors.New("gemini: certificate required")
ErrNotAFile = errors.New("gemini: not a file") ErrNotAFile = errors.New("gemini: not a file")
ErrNotAGeminiURL = errors.New("gemini: not a Gemini URL")
ErrBodyNotAllowed = errors.New("gemini: response status code does not allow for body") ErrBodyNotAllowed = errors.New("gemini: response status code does not allow for body")
ErrTooManyRedirects = errors.New("gemini: too many redirects")
ErrInputRequired = errors.New("gemini: input required")
) )
// DefaultClient is the default client. It is used by Send. // DefaultClient is the default client. It is used by Get and Do.
// //
// On the first request, DefaultClient will load the default list of known hosts. // On the first request, DefaultClient loads the default list of known hosts.
var DefaultClient Client var DefaultClient Client
var ( // Get performs a Gemini request for the given url.
crlf = []byte("\r\n")
)
func init() {
DefaultClient.TrustCertificate = func(hostname string, cert *x509.Certificate, knownHosts *KnownHosts) error {
// Load the hosts only once. This is so that the hosts don't have to be loaded
// for those using their own clients.
setupDefaultClientOnce.Do(setupDefaultClient)
return knownHosts.Lookup(hostname, cert)
}
DefaultClient.GetCertificate = func(hostname string, store *CertificateStore) *tls.Certificate {
// If the certificate is in the store, return it
if cert, err := store.Lookup(hostname); err == nil {
return cert
}
// Otherwise, generate a certificate
duration := time.Hour
cert, err := NewCertificate(hostname, duration)
if err != nil {
return nil
}
// Store and return the certificate
store.Add(hostname, cert)
return &cert
}
}
var setupDefaultClientOnce sync.Once
func setupDefaultClient() {
DefaultClient.KnownHosts.LoadDefault()
}
// Send sends a Gemini request and returns a Gemini response.
// //
// Send is a wrapper around DefaultClient.Send. // Get is a wrapper around DefaultClient.Get.
func Send(req *Request) (*Response, error) { func Get(url string) (*Response, error) {
return DefaultClient.Send(req) setupDefaultClientOnce()
return DefaultClient.Get(url)
}
// Do performs a Gemini request and returns a Gemini response.
//
// Do is a wrapper around DefaultClient.Do.
func Do(req *Request) (*Response, error) {
setupDefaultClientOnce()
return DefaultClient.Do(req)
}
var defaultClientOnce sync.Once
func setupDefaultClientOnce() {
defaultClientOnce.Do(func() {
DefaultClient.KnownHosts.LoadDefault()
})
} }

210
mux.go Normal file
View File

@@ -0,0 +1,210 @@
package gemini
import (
"net/url"
"path"
"sort"
"strings"
"sync"
)
// The following code is modified from the net/http package.
// Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// ServeMux is a Gemini request multiplexer.
// It matches the URL of each incoming request against a list of registered
// patterns and calls the handler for the pattern that
// most closely matches the URL.
//
// Patterns name fixed, rooted paths, like "/favicon.ico",
// or rooted subtrees, like "/images/" (note the trailing slash).
// Longer patterns take precedence over shorter ones, so that
// if there are handlers registered for both "/images/"
// and "/images/thumbnails/", the latter handler will be
// called for paths beginning "/images/thumbnails/" and the
// former will receive requests for any other paths in the
// "/images/" subtree.
//
// Note that since a pattern ending in a slash names a rooted subtree,
// the pattern "/" matches all paths not matched by other registered
// patterns, not just the URL with Path == "/".
//
// If a subtree has been registered and a request is received naming the
// subtree root without its trailing slash, ServeMux redirects that
// request to the subtree root (adding the trailing slash). This behavior can
// be overridden with a separate registration for the path without
// the trailing slash. For example, registering "/images/" causes ServeMux
// to redirect a request for "/images" to "/images/", unless "/images" has
// been registered separately.
//
// ServeMux also takes care of sanitizing the URL request path and
// redirecting any request containing . or .. elements or repeated slashes
// to an equivalent, cleaner URL.
type ServeMux struct {
mu sync.RWMutex
m map[string]muxEntry
es []muxEntry // slice of entries sorted from longest to shortest.
}
type muxEntry struct {
r Responder
pattern string
}
// cleanPath returns the canonical path for p, eliminating . and .. elements.
func cleanPath(p string) string {
if p == "" {
return "/"
}
if p[0] != '/' {
p = "/" + p
}
np := path.Clean(p)
// path.Clean removes trailing slash except for root;
// put the trailing slash back if necessary.
if p[len(p)-1] == '/' && np != "/" {
// Fast path for common case of p being the string we want:
if len(p) == len(np)+1 && strings.HasPrefix(p, np) {
np = p
} else {
np += "/"
}
}
return np
}
// Find a handler on a handler map given a path string.
// Most-specific (longest) pattern wins.
func (mux *ServeMux) match(path string) Responder {
// Check for exact match first.
v, ok := mux.m[path]
if ok {
return v.r
}
// Check for longest valid match. mux.es contains all patterns
// that end in / sorted from longest to shortest.
for _, e := range mux.es {
if strings.HasPrefix(path, e.pattern) {
return e.r
}
}
return nil
}
// redirectToPathSlash determines if the given path needs appending "/" to it.
// This occurs when a handler for path + "/" was already registered, but
// not for path itself. If the path needs appending to, it creates a new
// URL, setting the path to u.Path + "/" and returning true to indicate so.
func (mux *ServeMux) redirectToPathSlash(path string, u *url.URL) (*url.URL, bool) {
mux.mu.RLock()
shouldRedirect := mux.shouldRedirectRLocked(path)
mux.mu.RUnlock()
if !shouldRedirect {
return u, false
}
path = path + "/"
u = &url.URL{Path: path, RawQuery: u.RawQuery}
return u, true
}
// shouldRedirectRLocked reports whether the given path and host should be redirected to
// path+"/". This should happen if a handler is registered for path+"/" but
// not path -- see comments at ServeMux.
func (mux *ServeMux) shouldRedirectRLocked(path string) bool {
if _, exist := mux.m[path]; exist {
return false
}
n := len(path)
if n == 0 {
return false
}
if _, exist := mux.m[path+"/"]; exist {
return path[n-1] != '/'
}
return false
}
// Respond dispatches the request to the responder whose
// pattern most closely matches the request URL.
func (mux *ServeMux) Respond(w *ResponseWriter, r *Request) {
path := cleanPath(r.URL.Path)
// If the given path is /tree and its handler is not registered,
// redirect for /tree/.
if u, ok := mux.redirectToPathSlash(path, r.URL); ok {
w.WriteHeader(StatusRedirect, u.String())
return
}
if path != r.URL.Path {
u := *r.URL
u.Path = path
w.WriteHeader(StatusRedirect, u.String())
return
}
mux.mu.RLock()
defer mux.mu.RUnlock()
resp := mux.match(path)
if resp == nil {
w.WriteStatus(StatusNotFound)
return
}
resp.Respond(w, r)
}
// Handle registers the responder for the given pattern.
// If a responder already exists for pattern, Handle panics.
func (mux *ServeMux) Handle(pattern string, responder Responder) {
mux.mu.Lock()
defer mux.mu.Unlock()
if pattern == "" {
panic("gemini: invalid pattern")
}
if responder == nil {
panic("gemini: nil responder")
}
if _, exist := mux.m[pattern]; exist {
panic("gemini: multiple registrations for " + pattern)
}
if mux.m == nil {
mux.m = make(map[string]muxEntry)
}
e := muxEntry{responder, pattern}
mux.m[pattern] = e
if pattern[len(pattern)-1] == '/' {
mux.es = appendSorted(mux.es, e)
}
}
func appendSorted(es []muxEntry, e muxEntry) []muxEntry {
n := len(es)
i := sort.Search(n, func(i int) bool {
return len(es[i].pattern) < len(e.pattern)
})
if i == n {
return append(es, e)
}
// we now know that i points at where we want to insert
es = append(es, muxEntry{}) // try to grow the slice in place, any entry works.
copy(es[i+1:], es[i:]) // move shorter entries down
es[i] = e
return es
}
// HandleFunc registers the responder function for the given pattern.
func (mux *ServeMux) HandleFunc(pattern string, responder func(*ResponseWriter, *Request)) {
if responder == nil {
panic("gemini: nil responder")
}
mux.Handle(pattern, ResponderFunc(responder))
}

View File

@@ -33,45 +33,28 @@ type Request struct {
TLS tls.ConnectionState TLS tls.ConnectionState
} }
// hostname returns the host without the port. // NewRequest returns a new request. The host is inferred from the URL.
func hostname(host string) string {
hostname, _, err := net.SplitHostPort(host)
if err != nil {
return host
}
return hostname
}
// NewRequest returns a new request. The host is inferred from the provided URL.
func NewRequest(rawurl string) (*Request, error) { func NewRequest(rawurl string) (*Request, error) {
u, err := url.Parse(rawurl) u, err := url.Parse(rawurl)
if err != nil { if err != nil {
return nil, err return nil, err
} }
return NewRequestFromURL(u)
// If there is no port, use the default port of 1965
host := u.Host
if u.Port() == "" {
host += ":1965"
}
return &Request{
Host: host,
URL: u,
}, nil
} }
// NewRequestTo returns a new request for the provided URL to the provided host. // NewRequestFromURL returns a new request for the given URL.
// The host must contain a port. // The host is inferred from the URL.
func NewRequestTo(rawurl, host string) (*Request, error) { func NewRequestFromURL(url *url.URL) (*Request, error) {
u, err := url.Parse(rawurl) if url.Scheme != "" && url.Scheme != "gemini" {
if err != nil { return nil, ErrNotAGeminiURL
return nil, err }
host := url.Host
if url.Port() == "" {
host += ":1965"
} }
return &Request{ return &Request{
URL: url,
Host: host, Host: host,
URL: u,
}, nil }, nil
} }

View File

@@ -2,15 +2,17 @@ package gemini
import ( import (
"bufio" "bufio"
"bytes"
"crypto/tls" "crypto/tls"
"io"
"io/ioutil" "io/ioutil"
"strconv" "strconv"
) )
// Response is a Gemini response. // Response is a Gemini response.
type Response struct { type Response struct {
// Status represents the response status. // Status contains the response status code.
Status int Status Status
// Meta contains more information related to the response status. // Meta contains more information related to the response status.
// For successful responses, Meta should contain the mimetype of the response. // For successful responses, Meta should contain the mimetype of the response.
@@ -18,43 +20,48 @@ type Response struct {
// Meta should not be longer than 1024 bytes. // Meta should not be longer than 1024 bytes.
Meta string Meta string
// Body contains the response body. // Body contains the response body for successful responses.
Body []byte // Body is guaranteed to be non-nil.
Body io.ReadCloser
// Request is the request that was sent to obtain this response.
Request *Request
// TLS contains information about the TLS connection on which the response // TLS contains information about the TLS connection on which the response
// was received. // was received.
TLS tls.ConnectionState TLS tls.ConnectionState
} }
// read reads a Gemini response from the provided buffered reader. // read reads a Gemini response from the provided io.ReadCloser.
func (resp *Response) read(r *bufio.Reader) error { func (resp *Response) read(rc io.ReadCloser) error {
br := bufio.NewReader(rc)
// Read the status // Read the status
statusB := make([]byte, 2) statusB := make([]byte, 2)
if _, err := r.Read(statusB); err != nil { if _, err := br.Read(statusB); err != nil {
return err return err
} }
status, err := strconv.Atoi(string(statusB)) status, err := strconv.Atoi(string(statusB))
if err != nil { if err != nil {
return err return err
} }
resp.Status = status resp.Status = Status(status)
// Disregard invalid status codes // Disregard invalid status codes
const minStatus, maxStatus = 1, 6 const minStatus, maxStatus = 1, 6
statusClass := status / 10 statusClass := resp.Status.Class()
if statusClass < minStatus || statusClass > maxStatus { if statusClass < minStatus || statusClass > maxStatus {
return ErrInvalidResponse return ErrInvalidResponse
} }
// Read one space // Read one space
if b, err := r.ReadByte(); err != nil { if b, err := br.ReadByte(); err != nil {
return err return err
} else if b != ' ' { } else if b != ' ' {
return ErrInvalidResponse return ErrInvalidResponse
} }
// Read the meta // Read the meta
meta, err := r.ReadString('\r') meta, err := br.ReadString('\r')
if err != nil { if err != nil {
return err return err
} }
@@ -64,22 +71,50 @@ func (resp *Response) read(r *bufio.Reader) error {
if len(meta) > 1024 { if len(meta) > 1024 {
return ErrInvalidResponse return ErrInvalidResponse
} }
// Default mime type of text/gemini; charset=utf-8
if statusClass == StatusClassSuccess && meta == "" {
meta = "text/gemini; charset=utf-8"
}
resp.Meta = meta resp.Meta = meta
// Read terminating newline // Read terminating newline
if b, err := r.ReadByte(); err != nil { if b, err := br.ReadByte(); err != nil {
return err return err
} else if b != '\n' { } else if b != '\n' {
return ErrInvalidResponse return ErrInvalidResponse
} }
// Read response body if resp.Status.Class() == StatusClassSuccess {
if status/10 == StatusClassSuccess { resp.Body = newReadCloserBody(br, rc)
var err error } else {
resp.Body, err = ioutil.ReadAll(r) resp.Body = ioutil.NopCloser(bytes.NewReader([]byte{}))
if err != nil {
return err
}
} }
return nil return nil
} }
type readCloserBody struct {
br *bufio.Reader // used until empty
io.ReadCloser
}
func newReadCloserBody(br *bufio.Reader, rc io.ReadCloser) io.ReadCloser {
body := &readCloserBody{ReadCloser: rc}
if br.Buffered() != 0 {
body.br = br
}
return body
}
func (b *readCloserBody) Read(p []byte) (n int, err error) {
if b.br != nil {
if n := b.br.Buffered(); len(p) > n {
p = p[:n]
}
n, err = b.br.Read(p)
if b.br.Buffered() == 0 {
b.br = nil
}
return n, err
}
return b.ReadCloser.Read(p)
}

376
server.go
View File

@@ -7,11 +7,8 @@ import (
"log" "log"
"net" "net"
"net/url" "net/url"
"path"
"sort"
"strconv" "strconv"
"strings" "strings"
"sync"
"time" "time"
) )
@@ -21,28 +18,35 @@ type Server struct {
// If Addr is empty, the server will listen on the address ":1965". // If Addr is empty, the server will listen on the address ":1965".
Addr string Addr string
// CertificateStore contains the certificates used by the server. // ReadTimeout is the maximum duration for reading a request.
CertificateStore CertificateStore ReadTimeout time.Duration
// GetCertificate, if not nil, will be called to retrieve the certificate // WriteTimeout is the maximum duration before timing out
// to use for a given hostname. // writes of the response.
// If the certificate is nil, the connection will be aborted. WriteTimeout time.Duration
GetCertificate func(hostname string, store *CertificateStore) *tls.Certificate
// Certificates contains the certificates used by the server.
Certificates CertificateStore
// CreateCertificate, if not nil, will be called to create a new certificate
// if the current one is expired or missing.
CreateCertificate func(hostname string) (tls.Certificate, error)
// registered responders // registered responders
responders map[responderKey]Responder responders map[responderKey]Responder
hosts map[string]bool
} }
type responderKey struct { type responderKey struct {
scheme string scheme string
hostname string hostname string
wildcard bool
} }
// Register registers a responder for the given pattern. // Register registers a responder for the given pattern.
// Patterns must be in the form of scheme://hostname (e.g. gemini://example.com). //
// If no scheme is specified, a default scheme of gemini:// is assumed. // Patterns must be in the form of "hostname" or "scheme://hostname".
// Wildcard patterns are supported (e.g. *.example.com). // If no scheme is specified, a scheme of "gemini://" is implied.
// Wildcard patterns are supported (e.g. "*.example.com").
func (s *Server) Register(pattern string, responder Responder) { func (s *Server) Register(pattern string, responder Responder) {
if pattern == "" { if pattern == "" {
panic("gemini: invalid pattern") panic("gemini: invalid pattern")
@@ -52,6 +56,7 @@ func (s *Server) Register(pattern string, responder Responder) {
} }
if s.responders == nil { if s.responders == nil {
s.responders = map[responderKey]Responder{} s.responders = map[responderKey]Responder{}
s.hosts = map[string]bool{}
} }
split := strings.SplitN(pattern, "://", 2) split := strings.SplitN(pattern, "://", 2)
@@ -63,13 +68,12 @@ func (s *Server) Register(pattern string, responder Responder) {
key.scheme = "gemini" key.scheme = "gemini"
key.hostname = split[0] key.hostname = split[0]
} }
split = strings.SplitN(key.hostname, ".", 2)
if len(split) == 2 && split[0] == "*" {
key.hostname = split[1]
key.wildcard = true
}
if _, ok := s.responders[key]; ok {
panic("gemini: multiple registrations for " + pattern)
}
s.responders[key] = responder s.responders[key] = responder
s.hosts[key.hostname] = true
} }
// RegisterFunc registers a responder function for the given pattern. // RegisterFunc registers a responder function for the given pattern.
@@ -90,18 +94,11 @@ func (s *Server) ListenAndServe() error {
} }
defer ln.Close() defer ln.Close()
config := &tls.Config{ return s.Serve(tls.NewListener(ln, &tls.Config{
ClientAuth: tls.RequestClientCert, ClientAuth: tls.RequestClientCert,
MinVersion: tls.VersionTLS12, MinVersion: tls.VersionTLS12,
GetCertificate: func(h *tls.ClientHelloInfo) (*tls.Certificate, error) { GetCertificate: s.getCertificate,
if s.GetCertificate != nil { }))
return s.GetCertificate(h.ServerName, &s.CertificateStore), nil
}
return s.CertificateStore.Lookup(h.ServerName)
},
}
tlsListener := tls.NewListener(ln, config)
return s.Serve(tlsListener)
} }
// Serve listens for requests on the provided listener. // Serve listens for requests on the provided listener.
@@ -135,8 +132,47 @@ func (s *Server) Serve(l net.Listener) error {
} }
} }
func (s *Server) getCertificate(h *tls.ClientHelloInfo) (*tls.Certificate, error) {
cert, err := s.getCertificateFor(h.ServerName)
if err != nil {
// Try wildcard
wildcard := strings.SplitN(h.ServerName, ".", 2)
if len(wildcard) == 2 {
cert, err = s.getCertificateFor("*." + wildcard[1])
}
}
return cert, err
}
func (s *Server) getCertificateFor(hostname string) (*tls.Certificate, error) {
if _, ok := s.hosts[hostname]; !ok {
return nil, ErrCertificateNotFound
}
cert, err := s.Certificates.Lookup(hostname)
switch err {
case ErrCertificateNotFound, ErrCertificateExpired:
if s.CreateCertificate != nil {
cert, err := s.CreateCertificate(hostname)
if err == nil {
s.Certificates.Add(hostname, cert)
}
return &cert, err
}
}
return cert, err
}
// respond responds to a connection. // respond responds to a connection.
func (s *Server) respond(conn net.Conn) { func (s *Server) respond(conn net.Conn) {
if d := s.ReadTimeout; d != 0 {
conn.SetReadDeadline(time.Now().Add(d))
}
if d := s.WriteTimeout; d != 0 {
conn.SetWriteDeadline(time.Now().Add(d))
}
r := bufio.NewReader(conn) r := bufio.NewReader(conn)
w := newResponseWriter(conn) w := newResponseWriter(conn)
// Read requested URL // Read requested URL
@@ -148,16 +184,16 @@ func (s *Server) respond(conn net.Conn) {
if b, err := r.ReadByte(); err != nil { if b, err := r.ReadByte(); err != nil {
return return
} else if b != '\n' { } else if b != '\n' {
w.WriteHeader(StatusBadRequest, "Bad request") w.WriteStatus(StatusBadRequest)
} }
// Trim carriage return // Trim carriage return
rawurl = rawurl[:len(rawurl)-1] rawurl = rawurl[:len(rawurl)-1]
// Ensure URL is valid // Ensure URL is valid
if len(rawurl) > 1024 { if len(rawurl) > 1024 {
w.WriteHeader(StatusBadRequest, "Bad request") w.WriteStatus(StatusBadRequest)
} else if url, err := url.Parse(rawurl); err != nil || url.User != nil { } 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 // Note that we return an error status if User is specified in the URL
w.WriteHeader(StatusBadRequest, "Bad request") w.WriteStatus(StatusBadRequest)
} else { } else {
// If no scheme is specified, assume a default scheme of gemini:// // If no scheme is specified, assume a default scheme of gemini://
if url.Scheme == "" { if url.Scheme == "" {
@@ -168,23 +204,28 @@ func (s *Server) respond(conn net.Conn) {
RemoteAddr: conn.RemoteAddr(), RemoteAddr: conn.RemoteAddr(),
TLS: conn.(*tls.Conn).ConnectionState(), TLS: conn.(*tls.Conn).ConnectionState(),
} }
s.responder(req).Respond(w, req) resp := s.responder(req)
if resp != nil {
resp.Respond(w, req)
} else {
w.WriteStatus(StatusNotFound)
}
} }
w.b.Flush() w.b.Flush()
conn.Close() conn.Close()
} }
func (s *Server) responder(r *Request) Responder { func (s *Server) responder(r *Request) Responder {
if h, ok := s.responders[responderKey{r.URL.Scheme, r.URL.Hostname(), false}]; ok { if h, ok := s.responders[responderKey{r.URL.Scheme, r.URL.Hostname()}]; ok {
return h return h
} }
wildcard := strings.SplitN(r.URL.Hostname(), ".", 2) wildcard := strings.SplitN(r.URL.Hostname(), ".", 2)
if len(wildcard) == 2 { if len(wildcard) == 2 {
if h, ok := s.responders[responderKey{r.URL.Scheme, wildcard[1], true}]; ok { if h, ok := s.responders[responderKey{r.URL.Scheme, "*." + wildcard[1]}]; ok {
return h return h
} }
} }
return ResponderFunc(NotFound) return nil
} }
// ResponseWriter is used by a Gemini handler to construct a Gemini response. // ResponseWriter is used by a Gemini handler to construct a Gemini response.
@@ -208,25 +249,30 @@ func newResponseWriter(conn net.Conn) *ResponseWriter {
// For successful responses, Meta should contain the mimetype of the response. // For successful responses, Meta should contain the mimetype of the response.
// For failure responses, Meta should contain a short description of the failure. // For failure responses, Meta should contain a short description of the failure.
// Meta should not be longer than 1024 bytes. // Meta should not be longer than 1024 bytes.
func (w *ResponseWriter) WriteHeader(status int, meta string) { func (w *ResponseWriter) WriteHeader(status Status, meta string) {
if w.wroteHeader { if w.wroteHeader {
return return
} }
w.b.WriteString(strconv.Itoa(status)) w.b.WriteString(strconv.Itoa(int(status)))
w.b.WriteByte(' ') w.b.WriteByte(' ')
w.b.WriteString(meta) w.b.WriteString(meta)
w.b.Write(crlf) w.b.Write(crlf)
// Only allow body to be written on successful status codes. // Only allow body to be written on successful status codes.
if status/10 == StatusClassSuccess { if status.Class() == StatusClassSuccess {
w.bodyAllowed = true w.bodyAllowed = true
} }
w.wroteHeader = true w.wroteHeader = true
} }
// WriteStatus writes the response header with the given status code.
//
// WriteStatus is equivalent to WriteHeader(status, status.Message())
func (w *ResponseWriter) WriteStatus(status Status) {
w.WriteHeader(status, status.Message())
}
// SetMimetype sets the mimetype that will be written for a successful response. // 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". // If the mimetype is not set, it will default to "text/gemini".
func (w *ResponseWriter) SetMimetype(mimetype string) { func (w *ResponseWriter) SetMimetype(mimetype string) {
w.mimetype = mimetype w.mimetype = mimetype
@@ -236,9 +282,8 @@ func (w *ResponseWriter) SetMimetype(mimetype string) {
// If the response status does not allow for a response body, Write returns // If the response status does not allow for a response body, Write returns
// ErrBodyNotAllowed. // ErrBodyNotAllowed.
// //
// If WriteHeader has not yet been called, Write calls // If the response header has not yet been written, Write calls WriteHeader
// WriteHeader(StatusSuccess, mimetype) where mimetype is the mimetype set in // with StatusSuccess and the mimetype set in SetMimetype.
// SetMimetype. If no mimetype is set, a default of "text/gemini" will be used.
func (w *ResponseWriter) Write(b []byte) (int, error) { func (w *ResponseWriter) Write(b []byte) (int, error) {
if !w.wroteHeader { if !w.wroteHeader {
mimetype := w.mimetype mimetype := w.mimetype
@@ -263,7 +308,8 @@ type Responder interface {
// If no input is provided, it responds with StatusInput. // If no input is provided, it responds with StatusInput.
func Input(w *ResponseWriter, r *Request, prompt string) (string, bool) { func Input(w *ResponseWriter, r *Request, prompt string) (string, bool) {
if r.URL.ForceQuery || r.URL.RawQuery != "" { if r.URL.ForceQuery || r.URL.RawQuery != "" {
return r.URL.RawQuery, true query, err := url.QueryUnescape(r.URL.RawQuery)
return query, err == nil
} }
w.WriteHeader(StatusInput, prompt) w.WriteHeader(StatusInput, prompt)
return "", false return "", false
@@ -273,49 +319,18 @@ func Input(w *ResponseWriter, r *Request, prompt string) (string, bool) {
// If no input is provided, it responds with StatusSensitiveInput. // If no input is provided, it responds with StatusSensitiveInput.
func SensitiveInput(w *ResponseWriter, r *Request, prompt string) (string, bool) { func SensitiveInput(w *ResponseWriter, r *Request, prompt string) (string, bool) {
if r.URL.ForceQuery || r.URL.RawQuery != "" { if r.URL.ForceQuery || r.URL.RawQuery != "" {
return r.URL.RawQuery, true query, err := url.QueryUnescape(r.URL.RawQuery)
return query, err == nil
} }
w.WriteHeader(StatusSensitiveInput, prompt) w.WriteHeader(StatusSensitiveInput, prompt)
return "", false return "", false
} }
// Redirect replies to the request with a redirect to the given URL.
func Redirect(w *ResponseWriter, r *Request, url string) {
w.WriteHeader(StatusRedirect, url)
}
// PermanentRedirect replies to the request with a permanent redirect to the given URL.
func PermanentRedirect(w *ResponseWriter, r *Request, url string) {
w.WriteHeader(StatusRedirectPermanent, url)
}
// NotFound replies to the request with the NotFound status code.
func NotFound(w *ResponseWriter, r *Request) {
w.WriteHeader(StatusNotFound, "Not found")
}
// Gone replies to the request with the Gone status code.
func Gone(w *ResponseWriter, r *Request) {
w.WriteHeader(StatusGone, "Gone")
}
// CertificateRequired responds to the request with the CertificateRequired
// status code.
func CertificateRequired(w *ResponseWriter, r *Request) {
w.WriteHeader(StatusCertificateRequired, "Certificate required")
}
// CertificateNotAuthorized responds to the request with
// the CertificateNotAuthorized status code.
func CertificateNotAuthorized(w *ResponseWriter, r *Request) {
w.WriteHeader(StatusCertificateNotAuthorized, "Certificate not authorized")
}
// Certificate returns the request certificate. If one is not provided, // Certificate returns the request certificate. If one is not provided,
// it returns nil and responds with StatusCertificateRequired. // it returns nil and responds with StatusCertificateRequired.
func Certificate(w *ResponseWriter, r *Request) (*x509.Certificate, bool) { func Certificate(w *ResponseWriter, r *Request) (*x509.Certificate, bool) {
if len(r.TLS.PeerCertificates) == 0 { if len(r.TLS.PeerCertificates) == 0 {
CertificateRequired(w, r) w.WriteStatus(StatusCertificateRequired)
return nil, false return nil, false
} }
return r.TLS.PeerCertificates[0], true return r.TLS.PeerCertificates[0], true
@@ -327,204 +342,3 @@ type ResponderFunc func(*ResponseWriter, *Request)
func (f ResponderFunc) Respond(w *ResponseWriter, r *Request) { func (f ResponderFunc) Respond(w *ResponseWriter, r *Request) {
f(w, r) f(w, r)
} }
// The following code is modified from the net/http package.
// Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// ServeMux is a Gemini request multiplexer.
// It matches the URL of each incoming request against a list of registered
// patterns and calls the handler for the pattern that
// most closely matches the URL.
//
// Patterns name fixed, rooted paths, like "/favicon.ico",
// or rooted subtrees, like "/images/" (note the trailing slash).
// Longer patterns take precedence over shorter ones, so that
// if there are handlers registered for both "/images/"
// and "/images/thumbnails/", the latter handler will be
// called for paths beginning "/images/thumbnails/" and the
// former will receive requests for any other paths in the
// "/images/" subtree.
//
// Note that since a pattern ending in a slash names a rooted subtree,
// the pattern "/" matches all paths not matched by other registered
// patterns, not just the URL with Path == "/".
//
// If a subtree has been registered and a request is received naming the
// subtree root without its trailing slash, ServeMux redirects that
// request to the subtree root (adding the trailing slash). This behavior can
// be overridden with a separate registration for the path without
// the trailing slash. For example, registering "/images/" causes ServeMux
// to redirect a request for "/images" to "/images/", unless "/images" has
// been registered separately.
//
// ServeMux also takes care of sanitizing the URL request path and
// redirecting any request containing . or .. elements or repeated slashes
// to an equivalent, cleaner URL.
type ServeMux struct {
mu sync.RWMutex
m map[string]muxEntry
es []muxEntry // slice of entries sorted from longest to shortest.
}
type muxEntry struct {
r Responder
pattern string
}
// cleanPath returns the canonical path for p, eliminating . and .. elements.
func cleanPath(p string) string {
if p == "" {
return "/"
}
if p[0] != '/' {
p = "/" + p
}
np := path.Clean(p)
// path.Clean removes trailing slash except for root;
// put the trailing slash back if necessary.
if p[len(p)-1] == '/' && np != "/" {
// Fast path for common case of p being the string we want:
if len(p) == len(np)+1 && strings.HasPrefix(p, np) {
np = p
} else {
np += "/"
}
}
return np
}
// Find a handler on a handler map given a path string.
// Most-specific (longest) pattern wins.
func (mux *ServeMux) match(path string) Responder {
// Check for exact match first.
v, ok := mux.m[path]
if ok {
return v.r
}
// Check for longest valid match. mux.es contains all patterns
// that end in / sorted from longest to shortest.
for _, e := range mux.es {
if strings.HasPrefix(path, e.pattern) {
return e.r
}
}
return nil
}
// redirectToPathSlash determines if the given path needs appending "/" to it.
// This occurs when a handler for path + "/" was already registered, but
// not for path itself. If the path needs appending to, it creates a new
// URL, setting the path to u.Path + "/" and returning true to indicate so.
func (mux *ServeMux) redirectToPathSlash(path string, u *url.URL) (*url.URL, bool) {
mux.mu.RLock()
shouldRedirect := mux.shouldRedirectRLocked(path)
mux.mu.RUnlock()
if !shouldRedirect {
return u, false
}
path = path + "/"
u = &url.URL{Path: path, RawQuery: u.RawQuery}
return u, true
}
// shouldRedirectRLocked reports whether the given path and host should be redirected to
// path+"/". This should happen if a handler is registered for path+"/" but
// not path -- see comments at ServeMux.
func (mux *ServeMux) shouldRedirectRLocked(path string) bool {
if _, exist := mux.m[path]; exist {
return false
}
n := len(path)
if n == 0 {
return false
}
if _, exist := mux.m[path+"/"]; exist {
return path[n-1] != '/'
}
return false
}
// Respond dispatches the request to the responder whose
// pattern most closely matches the request URL.
func (mux *ServeMux) Respond(w *ResponseWriter, r *Request) {
path := cleanPath(r.URL.Path)
// If the given path is /tree and its handler is not registered,
// redirect for /tree/.
if u, ok := mux.redirectToPathSlash(path, r.URL); ok {
Redirect(w, r, u.String())
return
}
if path != r.URL.Path {
u := *r.URL
u.Path = path
Redirect(w, r, u.String())
return
}
mux.mu.RLock()
defer mux.mu.RUnlock()
resp := mux.match(path)
if resp == nil {
NotFound(w, r)
return
}
resp.Respond(w, r)
}
// Handle registers the responder for the given pattern.
// If a responder already exists for pattern, Handle panics.
func (mux *ServeMux) Handle(pattern string, responder Responder) {
mux.mu.Lock()
defer mux.mu.Unlock()
if pattern == "" {
panic("gemini: invalid pattern")
}
if responder == nil {
panic("gemini: nil responder")
}
if _, exist := mux.m[pattern]; exist {
panic("gemini: multiple registrations for " + pattern)
}
if mux.m == nil {
mux.m = make(map[string]muxEntry)
}
e := muxEntry{responder, pattern}
mux.m[pattern] = e
if pattern[len(pattern)-1] == '/' {
mux.es = appendSorted(mux.es, e)
}
}
func appendSorted(es []muxEntry, e muxEntry) []muxEntry {
n := len(es)
i := sort.Search(n, func(i int) bool {
return len(es[i].pattern) < len(e.pattern)
})
if i == n {
return append(es, e)
}
// we now know that i points at where we want to insert
es = append(es, muxEntry{}) // try to grow the slice in place, any entry works.
copy(es[i+1:], es[i:]) // move shorter entries down
es[i] = e
return es
}
// HandleFunc registers the responder function for the given pattern.
func (mux *ServeMux) HandleFunc(pattern string, responder func(*ResponseWriter, *Request)) {
if responder == nil {
panic("gemini: nil responder")
}
mux.Handle(pattern, ResponderFunc(responder))
}

85
status.go Normal file
View File

@@ -0,0 +1,85 @@
package gemini
// Status codes.
type Status int
const (
StatusInput Status = 10
StatusSensitiveInput Status = 11
StatusSuccess Status = 20
StatusRedirect Status = 30
StatusPermanentRedirect Status = 31
StatusTemporaryFailure Status = 40
StatusServerUnavailable Status = 41
StatusCGIError Status = 42
StatusProxyError Status = 43
StatusSlowDown Status = 44
StatusPermanentFailure Status = 50
StatusNotFound Status = 51
StatusGone Status = 52
StatusProxyRequestRefused Status = 53
StatusBadRequest Status = 59
StatusCertificateRequired Status = 60
StatusCertificateNotAuthorized Status = 61
StatusCertificateNotValid Status = 62
)
// Status code categories.
type StatusClass int
const (
StatusClassInput StatusClass = 1
StatusClassSuccess StatusClass = 2
StatusClassRedirect StatusClass = 3
StatusClassTemporaryFailure StatusClass = 4
StatusClassPermanentFailure StatusClass = 5
StatusClassCertificateRequired StatusClass = 6
)
// Class returns the status class for this status code.
func (s Status) Class() StatusClass {
return StatusClass(s / 10)
}
// Message returns a status message corresponding to this status code.
func (s Status) Message() string {
switch s {
case StatusInput:
return "Input"
case StatusSensitiveInput:
return "Sensitive input"
case StatusSuccess:
return "Success"
case StatusRedirect:
return "Redirect"
case StatusPermanentRedirect:
return "Permanent redirect"
case StatusTemporaryFailure:
return "Temporary failure"
case StatusServerUnavailable:
return "Server unavailable"
case StatusCGIError:
return "CGI error"
case StatusProxyError:
return "Proxy error"
case StatusSlowDown:
return "Slow down"
case StatusPermanentFailure:
return "Permanent failure"
case StatusNotFound:
return "Not found"
case StatusGone:
return "Gone"
case StatusProxyRequestRefused:
return "Proxy request refused"
case StatusBadRequest:
return "Bad request"
case StatusCertificateRequired:
return "Certificate required"
case StatusCertificateNotAuthorized:
return "Certificate not authorized"
case StatusCertificateNotValid:
return "Certificate not valid"
}
return ""
}

156
text.go
View File

@@ -3,7 +3,6 @@ package gemini
import ( import (
"bufio" "bufio"
"fmt" "fmt"
"html"
"io" "io"
"strings" "strings"
) )
@@ -88,58 +87,68 @@ func (l LineText) line() {}
// Text represents a Gemini text response. // Text represents a Gemini text response.
type Text []Line type Text []Line
// Parse parses Gemini text from the provided io.Reader. // ParseText parses Gemini text from the provided io.Reader.
func Parse(r io.Reader) Text { func ParseText(r io.Reader) Text {
const spacetab = " \t"
var t Text var t Text
ParseLines(r, func(line Line) {
t = append(t, line)
})
return t
}
// ParseLines parses Gemini text from the provided io.Reader.
// It calls handler with each line that it parses.
func ParseLines(r io.Reader, handler func(Line)) {
const spacetab = " \t"
var pre bool var pre bool
scanner := bufio.NewScanner(r) scanner := bufio.NewScanner(r)
for scanner.Scan() { for scanner.Scan() {
line := scanner.Text() var line Line
if strings.HasPrefix(line, "```") { text := scanner.Text()
if strings.HasPrefix(text, "```") {
pre = !pre pre = !pre
line = line[3:] text = text[3:]
t = append(t, LinePreformattingToggle(line)) line = LinePreformattingToggle(text)
} else if pre { } else if pre {
t = append(t, LinePreformattedText(line)) line = LinePreformattedText(text)
} else if strings.HasPrefix(line, "=>") { } else if strings.HasPrefix(text, "=>") {
line = line[2:] text = text[2:]
line = strings.TrimLeft(line, spacetab) text = strings.TrimLeft(text, spacetab)
split := strings.IndexAny(line, spacetab) split := strings.IndexAny(text, spacetab)
if split == -1 { if split == -1 {
// line is a URL // text is a URL
t = append(t, LineLink{URL: line}) line = LineLink{URL: text}
} else { } else {
url := line[:split] url := text[:split]
name := line[split:] name := text[split:]
name = strings.TrimLeft(name, spacetab) name = strings.TrimLeft(name, spacetab)
t = append(t, LineLink{url, name}) line = LineLink{url, name}
} }
} else if strings.HasPrefix(line, "*") { } else if strings.HasPrefix(text, "*") {
line = line[1:] text = text[1:]
line = strings.TrimLeft(line, spacetab) text = strings.TrimLeft(text, spacetab)
t = append(t, LineListItem(line)) line = LineListItem(text)
} else if strings.HasPrefix(line, "###") { } else if strings.HasPrefix(text, "###") {
line = line[3:] text = text[3:]
line = strings.TrimLeft(line, spacetab) text = strings.TrimLeft(text, spacetab)
t = append(t, LineHeading3(line)) line = LineHeading3(text)
} else if strings.HasPrefix(line, "##") { } else if strings.HasPrefix(text, "##") {
line = line[2:] text = text[2:]
line = strings.TrimLeft(line, spacetab) text = strings.TrimLeft(text, spacetab)
t = append(t, LineHeading2(line)) line = LineHeading2(text)
} else if strings.HasPrefix(line, "#") { } else if strings.HasPrefix(text, "#") {
line = line[1:] text = text[1:]
line = strings.TrimLeft(line, spacetab) text = strings.TrimLeft(text, spacetab)
t = append(t, LineHeading1(line)) line = LineHeading1(text)
} else if strings.HasPrefix(line, ">") { } else if strings.HasPrefix(text, ">") {
line = line[1:] text = text[1:]
line = strings.TrimLeft(line, spacetab) text = strings.TrimLeft(text, spacetab)
t = append(t, LineQuote(line)) line = LineQuote(text)
} else { } else {
t = append(t, LineText(line)) line = LineText(text)
} }
handler(line)
} }
return t
} }
// String writes the Gemini text response to a string and returns it. // String writes the Gemini text response to a string and returns it.
@@ -151,70 +160,3 @@ func (t Text) String() string {
} }
return b.String() return b.String()
} }
// HTML returns the Gemini text response as HTML.
func (t Text) HTML() string {
var b strings.Builder
var pre bool
var list bool
for _, l := range t {
if _, ok := l.(LineListItem); ok {
if !list {
list = true
fmt.Fprint(&b, "<ul>\n")
}
} else if list {
list = false
fmt.Fprint(&b, "</ul>\n")
}
switch l.(type) {
case LineLink:
link := l.(LineLink)
url := html.EscapeString(link.URL)
name := html.EscapeString(link.Name)
if name == "" {
name = url
}
fmt.Fprintf(&b, "<p><a href='%s'>%s</a></p>\n", url, name)
case LinePreformattingToggle:
pre = !pre
if pre {
fmt.Fprint(&b, "<pre>\n")
} else {
fmt.Fprint(&b, "</pre>\n")
}
case LinePreformattedText:
text := string(l.(LinePreformattedText))
fmt.Fprintf(&b, "%s\n", html.EscapeString(text))
case LineHeading1:
text := string(l.(LineHeading1))
fmt.Fprintf(&b, "<h1>%s</h1>\n", html.EscapeString(text))
case LineHeading2:
text := string(l.(LineHeading2))
fmt.Fprintf(&b, "<h2>%s</h2>\n", html.EscapeString(text))
case LineHeading3:
text := string(l.(LineHeading3))
fmt.Fprintf(&b, "<h3>%s</h3>\n", html.EscapeString(text))
case LineListItem:
text := string(l.(LineListItem))
fmt.Fprintf(&b, "<li>%s</li>\n", html.EscapeString(text))
case LineQuote:
text := string(l.(LineQuote))
fmt.Fprintf(&b, "<blockquote>%s</blockquote>\n", html.EscapeString(text))
case LineText:
text := string(l.(LineText))
if text == "" {
fmt.Fprint(&b, "<br>\n")
} else {
fmt.Fprintf(&b, "<p>%s</p>\n", html.EscapeString(text))
}
}
}
if pre {
fmt.Fprint(&b, "</pre>\n")
}
if list {
fmt.Fprint(&b, "</ul>\n")
}
return b.String()
}

31
tofu.go
View File

@@ -2,7 +2,6 @@ package gemini
import ( import (
"bufio" "bufio"
"bytes"
"crypto/sha512" "crypto/sha512"
"crypto/x509" "crypto/x509"
"fmt" "fmt"
@@ -14,6 +13,15 @@ import (
"time" "time"
) )
// Trust represents the trustworthiness of a certificate.
type Trust int
const (
TrustNone Trust = iota // The certificate is not trusted.
TrustOnce // The certificate is trusted once.
TrustAlways // The certificate is trusted always.
)
// KnownHosts represents a list of known hosts. // KnownHosts represents a list of known hosts.
// The zero value for KnownHosts is an empty list ready to use. // The zero value for KnownHosts is an empty list ready to use.
type KnownHosts struct { type KnownHosts struct {
@@ -87,26 +95,25 @@ func (k *KnownHosts) add(hostname string, cert *x509.Certificate, write bool) {
} }
// Lookup looks for the provided certificate in the list of known hosts. // Lookup looks for the provided certificate in the list of known hosts.
// If the hostname is in the list, but the fingerprint differs, // If the hostname is not in the list, Lookup returns ErrCertificateNotFound.
// Lookup returns ErrCertificateNotTrusted. // If the fingerprint doesn't match, Lookup returns ErrCertificateNotTrusted.
// If the hostname is not in the list, Lookup returns ErrCertificateUnknown. // Otherwise, Lookup returns nil.
// If the certificate is found and the fingerprint matches, error will be nil.
func (k *KnownHosts) Lookup(hostname string, cert *x509.Certificate) error { func (k *KnownHosts) Lookup(hostname string, cert *x509.Certificate) error {
now := time.Now().Unix() now := time.Now().Unix()
fingerprint := Fingerprint(cert) fingerprint := Fingerprint(cert)
if c, ok := k.hosts[hostname]; ok { if c, ok := k.hosts[hostname]; ok {
if c.Expires <= now { if c.Expires <= now {
// Certificate is expired // Certificate is expired
return ErrCertificateUnknown return ErrCertificateExpired
} }
if c.Fingerprint != fingerprint { if c.Fingerprint != fingerprint {
// Fingerprint does not match // Fingerprint does not match
return ErrCertificateNotTrusted return ErrCertificateNotTrusted
} }
// Certificate is trusted // Certificate is found
return nil return nil
} }
return ErrCertificateUnknown return ErrCertificateNotFound
} }
// Parse parses the provided reader and adds the parsed known hosts to the list. // Parse parses the provided reader and adds the parsed known hosts to the list.
@@ -162,14 +169,14 @@ func appendKnownHost(w io.Writer, hostname string, c certInfo) (int, error) {
// Fingerprint returns the SHA-512 fingerprint of the provided certificate. // Fingerprint returns the SHA-512 fingerprint of the provided certificate.
func Fingerprint(cert *x509.Certificate) string { func Fingerprint(cert *x509.Certificate) string {
sum512 := sha512.Sum512(cert.Raw) sum512 := sha512.Sum512(cert.Raw)
var buf bytes.Buffer var b strings.Builder
for i, f := range sum512 { for i, f := range sum512 {
if i > 0 { if i > 0 {
fmt.Fprintf(&buf, ":") b.WriteByte(':')
} }
fmt.Fprintf(&buf, "%02X", f) fmt.Fprintf(&b, "%02X", f)
} }
return buf.String() return b.String()
} }
// defaultKnownHostsPath returns the default known_hosts path. // defaultKnownHostsPath returns the default known_hosts path.