103 Commits

Author SHA1 Message Date
Adnan Maolood
0722f4008a Update documentation 2021-02-21 00:56:37 -05:00
Adnan Maolood
e3d48b2cad server: Return ErrServerClosed 2021-02-21 00:51:02 -05:00
Adnan Maolood
3fa55b52dd server: Use separate context to cancel listeners
Use a separate context to cancel listeners so that cancelling the
listener does not cancel it's connections.
2021-02-21 00:41:41 -05:00
Adnan Maolood
6c701ad9fe examples/stream: Showcase Server.Shutdown method 2021-02-21 00:29:41 -05:00
Adnan Maolood
7084a226f4 examples: Use context 2021-02-21 00:26:30 -05:00
Adnan Maolood
f6505ae4c4 server: Use explicit context arguments
Replace the Server.Context field with explicit context.Context arguments
to most Server functions.
2021-02-21 00:21:31 -05:00
Adnan Maolood
0c8c945eba client: Inline result type 2021-02-21 00:20:42 -05:00
Adnan Maolood
7668345daa server: Add Context field 2021-02-20 18:52:33 -05:00
Adnan Maolood
0baa66a4e7 Update examples 2021-02-20 18:30:49 -05:00
Adnan Maolood
d479c6391c certificate.Store: Support "*" wildcard pattern 2021-02-20 18:26:15 -05:00
Adnan Maolood
423914d6e0 certificate.Store: Generate certificates by default 2021-02-20 18:25:02 -05:00
Adnan Maolood
15f3e764c5 server: Populate Request.Host field 2021-02-20 18:12:51 -05:00
Adnan Maolood
fadb2aed97 mux: Use StatusHandler instead of RedirectHandler 2021-02-20 16:45:37 -05:00
Adnan Maolood
252fe678fd Rename RedirectHandler to StatusHandler 2021-02-20 16:44:42 -05:00
Adnan Maolood
351fb92c7e Remove NotFound function 2021-02-20 16:42:18 -05:00
Adnan Maolood
2308c6407f server: Make Request.RemoteAddr a net.Addr
A concrete type is better.
2021-02-20 16:27:35 -05:00
Adnan Maolood
8938038797 Make Status a type
Using a type is better than using an integer.
2021-02-20 16:16:32 -05:00
Adnan Maolood
99a8f09c22 TimeoutHandler: Use provided context 2021-02-20 15:52:54 -05:00
Adnan Maolood
e9a68917c9 handler: Make ServeGemini accept a Context 2021-02-20 15:49:14 -05:00
Adnan Maolood
eca2afeb32 examples/client: Remove dependency on go-xdg 2021-02-20 15:42:06 -05:00
Adnan Maolood
28b6232fbf examples/client: Use context 2021-02-20 15:39:47 -05:00
Adnan Maolood
3f4fd10b6d client: Make Get and Do accept a Context
This removes the need for Request.Context.
2021-02-20 15:34:21 -05:00
Adnan Maolood
a7f958b20d server: Make Request.RemoteAddr a string 2021-02-20 13:31:55 -05:00
Adnan Maolood
0ab236c736 client: Allow Request.Host to omit a port 2021-02-20 13:30:55 -05:00
Adnan Maolood
5922cff2e5 Implement TimeoutHandler 2021-02-20 00:49:21 -05:00
Adnan Maolood
64dbb3eecb server: Clarify GetCertificate documentation 2021-02-19 18:53:06 -05:00
Adnan Maolood
69674fcdd5 examples/server: Use certificate.Store 2021-02-19 18:45:19 -05:00
Adnan Maolood
66e03ef1e4 certificate: Implement GetCertificate callback 2021-02-19 18:42:53 -05:00
Adnan Maolood
76967dad2e mux: Reject empty patterns 2021-02-19 18:06:54 -05:00
Adnan Maolood
2e149c9ccd server: Remove Certificates field
Use GetCertificate to retrieve certificates without consulting
Certificates.
2021-02-18 22:22:20 -05:00
Adnan Maolood
229ebb4106 request.Write: Accept an io.Writer 2021-02-18 21:58:37 -05:00
Adnan Maolood
c70ef5c470 client: Remove superfluous call to Flush 2021-02-18 21:55:17 -05:00
Adnan Maolood
6928a1efef request.Write: return error from Flush 2021-02-18 21:54:38 -05:00
Adnan Maolood
a80aae44a9 doc: Update package documentation 2021-02-18 00:38:03 -05:00
Adnan Maolood
aab3ac4dfe response: Implement Write method 2021-02-18 00:07:43 -05:00
Adnan Maolood
a3a995df35 response: Rename statusCode to status 2021-02-18 00:06:34 -05:00
Adnan Maolood
9ed2363b66 response: Ensure that only one header is written 2021-02-17 23:05:24 -05:00
Adnan Maolood
33a1fa4e0d Remove .gitignore 2021-02-17 20:40:53 -05:00
Adnan Maolood
7475687caa examples: Use Server.Handler 2021-02-17 20:35:27 -05:00
Adnan Maolood
6edde376c4 server: Add Handler field and remove Handle methods 2021-02-17 20:31:03 -05:00
Adnan Maolood
f3cd70612b mux: Implement matching of schemes and hostnames 2021-02-17 20:09:42 -05:00
Adnan Maolood
3d6ac90e08 Reverse order of RedirectHandler arguments 2021-02-17 19:53:00 -05:00
Adnan Maolood
b5a3c0adc5 Add utility Handler functions 2021-02-17 19:27:25 -05:00
Adnan Maolood
f81c32a211 examples: Use new ResponseWriter interface 2021-02-17 13:39:23 -05:00
Adnan Maolood
110c2de6de Redesign ResponseWriter interface 2021-02-17 13:36:16 -05:00
Adnan Maolood
8543eca416 status: Fix typo 2021-02-17 12:23:03 -05:00
Adnan Maolood
ec22e762c3 Rename Meta to StatusText
Rename Meta to StatusText and support all status codes.
2021-02-17 12:06:43 -05:00
Adnan Maolood
a3c1804395 Move ResponseWriter.Flush to Flusher interface 2021-02-17 11:44:13 -05:00
Adnan Maolood
fb9b50871c fs: Reject potentially unsafe requests in ServeFile
Reject requests where r.URL.Path contains a ".." path element to protect
against callers who might unsafely use filepath.Join on r.URL.Path
without sanitizing it.
2021-02-17 11:17:13 -05:00
Adnan Maolood
96dc161b4a fs: Add ServeContent function 2021-02-17 11:15:30 -05:00
Adnan Maolood
246b252fd7 examples/server: Use os.DirFS 2021-02-17 09:25:44 -05:00
Adnan Maolood
2e5569d5b5 fs: Fix redirect to canonical file path 2021-02-17 09:24:09 -05:00
Adnan Maolood
8eccefb8c9 fs: Add redirects 2021-02-17 01:38:18 -05:00
Adnan Maolood
995769556c fs: Trim trailing slash from name in ServeFile 2021-02-17 01:36:53 -05:00
Adnan Maolood
73bf1a31b0 fs: Clean paths before handling with FileServer 2021-02-17 00:59:15 -05:00
Adnan Maolood
fa7ec1ac87 fs: Show listing for directories without index files 2021-02-17 00:08:14 -05:00
Adnan Maolood
e3d1fc2785 fs: Remove leading slash before opening files 2021-02-16 23:18:37 -05:00
Adnan Maolood
332dd253d0 Replace uses of ioutil with io 2021-02-16 18:57:24 -05:00
Adnan Maolood
d2001de5f3 fs: Replace FileSystem with io/fs.FS 2021-02-16 18:53:56 -05:00
Adnan Maolood
cf995c86c9 Require Go 1.16 2021-02-16 18:50:42 -05:00
Adnan Maolood
dfa37aaeb8 client: Don't try to verify unicode hostname 2021-02-16 11:27:53 -05:00
Adnan Maolood
7c1a5184c9 Update examples/auth.go 2021-02-16 11:26:09 -05:00
Adnan Maolood
779be8b95b request: Allow User in URLs 2021-02-16 00:55:56 -05:00
Adnan Maolood
2157b35c0b Add build status badge to README.md 2021-02-16 00:07:01 -05:00
Adnan Maolood
1cb31e2d65 Add build manifest 2021-02-16 00:05:10 -05:00
Adnan Maolood
1d6cbddc5b server: Prevent adding Listeners after Close
Check done after calling trackListener to prevent the listener from
being registered after the server is closed.
2021-02-15 20:19:44 -05:00
Adnan Maolood
a05fa6d6bd server: Avoid creating a new Listener after Close 2021-02-15 20:16:32 -05:00
Adnan Maolood
f158bb5f1d server: Use separate mutex for handlers 2021-02-15 20:05:47 -05:00
Adnan Maolood
ec269c5c9d Add some tests 2021-02-15 19:20:37 -05:00
Adnan Maolood
bf4959a8ba Return ErrInvalidResponse on error reading status
Return ErrInvalidResponse when unable to read the response status code
instead of returning the error from strconv.
2021-02-15 19:18:23 -05:00
Adnan Maolood
19678ef934 Remove NewRequestFromURL method
Use a Request struct literal instead.
2021-02-15 17:23:56 -05:00
Adnan Maolood
5a784693ef server: Rename responder to handler 2021-02-15 01:15:23 -05:00
Adnan Maolood
2c7f8273e9 server: Recover from ServeGemini panics 2021-02-15 00:36:33 -05:00
Adnan Maolood
96a84ddd38 request: Don't read more than 1026 bytes 2021-02-15 00:16:21 -05:00
Adnan Maolood
3f2d540579 server: Implement Close and Shutdown methods 2021-02-14 23:58:33 -05:00
Adnan Maolood
92e7a309c6 Tweak returned error for requests that are too long
Return ErrInvalidRequest instead of ErrInvalidURL in Request.Write.
2021-02-14 23:33:18 -05:00
Adnan Maolood
c5ccbf023a fs: Refactor 2021-02-14 19:50:38 -05:00
Adnan Maolood
ff06e50df5 status: Update documentation 2021-02-14 19:28:29 -05:00
Adnan Maolood
5ec8dea1ba fs: Update documentation 2021-02-14 19:27:56 -05:00
Adnan Maolood
46e10da3a8 Make Request.Host optional 2021-02-14 19:02:34 -05:00
Adnan Maolood
41eec39a1d Update examples/client.go 2021-02-14 18:59:33 -05:00
Adnan Maolood
198a0b31c8 Remove faulty status code check in ReadResponse 2021-02-14 18:57:13 -05:00
Adnan Maolood
6f7c183662 server: Don't populate Request.Certificate field
Handlers should instead use the certificate provided in Request.TLS.
2021-02-14 17:34:57 -05:00
Adnan Maolood
20e1b14108 Update Client documentation 2021-02-14 17:11:05 -05:00
Adnan Maolood
0c303588a4 Update Response documentation 2021-02-14 16:23:38 -05:00
Adnan Maolood
37e5686764 Remove StatusClass* constants
Re-use the existing Status* constants and adjust StatusClass to return a
valid Status.
2021-02-14 16:01:39 -05:00
Adnan Maolood
7c703e95de Update documentation 2021-02-14 15:50:41 -05:00
Adnan Maolood
595b0d0490 server: Populate Request.RemoteAddr field 2021-02-13 21:10:19 -05:00
Adnan Maolood
d2c70a33d5 client: Punycode request URL 2021-02-09 16:55:14 -05:00
Adnan Maolood
79e0296bed client: Support IDNs
Convert IDNs to punycode before performing DNS lookups.
2021-02-09 15:59:47 -05:00
Adnan Maolood
f0e9150663 Add Gemini specification version to README.md 2021-02-09 15:50:54 -05:00
Adnan Maolood
f4b80ef305 Update documentation 2021-02-09 10:00:04 -05:00
Adnan Maolood
0e3b61ed00 examples/client: Fix opening of known hosts file 2021-02-09 09:48:51 -05:00
Adnan Maolood
f6824bd813 Make ResponseWriter an interface 2021-02-09 09:46:18 -05:00
Adnan Maolood
5ef5824d6f Use plain integers to represent status codes 2021-02-09 09:46:13 -05:00
Adnan Maolood
9bfb007581 Update README.md 2021-02-08 12:53:37 -05:00
Adnan Maolood
7910ed433b Rename Responder to Handler 2021-02-08 12:50:52 -05:00
Adnan Maolood
29f2b3738d Make TLS field nil for unencrypted connections 2021-02-08 12:32:49 -05:00
Adnan Maolood
1f39cab063 Remove unused field 2021-02-08 12:30:53 -05:00
Adnan Maolood
62960266ac tofu: Implement PersistentHosts 2021-01-25 12:11:59 -05:00
Adnan Maolood
3efa17f6fb Update examples 2021-01-25 10:59:50 -05:00
Adnan Maolood
9e89b93bab server: Allow handling any hostname with "*"
Allow registering a responder with the special pattern "*" to handle any
hostname.
2021-01-25 10:55:40 -05:00
Adnan Maolood
31de8d49b0 Guarantee that (*Response).Body is not nil 2021-01-15 15:18:00 -05:00
27 changed files with 2108 additions and 702 deletions

9
.build.yml Normal file
View File

@@ -0,0 +1,9 @@
image: alpine/edge
packages:
- go
sources:
- https://git.sr.ht/~adnano/go-gemini
tasks:
- test: |
cd go-gemini
go test ./...

2
.gitignore vendored
View File

@@ -1,2 +0,0 @@
*.crt
*.key

View File

@@ -1,10 +1,12 @@
# go-gemini # go-gemini
[![godocs.io](https://godocs.io/git.sr.ht/~adnano/go-gemini?status.svg)](https://godocs.io/git.sr.ht/~adnano/go-gemini) [![godocs.io](https://godocs.io/git.sr.ht/~adnano/go-gemini?status.svg)](https://godocs.io/git.sr.ht/~adnano/go-gemini) [![builds.sr.ht status](https://builds.sr.ht/~adnano/go-gemini.svg)](https://builds.sr.ht/~adnano/go-gemini?)
Package gemini implements the [Gemini protocol](https://gemini.circumlunar.space) in Go. Package gemini implements the [Gemini protocol](https://gemini.circumlunar.space) in Go.
It aims to provide an API similar to that of net/http to make it easy to develop Gemini clients and servers. It provides an API similar to that of net/http to make it easy to develop Gemini clients and servers.
Compatible with version v0.14.3 of the Gemini specification.
## Usage ## Usage

View File

@@ -14,103 +14,9 @@ import (
"math/big" "math/big"
"net" "net"
"os" "os"
"path/filepath"
"strings"
"sync"
"time" "time"
) )
// Dir represents a directory of certificates.
// The zero value for Dir is an empty directory ready to use.
//
// Dir is safe for concurrent use by multiple goroutines.
type Dir struct {
certs map[string]tls.Certificate
path *string
mu sync.RWMutex
}
// Add adds a certificate for the given scope to the directory.
// It tries to parse the certificate if it is not already parsed.
func (d *Dir) Add(scope string, cert tls.Certificate) error {
d.mu.Lock()
defer d.mu.Unlock()
if d.certs == nil {
d.certs = map[string]tls.Certificate{}
}
// Parse certificate if not already parsed
if cert.Leaf == nil {
parsed, err := x509.ParseCertificate(cert.Certificate[0])
if err == nil {
cert.Leaf = parsed
}
}
if d.path != nil {
// Escape slash character
scope = strings.ReplaceAll(scope, "/", ":")
certPath := filepath.Join(*d.path, scope+".crt")
keyPath := filepath.Join(*d.path, scope+".key")
if err := Write(cert, certPath, keyPath); err != nil {
return err
}
}
d.certs[scope] = cert
return nil
}
// Lookup returns the certificate for the provided scope.
func (d *Dir) Lookup(scope string) (tls.Certificate, bool) {
d.mu.RLock()
defer d.mu.RUnlock()
cert, ok := d.certs[scope]
return cert, ok
}
// Entries returns a map of hostnames to certificates.
func (d *Dir) Entries() map[string]tls.Certificate {
certs := map[string]tls.Certificate{}
for key := range d.certs {
certs[key] = d.certs[key]
}
return certs
}
// Load loads certificates from the provided path.
// Add will write certificates to this path.
//
// The directory should contain certificates and private keys
// named scope.crt and scope.key respectively, where scope is
// the scope of the certificate.
func (d *Dir) Load(path string) error {
matches, err := filepath.Glob(filepath.Join(path, "*.crt"))
if err != nil {
return err
}
for _, crtPath := range matches {
keyPath := strings.TrimSuffix(crtPath, ".crt") + ".key"
cert, err := tls.LoadX509KeyPair(crtPath, keyPath)
if err != nil {
continue
}
scope := strings.TrimSuffix(filepath.Base(crtPath), ".crt")
// Unescape slash character
scope = strings.ReplaceAll(scope, ":", "/")
d.Add(scope, cert)
}
d.SetPath(path)
return nil
}
// SetPath sets the directory path.
// Add will write certificates to this path.
func (d *Dir) SetPath(path string) {
d.mu.Lock()
defer d.mu.Unlock()
d.path = &path
}
// CreateOptions configures the creation of a TLS certificate. // CreateOptions configures the creation of a TLS certificate.
type CreateOptions struct { type CreateOptions struct {
// Subject Alternate Name values. // Subject Alternate Name values.

170
certificate/store.go Normal file
View File

@@ -0,0 +1,170 @@
package certificate
import (
"crypto/tls"
"crypto/x509"
"crypto/x509/pkix"
"errors"
"fmt"
"path/filepath"
"strings"
"sync"
"time"
)
// Store represents a certificate store.
// The zero value for Store is an empty store ready to use.
//
// Store is safe for concurrent use by multiple goroutines.
type Store struct {
// CreateCertificate, if not nil, is called to create a new certificate
// to replace a missing or expired certificate. If CreateCertificate
// is nil, a certificate with a duration of 1 year will be created.
CreateCertificate func(scope string) (tls.Certificate, error)
certs map[string]tls.Certificate
path string
mu sync.RWMutex
}
// Register registers the provided scope in the certificate store.
// The certificate will be created upon calling GetCertificate.
func (s *Store) Register(scope string) {
s.mu.Lock()
defer s.mu.Unlock()
if s.certs == nil {
s.certs = make(map[string]tls.Certificate)
}
s.certs[scope] = tls.Certificate{}
}
// Add adds a certificate for the given scope to the certificate store.
func (s *Store) Add(scope string, cert tls.Certificate) error {
s.mu.Lock()
defer s.mu.Unlock()
if s.certs == nil {
s.certs = make(map[string]tls.Certificate)
}
// Parse certificate if not already parsed
if cert.Leaf == nil {
parsed, err := x509.ParseCertificate(cert.Certificate[0])
if err != nil {
return err
}
cert.Leaf = parsed
}
if s.path != "" {
// Escape slash character
path := strings.ReplaceAll(scope, "/", ":")
certPath := filepath.Join(s.path, path+".crt")
keyPath := filepath.Join(s.path, path+".key")
if err := Write(cert, certPath, keyPath); err != nil {
return err
}
}
s.certs[scope] = cert
return nil
}
// Lookup returns the certificate for the provided scope.
func (s *Store) Lookup(scope string) (tls.Certificate, bool) {
s.mu.RLock()
defer s.mu.RUnlock()
cert, ok := s.certs[scope]
return cert, ok
}
// GetCertificate retrieves the certificate for the given scope.
// If the retrieved certificate is expired or the scope is registered but
// has no certificate, it calls CreateCertificate to create a new certificate.
func (s *Store) GetCertificate(scope string) (*tls.Certificate, error) {
cert, ok := s.Lookup(scope)
if !ok {
// Try wildcard
wildcard := strings.SplitN(scope, ".", 2)
if len(wildcard) == 2 {
cert, ok = s.Lookup("*." + wildcard[1])
}
}
if !ok {
// Try "*"
_, ok = s.Lookup("*")
}
if !ok {
return nil, errors.New("unrecognized scope")
}
// If the certificate is empty or expired, generate a new one.
if cert.Leaf == nil || cert.Leaf.NotAfter.Before(time.Now()) {
var err error
cert, err = s.createCertificate(scope)
if err != nil {
return nil, err
}
if err := s.Add(scope, cert); err != nil {
return nil, fmt.Errorf("failed to add certificate for %s: %w", scope, err)
}
}
return &cert, nil
}
func (s *Store) createCertificate(scope string) (tls.Certificate, error) {
if s.CreateCertificate != nil {
return s.CreateCertificate(scope)
}
return Create(CreateOptions{
DNSNames: []string{scope},
Subject: pkix.Name{
CommonName: scope,
},
Duration: 365 * 24 * time.Hour,
})
}
// Load loads certificates from the provided path.
// New certificates will be written to this path.
//
// The path should lead to a directory containing certificates
// and private keys named "scope.crt" and "scope.key" respectively,
// where "scope" is the scope of the certificate.
func (s *Store) Load(path string) error {
matches, err := filepath.Glob(filepath.Join(path, "*.crt"))
if err != nil {
return err
}
for _, crtPath := range matches {
keyPath := strings.TrimSuffix(crtPath, ".crt") + ".key"
cert, err := tls.LoadX509KeyPair(crtPath, keyPath)
if err != nil {
continue
}
scope := strings.TrimSuffix(filepath.Base(crtPath), ".crt")
// Unescape slash character
scope = strings.ReplaceAll(scope, ":", "/")
s.Add(scope, cert)
}
s.SetPath(path)
return nil
}
// Entries returns a map of scopes to certificates.
func (s *Store) Entries() map[string]tls.Certificate {
s.mu.RLock()
defer s.mu.RUnlock()
certs := make(map[string]tls.Certificate)
for key := range s.certs {
certs[key] = s.certs[key]
}
return certs
}
// SetPath sets the path that new certificates will be written to.
func (s *Store) SetPath(path string) {
s.mu.Lock()
defer s.mu.Unlock()
s.path = path
}

196
client.go
View File

@@ -1,18 +1,16 @@
package gemini package gemini
import ( import (
"bufio"
"context" "context"
"crypto/tls" "crypto/tls"
"crypto/x509" "crypto/x509"
"errors" "errors"
"fmt"
"net" "net"
"strings" "net/url"
"time" "time"
) )
// Client is a Gemini client. // A Client is a Gemini client. Its zero value is a usable client.
type Client struct { type Client struct {
// TrustCertificate is called to determine whether the client // TrustCertificate is called to determine whether the client
// should trust the certificate provided by the server. // should trust the certificate provided by the server.
@@ -20,39 +18,99 @@ type Client struct {
// If the returned error is not nil, the certificate will not be trusted // If the returned error is not nil, the certificate will not be trusted
// and the request will be aborted. // and the request will be aborted.
// //
// For a basic trust on first use implementation, see (*KnownHosts).TOFU // See the tofu submodule for an implementation of trust on first use.
// in the tofu submodule.
TrustCertificate func(hostname string, cert *x509.Certificate) error TrustCertificate func(hostname string, cert *x509.Certificate) error
// Timeout specifies a time limit for requests made by this // Timeout specifies a time limit for requests made by this
// Client. The timeout includes connection time and reading // Client. The timeout includes connection time and reading
// the response body. The timer remains running after // the response body. The timer remains running after
// Get and Do return and will interrupt reading of the Response.Body. // Get or Do return and will interrupt reading of the Response.Body.
// //
// A Timeout of zero means no timeout. // A Timeout of zero means no timeout.
Timeout time.Duration Timeout time.Duration
// DialContext specifies the dial function for creating TCP connections.
// If DialContext is nil, the client dials using package net.
DialContext func(ctx context.Context, network, addr string) (net.Conn, error)
} }
// Get performs a Gemini request for the given URL. // Get sends a Gemini request for the given URL.
func (c *Client) Get(url string) (*Response, error) { //
// An error is returned if there was a Gemini protocol error.
// A non-2x status code doesn't cause an error.
//
// If the returned error is nil, the Response will contain a non-nil Body
// which the user is expected to close.
//
// For more control over requests, use NewRequest and Client.Do.
func (c *Client) Get(ctx context.Context, url string) (*Response, error) {
req, err := NewRequest(url) req, err := NewRequest(url)
if err != nil { if err != nil {
return nil, err return nil, err
} }
return c.Do(req) return c.Do(ctx, req)
} }
// Do performs a Gemini request and returns a Gemini response. // Do sends a Gemini request and returns a Gemini response, following
func (c *Client) Do(req *Request) (*Response, error) { // policy as configured on the client.
// Extract hostname //
colonPos := strings.LastIndex(req.Host, ":") // An error is returned if there was a Gemini protocol error.
if colonPos == -1 { // A non-2x status code doesn't cause an error.
colonPos = len(req.Host) //
// If the returned error is nil, the Response will contain a non-nil Body
// which the user is expected to close.
//
// Generally Get will be used instead of Do.
func (c *Client) Do(ctx context.Context, req *Request) (*Response, error) {
if ctx == nil {
panic("nil context")
} }
hostname := req.Host[:colonPos]
// Punycode request URL host
host, port := splitHostPort(req.URL.Host)
punycode, err := punycodeHostname(host)
if err != nil {
return nil, err
}
if host != punycode {
host = punycode
// Make a copy of the request
r2 := new(Request)
*r2 = *req
r2.URL = new(url.URL)
*r2.URL = *req.URL
req = r2
// Set the host
req.URL.Host = net.JoinHostPort(host, port)
}
// Use request host if provided
if req.Host != "" {
host, port = splitHostPort(req.Host)
host, err = punycodeHostname(host)
if err != nil {
return nil, err
}
}
addr := net.JoinHostPort(host, port)
// Connect to the host // Connect to the host
config := &tls.Config{ start := time.Now()
conn, err := c.dialContext(ctx, "tcp", addr)
if err != nil {
return nil, err
}
// Set the connection deadline
if c.Timeout != 0 {
conn.SetDeadline(start.Add(c.Timeout))
}
// Setup TLS
conn = tls.Client(conn, &tls.Config{
InsecureSkipVerify: true, InsecureSkipVerify: true,
MinVersion: tls.VersionTLS12, MinVersion: tls.VersionTLS12,
GetClientCertificate: func(_ *tls.CertificateRequestInfo) (*tls.Certificate, error) { GetClientCertificate: func(_ *tls.CertificateRequestInfo) (*tls.Certificate, error) {
@@ -62,63 +120,34 @@ func (c *Client) Do(req *Request) (*Response, error) {
return &tls.Certificate{}, nil return &tls.Certificate{}, nil
}, },
VerifyConnection: func(cs tls.ConnectionState) error { VerifyConnection: func(cs tls.ConnectionState) error {
return c.verifyConnection(req, cs) return c.verifyConnection(cs, host)
}, },
ServerName: hostname, ServerName: host,
} })
// Set connection context
ctx := req.Context type result struct {
if ctx == nil { resp *Response
ctx = context.Background() err error
}
start := time.Now()
dialer := net.Dialer{
Timeout: c.Timeout,
}
netConn, err := dialer.DialContext(ctx, "tcp", req.Host)
if err != nil {
return nil, err
}
conn := tls.Client(netConn, config)
// Set connection deadline
if c.Timeout != 0 {
err := conn.SetDeadline(start.Add(c.Timeout))
if err != nil {
return nil, fmt.Errorf(
"failed to set connection deadline: %w", err)
}
} }
res := make(chan result, 1)
go func() {
resp, err := c.do(conn, req) resp, err := c.do(conn, req)
if err != nil { res <- result{resp, err}
// If we fail to perform the request/response we have }()
// to take responsibility for closing the connection.
_ = conn.Close()
return nil, err select {
case <-ctx.Done():
conn.Close()
return nil, ctx.Err()
case r := <-res:
return r.resp, r.err
} }
// Store connection state
resp.TLS = conn.ConnectionState()
return resp, nil
} }
func (c *Client) do(conn *tls.Conn, req *Request) (*Response, error) { func (c *Client) do(conn net.Conn, req *Request) (*Response, error) {
// Write the request // Write the request
w := bufio.NewWriter(conn) if err := req.Write(conn); err != nil {
err := req.Write(w)
if err != nil {
return nil, fmt.Errorf(
"failed to write request data: %w", err)
}
if err := w.Flush(); err != nil {
return nil, err return nil, err
} }
@@ -128,18 +157,27 @@ func (c *Client) do(conn *tls.Conn, req *Request) (*Response, error) {
return nil, err return nil, err
} }
// Store TLS connection state
if tlsConn, ok := conn.(*tls.Conn); ok {
state := tlsConn.ConnectionState()
resp.TLS = &state
}
return resp, nil return resp, nil
} }
func (c *Client) verifyConnection(req *Request, cs tls.ConnectionState) error { func (c *Client) dialContext(ctx context.Context, network, addr string) (net.Conn, error) {
// Verify the hostname if c.DialContext != nil {
var hostname string return c.DialContext(ctx, network, addr)
if host, _, err := net.SplitHostPort(req.Host); err == nil {
hostname = host
} else {
hostname = req.Host
} }
return (&net.Dialer{
Timeout: c.Timeout,
}).DialContext(ctx, network, addr)
}
func (c *Client) verifyConnection(cs tls.ConnectionState, hostname string) error {
cert := cs.PeerCertificates[0] cert := cs.PeerCertificates[0]
// Verify hostname
if err := verifyHostname(cert, hostname); err != nil { if err := verifyHostname(cert, hostname); err != nil {
return err return err
} }
@@ -147,10 +185,20 @@ func (c *Client) verifyConnection(req *Request, cs tls.ConnectionState) error {
if !time.Now().Before(cert.NotAfter) { if !time.Now().Before(cert.NotAfter) {
return errors.New("gemini: certificate expired") return errors.New("gemini: certificate expired")
} }
// See if the client trusts the certificate // See if the client trusts the certificate
if c.TrustCertificate != nil { if c.TrustCertificate != nil {
return c.TrustCertificate(hostname, cert) return c.TrustCertificate(hostname, cert)
} }
return nil return nil
} }
func splitHostPort(hostport string) (host, port string) {
var err error
host, port, err = net.SplitHostPort(hostport)
if err != nil {
// Likely no port
host = hostport
port = "1965"
}
return
}

24
doc.go
View File

@@ -1,5 +1,5 @@
/* /*
Package gemini implements the Gemini protocol. Package gemini provides Gemini client and server implementations.
Client is a Gemini client. Client is a Gemini client.
@@ -8,11 +8,8 @@ Client is a Gemini client.
if err != nil { if err != nil {
// handle error // handle error
} }
if resp.Body != nil {
defer resp.Body.Close() defer resp.Body.Close()
// ... // ...
}
// ...
Server is a Gemini server. Server is a Gemini server.
@@ -23,26 +20,31 @@ Server is a Gemini server.
Servers should be configured with certificates: Servers should be configured with certificates:
err := server.Certificates.Load("/var/lib/gemini/certs") certificates := &certificate.Store{}
err := certificates.Load("/var/lib/gemini/certs")
if err != nil { if err != nil {
// handle error // handle error
} }
server.GetCertificate = certificates.GetCertificate
Servers can accept requests for multiple hosts and schemes: ServeMux is a Gemini request multiplexer.
ServeMux can handle requests for multiple hosts and schemes.
server.RegisterFunc("example.com", func(w *gemini.ResponseWriter, r *gemini.Request) { mux := &gemini.ServeMux{}
mux.HandleFunc("example.com", func(ctx context.Context, w gemini.ResponseWriter, r *gemini.Request) {
fmt.Fprint(w, "Welcome to example.com") fmt.Fprint(w, "Welcome to example.com")
}) })
server.RegisterFunc("example.org", func(w *gemini.ResponseWriter, r *gemini.Request) { mux.HandleFunc("example.org/about.gmi", func(ctx context.Context, w gemini.ResponseWriter, r *gemini.Request) {
fmt.Fprint(w, "Welcome to example.org") fmt.Fprint(w, "About example.org")
}) })
server.RegisterFunc("http://example.net", func(w *gemini.ResponseWriter, r *gemini.Request) { mux.HandleFunc("http://example.net", func(ctx context.Context, w gemini.ResponseWriter, r *gemini.Request) {
fmt.Fprint(w, "Proxied content from http://example.net") fmt.Fprint(w, "Proxied content from http://example.net")
}) })
server.Handler = mux
To start the server, call ListenAndServe: To start the server, call ListenAndServe:
err := server.ListenAndServe() err := server.ListenAndServe(context.Background())
if err != nil { if err != nil {
// handle error // handle error
} }

View File

@@ -3,10 +3,9 @@
package main package main
import ( import (
"context"
"crypto/sha512" "crypto/sha512"
"crypto/tls"
"crypto/x509" "crypto/x509"
"crypto/x509/pkix"
"fmt" "fmt"
"log" "log"
"time" "time"
@@ -25,26 +24,24 @@ var (
) )
func main() { func main() {
var mux gemini.ServeMux certificates := &certificate.Store{}
certificates.Register("localhost")
if err := certificates.Load("/var/lib/gemini/certs"); err != nil {
log.Fatal(err)
}
mux := &gemini.ServeMux{}
mux.HandleFunc("/", profile) mux.HandleFunc("/", profile)
mux.HandleFunc("/username", changeUsername) mux.HandleFunc("/username", changeUsername)
var server gemini.Server server := &gemini.Server{
if err := server.Certificates.Load("/var/lib/gemini/certs"); err != nil { Handler: mux,
log.Fatal(err) ReadTimeout: 30 * time.Second,
WriteTimeout: 1 * time.Minute,
GetCertificate: certificates.GetCertificate,
} }
server.CreateCertificate = func(hostname string) (tls.Certificate, error) {
return certificate.Create(certificate.CreateOptions{
Subject: pkix.Name{
CommonName: hostname,
},
DNSNames: []string{hostname},
Duration: time.Hour,
})
}
server.Handle("localhost", &mux)
if err := server.ListenAndServe(); err != nil { if err := server.ListenAndServe(context.Background()); err != nil {
log.Fatal(err) log.Fatal(err)
} }
} }
@@ -54,12 +51,12 @@ func fingerprint(cert *x509.Certificate) string {
return string(b[:]) return string(b[:])
} }
func profile(w *gemini.ResponseWriter, r *gemini.Request) { func profile(ctx context.Context, w gemini.ResponseWriter, r *gemini.Request) {
if r.Certificate == nil { if len(r.TLS.PeerCertificates) == 0 {
w.Status(gemini.StatusCertificateRequired) w.WriteHeader(gemini.StatusCertificateRequired, "Certificate required")
return return
} }
fingerprint := fingerprint(r.Certificate.Leaf) fingerprint := fingerprint(r.TLS.PeerCertificates[0])
user, ok := users[fingerprint] user, ok := users[fingerprint]
if !ok { if !ok {
user = &User{} user = &User{}
@@ -69,23 +66,23 @@ func profile(w *gemini.ResponseWriter, r *gemini.Request) {
fmt.Fprintln(w, "=> /username Change username") fmt.Fprintln(w, "=> /username Change username")
} }
func changeUsername(w *gemini.ResponseWriter, r *gemini.Request) { func changeUsername(ctx context.Context, w gemini.ResponseWriter, r *gemini.Request) {
if r.Certificate == nil { if len(r.TLS.PeerCertificates) == 0 {
w.Status(gemini.StatusCertificateRequired) w.WriteHeader(gemini.StatusCertificateRequired, "Certificate required")
return return
} }
username, err := gemini.QueryUnescape(r.URL.RawQuery) username, err := gemini.QueryUnescape(r.URL.RawQuery)
if err != nil || username == "" { if err != nil || username == "" {
w.Header(gemini.StatusInput, "Username") w.WriteHeader(gemini.StatusInput, "Username")
return return
} }
fingerprint := fingerprint(r.Certificate.Leaf) fingerprint := fingerprint(r.TLS.PeerCertificates[0])
user, ok := users[fingerprint] user, ok := users[fingerprint]
if !ok { if !ok {
user = &User{} user = &User{}
users[fingerprint] = user users[fingerprint] = user
} }
user.Name = username user.Name = username
w.Header(gemini.StatusRedirect, "/") w.WriteHeader(gemini.StatusRedirect, "/")
} }

View File

@@ -7,10 +7,11 @@ package main
import ( import (
"bufio" "bufio"
"bytes" "bytes"
"context"
"crypto/x509" "crypto/x509"
"errors" "errors"
"fmt" "fmt"
"io/ioutil" "io"
"log" "log"
"net/url" "net/url"
"os" "os"
@@ -19,7 +20,6 @@ import (
"git.sr.ht/~adnano/go-gemini" "git.sr.ht/~adnano/go-gemini"
"git.sr.ht/~adnano/go-gemini/tofu" "git.sr.ht/~adnano/go-gemini/tofu"
"git.sr.ht/~adnano/go-xdg"
) )
var ( var (
@@ -28,15 +28,22 @@ var (
scanner *bufio.Scanner scanner *bufio.Scanner
) )
func xdgDataHome() string {
if s, ok := os.LookupEnv("XDG_DATA_HOME"); ok {
return s
}
return filepath.Join(os.Getenv("HOME"), ".local", "share")
}
func init() { func init() {
// Load known hosts file // Load known hosts file
path := filepath.Join(xdg.DataHome(), "gemini", "known_hosts") path := filepath.Join(xdgDataHome(), "gemini", "known_hosts")
err := hosts.Load(path) err := hosts.Load(path)
if err != nil { if err != nil {
log.Fatal(err) log.Fatal(err)
} }
hostsfile, err = tofu.NewHostsFile(path) hostsfile, err = tofu.OpenHostsFile(path)
if err != nil { if err != nil {
log.Fatal(err) log.Fatal(err)
} }
@@ -90,13 +97,13 @@ func do(req *gemini.Request, via []*gemini.Request) (*gemini.Response, error) {
client := gemini.Client{ client := gemini.Client{
TrustCertificate: trustCertificate, TrustCertificate: trustCertificate,
} }
resp, err := client.Do(req) resp, err := client.Do(context.Background(), req)
if err != nil { if err != nil {
return resp, err return resp, err
} }
switch resp.Status.Class() { switch resp.Status.Class() {
case gemini.StatusClassInput: case gemini.StatusInput:
input, ok := getInput(resp.Meta, resp.Status == gemini.StatusSensitiveInput) input, ok := getInput(resp.Meta, resp.Status == gemini.StatusSensitiveInput)
if !ok { if !ok {
break break
@@ -105,7 +112,7 @@ func do(req *gemini.Request, via []*gemini.Request) (*gemini.Response, error) {
req.URL.RawQuery = gemini.QueryEscape(input) req.URL.RawQuery = gemini.QueryEscape(input)
return do(req, via) return do(req, via)
case gemini.StatusClassRedirect: case gemini.StatusRedirect:
via = append(via, req) via = append(via, req)
if len(via) > 5 { if len(via) > 5 {
return resp, errors.New("too many redirects") return resp, errors.New("too many redirects")
@@ -145,11 +152,11 @@ func main() {
fmt.Println(err) fmt.Println(err)
os.Exit(1) os.Exit(1)
} }
defer resp.Body.Close()
// Handle response // Handle response
if resp.Status.Class() == gemini.StatusClassSuccess { if resp.Status.Class() == gemini.StatusSuccess {
defer resp.Body.Close() body, err := io.ReadAll(resp.Body)
body, err := ioutil.ReadAll(resp.Body)
if err != nil { if err != nil {
log.Fatal(err) log.Fatal(err)
} }

View File

@@ -5,9 +5,9 @@
package main package main
import ( import (
"crypto/tls" "context"
"crypto/x509/pkix"
"log" "log"
"os"
"time" "time"
"git.sr.ht/~adnano/go-gemini" "git.sr.ht/~adnano/go-gemini"
@@ -15,27 +15,23 @@ import (
) )
func main() { func main() {
var server gemini.Server certificates := &certificate.Store{}
server.ReadTimeout = 30 * time.Second certificates.Register("localhost")
server.WriteTimeout = 1 * time.Minute if err := certificates.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.CreateCertificate = func(hostname string) (tls.Certificate, error) {
return certificate.Create(certificate.CreateOptions{ mux := &gemini.ServeMux{}
Subject: pkix.Name{ mux.Handle("/", gemini.FileServer(os.DirFS("/var/www")))
CommonName: hostname,
}, server := &gemini.Server{
DNSNames: []string{hostname}, Handler: mux,
Duration: 365 * 24 * time.Hour, ReadTimeout: 30 * time.Second,
}) WriteTimeout: 1 * time.Minute,
GetCertificate: certificates.GetCertificate,
} }
var mux gemini.ServeMux if err := server.ListenAndServe(context.Background()); err != nil {
mux.Handle("/", gemini.FileServer(gemini.Dir("/var/www")))
server.Handle("localhost", &mux)
if err := server.ListenAndServe(); err != nil {
log.Fatal(err) log.Fatal(err)
} }
} }

View File

@@ -6,10 +6,9 @@ package main
import ( import (
"context" "context"
"crypto/tls"
"crypto/x509/pkix"
"fmt" "fmt"
"log" "log"
"sync"
"time" "time"
"git.sr.ht/~adnano/go-gemini" "git.sr.ht/~adnano/go-gemini"
@@ -17,30 +16,52 @@ import (
) )
func main() { func main() {
var server gemini.Server certificates := &certificate.Store{}
if err := server.Certificates.Load("/var/lib/gemini/certs"); err != nil { certificates.Register("localhost")
if err := certificates.Load("/var/lib/gemini/certs"); err != nil {
log.Fatal(err) log.Fatal(err)
} }
server.CreateCertificate = func(hostname string) (tls.Certificate, error) {
return certificate.Create(certificate.CreateOptions{
Subject: pkix.Name{
CommonName: hostname,
},
DNSNames: []string{hostname},
Duration: 365 * 24 * time.Hour,
})
}
server.HandleFunc("localhost", stream) mux := &gemini.ServeMux{}
if err := server.ListenAndServe(); err != nil { mux.HandleFunc("/", stream)
log.Fatal(err)
server := &gemini.Server{
Handler: mux,
ReadTimeout: 30 * time.Second,
WriteTimeout: 1 * time.Minute,
GetCertificate: certificates.GetCertificate,
}
var shutdownOnce sync.Once
var wg sync.WaitGroup
wg.Add(1)
defer wg.Wait()
mux.HandleFunc("/shutdown", func(ctx context.Context, w gemini.ResponseWriter, r *gemini.Request) {
fmt.Fprintln(w, "Shutting down...")
if flusher, ok := w.(gemini.Flusher); ok {
flusher.Flush()
}
go shutdownOnce.Do(func() {
server.Shutdown(context.Background())
wg.Done()
})
})
if err := server.ListenAndServe(context.Background()); err != nil {
log.Println(err)
} }
} }
// stream writes an infinite stream to w. // stream writes an infinite stream to w.
func stream(w *gemini.ResponseWriter, r *gemini.Request) { func stream(ctx context.Context, w gemini.ResponseWriter, r *gemini.Request) {
flusher, ok := w.(gemini.Flusher)
if !ok {
w.WriteHeader(gemini.StatusTemporaryFailure, "Internal error")
return
}
ch := make(chan string) ch := make(chan string)
ctx, cancel := context.WithCancel(context.Background()) ctx, cancel := context.WithCancel(ctx)
go func(ctx context.Context) { go func(ctx context.Context) {
for { for {
@@ -63,7 +84,7 @@ func stream(w *gemini.ResponseWriter, r *gemini.Request) {
break break
} }
fmt.Fprintln(w, s) fmt.Fprintln(w, s)
if err := w.Flush(); err != nil { if err := flusher.Flush(); err != nil {
cancel() cancel()
return return
} }

242
fs.go
View File

@@ -1,10 +1,15 @@
package gemini package gemini
import ( import (
"context"
"fmt"
"io" "io"
"io/fs"
"mime" "mime"
"os" "net/url"
"path" "path"
"sort"
"strings"
) )
func init() { func init() {
@@ -13,102 +18,189 @@ func init() {
mime.AddExtensionType(".gemini", "text/gemini") mime.AddExtensionType(".gemini", "text/gemini")
} }
// FileServer takes a filesystem and returns a Responder which uses that filesystem. // FileServer returns a handler that serves Gemini requests with the contents
// The returned Responder cleans paths before handling them. // of the provided file system.
// //
// TODO: Use io/fs.FS when available. // To use the operating system's file system implementation, use os.DirFS:
func FileServer(fsys FS) Responder { //
return fsHandler{fsys} // gemini.FileServer(os.DirFS("/tmp"))
func FileServer(fsys fs.FS) Handler {
return fileServer{fsys}
} }
type fsHandler struct { type fileServer struct {
FS fs.FS
} }
func (fsh fsHandler) Respond(w *ResponseWriter, r *Request) { func (fs fileServer) ServeGemini(ctx context.Context, w ResponseWriter, r *Request) {
p := path.Clean(r.URL.Path) serveFile(ctx, w, r, fs, path.Clean(r.URL.Path), true)
f, err := fsh.Open(p) }
if err != nil {
w.Status(StatusNotFound) // ServeContent replies to the request using the content in the
return // provided Reader. The main benefit of ServeContent over io.Copy
} // is that it sets the MIME type of the response.
// Detect mimetype //
ext := path.Ext(p) // ServeContent tries to deduce the type from name's file extension.
// The name is otherwise unused; it is never sent in the response.
func ServeContent(ctx context.Context, w ResponseWriter, r *Request, name string, content io.Reader) {
serveContent(ctx, w, name, content)
}
func serveContent(ctx context.Context, w ResponseWriter, name string, content io.Reader) {
// Detect mimetype from file extension
ext := path.Ext(name)
mimetype := mime.TypeByExtension(ext) mimetype := mime.TypeByExtension(ext)
w.Meta(mimetype) w.MediaType(mimetype)
// Copy file to response writer io.Copy(w, content)
_, _ = io.Copy(w, f)
}
// FS represents a filesystem.
//
// TODO: Replace with io/fs.FS when available.
type FS interface {
Open(name string) (File, error)
}
// File represents a file.
//
// TODO: Replace with io/fs.File when available.
type File interface {
Stat() (os.FileInfo, error)
Read([]byte) (int, error)
Close() error
}
// Dir implements FS using the native filesystem restricted to a specific directory.
//
// TODO: replace with os.DirFS when available.
type Dir string
// Open tries to open the file with the given name.
// If the file is a directory, it tries to open the index file in that directory.
func (d Dir) Open(name string) (File, error) {
p := path.Join(string(d), name)
return openFile(p)
} }
// ServeFile responds to the request with the contents of the named file // ServeFile responds to the request with the contents of the named file
// or directory. // or directory.
// //
// TODO: Use io/fs.FS when available. // If the provided file or directory name is a relative path, it is interpreted
func ServeFile(w *ResponseWriter, fs FS, name string) { // relative to the current directory and may ascend to parent directories. If
f, err := fs.Open(name) // the provided name is constructed from user input, it should be sanitized
if err != nil { // before calling ServeFile.
w.Status(StatusNotFound) //
// As a precaution, ServeFile will reject requests where r.URL.Path contains a
// ".." path element; this protects against callers who might unsafely use
// filepath.Join on r.URL.Path without sanitizing it and then use that
// filepath.Join result as the name argument.
//
// As another special case, ServeFile redirects any request where r.URL.Path
// ends in "/index.gmi" to the same path, without the final "index.gmi". To
// avoid such redirects either modify the path or use ServeContent.
//
// Outside of those two special cases, ServeFile does not use r.URL.Path for
// selecting the file or directory to serve; only the file or directory
// provided in the name argument is used.
func ServeFile(ctx context.Context, w ResponseWriter, r *Request, fsys fs.FS, name string) {
if containsDotDot(r.URL.Path) {
// Too many programs use r.URL.Path to construct the argument to
// serveFile. Reject the request under the assumption that happened
// here and ".." may not be wanted.
// Note that name might not contain "..", for example if code (still
// incorrectly) used filepath.Join(myDir, r.URL.Path).
w.WriteHeader(StatusBadRequest, "invalid URL path")
return return
} }
// Detect mimetype serveFile(ctx, w, r, fsys, name, false)
ext := path.Ext(name)
mimetype := mime.TypeByExtension(ext)
w.Meta(mimetype)
// Copy file to response writer
_, _ = io.Copy(w, f)
} }
func openFile(p string) (File, error) { func containsDotDot(v string) bool {
f, err := os.OpenFile(p, os.O_RDONLY, 0644) if !strings.Contains(v, "..") {
if err != nil { return false
return nil, err }
for _, ent := range strings.FieldsFunc(v, isSlashRune) {
if ent == ".." {
return true
}
}
return false
}
func isSlashRune(r rune) bool { return r == '/' || r == '\\' }
func serveFile(ctx context.Context, w ResponseWriter, r *Request, fsys fs.FS, name string, redirect bool) {
const indexPage = "/index.gmi"
// Redirect .../index.gmi to .../
if strings.HasSuffix(r.URL.Path, indexPage) {
w.WriteHeader(StatusPermanentRedirect, "./")
return
} }
if stat, err := f.Stat(); err == nil { if name == "/" {
if stat.IsDir() { name = "."
f, err := os.Open(path.Join(p, "index.gmi")) } else {
if err != nil { name = strings.Trim(name, "/")
return nil, err
} }
f, err := fsys.Open(name)
if err != nil {
w.WriteHeader(StatusNotFound, "Not found")
return
}
defer f.Close()
stat, err := f.Stat() stat, err := f.Stat()
if err != nil { if err != nil {
return nil, err w.WriteHeader(StatusTemporaryFailure, "Temporary failure")
return
} }
if stat.Mode().IsRegular() {
return f, nil // Redirect to canonical path
if redirect {
url := r.URL.Path
if stat.IsDir() {
// Add trailing slash
if url[len(url)-1] != '/' {
w.WriteHeader(StatusPermanentRedirect, path.Base(url)+"/")
return
} }
return nil, os.ErrNotExist } else {
} else if !stat.Mode().IsRegular() { // Remove trailing slash
return nil, os.ErrNotExist if url[len(url)-1] == '/' {
w.WriteHeader(StatusPermanentRedirect, "../"+path.Base(url))
return
} }
} }
return f, nil }
if stat.IsDir() {
// Redirect if the directory name doesn't end in a slash
url := r.URL.Path
if url[len(url)-1] != '/' {
w.WriteHeader(StatusRedirect, path.Base(url)+"/")
return
}
// Use contents of index.gmi if present
index, err := fsys.Open(path.Join(name, indexPage))
if err == nil {
defer index.Close()
istat, err := index.Stat()
if err == nil {
f = index
stat = istat
}
}
}
if stat.IsDir() {
// Failed to find index file
dirList(w, f)
return
}
serveContent(ctx, w, name, f)
}
func dirList(w ResponseWriter, f fs.File) {
var entries []fs.DirEntry
var err error
d, ok := f.(fs.ReadDirFile)
if ok {
entries, err = d.ReadDir(-1)
}
if !ok || err != nil {
w.WriteHeader(StatusTemporaryFailure, "Error reading directory")
return
}
sort.Slice(entries, func(i, j int) bool {
return entries[i].Name() < entries[j].Name()
})
for _, entry := range entries {
name := entry.Name()
if entry.IsDir() {
name += "/"
}
link := LineLink{
Name: name,
URL: (&url.URL{Path: name}).EscapedPath(),
}
fmt.Fprintln(w, link.String())
}
} }

View File

@@ -11,5 +11,22 @@ var (
ErrInvalidURL = errors.New("gemini: invalid URL") ErrInvalidURL = errors.New("gemini: invalid URL")
ErrInvalidRequest = errors.New("gemini: invalid request") ErrInvalidRequest = errors.New("gemini: invalid request")
ErrInvalidResponse = errors.New("gemini: invalid response") ErrInvalidResponse = errors.New("gemini: invalid response")
ErrBodyNotAllowed = errors.New("gemini: response body not allowed")
// ErrBodyNotAllowed is returned by ResponseWriter.Write calls
// when the response status code does not permit a body.
ErrBodyNotAllowed = errors.New("gemini: response status code does not allow body")
// ErrServerClosed is returned by the Server's Serve and ListenAndServe
// methods after a call to Shutdown or Close.
ErrServerClosed = errors.New("gemini: server closed")
// ErrAbortHandler is a sentinel panic value to abort a handler.
// While any panic from ServeGemini aborts the response to the client,
// panicking with ErrAbortHandler also suppresses logging of a stack
// trace to the server's error log.
ErrAbortHandler = errors.New("gemini: abort Handler")
// ErrHandlerTimeout is returned on ResponseWriter Write calls
// in handlers which have timed out.
ErrHandlerTimeout = errors.New("gemini: Handler timeout")
) )

4
go.mod
View File

@@ -1,3 +1,5 @@
module git.sr.ht/~adnano/go-gemini module git.sr.ht/~adnano/go-gemini
go 1.15 go 1.16
require golang.org/x/net v0.0.0-20210119194325-5f4716e94777

7
go.sum Normal file
View File

@@ -0,0 +1,7 @@
golang.org/x/net v0.0.0-20210119194325-5f4716e94777 h1:003p0dJM77cxMSyCPFphvZf/Y5/NXf5fzg6ufd1/Oew=
golang.org/x/net v0.0.0-20210119194325-5f4716e94777/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg=
golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
golang.org/x/text v0.3.3 h1:cokOdA+Jmi5PJGXLlLllQSgYigAEfHXJAERHVMaCc2k=
golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=

86
handler.go Normal file
View File

@@ -0,0 +1,86 @@
package gemini
import (
"context"
"net/url"
"strings"
)
// A Handler responds to a Gemini request.
//
// ServeGemini should write the response header and data to the ResponseWriter
// and then return. Returning signals that the request is finished; it is not
// valid to use the ResponseWriter after or concurrently with the completion
// of the ServeGemini call.
//
// Handlers should not modify the provided Request.
//
// If ServeGemini panics, the server (the caller of ServeGemini) assumes that
// the effect of the panic was isolated to the active request. It recovers
// the panic, logs a stack trace to the server error log, and closes the
// network connection. To abort a handler so the client sees an interrupted
// response but the server doesn't log an error, panic with the value
// ErrAbortHandler.
type Handler interface {
ServeGemini(context.Context, ResponseWriter, *Request)
}
// The HandlerFunc type is an adapter to allow the use of ordinary functions
// as Gemini handlers. If f is a function with the appropriate signature,
// HandlerFunc(f) is a Handler that calls f.
type HandlerFunc func(context.Context, ResponseWriter, *Request)
// ServeGemini calls f(ctx, w, r).
func (f HandlerFunc) ServeGemini(ctx context.Context, w ResponseWriter, r *Request) {
f(ctx, w, r)
}
// StatusHandler returns a request handler that responds to each request
// with the provided status code and meta.
func StatusHandler(status Status, meta string) Handler {
return &statusHandler{status, meta}
}
type statusHandler struct {
status Status
meta string
}
func (h *statusHandler) ServeGemini(ctx context.Context, w ResponseWriter, r *Request) {
w.WriteHeader(h.status, h.meta)
}
// NotFoundHandler returns a simple request handler that replies to each
// request with a “51 Not found” reply.
func NotFoundHandler() Handler {
return HandlerFunc(func(ctx context.Context, w ResponseWriter, r *Request) {
w.WriteHeader(StatusNotFound, "Not found")
})
}
// StripPrefix returns a handler that serves Gemini requests by removing the
// given prefix from the request URL's Path (and RawPath if set) and invoking
// the handler h. StripPrefix handles a request for a path that doesn't begin
// with prefix by replying with a Gemini 51 not found error. The prefix must
// match exactly: if the prefix in the request contains escaped characters the
// reply is also a Gemini 51 not found error.
func StripPrefix(prefix string, h Handler) Handler {
if prefix == "" {
return h
}
return HandlerFunc(func(ctx context.Context, w ResponseWriter, r *Request) {
p := strings.TrimPrefix(r.URL.Path, prefix)
rp := strings.TrimPrefix(r.URL.RawPath, prefix)
if len(p) < len(r.URL.Path) && (r.URL.RawPath == "" || len(rp) < len(r.URL.RawPath)) {
r2 := new(Request)
*r2 = *r
r2.URL = new(url.URL)
*r2.URL = *r.URL
r2.URL.Path = p
r2.URL.RawPath = rp
h.ServeGemini(ctx, w, r2)
} else {
w.WriteHeader(StatusNotFound, "Not found")
}
})
}

208
mux.go
View File

@@ -1,6 +1,8 @@
package gemini package gemini
import ( import (
"context"
"net"
"net/url" "net/url"
"path" "path"
"sort" "sort"
@@ -8,12 +10,6 @@ import (
"sync" "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. // ServeMux is a Gemini request multiplexer.
// It matches the URL of each incoming request against a list of registered // It matches the URL of each incoming request against a list of registered
// patterns and calls the handler for the pattern that // patterns and calls the handler for the pattern that
@@ -32,6 +28,32 @@ import (
// the pattern "/" matches all paths not matched by other registered // the pattern "/" matches all paths not matched by other registered
// patterns, not just the URL with Path == "/". // patterns, not just the URL with Path == "/".
// //
// Patterns may also contain schemes and hostnames.
// Wildcard patterns can be used to match multiple hostnames (e.g. "*.example.com").
//
// The following are examples of valid patterns, along with the scheme,
// hostname, and path that they match.
//
// Pattern │ Scheme │ Hostname │ Path
// ─────────────────────────────┼────────┼──────────┼─────────────
// /file │ gemini │ * │ /file
// /directory/ │ gemini │ * │ /directory/*
// hostname/file │ gemini │ hostname │ /file
// hostname/directory/ │ gemini │ hostname │ /directory/*
// scheme://hostname/file │ scheme │ hostname │ /file
// scheme://hostname/directory/ │ scheme │ hostname │ /directory/*
// //hostname/file │ * │ hostname │ /file
// //hostname/directory/ │ * │ hostname │ /directory/*
// scheme:///file │ scheme │ * │ /file
// scheme:///directory/ │ scheme │ * │ /directory/*
// ///file │ * │ * │ /file
// ///directory/ │ * │ * │ /directory/*
//
// A pattern without a hostname will match any hostname.
// If a pattern begins with "//", it will match any scheme.
// Otherwise, a pattern with no scheme is treated as though it has a
// scheme of "gemini".
//
// If a subtree has been registered and a request is received naming the // If a subtree has been registered and a request is received naming the
// subtree root without its trailing slash, ServeMux redirects that // subtree root without its trailing slash, ServeMux redirects that
// request to the subtree root (adding the trailing slash). This behavior can // request to the subtree root (adding the trailing slash). This behavior can
@@ -45,13 +67,19 @@ import (
// to an equivalent, cleaner URL. // to an equivalent, cleaner URL.
type ServeMux struct { type ServeMux struct {
mu sync.RWMutex mu sync.RWMutex
m map[string]muxEntry m map[muxKey]Handler
es []muxEntry // slice of entries sorted from longest to shortest. es []muxEntry // slice of entries sorted from longest to shortest
}
type muxKey struct {
scheme string
host string
path string
} }
type muxEntry struct { type muxEntry struct {
r Responder handler Handler
pattern string key muxKey
} }
// cleanPath returns the canonical path for p, eliminating . and .. elements. // cleanPath returns the canonical path for p, eliminating . and .. elements.
@@ -78,18 +106,25 @@ func cleanPath(p string) string {
// Find a handler on a handler map given a path string. // Find a handler on a handler map given a path string.
// Most-specific (longest) pattern wins. // Most-specific (longest) pattern wins.
func (mux *ServeMux) match(path string) Responder { func (mux *ServeMux) match(key muxKey) Handler {
// Check for exact match first. // Check for exact match first.
v, ok := mux.m[path] if r, ok := mux.m[key]; ok {
if ok { return r
return v.r } else if r, ok := mux.m[muxKey{"", key.host, key.path}]; ok {
return r
} else if r, ok := mux.m[muxKey{key.scheme, "", key.path}]; ok {
return r
} else if r, ok := mux.m[muxKey{"", "", key.path}]; ok {
return r
} }
// Check for longest valid match. mux.es contains all patterns // Check for longest valid match. mux.es contains all patterns
// that end in / sorted from longest to shortest. // that end in / sorted from longest to shortest.
for _, e := range mux.es { for _, e := range mux.es {
if strings.HasPrefix(path, e.pattern) { if (e.key.scheme == "" || key.scheme == e.key.scheme) &&
return e.r (e.key.host == "" || key.host == e.key.host) &&
strings.HasPrefix(key.path, e.key.path) {
return e.handler
} }
} }
return nil return nil
@@ -99,89 +134,144 @@ func (mux *ServeMux) match(path string) Responder {
// This occurs when a handler for path + "/" was already registered, but // 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 // 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. // 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) { func (mux *ServeMux) redirectToPathSlash(key muxKey, u *url.URL) (*url.URL, bool) {
mux.mu.RLock() mux.mu.RLock()
shouldRedirect := mux.shouldRedirectRLocked(path) shouldRedirect := mux.shouldRedirectRLocked(key)
mux.mu.RUnlock() mux.mu.RUnlock()
if !shouldRedirect { if !shouldRedirect {
return u, false return u, false
} }
path = path + "/" return u.ResolveReference(&url.URL{Path: key.path + "/"}), true
u = &url.URL{Path: path, RawQuery: u.RawQuery}
return u, true
} }
// shouldRedirectRLocked reports whether the given path and host should be redirected to // shouldRedirectRLocked reports whether the given path and host should be redirected to
// path+"/". This should happen if a handler is registered for path+"/" but // path+"/". This should happen if a handler is registered for path+"/" but
// not path -- see comments at ServeMux. // not path -- see comments at ServeMux.
func (mux *ServeMux) shouldRedirectRLocked(path string) bool { func (mux *ServeMux) shouldRedirectRLocked(key muxKey) bool {
if _, exist := mux.m[path]; exist { if _, exist := mux.m[key]; exist {
return false return false
} }
n := len(path) n := len(key.path)
if n == 0 { if n == 0 {
return false return false
} }
if _, exist := mux.m[path+"/"]; exist { if _, exist := mux.m[muxKey{key.scheme, key.host, key.path + "/"}]; exist {
return path[n-1] != '/' return key.path[n-1] != '/'
} }
return false return false
} }
// Respond dispatches the request to the responder whose func getWildcard(hostname string) (string, bool) {
// pattern most closely matches the request URL. if net.ParseIP(hostname) == nil {
func (mux *ServeMux) Respond(w *ResponseWriter, r *Request) { split := strings.SplitN(hostname, ".", 2)
if len(split) == 2 {
return "*." + split[1], true
}
}
return "", false
}
// Handler returns the handler to use for the given request, consulting
// r.URL.Scheme, r.URL.Host, and r.URL.Path. It always returns a non-nil handler. If
// the path is not in its canonical form, the handler will be an
// internally-generated handler that redirects to the canonical path. If the
// host contains a port, it is ignored when matching handlers.
func (mux *ServeMux) Handler(r *Request) Handler {
scheme := r.URL.Scheme
host := r.URL.Hostname()
path := cleanPath(r.URL.Path) path := cleanPath(r.URL.Path)
// If the given path is /tree and its handler is not registered, // If the given path is /tree and its handler is not registered,
// redirect for /tree/. // redirect for /tree/.
if u, ok := mux.redirectToPathSlash(path, r.URL); ok { if u, ok := mux.redirectToPathSlash(muxKey{scheme, host, path}, r.URL); ok {
w.Header(StatusRedirect, u.String()) return StatusHandler(StatusPermanentRedirect, u.String())
return
} }
if path != r.URL.Path { if path != r.URL.Path {
u := *r.URL u := *r.URL
u.Path = path u.Path = path
w.Header(StatusRedirect, u.String()) return StatusHandler(StatusPermanentRedirect, u.String())
return
} }
mux.mu.RLock() mux.mu.RLock()
defer mux.mu.RUnlock() defer mux.mu.RUnlock()
resp := mux.match(path) h := mux.match(muxKey{scheme, host, path})
if resp == nil { if h == nil {
w.Status(StatusNotFound) // Try wildcard
return if wildcard, ok := getWildcard(host); ok {
h = mux.match(muxKey{scheme, wildcard, path})
} }
resp.Respond(w, r) }
if h == nil {
h = NotFoundHandler()
}
return h
} }
// Handle registers the responder for the given pattern. // ServeGemini dispatches the request to the handler whose
// If a responder already exists for pattern, Handle panics. // pattern most closely matches the request URL.
func (mux *ServeMux) Handle(pattern string, responder Responder) { func (mux *ServeMux) ServeGemini(ctx context.Context, w ResponseWriter, r *Request) {
mux.mu.Lock() h := mux.Handler(r)
defer mux.mu.Unlock() h.ServeGemini(ctx, w, r)
}
// Handle registers the handler for the given pattern.
// If a handler already exists for pattern, Handle panics.
func (mux *ServeMux) Handle(pattern string, handler Handler) {
if pattern == "" { if pattern == "" {
panic("gemini: invalid pattern") panic("gemini: invalid pattern")
} }
if responder == nil { if handler == nil {
panic("gemini: nil responder") panic("gemini: nil handler")
} }
if _, exist := mux.m[pattern]; exist {
mux.mu.Lock()
defer mux.mu.Unlock()
var key muxKey
if strings.HasPrefix(pattern, "//") {
// match any scheme
key.scheme = ""
pattern = pattern[2:]
} else {
// extract scheme
cut := strings.Index(pattern, "://")
if cut == -1 {
// default scheme of gemini
key.scheme = "gemini"
} else {
key.scheme = pattern[:cut]
pattern = pattern[cut+3:]
}
}
// extract hostname and path
cut := strings.Index(pattern, "/")
if cut == -1 {
key.host = pattern
key.path = "/"
} else {
key.host = pattern[:cut]
key.path = pattern[cut:]
}
// strip port from hostname
if hostname, _, err := net.SplitHostPort(key.host); err == nil {
key.host = hostname
}
if _, exist := mux.m[key]; exist {
panic("gemini: multiple registrations for " + pattern) panic("gemini: multiple registrations for " + pattern)
} }
if mux.m == nil { if mux.m == nil {
mux.m = make(map[string]muxEntry) mux.m = make(map[muxKey]Handler)
} }
e := muxEntry{responder, pattern} mux.m[key] = handler
mux.m[pattern] = e e := muxEntry{handler, key}
if pattern[len(pattern)-1] == '/' { if key.path[len(key.path)-1] == '/' {
mux.es = appendSorted(mux.es, e) mux.es = appendSorted(mux.es, e)
} }
} }
@@ -189,7 +279,9 @@ func (mux *ServeMux) Handle(pattern string, responder Responder) {
func appendSorted(es []muxEntry, e muxEntry) []muxEntry { func appendSorted(es []muxEntry, e muxEntry) []muxEntry {
n := len(es) n := len(es)
i := sort.Search(n, func(i int) bool { i := sort.Search(n, func(i int) bool {
return len(es[i].pattern) < len(e.pattern) return len(es[i].key.scheme) < len(e.key.scheme) ||
len(es[i].key.host) < len(es[i].key.host) ||
len(es[i].key.path) < len(e.key.path)
}) })
if i == n { if i == n {
return append(es, e) return append(es, e)
@@ -201,10 +293,10 @@ func appendSorted(es []muxEntry, e muxEntry) []muxEntry {
return es return es
} }
// HandleFunc registers the responder function for the given pattern. // HandleFunc registers the handler function for the given pattern.
func (mux *ServeMux) HandleFunc(pattern string, responder func(*ResponseWriter, *Request)) { func (mux *ServeMux) HandleFunc(pattern string, handler func(context.Context, ResponseWriter, *Request)) {
if responder == nil { if handler == nil {
panic("gemini: nil responder") panic("gemini: nil handler")
} }
mux.Handle(pattern, ResponderFunc(responder)) mux.Handle(pattern, HandlerFunc(handler))
} }

315
mux_test.go Normal file
View File

@@ -0,0 +1,315 @@
package gemini
import (
"context"
"net/url"
"testing"
)
type nopHandler struct{}
func (*nopHandler) ServeGemini(context.Context, ResponseWriter, *Request) {}
func TestServeMuxMatch(t *testing.T) {
type Match struct {
URL string
Ok bool
}
tests := []struct {
Pattern string
Matches []Match
}{
{
// scheme: gemini, hostname: *, path: /*
Pattern: "/",
Matches: []Match{
{"gemini://example.com/path", true},
{"gemini://example.com/", true},
{"gemini://example.com/path.gmi", true},
{"gemini://example.com/path/", true},
{"gemini://example.org/path", true},
{"http://example.com/path", false},
{"http://example.org/path", false},
},
},
{
// scheme: gemini, hostname: *, path: /path
Pattern: "/path",
Matches: []Match{
{"gemini://example.com/path", true},
{"gemini://example.com/", false},
{"gemini://example.com/path.gmi", false},
{"gemini://example.com/path/", false},
{"gemini://example.org/path", true},
{"http://example.com/path", false},
{"http://example.org/path", false},
},
},
{
// scheme: gemini, hostname: *, path: /subtree/*
Pattern: "/subtree/",
Matches: []Match{
{"gemini://example.com/subtree/", true},
{"gemini://example.com/subtree/nested/", true},
{"gemini://example.com/subtree/nested/file", true},
{"gemini://example.org/subtree/", true},
{"gemini://example.org/subtree/nested/", true},
{"gemini://example.org/subtree/nested/file", true},
{"gemini://example.com/subtree", false},
{"gemini://www.example.com/subtree/", true},
{"http://example.com/subtree/", false},
},
},
{
// scheme: gemini, hostname: example.com, path: /*
Pattern: "example.com",
Matches: []Match{
{"gemini://example.com/path", true},
{"gemini://example.com/", true},
{"gemini://example.com/path.gmi", true},
{"gemini://example.com/path/", true},
{"gemini://example.org/path", false},
{"http://example.com/path", false},
{"http://example.org/path", false},
},
},
{
// scheme: gemini, hostname: example.com, path: /path
Pattern: "example.com/path",
Matches: []Match{
{"gemini://example.com/path", true},
{"gemini://example.com/", false},
{"gemini://example.com/path.gmi", false},
{"gemini://example.com/path/", false},
{"gemini://example.org/path", false},
{"http://example.com/path", false},
{"http://example.org/path", false},
},
},
{
// scheme: gemini, hostname: example.com, path: /subtree/*
Pattern: "example.com/subtree/",
Matches: []Match{
{"gemini://example.com/subtree/", true},
{"gemini://example.com/subtree/nested/", true},
{"gemini://example.com/subtree/nested/file", true},
{"gemini://example.org/subtree/", false},
{"gemini://example.org/subtree/nested/", false},
{"gemini://example.org/subtree/nested/file", false},
{"gemini://example.com/subtree", false},
{"gemini://www.example.com/subtree/", false},
{"http://example.com/subtree/", false},
},
},
{
// scheme: http, hostname: example.com, path: /*
Pattern: "http://example.com",
Matches: []Match{
{"http://example.com/path", true},
{"http://example.com/", true},
{"http://example.com/path.gmi", true},
{"http://example.com/path/", true},
{"http://example.org/path", false},
{"gemini://example.com/path", false},
{"gemini://example.org/path", false},
},
},
{
// scheme: http, hostname: example.com, path: /path
Pattern: "http://example.com/path",
Matches: []Match{
{"http://example.com/path", true},
{"http://example.com/", false},
{"http://example.com/path.gmi", false},
{"http://example.com/path/", false},
{"http://example.org/path", false},
{"gemini://example.com/path", false},
{"gemini://example.org/path", false},
},
},
{
// scheme: http, hostname: example.com, path: /subtree/*
Pattern: "http://example.com/subtree/",
Matches: []Match{
{"http://example.com/subtree/", true},
{"http://example.com/subtree/nested/", true},
{"http://example.com/subtree/nested/file", true},
{"http://example.org/subtree/", false},
{"http://example.org/subtree/nested/", false},
{"http://example.org/subtree/nested/file", false},
{"http://example.com/subtree", false},
{"http://www.example.com/subtree/", false},
{"gemini://example.com/subtree/", false},
},
},
{
// scheme: *, hostname: example.com, path: /*
Pattern: "//example.com",
Matches: []Match{
{"gemini://example.com/path", true},
{"gemini://example.com/", true},
{"gemini://example.com/path.gmi", true},
{"gemini://example.com/path/", true},
{"gemini://example.org/path", false},
{"http://example.com/path", true},
{"http://example.org/path", false},
},
},
{
// scheme: *, hostname: example.com, path: /path
Pattern: "//example.com/path",
Matches: []Match{
{"gemini://example.com/path", true},
{"gemini://example.com/", false},
{"gemini://example.com/path.gmi", false},
{"gemini://example.com/path/", false},
{"gemini://example.org/path", false},
{"http://example.com/path", true},
{"http://example.org/path", false},
},
},
{
// scheme: *, hostname: example.com, path: /subtree/*
Pattern: "//example.com/subtree/",
Matches: []Match{
{"gemini://example.com/subtree/", true},
{"gemini://example.com/subtree/nested/", true},
{"gemini://example.com/subtree/nested/file", true},
{"gemini://example.org/subtree/", false},
{"gemini://example.org/subtree/nested/", false},
{"gemini://example.org/subtree/nested/file", false},
{"gemini://example.com/subtree", false},
{"gemini://www.example.com/subtree/", false},
{"http://example.com/subtree/", true},
},
},
{
// scheme: http, hostname: *, path: /*
Pattern: "http://",
Matches: []Match{
{"http://example.com/path", true},
{"http://example.com/", true},
{"http://example.com/path.gmi", true},
{"http://example.com/path/", true},
{"http://example.org/path", true},
{"gemini://example.com/path", false},
{"gemini://example.org/path", false},
},
},
{
// scheme: http, hostname: *, path: /path
Pattern: "http:///path",
Matches: []Match{
{"http://example.com/path", true},
{"http://example.com/", false},
{"http://example.com/path.gmi", false},
{"http://example.com/path/", false},
{"http://example.org/path", true},
{"gemini://example.com/path", false},
{"gemini://example.org/path", false},
},
},
{
// scheme: http, hostname: *, path: /subtree/*
Pattern: "http:///subtree/",
Matches: []Match{
{"http://example.com/subtree/", true},
{"http://example.com/subtree/nested/", true},
{"http://example.com/subtree/nested/file", true},
{"http://example.org/subtree/", true},
{"http://example.org/subtree/nested/", true},
{"http://example.org/subtree/nested/file", true},
{"http://example.com/subtree", false},
{"http://www.example.com/subtree/", true},
{"gemini://example.com/subtree/", false},
},
},
{
// scheme: *, hostname: *, path: /*
Pattern: "//",
Matches: []Match{
{"gemini://example.com/path", true},
{"gemini://example.com/", true},
{"gemini://example.com/path.gmi", true},
{"gemini://example.com/path/", true},
{"gemini://example.org/path", true},
{"http://example.com/path", true},
{"http://example.org/path", true},
},
},
{
// scheme: *, hostname: *, path: /path
Pattern: "///path",
Matches: []Match{
{"gemini://example.com/path", true},
{"gemini://example.com/", false},
{"gemini://example.com/path.gmi", false},
{"gemini://example.com/path/", false},
{"gemini://example.org/path", true},
{"http://example.com/path", true},
{"http://example.org/path", true},
},
},
{
// scheme: *, hostname: *, path: /subtree/*
Pattern: "///subtree/",
Matches: []Match{
{"gemini://example.com/subtree/", true},
{"gemini://example.com/subtree/nested/", true},
{"gemini://example.com/subtree/nested/file", true},
{"gemini://example.org/subtree/", true},
{"gemini://example.org/subtree/nested/", true},
{"gemini://example.org/subtree/nested/file", true},
{"gemini://example.com/subtree", false},
{"gemini://www.example.com/subtree/", true},
{"http://example.com/subtree/", true},
},
},
{
// scheme: gemini, hostname: *.example.com, path: /*
Pattern: "*.example.com",
Matches: []Match{
{"gemini://mail.example.com/", true},
{"gemini://www.example.com/index.gmi", true},
{"gemini://example.com/", false},
{"gemini://a.b.example.com/", false},
{"http://www.example.com/", false},
},
},
{
// scheme: http, hostname: *.example.com, path: /*
Pattern: "http://*.example.com",
Matches: []Match{
{"http://mail.example.com/", true},
{"http://www.example.com/index.gmi", true},
{"http://example.com/", false},
{"http://a.b.example.com/", false},
{"gemini://www.example.com/", false},
},
},
}
for i, test := range tests {
h := &nopHandler{}
var mux ServeMux
mux.Handle(test.Pattern, h)
for _, match := range tests[i].Matches {
u, err := url.Parse(match.URL)
if err != nil {
panic(err)
}
got := mux.Handler(&Request{URL: u})
if match.Ok {
if h != got {
t.Errorf("expected %s to match %s", test.Pattern, match.URL)
}
} else {
if h == got {
t.Errorf("expected %s not to match %s", test.Pattern, match.URL)
}
}
}
}
}

28
punycode.go Normal file
View File

@@ -0,0 +1,28 @@
package gemini
import (
"net"
"unicode/utf8"
"golang.org/x/net/idna"
)
func isASCII(s string) bool {
for i := 0; i < len(s); i++ {
if s[i] >= utf8.RuneSelf {
return false
}
}
return true
}
// punycodeHostname returns the punycoded version of hostname.
func punycodeHostname(hostname string) (string, error) {
if net.ParseIP(hostname) != nil {
return hostname, nil
}
if isASCII(hostname) {
return hostname, nil
}
return idna.Lookup.ToASCII(hostname)
}

View File

@@ -2,76 +2,76 @@ package gemini
import ( import (
"bufio" "bufio"
"context"
"crypto/tls" "crypto/tls"
"io" "io"
"net" "net"
"net/url" "net/url"
) )
// Request represents a Gemini request. // A Request represents a Gemini request received by a server or to be sent
// by a client.
//
// The field semantics differ slightly between client and server usage.
type Request struct { type Request struct {
// URL specifies the URL being requested. // URL specifies the URL being requested (for server
// requests) or the URL to access (for client requests).
URL *url.URL URL *url.URL
// For client requests, Host specifies the host on which the URL is sought. // For client requests, Host optionally specifies the server to
// Host must contain a port. // connect to. It may be of the form "host" or "host:port".
// If empty, the value of URL.Host is used.
// For international domain names, Host may be in Punycode or
// Unicode form. Use golang.org/x/net/idna to convert it to
// either format if needed.
// //
// This field is ignored by the server. // For server requests, Host specifies the host on which the URL
// is sought.
Host string Host string
// Certificate specifies the TLS certificate to use for the request. // For client requests, Certificate optionally specifies the
// // TLS certificate to present to the other side of the connection.
// On the server side, if the client provided a certificate then // This field is ignored by the Gemini server.
// Certificate.Leaf is guaranteed to be non-nil.
Certificate *tls.Certificate Certificate *tls.Certificate
// RemoteAddr allows servers and other software to record the network // RemoteAddr allows Gemini servers and other software to record
// address that sent the request. // the network address that sent the request, usually for
// // logging. This field is not filled in by ReadRequest.
// This field is ignored by the client. // This field is ignored by the Gemini client.
RemoteAddr net.Addr RemoteAddr net.Addr
// TLS allows servers and other software to record information about the TLS // TLS allows Gemini servers and other software to record
// connection on which the request was received. // information about the TLS connection on which the request
// // was received. This field is not filled in by ReadRequest.
// This field is ignored by the client. // The Gemini server in this package sets the field for
TLS tls.ConnectionState // TLS-enabled connections before invoking a handler;
// otherwise it leaves the field nil.
// Context specifies the context to use for client requests. // This field is ignored by the Gemini client.
// If Context is nil, the background context will be used. TLS *tls.ConnectionState
Context context.Context
} }
// NewRequest returns a new request. The host is inferred from the URL. // NewRequest returns a new request.
//
// The returned Request is suitable for use with Client.Do.
//
// Callers should be careful that the URL query is properly escaped.
// See the documentation for QueryEscape for more information.
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), nil return &Request{URL: u}, nil
} }
// NewRequestFromURL returns a new request for the given URL. // ReadRequest reads and parses an incoming request from r.
// The host is inferred from the URL.
// //
// Callers should be careful that the URL query is properly escaped. // ReadRequest is a low-level function and should only be used
// See the documentation for QueryEscape for more information. // for specialized applications; most code should use the Server
func NewRequestFromURL(url *url.URL) *Request { // to read requests and handle them via the Handler interface.
host := url.Host
if url.Port() == "" {
host += ":1965"
}
return &Request{
URL: url,
Host: host,
}
}
// ReadRequest reads a Gemini request from the provided io.Reader
func ReadRequest(r io.Reader) (*Request, error) { func ReadRequest(r io.Reader) (*Request, error) {
// Read URL // Read URL
br := bufio.NewReader(r) r = io.LimitReader(r, 1026)
br := bufio.NewReaderSize(r, 1026)
rawurl, err := br.ReadString('\r') rawurl, err := br.ReadString('\r')
if err != nil { if err != nil {
return nil, err return nil, err
@@ -92,25 +92,22 @@ func ReadRequest(r io.Reader) (*Request, error) {
if err != nil { if err != nil {
return nil, err return nil, err
} }
if u.User != nil {
// User is not allowed
return nil, ErrInvalidURL
}
return &Request{URL: u}, nil return &Request{URL: u}, nil
} }
// Write writes the Gemini request to the provided buffered writer. // Write writes a Gemini request in wire format.
func (r *Request) Write(w *bufio.Writer) error { // This method consults the request URL only.
func (r *Request) Write(w io.Writer) error {
bw := bufio.NewWriterSize(w, 1026)
url := r.URL.String() url := r.URL.String()
// User is invalid if len(url) > 1024 {
if r.URL.User != nil || len(url) > 1024 { return ErrInvalidRequest
return ErrInvalidURL
} }
if _, err := w.WriteString(url); err != nil { if _, err := bw.WriteString(url); err != nil {
return err return err
} }
if _, err := w.Write(crlf); err != nil { if _, err := bw.Write(crlf); err != nil {
return err return err
} }
return nil return bw.Flush()
} }

132
request_test.go Normal file
View File

@@ -0,0 +1,132 @@
package gemini
import (
"bufio"
"io"
"net/url"
"strings"
"testing"
)
// 1024 bytes
const maxURL = "gemini://example.net/xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
func TestReadRequest(t *testing.T) {
tests := []struct {
Raw string
URL *url.URL
Err error
}{
{
Raw: "gemini://example.com\r\n",
URL: &url.URL{
Scheme: "gemini",
Host: "example.com",
},
},
{
Raw: "http://example.org/path/?query#fragment\r\n",
URL: &url.URL{
Scheme: "http",
Host: "example.org",
Path: "/path/",
RawQuery: "query",
Fragment: "fragment",
},
},
{
Raw: "\r\n",
URL: &url.URL{},
},
{
Raw: "gemini://example.com\n",
Err: io.EOF,
},
{
Raw: "gemini://example.com",
Err: io.EOF,
},
{
// 1030 bytes
Raw: maxURL + "xxxxxx",
Err: io.EOF,
},
{
// 1027 bytes
Raw: maxURL + "x" + "\r\n",
Err: io.EOF,
},
{
// 1024 bytes
Raw: maxURL[:len(maxURL)-2] + "\r\n",
URL: &url.URL{
Scheme: "gemini",
Host: "example.net",
Path: maxURL[len("gemini://example.net") : len(maxURL)-2],
},
},
}
for _, test := range tests {
t.Logf("%#v", test.Raw)
req, err := ReadRequest(strings.NewReader(test.Raw))
if err != test.Err {
t.Errorf("expected err = %v, got %v", test.Err, err)
}
if req == nil && test.URL != nil {
t.Errorf("expected url = %s, got nil", test.URL)
} else if req != nil && test.URL == nil {
t.Errorf("expected req = nil, got %v", req)
} else if req != nil && *req.URL != *test.URL {
t.Errorf("expected url = %v, got %v", *test.URL, *req.URL)
}
}
}
func newRequest(rawurl string) *Request {
req, err := NewRequest(rawurl)
if err != nil {
panic(err)
}
return req
}
func TestWriteRequest(t *testing.T) {
tests := []struct {
Req *Request
Raw string
Err error
}{
{
Req: newRequest("gemini://example.com"),
Raw: "gemini://example.com\r\n",
},
{
Req: newRequest("gemini://example.com/path/?query#fragment"),
Raw: "gemini://example.com/path/?query#fragment\r\n",
},
{
Req: newRequest(maxURL),
Raw: maxURL + "\r\n",
},
{
Req: newRequest(maxURL + "x"),
Err: ErrInvalidRequest,
},
}
for _, test := range tests {
t.Logf("%s", test.Req.URL)
var b strings.Builder
bw := bufio.NewWriter(&b)
err := test.Req.Write(bw)
if err != test.Err {
t.Errorf("expected err = %v, got %v", test.Err, err)
}
bw.Flush()
got := b.String()
if got != test.Raw {
t.Errorf("expected %#v, got %#v", test.Raw, got)
}
}
}

View File

@@ -3,11 +3,19 @@ package gemini
import ( import (
"bufio" "bufio"
"crypto/tls" "crypto/tls"
"fmt"
"io" "io"
"strconv" "strconv"
) )
// Response is a Gemini response. // The default media type for responses.
const defaultMediaType = "text/gemini; charset=utf-8"
// Response represents the response from a Gemini request.
//
// The Client returns Responses from servers once the response
// header has been received. The response body is streamed on demand
// as the Body field is read.
type Response struct { type Response struct {
// Status contains the response status code. // Status contains the response status code.
Status Status Status Status
@@ -18,12 +26,21 @@ 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 for successful responses. // Body represents the response body.
//
// The response body is streamed on demand as the Body field
// is read. If the network connection fails or the server
// terminates the response, Body.Read calls return an error.
//
// The Gemini client guarantees that Body is always
// non-nil, even on responses without a body or responses with
// a zero-length body. It is the caller's responsibility to
// close Body.
Body io.ReadCloser Body io.ReadCloser
// TLS contains information about the TLS connection on which the response // TLS contains information about the TLS connection on which the
// was received. // response was received. It is nil for unencrypted responses.
TLS tls.ConnectionState TLS *tls.ConnectionState
} }
// ReadResponse reads a Gemini response from the provided io.ReadCloser. // ReadResponse reads a Gemini response from the provided io.ReadCloser.
@@ -38,16 +55,9 @@ func ReadResponse(rc io.ReadCloser) (*Response, error) {
} }
status, err := strconv.Atoi(string(statusB)) status, err := strconv.Atoi(string(statusB))
if err != nil { if err != nil {
return nil, err
}
resp.Status = Status(status)
// Disregard invalid status codes
const minStatus, maxStatus = 1, 6
statusClass := resp.Status.Class()
if statusClass < minStatus || statusClass > maxStatus {
return nil, ErrInvalidResponse return nil, ErrInvalidResponse
} }
resp.Status = Status(status)
// Read one space // Read one space
if b, err := br.ReadByte(); err != nil { if b, err := br.ReadByte(); err != nil {
@@ -67,9 +77,9 @@ func ReadResponse(rc io.ReadCloser) (*Response, error) {
if len(meta) > 1024 { if len(meta) > 1024 {
return nil, ErrInvalidResponse return nil, ErrInvalidResponse
} }
// Default mime type of text/gemini; charset=utf-8 if resp.Status.Class() == StatusSuccess && meta == "" {
if statusClass == StatusClassSuccess && meta == "" { // Use default media type
meta = "text/gemini; charset=utf-8" meta = defaultMediaType
} }
resp.Meta = meta resp.Meta = meta
@@ -80,14 +90,25 @@ func ReadResponse(rc io.ReadCloser) (*Response, error) {
return nil, ErrInvalidResponse return nil, ErrInvalidResponse
} }
if resp.Status.Class() == StatusClassSuccess { if resp.Status.Class() == StatusSuccess {
resp.Body = newReadCloserBody(br, rc) resp.Body = newReadCloserBody(br, rc)
} else { } else {
resp.Body = nopReadCloser{}
rc.Close() rc.Close()
} }
return resp, nil return resp, nil
} }
type nopReadCloser struct{}
func (nopReadCloser) Read(p []byte) (int, error) {
return 0, io.EOF
}
func (nopReadCloser) Close() error {
return nil
}
type readCloserBody struct { type readCloserBody struct {
br *bufio.Reader // used until empty br *bufio.Reader // used until empty
io.ReadCloser io.ReadCloser
@@ -115,54 +136,100 @@ func (b *readCloserBody) Read(p []byte) (n int, err error) {
return b.ReadCloser.Read(p) return b.ReadCloser.Read(p)
} }
// ResponseWriter is used to construct a Gemini response. // Write writes r to w in the Gemini response format, including the
type ResponseWriter struct { // header and body.
//
// This method consults the Status, Meta, and Body fields of the response.
// The Response Body is closed after it is sent.
func (r *Response) Write(w io.Writer) error {
if _, err := fmt.Fprintf(w, "%02d %s\r\n", r.Status, r.Meta); err != nil {
return err
}
if r.Body != nil {
defer r.Body.Close()
if _, err := io.Copy(w, r.Body); err != nil {
return err
}
}
return nil
}
// A ResponseWriter interface is used by a Gemini handler to construct
// a Gemini response.
//
// A ResponseWriter may not be used after the Handler.ServeGemini method
// has returned.
type ResponseWriter interface {
// MediaType sets the media type that will be sent by Write for a
// successful response. If no media type is set, a default of
// "text/gemini; charset=utf-8" will be used.
//
// Setting the media type after a call to Write or WriteHeader has
// no effect.
MediaType(string)
// Write writes the data to the connection as part of a Gemini response.
//
// If WriteHeader has not yet been called, Write calls WriteHeader with
// StatusSuccess and the media type set in MediaType before writing the data.
// If no media type was set, Write uses a default media type of
// "text/gemini; charset=utf-8".
Write([]byte) (int, error)
// WriteHeader sends a Gemini response header with the provided
// status code and meta.
//
// If WriteHeader is not called explicitly, the first call to Write
// will trigger an implicit call to WriteHeader with a successful
// status code and the media type set in MediaType.
//
// The provided code must be a valid Gemini status code.
// The provided meta must not be longer than 1024 bytes.
// Only one header may be written.
WriteHeader(status Status, meta string)
}
// The Flusher interface is implemented by ResponseWriters that allow a
// Gemini handler to flush buffered data to the client.
//
// The default Gemini ResponseWriter implementation supports Flusher,
// but ResponseWriter wrappers may not. Handlers should always test
// for this ability at runtime.
type Flusher interface {
// Flush sends any buffered data to the client.
Flush() error
}
type responseWriter struct {
b *bufio.Writer b *bufio.Writer
status Status mediatype string
meta string
setHeader bool
wroteHeader bool wroteHeader bool
bodyAllowed bool bodyAllowed bool
} }
// NewResponseWriter returns a ResponseWriter that uses the provided io.Writer. // NewResponseWriter returns a ResponseWriter that uses the provided io.Writer.
func NewResponseWriter(w io.Writer) *ResponseWriter { func NewResponseWriter(w io.Writer) ResponseWriter {
return &ResponseWriter{ return newResponseWriter(w)
}
func newResponseWriter(w io.Writer) *responseWriter {
return &responseWriter{
b: bufio.NewWriter(w), b: bufio.NewWriter(w),
} }
} }
// Header sets the response header. func (w *responseWriter) MediaType(mediatype string) {
func (w *ResponseWriter) Header(status Status, meta string) { w.mediatype = mediatype
w.status = status
w.meta = meta
} }
// Status sets the response status code. func (w *responseWriter) Write(b []byte) (int, error) {
// It also sets the response meta to status.Meta().
func (w *ResponseWriter) Status(status Status) {
w.status = status
w.meta = status.Meta()
}
// Meta sets the response meta.
//
// For successful responses, meta should contain the media type of the response.
// For failure responses, meta should contain a short description of the failure.
// The response meta should not be greater than 1024 bytes.
func (w *ResponseWriter) Meta(meta string) {
w.meta = meta
}
// Write writes data to the connection as part of the response body.
// If the response status does not allow for a response body, Write returns
// ErrBodyNotAllowed.
//
// Write writes the response header if it has not already been written.
// It writes a successful status code if one is not set.
func (w *ResponseWriter) Write(b []byte) (int, error) {
if !w.wroteHeader { if !w.wroteHeader {
w.writeHeader(StatusSuccess) meta := w.mediatype
if meta == "" {
// Use default media type
meta = defaultMediaType
}
w.WriteHeader(StatusSuccess, meta)
} }
if !w.bodyAllowed { if !w.bodyAllowed {
return 0, ErrBodyNotAllowed return 0, ErrBodyNotAllowed
@@ -170,19 +237,13 @@ func (w *ResponseWriter) Write(b []byte) (int, error) {
return w.b.Write(b) return w.b.Write(b)
} }
func (w *ResponseWriter) writeHeader(defaultStatus Status) { func (w *responseWriter) WriteHeader(status Status, meta string) {
status := w.status if w.wroteHeader {
if status == 0 { return
status = defaultStatus
} }
meta := w.meta if status.Class() == StatusSuccess {
if status.Class() == StatusClassSuccess {
w.bodyAllowed = true w.bodyAllowed = true
if meta == "" {
meta = "text/gemini"
}
} }
w.b.WriteString(strconv.Itoa(int(status))) w.b.WriteString(strconv.Itoa(int(status)))
@@ -192,13 +253,9 @@ func (w *ResponseWriter) writeHeader(defaultStatus Status) {
w.wroteHeader = true w.wroteHeader = true
} }
// Flush writes any buffered data to the underlying io.Writer. func (w *responseWriter) Flush() error {
//
// Flush writes the response header if it has not already been written.
// It writes a failure status code if one is not set.
func (w *ResponseWriter) Flush() error {
if !w.wroteHeader { if !w.wroteHeader {
w.writeHeader(StatusTemporaryFailure) w.WriteHeader(StatusTemporaryFailure, "Temporary failure")
} }
// Write errors from writeHeader will be returned here. // Write errors from writeHeader will be returned here.
return w.b.Flush() return w.b.Flush()

127
response_test.go Normal file
View File

@@ -0,0 +1,127 @@
package gemini
import (
"io"
"strings"
"testing"
)
func TestReadWriteResponse(t *testing.T) {
tests := []struct {
Raw string
Status Status
Meta string
Body string
Err error
SkipWrite bool
}{
{
Raw: "20 text/gemini\r\nHello, world!\nWelcome to my capsule.",
Status: 20,
Meta: "text/gemini",
Body: "Hello, world!\nWelcome to my capsule.",
},
{
Raw: "10 Search query\r\n",
Status: 10,
Meta: "Search query",
},
{
Raw: "30 /redirect\r\n",
Status: 30,
Meta: "/redirect",
},
{
Raw: "31 /redirect\r\nThis body is ignored.",
Status: 31,
Meta: "/redirect",
SkipWrite: true, // skip write test since result won't match Raw
},
{
Raw: "99 Unknown status code\r\n",
Status: 99,
Meta: "Unknown status code",
},
{
Raw: "\r\n",
Err: ErrInvalidResponse,
},
{
Raw: "\n",
Err: ErrInvalidResponse,
},
{
Raw: "1 Bad response\r\n",
Err: ErrInvalidResponse,
},
{
Raw: "",
Err: io.EOF,
},
{
Raw: "10 Search query",
Err: io.EOF,
},
{
Raw: "20 text/gemini\nHello, world!",
Err: io.EOF,
},
{
Raw: "20 text/gemini\rHello, world!",
Err: ErrInvalidResponse,
},
{
Raw: "20 text/gemini\r",
Err: io.EOF,
},
{
Raw: "abcdefghijklmnopqrstuvwxyz",
Err: ErrInvalidResponse,
},
}
for _, test := range tests {
t.Logf("%#v", test.Raw)
resp, err := ReadResponse(io.NopCloser(strings.NewReader(test.Raw)))
if err != test.Err {
t.Errorf("expected err = %v, got %v", test.Err, err)
}
if test.Err != nil {
// No response
continue
}
if resp.Status != test.Status {
t.Errorf("expected status = %d, got %d", test.Status, resp.Status)
}
if resp.Meta != test.Meta {
t.Errorf("expected meta = %s, got %s", test.Meta, resp.Meta)
}
b, _ := io.ReadAll(resp.Body)
body := string(b)
if body != test.Body {
t.Errorf("expected body = %#v, got %#v", test.Body, body)
}
}
for _, test := range tests {
if test.Err != nil || test.SkipWrite {
continue
}
resp := &Response{
Status: test.Status,
Meta: test.Meta,
Body: io.NopCloser(strings.NewReader(test.Body)),
}
var b strings.Builder
if err := resp.Write(&b); err != nil {
t.Error(err)
continue
}
got := b.String()
if got != test.Raw {
t.Errorf("expected %#v, got %#v", test.Raw, got)
}
}
}

410
server.go
View File

@@ -1,117 +1,249 @@
package gemini package gemini
import ( import (
"context"
"crypto/tls" "crypto/tls"
"errors" "errors"
"log" "log"
"net" "net"
"strings" "runtime"
"sync"
"sync/atomic"
"time" "time"
"git.sr.ht/~adnano/go-gemini/certificate"
) )
// Server is a Gemini server. // A Server defines parameters for running a Gemini server. The zero value for
// Server is a valid configuration.
type Server struct { type Server struct {
// Addr specifies the address that the server should listen on. // Addr optionally specifies the TCP address for the server to listen on,
// If Addr is empty, the server will listen on the address ":1965". // in the form "host:port". If empty, ":1965" (port 1965) is used.
// See net.Dial for details of the address format.
Addr string Addr string
// ReadTimeout is the maximum duration for reading a request. // The Handler to invoke.
Handler Handler
// ReadTimeout is the maximum duration for reading the entire
// request.
//
// A ReadTimeout of zero means no timeout.
ReadTimeout time.Duration ReadTimeout time.Duration
// WriteTimeout is the maximum duration before timing out // WriteTimeout is the maximum duration before timing out
// writes of the response. // writes of the response.
//
// A WriteTimeout of zero means no timeout.
WriteTimeout time.Duration WriteTimeout time.Duration
// Certificates contains the certificates used by the server. // GetCertificate returns a TLS certificate based on the given
Certificates certificate.Dir // hostname.
//
// If GetCertificate is nil or returns nil, then no certificate
// will be used and the connection will be aborted.
GetCertificate func(hostname string) (*tls.Certificate, error)
// CreateCertificate, if not nil, will be called to create a new certificate // ErrorLog specifies an optional logger for errors accepting connections,
// if the current one is expired or missing. // unexpected behavior from handlers, and underlying file system errors.
CreateCertificate func(hostname string) (tls.Certificate, error)
// ErrorLog specifies an optional logger for errors accepting connections
// and file system errors.
// If nil, logging is done via the log package's standard logger. // If nil, logging is done via the log package's standard logger.
ErrorLog *log.Logger ErrorLog *log.Logger
// registered responders listeners map[*net.Listener]context.CancelFunc
responders map[responderKey]Responder conns map[*net.Conn]context.CancelFunc
hosts map[string]bool doneChan chan struct{}
closed int32
mu sync.Mutex
} }
type responderKey struct { // done returns a channel that's closed when the server has finished closing.
scheme string func (srv *Server) done() chan struct{} {
hostname string srv.mu.Lock()
defer srv.mu.Unlock()
return srv.doneLocked()
} }
// Handle registers a responder for the given pattern. func (srv *Server) doneLocked() chan struct{} {
if srv.doneChan == nil {
srv.doneChan = make(chan struct{})
}
return srv.doneChan
}
// tryFinishShutdown closes srv.done() if there are no active listeners or requests.
func (srv *Server) tryFinishShutdown() {
srv.mu.Lock()
defer srv.mu.Unlock()
if len(srv.listeners) == 0 && len(srv.conns) == 0 {
done := srv.doneLocked()
select {
case <-done:
default:
close(done)
}
}
}
// Close immediately closes all active net.Listeners and connections.
// For a graceful shutdown, use Shutdown.
func (srv *Server) Close() error {
if !atomic.CompareAndSwapInt32(&srv.closed, 0, 1) {
return ErrServerClosed
}
// Close active listeners and connections.
srv.mu.Lock()
for _, cancel := range srv.listeners {
cancel()
}
for _, cancel := range srv.conns {
cancel()
}
srv.mu.Unlock()
select {
case <-srv.done():
return nil
}
}
// Shutdown gracefully shuts down the server without interrupting any
// active connections. Shutdown works by first closing all open
// listeners and then waiting indefinitely for connections
// to close and then shut down.
// If the provided context expires before the shutdown is complete,
// Shutdown returns the context's error.
// //
// The pattern must be in the form of "hostname" or "scheme://hostname". // When Shutdown is called, Serve and ListenAndServer immediately
// If no scheme is specified, a scheme of "gemini://" is implied. // return ErrServerClosed. Make sure the program doesn't exit and
// Wildcard patterns are supported (e.g. "*.example.com"). // waits instead for Shutdown to return.
func (s *Server) Handle(pattern string, responder Responder) { //
if pattern == "" { // Once Shutdown has been called on a server, it may not be reused;
panic("gemini: invalid pattern") // future calls to methods such as Serve will return ErrServerClosed.
} func (srv *Server) Shutdown(ctx context.Context) error {
if responder == nil { if !atomic.CompareAndSwapInt32(&srv.closed, 0, 1) {
panic("gemini: nil responder") return ErrServerClosed
}
if s.responders == nil {
s.responders = map[responderKey]Responder{}
s.hosts = map[string]bool{}
} }
split := strings.SplitN(pattern, "://", 2) // Close active listeners.
var key responderKey srv.mu.Lock()
if len(split) == 2 { for _, cancel := range srv.listeners {
key.scheme = split[0] cancel()
key.hostname = split[1]
} else {
key.scheme = "gemini"
key.hostname = split[0]
} }
srv.mu.Unlock()
if _, ok := s.responders[key]; ok { // Wait for active connections to finish.
panic("gemini: multiple registrations for " + pattern) select {
case <-ctx.Done():
return ctx.Err()
case <-srv.done():
return nil
} }
s.responders[key] = responder
s.hosts[key.hostname] = true
}
// HandleFunc registers a responder function for the given pattern.
func (s *Server) HandleFunc(pattern string, responder func(*ResponseWriter, *Request)) {
s.Handle(pattern, ResponderFunc(responder))
} }
// ListenAndServe listens for requests at the server's configured address. // ListenAndServe listens for requests at the server's configured address.
func (s *Server) ListenAndServe() error { // ListenAndServe listens on the TCP network address srv.Addr and then calls
addr := s.Addr // Serve to handle requests on incoming connections.
//
// If srv.Addr is blank, ":1965" is used.
//
// ListenAndServe always returns a non-nil error. After Shutdown or Close, the
// returned error is ErrServerClosed.
func (srv *Server) ListenAndServe(ctx context.Context) error {
if atomic.LoadInt32(&srv.closed) == 1 {
return ErrServerClosed
}
addr := srv.Addr
if addr == "" { if addr == "" {
addr = ":1965" addr = ":1965"
} }
ln, err := net.Listen("tcp", addr) l, err := net.Listen("tcp", addr)
if err != nil { if err != nil {
return err return err
} }
defer ln.Close()
return s.Serve(tls.NewListener(ln, &tls.Config{ l = tls.NewListener(l, &tls.Config{
ClientAuth: tls.RequestClientCert, ClientAuth: tls.RequestClientCert,
MinVersion: tls.VersionTLS12, MinVersion: tls.VersionTLS12,
GetCertificate: s.getCertificate, GetCertificate: srv.getCertificate,
})) })
return srv.Serve(ctx, l)
} }
// Serve listens for requests on the provided listener. func (srv *Server) getCertificate(h *tls.ClientHelloInfo) (*tls.Certificate, error) {
func (s *Server) Serve(l net.Listener) error { if srv.GetCertificate == nil {
var tempDelay time.Duration // how long to sleep on accept failure return nil, errors.New("gemini: GetCertificate is nil")
}
return srv.GetCertificate(h.ServerName)
}
func (srv *Server) trackListener(l *net.Listener, cancel context.CancelFunc) {
srv.mu.Lock()
defer srv.mu.Unlock()
if srv.listeners == nil {
srv.listeners = make(map[*net.Listener]context.CancelFunc)
}
srv.listeners[l] = cancel
}
func (srv *Server) deleteListener(l *net.Listener) {
srv.mu.Lock()
defer srv.mu.Unlock()
delete(srv.listeners, l)
}
// Serve accepts incoming connections on the Listener l, creating a new
// service goroutine for each. The service goroutines read requests and
// then calls the appropriate Handler to reply to them.
//
// Serve always returns a non-nil error and closes l. After Shutdown or Close,
// the returned error is ErrServerClosed.
func (srv *Server) Serve(ctx context.Context, l net.Listener) error {
defer l.Close()
if atomic.LoadInt32(&srv.closed) == 1 {
return ErrServerClosed
}
lnctx, cancel := context.WithCancel(ctx)
defer cancel()
srv.trackListener(&l, cancel)
defer srv.tryFinishShutdown()
defer srv.deleteListener(&l)
errch := make(chan error, 1)
go func() {
errch <- srv.serve(ctx, l)
}()
select {
case <-lnctx.Done():
if atomic.LoadInt32(&srv.closed) == 1 {
return ErrServerClosed
}
return lnctx.Err()
case err := <-errch:
return err
}
}
func (srv *Server) serve(ctx context.Context, l net.Listener) error {
// how long to sleep on accept failure
var tempDelay time.Duration
for { for {
rw, err := l.Accept() rw, err := l.Accept()
if err != nil { if err != nil {
select {
case <-ctx.Done():
if atomic.LoadInt32(&srv.closed) == 1 {
return ErrServerClosed
}
return ctx.Err()
default:
}
// If this is a temporary error, sleep // If this is a temporary error, sleep
if ne, ok := err.(net.Error); ok && ne.Temporary() { if ne, ok := err.(net.Error); ok && ne.Temporary() {
if tempDelay == 0 { if tempDelay == 0 {
@@ -122,127 +254,111 @@ func (s *Server) Serve(l net.Listener) error {
if max := 1 * time.Second; tempDelay > max { if max := 1 * time.Second; tempDelay > max {
tempDelay = max tempDelay = max
} }
s.logf("gemini: Accept error: %v; retrying in %v", err, tempDelay) srv.logf("gemini: Accept error: %v; retrying in %v", err, tempDelay)
time.Sleep(tempDelay) time.Sleep(tempDelay)
continue continue
} }
// Otherwise, return the error
return err return err
} }
tempDelay = 0 tempDelay = 0
go s.respond(rw) go srv.serveConn(ctx, rw)
} }
} }
func (s *Server) getCertificate(h *tls.ClientHelloInfo) (*tls.Certificate, error) { func (srv *Server) trackConn(conn *net.Conn, cancel context.CancelFunc) {
cert, err := s.getCertificateFor(h.ServerName) srv.mu.Lock()
if err != nil { defer srv.mu.Unlock()
// Try wildcard if srv.conns == nil {
wildcard := strings.SplitN(h.ServerName, ".", 2) srv.conns = make(map[*net.Conn]context.CancelFunc)
if len(wildcard) == 2 {
cert, err = s.getCertificateFor("*." + wildcard[1])
} }
} srv.conns[conn] = cancel
return cert, err
} }
func (s *Server) getCertificateFor(hostname string) (*tls.Certificate, error) { func (srv *Server) deleteConn(conn *net.Conn) {
if _, ok := s.hosts[hostname]; !ok { srv.mu.Lock()
return nil, errors.New("hostname not registered") defer srv.mu.Unlock()
} delete(srv.conns, conn)
// Generate a new certificate if it is missing or expired
cert, ok := s.Certificates.Lookup(hostname)
if !ok || cert.Leaf != nil && cert.Leaf.NotAfter.Before(time.Now()) {
if s.CreateCertificate != nil {
cert, err := s.CreateCertificate(hostname)
if err == nil {
if err := s.Certificates.Add(hostname, cert); err != nil {
s.logf("gemini: Failed to write new certificate for %s: %s", hostname, err)
}
}
return &cert, err
}
return nil, errors.New("no certificate")
}
return &cert, nil
} }
// respond responds to a connection. // serveConn serves a Gemini response over the provided connection.
func (s *Server) respond(conn net.Conn) { // It closes the connection when the response has been completed.
func (srv *Server) serveConn(ctx context.Context, conn net.Conn) {
defer conn.Close() defer conn.Close()
if d := s.ReadTimeout; d != 0 {
_ = conn.SetReadDeadline(time.Now().Add(d)) if atomic.LoadInt32(&srv.closed) == 1 {
} return
if d := s.WriteTimeout; d != 0 {
_ = conn.SetWriteDeadline(time.Now().Add(d))
} }
w := NewResponseWriter(conn) ctx, cancel := context.WithCancel(ctx)
defer cancel()
srv.trackConn(&conn, cancel)
defer srv.tryFinishShutdown()
defer srv.deleteConn(&conn)
defer func() { defer func() {
_ = w.Flush() if err := recover(); err != nil && err != ErrAbortHandler {
const size = 64 << 10
buf := make([]byte, size)
buf = buf[:runtime.Stack(buf, false)]
srv.logf("gemini: panic serving %v: %v\n%s", conn.RemoteAddr(), err, buf)
}
}() }()
if d := srv.ReadTimeout; d != 0 {
conn.SetReadDeadline(time.Now().Add(d))
}
if d := srv.WriteTimeout; d != 0 {
conn.SetWriteDeadline(time.Now().Add(d))
}
done := make(chan struct{})
go func() {
srv.respond(ctx, conn)
close(done)
}()
select {
case <-ctx.Done():
case <-done:
}
}
func (srv *Server) respond(ctx context.Context, conn net.Conn) {
w := newResponseWriter(conn)
defer w.Flush()
req, err := ReadRequest(conn) req, err := ReadRequest(conn)
if err != nil { if err != nil {
w.Status(StatusBadRequest) w.WriteHeader(StatusBadRequest, "Bad request")
return return
} }
// Store information about the TLS connection // Store the TLS connection state
if tlsConn, ok := conn.(*tls.Conn); ok { if tlsConn, ok := conn.(*tls.Conn); ok {
req.TLS = tlsConn.ConnectionState() state := tlsConn.ConnectionState()
if len(req.TLS.PeerCertificates) > 0 { req.TLS = &state
peerCert := req.TLS.PeerCertificates[0] req.Host = state.ServerName
// Store the TLS certificate
req.Certificate = &tls.Certificate{
Certificate: [][]byte{peerCert.Raw},
Leaf: peerCert,
}
}
} }
resp := s.responder(req) // Store remote address
if resp == nil { req.RemoteAddr = conn.RemoteAddr()
w.Status(StatusNotFound)
h := srv.Handler
if h == nil {
w.WriteHeader(StatusNotFound, "Not found")
return return
} }
resp.Respond(w, req) h.ServeGemini(ctx, w, req)
} }
func (s *Server) responder(r *Request) Responder { func (srv *Server) logf(format string, args ...interface{}) {
if h, ok := s.responders[responderKey{r.URL.Scheme, r.URL.Hostname()}]; ok { if srv.ErrorLog != nil {
return h srv.ErrorLog.Printf(format, args...)
}
wildcard := strings.SplitN(r.URL.Hostname(), ".", 2)
if len(wildcard) == 2 {
if h, ok := s.responders[responderKey{r.URL.Scheme, "*." + wildcard[1]}]; ok {
return h
}
}
return nil
}
func (s *Server) logf(format string, args ...interface{}) {
if s.ErrorLog != nil {
s.ErrorLog.Printf(format, args...)
} else { } else {
log.Printf(format, args...) log.Printf(format, args...)
} }
} }
// A Responder responds to a Gemini request.
type Responder interface {
// Respond accepts a Request and constructs a Response.
Respond(*ResponseWriter, *Request)
}
// ResponderFunc is a wrapper around a bare function that implements Responder.
type ResponderFunc func(*ResponseWriter, *Request)
func (f ResponderFunc) Respond(w *ResponseWriter, r *Request) {
f(w, r)
}

View File

@@ -1,8 +1,9 @@
package gemini package gemini
// Status codes. // Status represents a Gemini status code.
type Status int type Status int
// Gemini status codes.
const ( const (
StatusInput Status = 10 StatusInput Status = 10
StatusSensitiveInput Status = 11 StatusSensitiveInput Status = 11
@@ -24,28 +25,26 @@ const (
StatusCertificateNotValid Status = 62 StatusCertificateNotValid Status = 62
) )
// Status code categories. // Class returns the status class for the status code.
type StatusClass int // 1x becomes 10, 2x becomes 20, and so on.
func (s Status) Class() Status {
const ( return (s / 10) * 10
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)
} }
// Meta returns a description of the status code appropriate for use in a response. // String returns a text for the status code.
// // It returns the empty string if the status code is unknown.
// Meta returns an empty string for input, success, and redirect status codes. func (s Status) String() string {
func (s Status) Meta() string {
switch s { 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: case StatusTemporaryFailure:
return "Temporary failure" return "Temporary failure"
case StatusServerUnavailable: case StatusServerUnavailable:

110
timeout.go Normal file
View File

@@ -0,0 +1,110 @@
package gemini
import (
"bytes"
"context"
"sync"
"time"
)
// TimeoutHandler returns a Handler that runs h with the given time limit.
//
// The new Handler calls h.ServeGemini to handle each request, but
// if a call runs for longer than its time limit, the handler responds with a
// 40 Temporary Failure error. After such a timeout, writes by h to its
// ResponseWriter will return ErrHandlerTimeout.
//
// TimeoutHandler does not support the Hijacker or Flusher interfaces.
func TimeoutHandler(h Handler, dt time.Duration) Handler {
return &timeoutHandler{
h: h,
dt: dt,
}
}
type timeoutHandler struct {
h Handler
dt time.Duration
}
func (t *timeoutHandler) ServeGemini(ctx context.Context, w ResponseWriter, r *Request) {
ctx, cancel := context.WithTimeout(ctx, t.dt)
defer cancel()
done := make(chan struct{})
tw := &timeoutWriter{}
panicChan := make(chan interface{}, 1)
go func() {
defer func() {
if p := recover(); p != nil {
panicChan <- p
}
}()
t.h.ServeGemini(ctx, tw, r)
close(done)
}()
select {
case p := <-panicChan:
panic(p)
case <-done:
tw.mu.Lock()
defer tw.mu.Unlock()
if !tw.wroteHeader {
tw.status = StatusSuccess
}
w.WriteHeader(tw.status, tw.meta)
w.Write(tw.b.Bytes())
case <-ctx.Done():
tw.mu.Lock()
defer tw.mu.Unlock()
w.WriteHeader(StatusTemporaryFailure, "Timeout")
tw.timedOut = true
}
}
type timeoutWriter struct {
mu sync.Mutex
b bytes.Buffer
status Status
meta string
mediatype string
wroteHeader bool
timedOut bool
}
func (w *timeoutWriter) MediaType(mediatype string) {
w.mu.Lock()
defer w.mu.Unlock()
w.mediatype = mediatype
}
func (w *timeoutWriter) Write(b []byte) (int, error) {
w.mu.Lock()
defer w.mu.Unlock()
if w.timedOut {
return 0, ErrHandlerTimeout
}
if !w.wroteHeader {
w.writeHeaderLocked(StatusSuccess, w.mediatype)
}
return w.b.Write(b)
}
func (w *timeoutWriter) WriteHeader(status Status, meta string) {
w.mu.Lock()
defer w.mu.Unlock()
if w.timedOut {
return
}
w.writeHeaderLocked(status, meta)
}
func (w *timeoutWriter) writeHeaderLocked(status Status, meta string) {
if w.wroteHeader {
return
}
w.status = status
w.meta = meta
w.wroteHeader = true
}

View File

@@ -27,7 +27,7 @@ type KnownHosts struct {
} }
// Add adds a host to the list of known hosts. // Add adds a host to the list of known hosts.
func (k *KnownHosts) Add(h Host) error { func (k *KnownHosts) Add(h Host) {
k.mu.Lock() k.mu.Lock()
defer k.mu.Unlock() defer k.mu.Unlock()
if k.hosts == nil { if k.hosts == nil {
@@ -35,7 +35,6 @@ func (k *KnownHosts) Add(h Host) error {
} }
k.hosts[h.Hostname] = h k.hosts[h.Hostname] = h
return nil
} }
// Lookup returns the known host entry corresponding to the given hostname. // Lookup returns the known host entry corresponding to the given hostname.
@@ -144,7 +143,7 @@ func (k *KnownHosts) Parse(r io.Reader) error {
// TOFU implements basic trust on first use. // TOFU implements basic trust on first use.
// //
// If the host is not on file, it is added to the list. // If the host is not on file, it is added to the list.
// If the host on file is expired, it is replaced with the provided host. // If the host on file is expired, a new entry is added to the list.
// If the fingerprint does not match the one on file, an error is returned. // If the fingerprint does not match the one on file, an error is returned.
func (k *KnownHosts) TOFU(hostname string, cert *x509.Certificate) error { func (k *KnownHosts) TOFU(hostname string, cert *x509.Certificate) error {
host := NewHost(hostname, cert.Raw, cert.NotAfter) host := NewHost(hostname, cert.Raw, cert.NotAfter)
@@ -181,9 +180,9 @@ func NewHostWriter(w io.WriteCloser) *HostWriter {
} }
} }
// NewHostsFile returns a new host writer that appends to the file at the given path. // OpenHostsFile returns a new host writer that appends to the file at the given path.
// The file is created if it does not exist. // The file is created if it does not exist.
func NewHostsFile(path string) (*HostWriter, error) { func OpenHostsFile(path string) (*HostWriter, error) {
f, err := os.OpenFile(path, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644) f, err := os.OpenFile(path, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
if err != nil { if err != nil {
return nil, err return nil, err
@@ -212,6 +211,83 @@ func (h *HostWriter) Close() error {
return h.cl.Close() return h.cl.Close()
} }
// PersistentHosts represents a persistent set of known hosts.
type PersistentHosts struct {
hosts *KnownHosts
writer *HostWriter
}
// NewPersistentHosts returns a new persistent set of known hosts.
func NewPersistentHosts(hosts *KnownHosts, writer *HostWriter) *PersistentHosts {
return &PersistentHosts{
hosts,
writer,
}
}
// LoadPersistentHosts loads persistent hosts from the file at the given path.
func LoadPersistentHosts(path string) (*PersistentHosts, error) {
hosts := &KnownHosts{}
if err := hosts.Load(path); err != nil {
return nil, err
}
writer, err := OpenHostsFile(path)
if err != nil {
return nil, err
}
return &PersistentHosts{
hosts,
writer,
}, nil
}
// Add adds a host to the list of known hosts.
// It returns an error if the host could not be persisted.
func (p *PersistentHosts) Add(h Host) error {
err := p.writer.WriteHost(h)
if err != nil {
return fmt.Errorf("failed to persist host: %w", err)
}
p.hosts.Add(h)
return nil
}
// Lookup returns the known host entry corresponding to the given hostname.
func (p *PersistentHosts) Lookup(hostname string) (Host, bool) {
return p.hosts.Lookup(hostname)
}
// Entries returns the known host entries sorted by hostname.
func (p *PersistentHosts) Entries() []Host {
return p.hosts.Entries()
}
// TOFU implements trust on first use with a persistent set of known hosts.
//
// If the host is not on file, it is added to the list.
// If the host on file is expired, a new entry is added to the list.
// If the fingerprint does not match the one on file, an error is returned.
func (p *PersistentHosts) TOFU(hostname string, cert *x509.Certificate) error {
host := NewHost(hostname, cert.Raw, cert.NotAfter)
knownHost, ok := p.Lookup(hostname)
if !ok || time.Now().After(knownHost.Expires) {
return p.Add(host)
}
// Check fingerprint
if !bytes.Equal(knownHost.Fingerprint, host.Fingerprint) {
return fmt.Errorf("fingerprint for %q does not match", hostname)
}
return nil
}
// Close closes the underlying HostWriter.
func (p *PersistentHosts) Close() error {
return p.writer.Close()
}
// Host represents a host entry with a fingerprint using a certain algorithm. // Host represents a host entry with a fingerprint using a certain algorithm.
type Host struct { type Host struct {
Hostname string // hostname Hostname string // hostname
@@ -259,8 +335,7 @@ func (h *Host) UnmarshalText(text []byte) error {
parts := bytes.Split(text, []byte(" ")) parts := bytes.Split(text, []byte(" "))
if len(parts) != 4 { if len(parts) != 4 {
return fmt.Errorf( return fmt.Errorf("expected the format %q", format)
"expected the format %q", format)
} }
if len(parts[0]) == 0 { if len(parts[0]) == 0 {
@@ -271,8 +346,7 @@ func (h *Host) UnmarshalText(text []byte) error {
algorithm := string(parts[1]) algorithm := string(parts[1])
if algorithm != "SHA-512" { if algorithm != "SHA-512" {
return fmt.Errorf( return fmt.Errorf("unsupported algorithm %q", algorithm)
"unsupported algorithm %q", algorithm)
} }
h.Algorithm = algorithm h.Algorithm = algorithm
@@ -298,8 +372,7 @@ func (h *Host) UnmarshalText(text []byte) error {
unix, err := strconv.ParseInt(string(parts[3]), 10, 0) unix, err := strconv.ParseInt(string(parts[3]), 10, 0)
if err != nil { if err != nil {
return fmt.Errorf( return fmt.Errorf("invalid unix timestamp: %w", err)
"invalid unix timestamp: %w", err)
} }
h.Expires = time.Unix(unix, 0) h.Expires = time.Unix(unix, 0)