48 Commits

Author SHA1 Message Date
Adnan Maolood
f6b0443a62 Update KnownHosts documentation 2020-11-09 13:57:30 -05:00
Adnan Maolood
3dee6dcff3 Add (*CertificateStore).Write function 2020-11-09 13:54:15 -05:00
Adnan Maolood
85f8e84bd5 Rename (*ResponseWriter).SetMimetype to SetMediaType 2020-11-09 13:44:42 -05:00
Adnan Maolood
9338681256 Add (*KnownHosts).SetOutput function 2020-11-09 12:26:08 -05:00
Adnan Maolood
f2a1510375 Move documentation to gemini.go 2020-11-09 12:07:49 -05:00
Adnan Maolood
46cbcfcaa4 Remove top-level Get and Do functions 2020-11-09 12:04:53 -05:00
Adnan Maolood
76dfe257f1 Remove (*KnownHosts).LoadDefault function 2020-11-09 09:28:44 -05:00
Adnan Maolood
5332dc6280 Don't guarantee that (*Response).Body is always non-nil 2020-11-08 18:38:08 -05:00
Adnan Maolood
6b3cf1314b Fix relative redirects 2020-11-07 23:43:07 -05:00
Adnan Maolood
fe92db1e9c Allow redirects to non-gemini schemes 2020-11-06 11:18:58 -05:00
Adnan Maolood
ff6c95930b Fix TOFU 2020-11-05 22:30:13 -05:00
Adnan Maolood
a5712c7705 Don't check if certificate is expired 2020-11-05 18:35:25 -05:00
Adnan Maolood
520d0a7fb1 Don't redirect by default 2020-11-05 15:44:01 -05:00
Adnan Maolood
bf185e4091 update examples/cert.go 2020-11-05 15:38:41 -05:00
Adnan Maolood
8101fbe473 Update examples/auth.go 2020-11-05 15:37:46 -05:00
Adnan Maolood
b76080c863 Refactor KnownHosts 2020-11-05 15:27:12 -05:00
Adnan Maolood
53390dad6b Document CertificateOptions 2020-11-05 00:04:58 -05:00
Adnan Maolood
cec1f118fb Remove some unnecessary errors 2020-11-04 23:46:05 -05:00
Adnan Maolood
95716296b4 Use ECDSA keys by default 2020-11-03 19:43:04 -05:00
Adnan Maolood
1490bf6a75 Update examples/auth.go 2020-11-03 16:29:39 -05:00
Adnan Maolood
610c6fc533 Add ErrorLog field to Server 2020-11-03 16:11:31 -05:00
Adnan Maolood
01670647d2 Add Subject option in CertificateOptions 2020-11-02 23:11:46 -05:00
Adnan Maolood
5b3194695f Store request certificate to prevent infinite loop 2020-11-02 13:47:07 -05:00
Adnan Maolood
b6475aa7d9 server: Populate (*Request).Certificate field 2020-11-01 16:25:59 -05:00
Adnan Maolood
cc372e8768 Prevent infinite loop in client requests 2020-11-01 15:14:56 -05:00
adnano
8e442146c3 Update examples/auth.go 2020-11-01 14:47:26 -05:00
adnano
e4dea6f2c8 Refactor Certificate and Input functions 2020-11-01 14:35:03 -05:00
adnano
b57ea57fec Don't expose DefaultClient 2020-11-01 14:27:49 -05:00
adnano
c3fc9a4e9f examples: Tweak client and server timeouts 2020-11-01 14:20:24 -05:00
adnano
22d57dfc9e Update examples/cert.go 2020-11-01 14:19:18 -05:00
Adnan Maolood
12bdb2f997 Update examples/html.go 2020-11-01 00:58:34 -04:00
Adnan Maolood
7fb1b6c6a4 Update documentation 2020-11-01 00:10:30 -04:00
Adnan Maolood
0d3230a7d5 Rename InsecureTrustAlways to InsecureSkipTrust 2020-10-31 23:41:30 -04:00
Adnan Maolood
79b3b22e69 Update documentation 2020-10-31 23:05:31 -04:00
Adnan Maolood
33c1dc435d Guarantee that (*Response).Body is non-nil 2020-10-31 23:04:47 -04:00
Adnan Maolood
dad8f38bfb Fix examples/client.go 2020-10-31 22:50:42 -04:00
Adnan Maolood
8181b86759 Add option to skip trust checks 2020-10-31 22:45:21 -04:00
Adnan Maolood
65a5065250 Refactor client.TrustCertificate workflow 2020-10-31 22:34:51 -04:00
Adnan Maolood
b9cb7fe71d Update log.Printf calls 2020-10-31 21:33:59 -04:00
Adnan Maolood
7d470c5fb1 Implement Server read and write timeouts 2020-10-31 21:07:02 -04:00
Adnan Maolood
42c95f8c8d Implement Client connection timeout 2020-10-31 20:55:56 -04:00
Adnan Maolood
a2fc1772bf Set default mimetype if META is empty 2020-10-31 20:32:38 -04:00
Adnan Maolood
63b9b484d1 Remove Redirect and PermanentRedirect functions
Use (*ResponseWriter).WriteHeader instead.
2020-10-31 16:51:10 -04:00
Adnan Maolood
ca8e0166fc Add ErrCertificateNotFound 2020-10-31 16:45:38 -04:00
Adnan Maolood
14ef3be6fe server: Automatically write new certificates to disk 2020-10-31 16:33:56 -04:00
Adnan Maolood
3aa254870a Call CreateCertificate for missing certificates 2020-10-31 15:38:39 -04:00
Adnan Maolood
a89065babb Fix handling of wildcard hostnames 2020-10-31 15:11:05 -04:00
Adnan Maolood
eb466ad02f Add ParseLines function 2020-10-29 09:42:53 -04:00
17 changed files with 591 additions and 676 deletions

123
cert.go
View File

@@ -2,21 +2,28 @@ package gemini
import ( import (
"crypto" "crypto"
"crypto/ecdsa"
"crypto/ed25519" "crypto/ed25519"
"crypto/elliptic"
"crypto/rand" "crypto/rand"
"crypto/tls" "crypto/tls"
"crypto/x509" "crypto/x509"
"crypto/x509/pkix"
"encoding/pem"
"math/big" "math/big"
"net" "net"
"os"
"path/filepath" "path/filepath"
"strings" "strings"
"time" "time"
) )
// CertificateStore maps hostnames to certificates. // CertificateStore maps certificate scopes to certificates.
// The zero value of CertificateStore is an empty store ready to use. // The zero value of CertificateStore is an empty store ready to use.
type CertificateStore struct { type CertificateStore struct {
store map[string]tls.Certificate store map[string]tls.Certificate
dir bool
path string
} }
// Add adds a certificate for the given scope to the store. // Add adds a certificate for the given scope to the store.
@@ -35,17 +42,22 @@ func (c *CertificateStore) Add(scope string, cert tls.Certificate) {
c.store[scope] = cert c.store[scope] = cert
} }
// Write writes the provided certificate to the certificate directory.
func (c *CertificateStore) Write(scope string, cert tls.Certificate) error {
if c.dir {
certPath := filepath.Join(c.path, scope+".crt")
keyPath := filepath.Join(c.path, scope+".key")
if err := WriteCertificate(cert, certPath, keyPath); err != nil {
return err
}
}
return nil
}
// Lookup returns the certificate for the given scope. // Lookup returns the certificate for the given scope.
func (c *CertificateStore) Lookup(scope string) (*tls.Certificate, error) { func (c *CertificateStore) Lookup(scope string) (tls.Certificate, bool) {
cert, ok := c.store[scope] cert, ok := c.store[scope]
if !ok { return cert, ok
return nil, ErrCertificateUnknown
}
// Ensure that the certificate is not expired
if cert.Leaf != nil && cert.Leaf.NotAfter.Before(time.Now()) {
return &cert, ErrCertificateExpired
}
return &cert, nil
} }
// Load loads certificates from the given path. // Load loads certificates from the given path.
@@ -53,6 +65,7 @@ func (c *CertificateStore) Lookup(scope string) (*tls.Certificate, error) {
// in the form scope.crt and scope.key. // in the form scope.crt and scope.key.
// For example, the hostname "localhost" would have the corresponding files // For example, the hostname "localhost" would have the corresponding files
// localhost.crt (certificate) and localhost.key (private key). // localhost.crt (certificate) and localhost.key (private key).
// New certificates will be written to this directory.
func (c *CertificateStore) Load(path string) error { func (c *CertificateStore) Load(path string) error {
matches, err := filepath.Glob(filepath.Join(path, "*.crt")) matches, err := filepath.Glob(filepath.Join(path, "*.crt"))
if err != nil { if err != nil {
@@ -67,14 +80,42 @@ func (c *CertificateStore) Load(path string) error {
scope := strings.TrimSuffix(filepath.Base(crtPath), ".crt") scope := strings.TrimSuffix(filepath.Base(crtPath), ".crt")
c.Add(scope, cert) c.Add(scope, cert)
} }
c.dir = true
c.path = path
return nil return nil
} }
// CertificateOptions configures how a certificate is created. // SetOutput sets the directory that new certificates will be written to.
func (c *CertificateStore) SetOutput(path string) {
c.dir = true
c.path = path
}
// CertificateOptions configures the creation of a certificate.
type CertificateOptions struct { type CertificateOptions struct {
// Subject Alternate Name values.
// Should contain the IP addresses that the certificate is valid for.
IPAddresses []net.IP IPAddresses []net.IP
DNSNames []string
Duration time.Duration // Subject Alternate Name values.
// Should contain the DNS names that this certificate is valid for.
// E.g. example.com, *.example.com
DNSNames []string
// Subject specifies the certificate Subject.
//
// Subject.CommonName can contain the DNS name that this certificate
// is valid for. Server certificates should specify both a Subject
// and a Subject Alternate Name.
Subject pkix.Name
// Duration specifies the amount of time that the certificate is valid for.
Duration time.Duration
// Ed25519 specifies whether to generate an Ed25519 key pair.
// If false, an ECDSA key will be generated instead.
// Ed25519 is not as widely supported as ECDSA.
Ed25519 bool
} }
// CreateCertificate creates a new TLS certificate. // CreateCertificate creates a new TLS certificate.
@@ -92,15 +133,27 @@ func CreateCertificate(options CertificateOptions) (tls.Certificate, error) {
// newX509KeyPair creates and returns a new certificate and private key. // newX509KeyPair creates and returns a new certificate and private key.
func newX509KeyPair(options CertificateOptions) (*x509.Certificate, crypto.PrivateKey, error) { func newX509KeyPair(options CertificateOptions) (*x509.Certificate, crypto.PrivateKey, error) {
// Generate an ED25519 private key var pub crypto.PublicKey
_, priv, err := ed25519.GenerateKey(rand.Reader) var priv crypto.PrivateKey
if err != nil { if options.Ed25519 {
return nil, nil, err // Generate an Ed25519 private key
var err error
pub, priv, err = ed25519.GenerateKey(rand.Reader)
if err != nil {
return nil, nil, err
}
} else {
// Generate an ECDSA private key
private, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
if err != nil {
return nil, nil, err
}
priv = private
pub = &private.PublicKey
} }
public := priv.Public()
// ED25519 keys should have the DigitalSignature KeyUsage bits set // ECDSA and Ed25519 keys should have the DigitalSignature KeyUsage bits
// in the x509.Certificate template // set in the x509.Certificate template
keyUsage := x509.KeyUsageDigitalSignature keyUsage := x509.KeyUsageDigitalSignature
serialNumberLimit := new(big.Int).Lsh(big.NewInt(1), 128) serialNumberLimit := new(big.Int).Lsh(big.NewInt(1), 128)
@@ -121,9 +174,10 @@ func newX509KeyPair(options CertificateOptions) (*x509.Certificate, crypto.Priva
BasicConstraintsValid: true, BasicConstraintsValid: true,
IPAddresses: options.IPAddresses, IPAddresses: options.IPAddresses,
DNSNames: options.DNSNames, DNSNames: options.DNSNames,
Subject: options.Subject,
} }
crt, err := x509.CreateCertificate(rand.Reader, &template, &template, public, priv) crt, err := x509.CreateCertificate(rand.Reader, &template, &template, pub, priv)
if err != nil { if err != nil {
return nil, nil, err return nil, nil, err
} }
@@ -133,3 +187,30 @@ func newX509KeyPair(options CertificateOptions) (*x509.Certificate, crypto.Priva
} }
return cert, priv, nil return cert, priv, nil
} }
// WriteCertificate writes the provided certificate and private key
// to certPath and keyPath respectively.
func WriteCertificate(cert tls.Certificate, certPath, keyPath string) error {
certOut, err := os.OpenFile(certPath, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0600)
if err != nil {
return err
}
defer certOut.Close()
if err := pem.Encode(certOut, &pem.Block{
Type: "CERTIFICATE",
Bytes: cert.Leaf.Raw,
}); err != nil {
return err
}
keyOut, err := os.OpenFile(keyPath, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0600)
if err != nil {
return err
}
defer keyOut.Close()
privBytes, err := x509.MarshalPKCS8PrivateKey(cert.PrivateKey)
if err != nil {
return err
}
return pem.Encode(keyOut, &pem.Block{Type: "PRIVATE KEY", Bytes: privBytes})
}

107
client.go
View File

@@ -4,10 +4,12 @@ import (
"bufio" "bufio"
"crypto/tls" "crypto/tls"
"crypto/x509" "crypto/x509"
"errors"
"net" "net"
"net/url" "net/url"
"path" "path"
"strings" "strings"
"time"
) )
// Client is a Gemini client. // Client is a Gemini client.
@@ -18,28 +20,45 @@ type Client struct {
// Certificates stores client-side certificates. // Certificates stores client-side certificates.
Certificates CertificateStore Certificates CertificateStore
// Timeout specifies a time limit for requests made by this
// Client. The timeout includes connection time and reading
// the response body. The timer remains running after
// Get and Do return and will interrupt reading of the Response.Body.
//
// A Timeout of zero means no timeout.
Timeout time.Duration
// InsecureSkipTrust specifies whether the client should trust
// any certificate it receives without checking KnownHosts
// or calling TrustCertificate.
// Use with caution.
InsecureSkipTrust bool
// GetInput is called to retrieve input when the server requests it. // GetInput is called to retrieve input when the server requests it.
// If GetInput is nil or returns false, no input will be sent and // If GetInput is nil or returns false, no input will be sent and
// the response will be returned. // the response will be returned.
GetInput func(prompt string, sensitive bool) (input string, ok bool) GetInput func(prompt string, sensitive bool) (input string, ok bool)
// CheckRedirect determines whether to follow a redirect. // CheckRedirect determines whether to follow a redirect.
// If CheckRedirect is nil, a default policy of no more than 5 consecutive // If CheckRedirect is nil, redirects will not be followed.
// redirects will be enforced.
CheckRedirect func(req *Request, via []*Request) error CheckRedirect func(req *Request, via []*Request) error
// CreateCertificate is called to generate a certificate upon // CreateCertificate is called to generate a certificate upon
// the request of a server. // the request of a server.
// If CreateCertificate is nil or the returned error is not nil, // If CreateCertificate is nil or the returned error is not nil,
// the request will not be sent again and the response will be returned. // the request will not be sent again and the response will be returned.
CreateCertificate func(hostname, path string) (tls.Certificate, error) CreateCertificate func(scope, path string) (tls.Certificate, error)
// TrustCertificate determines whether the client should trust // TrustCertificate is called to determine whether the client
// the provided certificate. // should trust a certificate it has not seen before.
// If the returned error is not nil, the connection will be aborted. // If TrustCertificate is nil, the certificate will not be trusted
// If TrustCertificate is nil, the client will check KnownHosts // and the connection will be aborted.
// for the certificate. //
TrustCertificate func(hostname string, cert *x509.Certificate, knownHosts *KnownHosts) error // If TrustCertificate returns TrustOnce, the certificate will be added
// to the client's list of known hosts.
// If TrustCertificate returns TrustAlways, the certificate will also be
// written to the known hosts file.
TrustCertificate func(hostname string, cert *x509.Certificate) Trust
} }
// Get performs a Gemini request for the given url. // Get performs a Gemini request for the given url.
@@ -72,7 +91,10 @@ func (c *Client) do(req *Request, via []*Request) (*Response, error) {
if err != nil { if err != nil {
return nil, err return nil, err
} }
// TODO: Set connection deadline // Set connection deadline
if d := c.Timeout; d != 0 {
conn.SetDeadline(time.Now().Add(d))
}
// Write the request // Write the request
w := bufio.NewWriter(conn) w := bufio.NewWriter(conn)
@@ -86,6 +108,7 @@ func (c *Client) do(req *Request, via []*Request) (*Response, error) {
if err := resp.read(conn); err != nil { if err := resp.read(conn); err != nil {
return nil, err return nil, err
} }
resp.Request = req
// Store connection state // Store connection state
resp.TLS = conn.ConnectionState() resp.TLS = conn.ConnectionState()
@@ -103,9 +126,10 @@ func (c *Client) do(req *Request, via []*Request) (*Response, error) {
return resp, err return resp, err
} }
c.Certificates.Add(hostname+path, cert) c.Certificates.Add(hostname+path, cert)
req.Certificate = &cert
return c.do(req, via) return c.do(req, via)
} }
return resp, ErrCertificateRequired return resp, nil
case resp.Status.Class() == StatusClassInput: case resp.Status.Class() == StatusClassInput:
if c.GetInput != nil { if c.GetInput != nil {
@@ -116,7 +140,7 @@ func (c *Client) do(req *Request, via []*Request) (*Response, error) {
return c.do(req, via) return c.do(req, via)
} }
} }
return resp, ErrInputRequired return resp, nil
case resp.Status.Class() == StatusClassRedirect: case resp.Status.Class() == StatusClassRedirect:
if via == nil { if via == nil {
@@ -129,23 +153,16 @@ func (c *Client) do(req *Request, via []*Request) (*Response, error) {
return resp, err return resp, err
} }
target = req.URL.ResolveReference(target) target = req.URL.ResolveReference(target)
redirect, err := NewRequestFromURL(target)
if err != nil {
return resp, err
}
redirect := NewRequestFromURL(target)
if c.CheckRedirect != nil { if c.CheckRedirect != nil {
if err := c.CheckRedirect(redirect, via); err != nil { if err := c.CheckRedirect(redirect, via); err != nil {
return resp, err return resp, err
} }
} else if len(via) > 5 { return c.do(redirect, via)
// Default policy of no more than 5 redirects
return resp, ErrTooManyRedirects
} }
return c.do(redirect, via)
} }
resp.Request = req
return resp, nil return resp, nil
} }
@@ -158,11 +175,14 @@ func (c *Client) getClientCertificate(req *Request) (*tls.Certificate, error) {
// Search recursively for the certificate // Search recursively for the certificate
scope := req.URL.Hostname() + strings.TrimSuffix(req.URL.Path, "/") scope := req.URL.Hostname() + strings.TrimSuffix(req.URL.Path, "/")
for { for {
cert, err := c.Certificates.Lookup(scope) cert, ok := c.Certificates.Lookup(scope)
if err == nil { if ok {
return cert, err // Ensure that the certificate is not expired
} if cert.Leaf != nil && !time.Now().After(cert.Leaf.NotAfter) {
if err == ErrCertificateExpired { // Store the certificate
req.Certificate = &cert
return &cert, nil
}
break break
} }
scope = path.Dir(scope) scope = path.Dir(scope)
@@ -186,12 +206,33 @@ func (c *Client) verifyConnection(req *Request, cs tls.ConnectionState) error {
if err := verifyHostname(cert, hostname); err != nil { if err := verifyHostname(cert, hostname); err != nil {
return err return err
} }
// Check that the client trusts the certificate if c.InsecureSkipTrust {
var err error return nil
if c.TrustCertificate != nil {
return c.TrustCertificate(hostname, cert, &c.KnownHosts)
} else {
err = c.KnownHosts.Lookup(hostname, cert)
} }
return err
// Check the known hosts
knownHost, ok := c.KnownHosts.Lookup(hostname)
if !ok || time.Now().Unix() >= knownHost.Expires {
// See if the client trusts the certificate
if c.TrustCertificate != nil {
switch c.TrustCertificate(hostname, cert) {
case TrustOnce:
fingerprint := NewFingerprint(cert.Raw, cert.NotAfter)
c.KnownHosts.Add(hostname, fingerprint)
return nil
case TrustAlways:
fingerprint := NewFingerprint(cert.Raw, cert.NotAfter)
c.KnownHosts.Add(hostname, fingerprint)
c.KnownHosts.Write(hostname, fingerprint)
return nil
}
}
return errors.New("gemini: certificate not trusted")
}
fingerprint := NewFingerprint(cert.Raw, cert.NotAfter)
if knownHost.Hex == fingerprint.Hex {
return nil
}
return errors.New("gemini: fingerprint does not match")
} }

82
doc.go
View File

@@ -1,82 +0,0 @@
/*
Package gemini implements the Gemini protocol.
Get makes a Gemini request:
resp, err := gemini.Get("gemini://example.com")
if err != nil {
// handle error
}
// ...
The client must close the response body when finished with it:
resp, err := gemini.Get("gemini://example.com")
if err != nil {
// handle error
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
// ...
For control over client behavior, create a Client:
var client gemini.Client
resp, err := client.Get("gemini://example.com")
if err != nil {
// handle error
}
// ...
Clients can load their own list of known hosts:
err := client.KnownHosts.Load("path/to/my/known_hosts")
if err != nil {
// handle error
}
Clients can control when to trust certificates with TrustCertificate:
client.TrustCertificate = func(hostname string, cert *x509.Certificate, knownHosts *gemini.KnownHosts) error {
return knownHosts.Lookup(hostname, cert)
}
Clients can create client certificates upon the request of a server:
client.CreateCertificate = func(hostname, path string) (tls.Certificate, error) {
return gemini.CreateCertificate(gemini.CertificateOptions{
Duration: time.Hour,
})
}
Server is a Gemini server.
var server gemini.Server
Servers must be configured with certificates:
err := server.Certificates.Load("/var/lib/gemini/certs")
if err != nil {
// handle error
}
Servers can accept requests for multiple hosts and schemes:
server.RegisterFunc("example.com", func(w *gemini.ResponseWriter, r *gemini.Request) {
fmt.Fprint(w, "Welcome to example.com")
})
server.RegisterFunc("example.org", func(w *gemini.ResponseWriter, r *gemini.Request) {
fmt.Fprint(w, "Welcome to example.org")
})
server.RegisterFunc("http://example.net", func(w *gemini.ResponseWriter, r *gemini.Request) {
fmt.Fprint(w, "Proxied content from http://example.net")
})
To start the server, call ListenAndServe:
err := server.ListenAndServe()
if err != nil {
// handle error
}
*/
package gemini

View File

@@ -3,9 +3,12 @@
package main package main
import ( import (
"crypto/tls"
"crypto/x509" "crypto/x509"
"crypto/x509/pkix"
"fmt" "fmt"
"log" "log"
"time"
"git.sr.ht/~adnano/go-gemini" "git.sr.ht/~adnano/go-gemini"
) )
@@ -44,6 +47,15 @@ func main() {
if err := server.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 gemini.CreateCertificate(gemini.CertificateOptions{
Subject: pkix.Name{
CommonName: hostname,
},
DNSNames: []string{hostname},
Duration: time.Hour,
})
}
server.Register("localhost", &mux) server.Register("localhost", &mux)
if err := server.ListenAndServe(); err != nil { if err := server.ListenAndServe(); err != nil {
@@ -51,68 +63,73 @@ func main() {
} }
} }
func getSession(crt *x509.Certificate) (*session, bool) { func getSession(cert *x509.Certificate) (*session, bool) {
fingerprint := gemini.Fingerprint(crt) fingerprint := gemini.NewFingerprint(cert.Raw, cert.NotAfter)
session, ok := sessions[fingerprint] session, ok := sessions[fingerprint.Hex]
return session, ok return session, ok
} }
func login(w *gemini.ResponseWriter, r *gemini.Request) { func login(w *gemini.ResponseWriter, r *gemini.Request) {
cert, ok := gemini.Certificate(w, r) if r.Certificate == nil {
if !ok { w.WriteStatus(gemini.StatusCertificateRequired)
return return
} }
username, ok := gemini.Input(w, r, "Username") username, ok := gemini.Input(r)
if !ok { if !ok {
w.WriteHeader(gemini.StatusInput, "Username")
return return
} }
fingerprint := gemini.Fingerprint(cert) cert := r.Certificate.Leaf
sessions[fingerprint] = &session{ fingerprint := gemini.NewFingerprint(cert.Raw, cert.NotAfter)
sessions[fingerprint.Hex] = &session{
username: username, username: username,
} }
gemini.Redirect(w, "/password") w.WriteHeader(gemini.StatusRedirect, "/password")
} }
func loginPassword(w *gemini.ResponseWriter, r *gemini.Request) { func loginPassword(w *gemini.ResponseWriter, r *gemini.Request) {
cert, ok := gemini.Certificate(w, r) if r.Certificate == nil {
if !ok { w.WriteStatus(gemini.StatusCertificateRequired)
return return
} }
session, ok := getSession(cert) session, ok := getSession(r.Certificate.Leaf)
if !ok { if !ok {
w.WriteStatus(gemini.StatusCertificateNotAuthorized) w.WriteStatus(gemini.StatusCertificateNotAuthorized)
return return
} }
password, ok := gemini.SensitiveInput(w, r, "Password") password, ok := gemini.Input(r)
if !ok { if !ok {
w.WriteHeader(gemini.StatusSensitiveInput, "Password")
return return
} }
expected := logins[session.username].password expected := logins[session.username].password
if password == expected { if password == expected {
session.authorized = true session.authorized = true
gemini.Redirect(w, "/profile") w.WriteHeader(gemini.StatusRedirect, "/profile")
} else { } else {
gemini.SensitiveInput(w, r, "Wrong password. Try again") w.WriteHeader(gemini.StatusSensitiveInput, "Password")
} }
} }
func logout(w *gemini.ResponseWriter, r *gemini.Request) { func logout(w *gemini.ResponseWriter, r *gemini.Request) {
cert, ok := gemini.Certificate(w, r) if r.Certificate == nil {
if !ok { w.WriteStatus(gemini.StatusCertificateRequired)
return return
} }
fingerprint := gemini.Fingerprint(cert) cert := r.Certificate.Leaf
delete(sessions, fingerprint) fingerprint := gemini.NewFingerprint(cert.Raw, cert.NotAfter)
delete(sessions, fingerprint.Hex)
fmt.Fprintln(w, "Successfully logged out.") fmt.Fprintln(w, "Successfully logged out.")
fmt.Fprintln(w, "=> / Index")
} }
func profile(w *gemini.ResponseWriter, r *gemini.Request) { func profile(w *gemini.ResponseWriter, r *gemini.Request) {
cert, ok := gemini.Certificate(w, r) if r.Certificate == nil {
if !ok { w.WriteStatus(gemini.StatusCertificateRequired)
return return
} }
session, ok := getSession(cert) session, ok := getSession(r.Certificate.Leaf)
if !ok { if !ok {
w.WriteStatus(gemini.StatusCertificateNotAuthorized) w.WriteStatus(gemini.StatusCertificateNotAuthorized)
return return
@@ -124,11 +141,11 @@ func profile(w *gemini.ResponseWriter, r *gemini.Request) {
} }
func admin(w *gemini.ResponseWriter, r *gemini.Request) { func admin(w *gemini.ResponseWriter, r *gemini.Request) {
cert, ok := gemini.Certificate(w, r) if r.Certificate == nil {
if !ok { w.WriteStatus(gemini.StatusCertificateRequired)
return return
} }
session, ok := getSession(cert) session, ok := getSession(r.Certificate.Leaf)
if !ok { if !ok {
w.WriteStatus(gemini.StatusCertificateNotAuthorized) w.WriteStatus(gemini.StatusCertificateNotAuthorized)
return return

View File

@@ -3,10 +3,7 @@
package main package main
import ( import (
"bytes" "crypto/x509/pkix"
"crypto/tls"
"crypto/x509"
"encoding/pem"
"fmt" "fmt"
"log" "log"
"os" "os"
@@ -26,6 +23,9 @@ func main() {
log.Fatal(err) log.Fatal(err)
} }
options := gemini.CertificateOptions{ options := gemini.CertificateOptions{
Subject: pkix.Name{
CommonName: host,
},
DNSNames: []string{host}, DNSNames: []string{host},
Duration: duration, Duration: duration,
} }
@@ -33,63 +33,9 @@ func main() {
if err != nil { if err != nil {
log.Fatal(err) log.Fatal(err)
} }
if err := writeCertificate(host, cert); err != nil { certPath := host + ".crt"
keyPath := host + ".key"
if err := gemini.WriteCertificate(cert, certPath, keyPath); err != nil {
log.Fatal(err) log.Fatal(err)
} }
} }
// writeCertificate writes the provided certificate and private key
// to path.crt and path.key respectively.
func writeCertificate(path string, cert tls.Certificate) error {
crt, err := marshalX509Certificate(cert.Leaf.Raw)
if err != nil {
return err
}
key, err := marshalPrivateKey(cert.PrivateKey)
if err != nil {
return err
}
// Write the certificate
crtPath := path + ".crt"
crtOut, err := os.OpenFile(crtPath, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0600)
if err != nil {
return err
}
if _, err := crtOut.Write(crt); err != nil {
return err
}
// Write the private key
keyPath := path + ".key"
keyOut, err := os.OpenFile(keyPath, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0600)
if err != nil {
return err
}
if _, err := keyOut.Write(key); err != nil {
return err
}
return nil
}
// marshalX509Certificate returns a PEM-encoded version of the given raw certificate.
func marshalX509Certificate(cert []byte) ([]byte, error) {
var b bytes.Buffer
if err := pem.Encode(&b, &pem.Block{Type: "CERTIFICATE", Bytes: cert}); err != nil {
return nil, err
}
return b.Bytes(), nil
}
// marshalPrivateKey returns PEM encoded versions of the given certificate and private key.
func marshalPrivateKey(priv interface{}) ([]byte, error) {
var b bytes.Buffer
privBytes, err := x509.MarshalPKCS8PrivateKey(priv)
if err != nil {
return nil, err
}
if err := pem.Encode(&b, &pem.Block{Type: "PRIVATE KEY", Bytes: privBytes}); err != nil {
return nil, err
}
return b.Bytes(), nil
}

View File

@@ -8,43 +8,44 @@ import (
"crypto/x509" "crypto/x509"
"fmt" "fmt"
"io/ioutil" "io/ioutil"
"log"
"os" "os"
"path/filepath"
"time" "time"
"git.sr.ht/~adnano/go-gemini" "git.sr.ht/~adnano/go-gemini"
"git.sr.ht/~adnano/go-xdg"
) )
const trustPrompt = `The certificate offered by %s is of unknown trust. Its fingerprint is:
%s
If you knew the fingerprint to expect in advance, verify that this matches.
Otherwise, this should be safe to trust.
[t]rust always; trust [o]nce; [a]bort
=> `
var ( var (
scanner = bufio.NewScanner(os.Stdin) scanner = bufio.NewScanner(os.Stdin)
client = &gemini.Client{} client = &gemini.Client{}
) )
func init() { func init() {
client.KnownHosts.LoadDefault() client.Timeout = 30 * time.Second
client.TrustCertificate = func(hostname string, cert *x509.Certificate, knownHosts *gemini.KnownHosts) error { client.KnownHosts.Load(filepath.Join(xdg.DataHome(), "gemini", "known_hosts"))
err := knownHosts.Lookup(hostname, cert) client.TrustCertificate = func(hostname string, cert *x509.Certificate) gemini.Trust {
if err != nil { fingerprint := gemini.NewFingerprint(cert.Raw, cert.NotAfter)
switch err { fmt.Printf(trustPrompt, hostname, fingerprint.Hex)
case gemini.ErrCertificateNotTrusted: scanner.Scan()
// Alert the user that the certificate is not trusted switch scanner.Text() {
fmt.Printf("Warning: Certificate for %s is not trusted!\n", hostname) case "t":
fmt.Println("This could indicate a Man-in-the-Middle attack.") return gemini.TrustAlways
case gemini.ErrCertificateUnknown: case "o":
// Prompt the user to trust the certificate return gemini.TrustOnce
trust := trustCertificate(cert) default:
switch trust { return gemini.TrustNone
case trustOnce:
// Temporarily trust the certificate
knownHosts.AddTemporary(hostname, cert)
return nil
case trustAlways:
// Add the certificate to the known hosts file
knownHosts.Add(hostname, cert)
return nil
}
}
} }
return err
} }
client.CreateCertificate = func(hostname, path string) (tls.Certificate, error) { client.CreateCertificate = func(hostname, path string) (tls.Certificate, error) {
fmt.Println("Generating client certificate for", hostname, path) fmt.Println("Generating client certificate for", hostname, path)
@@ -59,54 +60,6 @@ func init() {
} }
} }
func doRequest(req *gemini.Request) error {
resp, err := client.Do(req)
if err != nil {
return err
}
if resp.Status.Class() == gemini.StatusClassSuccess {
body, err := ioutil.ReadAll(resp.Body)
resp.Body.Close()
if err != nil {
return err
}
fmt.Print(string(body))
return nil
}
return fmt.Errorf("request failed: %d %s: %s", resp.Status, resp.Status.Message(), resp.Meta)
}
type trust int
const (
trustAbort trust = iota
trustOnce
trustAlways
)
const trustPrompt = `The certificate offered by this server is of unknown trust. Its fingerprint is:
%s
If you knew the fingerprint to expect in advance, verify that this matches.
Otherwise, this should be safe to trust.
[t]rust always; trust [o]nce; [a]bort
=> `
func trustCertificate(cert *x509.Certificate) trust {
fmt.Printf(trustPrompt, gemini.Fingerprint(cert))
scanner.Scan()
switch scanner.Text() {
case "t":
return trustAlways
case "o":
return trustOnce
default:
return trustAbort
}
}
func main() { func main() {
if len(os.Args) < 2 { if len(os.Args) < 2 {
fmt.Printf("usage: %s gemini://... [host]", os.Args[0]) fmt.Printf("usage: %s gemini://... [host]", os.Args[0])
@@ -124,8 +77,20 @@ func main() {
req.Host = os.Args[2] req.Host = os.Args[2]
} }
if err := doRequest(req); err != nil { resp, err := client.Do(req)
if err != nil {
fmt.Println(err) fmt.Println(err)
os.Exit(1) os.Exit(1)
} }
if resp.Status.Class() == gemini.StatusClassSuccess {
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
log.Fatal(err)
}
fmt.Print(string(body))
} else {
fmt.Printf("request failed: %d %s: %s", resp.Status, resp.Status.Message(), resp.Meta)
}
} }

View File

@@ -37,11 +37,10 @@ func textToHTML(text gemini.Text) string {
list = false list = false
fmt.Fprint(&b, "</ul>\n") fmt.Fprint(&b, "</ul>\n")
} }
switch l.(type) { switch l := l.(type) {
case gemini.LineLink: case gemini.LineLink:
link := l.(gemini.LineLink) url := html.EscapeString(l.URL)
url := html.EscapeString(link.URL) name := html.EscapeString(l.Name)
name := html.EscapeString(link.Name)
if name == "" { if name == "" {
name = url name = url
} }
@@ -54,29 +53,22 @@ func textToHTML(text gemini.Text) string {
fmt.Fprint(&b, "</pre>\n") fmt.Fprint(&b, "</pre>\n")
} }
case gemini.LinePreformattedText: case gemini.LinePreformattedText:
text := string(l.(gemini.LinePreformattedText)) fmt.Fprintf(&b, "%s\n", html.EscapeString(string(l)))
fmt.Fprintf(&b, "%s\n", html.EscapeString(text))
case gemini.LineHeading1: case gemini.LineHeading1:
text := string(l.(gemini.LineHeading1)) fmt.Fprintf(&b, "<h1>%s</h1>\n", html.EscapeString(string(l)))
fmt.Fprintf(&b, "<h1>%s</h1>\n", html.EscapeString(text))
case gemini.LineHeading2: case gemini.LineHeading2:
text := string(l.(gemini.LineHeading2)) fmt.Fprintf(&b, "<h2>%s</h2>\n", html.EscapeString(string(l)))
fmt.Fprintf(&b, "<h2>%s</h2>\n", html.EscapeString(text))
case gemini.LineHeading3: case gemini.LineHeading3:
text := string(l.(gemini.LineHeading3)) fmt.Fprintf(&b, "<h3>%s</h3>\n", html.EscapeString(string(l)))
fmt.Fprintf(&b, "<h3>%s</h3>\n", html.EscapeString(text))
case gemini.LineListItem: case gemini.LineListItem:
text := string(l.(gemini.LineListItem)) fmt.Fprintf(&b, "<li>%s</li>\n", html.EscapeString(string(l)))
fmt.Fprintf(&b, "<li>%s</li>\n", html.EscapeString(text))
case gemini.LineQuote: case gemini.LineQuote:
text := string(l.(gemini.LineQuote)) fmt.Fprintf(&b, "<blockquote>%s</blockquote>\n", html.EscapeString(string(l)))
fmt.Fprintf(&b, "<blockquote>%s</blockquote>\n", html.EscapeString(text))
case gemini.LineText: case gemini.LineText:
text := string(l.(gemini.LineText)) if l == "" {
if text == "" {
fmt.Fprint(&b, "<br>\n") fmt.Fprint(&b, "<br>\n")
} else { } else {
fmt.Fprintf(&b, "<p>%s</p>\n", html.EscapeString(text)) fmt.Fprintf(&b, "<p>%s</p>\n", html.EscapeString(string(l)))
} }
} }
} }

View File

@@ -3,14 +3,9 @@
package main package main
import ( import (
"crypto"
"crypto/tls" "crypto/tls"
"crypto/x509" "crypto/x509/pkix"
"encoding/pem"
"fmt"
"io"
"log" "log"
"os"
"time" "time"
"git.sr.ht/~adnano/go-gemini" "git.sr.ht/~adnano/go-gemini"
@@ -18,20 +13,19 @@ import (
func main() { func main() {
var server gemini.Server var server gemini.Server
server.ReadTimeout = 30 * time.Second
server.WriteTimeout = 1 * time.Minute
if err := server.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) { server.CreateCertificate = func(hostname string) (tls.Certificate, error) {
fmt.Println("Generating certificate for", hostname) return gemini.CreateCertificate(gemini.CertificateOptions{
cert, err := gemini.CreateCertificate(gemini.CertificateOptions{ Subject: pkix.Name{
CommonName: hostname,
},
DNSNames: []string{hostname}, DNSNames: []string{hostname},
Duration: time.Minute, // for testing purposes Duration: time.Minute, // for testing purposes
}) })
if err == nil {
// Write the new certificate to disk
err = writeCertificate("/var/lib/gemini/certs/"+hostname, cert)
}
return cert, err
} }
var mux gemini.ServeMux var mux gemini.ServeMux
@@ -42,39 +36,3 @@ func main() {
log.Fatal(err) log.Fatal(err)
} }
} }
// writeCertificate writes the provided certificate and private key
// to path.crt and path.key respectively.
func writeCertificate(path string, cert tls.Certificate) error {
// Write the certificate
crtPath := path + ".crt"
crtOut, err := os.OpenFile(crtPath, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0600)
if err != nil {
return err
}
if err := marshalX509Certificate(crtOut, cert.Leaf.Raw); err != nil {
return err
}
// Write the private key
keyPath := path + ".key"
keyOut, err := os.OpenFile(keyPath, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0600)
if err != nil {
return err
}
return marshalPrivateKey(keyOut, cert.PrivateKey)
}
// marshalX509Certificate writes a PEM-encoded version of the given certificate.
func marshalX509Certificate(w io.Writer, cert []byte) error {
return pem.Encode(w, &pem.Block{Type: "CERTIFICATE", Bytes: cert})
}
// marshalPrivateKey writes a PEM-encoded version of the given private key.
func marshalPrivateKey(w io.Writer, priv crypto.PrivateKey) error {
privBytes, err := x509.MarshalPKCS8PrivateKey(priv)
if err != nil {
return err
}
return pem.Encode(w, &pem.Block{Type: "PRIVATE KEY", Bytes: privBytes})
}

8
fs.go
View File

@@ -33,7 +33,7 @@ func (fsh fsHandler) Respond(w *ResponseWriter, r *Request) {
// Detect mimetype // Detect mimetype
ext := path.Ext(p) ext := path.Ext(p)
mimetype := mime.TypeByExtension(ext) mimetype := mime.TypeByExtension(ext)
w.SetMimetype(mimetype) w.SetMediaType(mimetype)
// Copy file to response writer // Copy file to response writer
io.Copy(w, f) io.Copy(w, f)
} }
@@ -72,7 +72,7 @@ func ServeFile(w *ResponseWriter, fs FS, name string) {
// Detect mimetype // Detect mimetype
ext := path.Ext(name) ext := path.Ext(name)
mimetype := mime.TypeByExtension(ext) mimetype := mime.TypeByExtension(ext)
w.SetMimetype(mimetype) w.SetMediaType(mimetype)
// Copy file to response writer // Copy file to response writer
io.Copy(w, f) io.Copy(w, f)
} }
@@ -96,9 +96,9 @@ func openFile(p string) (File, error) {
if stat.Mode().IsRegular() { if stat.Mode().IsRegular() {
return f, nil return f, nil
} }
return nil, ErrNotAFile return nil, os.ErrNotExist
} else if !stat.Mode().IsRegular() { } else if !stat.Mode().IsRegular() {
return nil, ErrNotAFile return nil, os.ErrNotExist
} }
} }
return f, nil return f, nil

100
gemini.go
View File

@@ -1,59 +1,63 @@
/*
Package gemini implements the Gemini protocol.
Client is a Gemini client.
client := &gemini.Client{}
resp, err := client.Get("gemini://example.com")
if err != nil {
// handle error
}
if resp.Status.Class() == gemini.StatusClassSucess {
defer resp.Body.Close()
// ...
}
// ...
Server is a Gemini server.
server := &gemini.Server{
ReadTimeout: 10 * time.Second,
WriteTimeout: 10 * time.Second,
}
Servers should be configured with certificates:
err := server.Certificates.Load("/var/lib/gemini/certs")
if err != nil {
// handle error
}
Servers can accept requests for multiple hosts and schemes:
server.RegisterFunc("example.com", func(w *gemini.ResponseWriter, r *gemini.Request) {
fmt.Fprint(w, "Welcome to example.com")
})
server.RegisterFunc("example.org", func(w *gemini.ResponseWriter, r *gemini.Request) {
fmt.Fprint(w, "Welcome to example.org")
})
server.RegisterFunc("http://example.net", func(w *gemini.ResponseWriter, r *gemini.Request) {
fmt.Fprint(w, "Proxied content from http://example.net")
})
To start the server, call ListenAndServe:
err := server.ListenAndServe()
if err != nil {
// handle error
}
*/
package gemini package gemini
import ( import (
"crypto/tls"
"crypto/x509"
"errors" "errors"
"sync"
"time"
) )
var crlf = []byte("\r\n") var crlf = []byte("\r\n")
// Errors. // Errors.
var ( var (
ErrInvalidURL = errors.New("gemini: invalid URL") ErrInvalidURL = errors.New("gemini: invalid URL")
ErrInvalidResponse = errors.New("gemini: invalid response") ErrInvalidResponse = errors.New("gemini: invalid response")
ErrCertificateUnknown = errors.New("gemini: unknown certificate") ErrBodyNotAllowed = errors.New("gemini: response body not allowed")
ErrCertificateExpired = errors.New("gemini: certificate expired")
ErrCertificateNotTrusted = errors.New("gemini: certificate is not trusted")
ErrNotAFile = errors.New("gemini: not a file")
ErrNotAGeminiURL = errors.New("gemini: not a Gemini URL")
ErrBodyNotAllowed = errors.New("gemini: response status code does not allow for body")
ErrTooManyRedirects = errors.New("gemini: too many redirects")
ErrInputRequired = errors.New("gemini: input required")
ErrCertificateRequired = errors.New("gemini: certificate required")
) )
// DefaultClient is the default client. It is used by Get and Do.
//
// On the first request, DefaultClient loads the default list of known hosts.
var DefaultClient Client
// Get performs a Gemini request for the given url.
//
// Get is a wrapper around DefaultClient.Get.
func Get(url string) (*Response, error) {
return DefaultClient.Get(url)
}
// Do performs a Gemini request and returns a Gemini response.
//
// Do is a wrapper around DefaultClient.Do.
func Do(req *Request) (*Response, error) {
return DefaultClient.Do(req)
}
var defaultClientOnce sync.Once
func init() {
DefaultClient.TrustCertificate = func(hostname string, cert *x509.Certificate, knownHosts *KnownHosts) error {
defaultClientOnce.Do(func() { knownHosts.LoadDefault() })
return knownHosts.Lookup(hostname, cert)
}
DefaultClient.CreateCertificate = func(hostname, path string) (tls.Certificate, error) {
return CreateCertificate(CertificateOptions{
Duration: time.Hour,
})
}
}

4
mux.go
View File

@@ -138,14 +138,14 @@ func (mux *ServeMux) Respond(w *ResponseWriter, r *Request) {
// 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(path, r.URL); ok {
Redirect(w, u.String()) w.WriteHeader(StatusRedirect, u.String())
return return
} }
if path != r.URL.Path { if path != r.URL.Path {
u := *r.URL u := *r.URL
u.Path = path u.Path = path
Redirect(w, u.String()) w.WriteHeader(StatusRedirect, u.String())
return return
} }

View File

@@ -19,7 +19,9 @@ type Request struct {
// Certificate specifies the TLS certificate to use for the request. // Certificate specifies the TLS certificate to use for the request.
// Request certificates take precedence over client certificates. // Request certificates take precedence over client certificates.
// This field is ignored by the server. //
// On the server side, if the client provided a certificate then
// 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 servers and other software to record the network
@@ -39,15 +41,12 @@ func NewRequest(rawurl string) (*Request, error) {
if err != nil { if err != nil {
return nil, err return nil, err
} }
return NewRequestFromURL(u) return NewRequestFromURL(u), nil
} }
// NewRequestFromURL returns a new request for the given URL. // NewRequestFromURL returns a new request for the given URL.
// The host is inferred from the URL. // The host is inferred from the URL.
func NewRequestFromURL(url *url.URL) (*Request, error) { func NewRequestFromURL(url *url.URL) *Request {
if url.Scheme != "" && url.Scheme != "gemini" {
return nil, ErrNotAGeminiURL
}
host := url.Host host := url.Host
if url.Port() == "" { if url.Port() == "" {
host += ":1965" host += ":1965"
@@ -55,7 +54,7 @@ func NewRequestFromURL(url *url.URL) (*Request, error) {
return &Request{ return &Request{
URL: url, URL: url,
Host: host, Host: host,
}, nil }
} }
// write writes the Gemini request to the provided buffered writer. // write writes the Gemini request to the provided buffered writer.

View File

@@ -9,7 +9,7 @@ import (
// Response is a Gemini response. // Response is a Gemini response.
type Response struct { type Response struct {
// Status represents the response status. // Status contains the response status code.
Status Status Status Status
// Meta contains more information related to the response status. // Meta contains more information related to the response status.
@@ -21,7 +21,7 @@ type Response struct {
// Body contains the response body for successful responses. // Body contains the response body for successful responses.
Body io.ReadCloser Body io.ReadCloser
// Request is the request that was sent to obtain this Response. // Request is the request that was sent to obtain this response.
Request *Request Request *Request
// TLS contains information about the TLS connection on which the response // TLS contains information about the TLS connection on which the response
@@ -68,6 +68,10 @@ func (resp *Response) read(rc io.ReadCloser) error {
if len(meta) > 1024 { if len(meta) > 1024 {
return ErrInvalidResponse return ErrInvalidResponse
} }
// Default mime type of text/gemini; charset=utf-8
if statusClass == StatusClassSuccess && meta == "" {
meta = "text/gemini; charset=utf-8"
}
resp.Meta = meta resp.Meta = meta
// Read terminating newline // Read terminating newline

207
server.go
View File

@@ -3,7 +3,7 @@ package gemini
import ( import (
"bufio" "bufio"
"crypto/tls" "crypto/tls"
"crypto/x509" "errors"
"log" "log"
"net" "net"
"net/url" "net/url"
@@ -18,6 +18,13 @@ type Server struct {
// If Addr is empty, the server will listen on the address ":1965". // If Addr is empty, the server will listen on the address ":1965".
Addr string Addr string
// ReadTimeout is the maximum duration for reading a request.
ReadTimeout time.Duration
// WriteTimeout is the maximum duration before timing out
// writes of the response.
WriteTimeout time.Duration
// Certificates contains the certificates used by the server. // Certificates contains the certificates used by the server.
Certificates CertificateStore Certificates CertificateStore
@@ -25,27 +32,26 @@ type Server struct {
// if the current one is expired or missing. // if the current one is expired or missing.
CreateCertificate func(hostname string) (tls.Certificate, error) 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.
ErrorLog *log.Logger
// registered responders // registered responders
responders map[responderKey]Responder responders map[responderKey]Responder
hosts map[string]bool
} }
type responderKey struct { type responderKey struct {
scheme string scheme string
hostname string hostname string
wildcard bool
} }
// Register registers a responder for the given pattern. // Register registers a responder for the given pattern.
// //
// Patterns must be in the form of hostname or scheme://hostname // Patterns must be in the form of "hostname" or "scheme://hostname".
// (e.g. gemini://example.com). // If no scheme is specified, a scheme of "gemini://" is implied.
// If no scheme is specified, a default scheme of gemini:// is assumed. // Wildcard patterns are supported (e.g. "*.example.com").
//
// Wildcard patterns are supported (e.g. *.example.com).
// To register a certificate for a wildcard hostname, call Certificates.Add:
//
// var s gemini.Server
// s.Certificates.Add("*.example.com", cert)
func (s *Server) Register(pattern string, responder Responder) { func (s *Server) Register(pattern string, responder Responder) {
if pattern == "" { if pattern == "" {
panic("gemini: invalid pattern") panic("gemini: invalid pattern")
@@ -55,6 +61,7 @@ func (s *Server) Register(pattern string, responder Responder) {
} }
if s.responders == nil { if s.responders == nil {
s.responders = map[responderKey]Responder{} s.responders = map[responderKey]Responder{}
s.hosts = map[string]bool{}
} }
split := strings.SplitN(pattern, "://", 2) split := strings.SplitN(pattern, "://", 2)
@@ -66,16 +73,12 @@ func (s *Server) Register(pattern string, responder Responder) {
key.scheme = "gemini" key.scheme = "gemini"
key.hostname = split[0] key.hostname = split[0]
} }
split = strings.SplitN(key.hostname, ".", 2)
if len(split) == 2 && split[0] == "*" {
key.hostname = split[1]
key.wildcard = true
}
if _, ok := s.responders[key]; ok { if _, ok := s.responders[key]; ok {
panic("gemini: multiple registrations for " + pattern) panic("gemini: multiple registrations for " + pattern)
} }
s.responders[key] = responder s.responders[key] = responder
s.hosts[key.hostname] = true
} }
// RegisterFunc registers a responder function for the given pattern. // RegisterFunc registers a responder function for the given pattern.
@@ -120,7 +123,7 @@ 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
} }
log.Printf("gemini: Accept error: %v; retrying in %v", err, tempDelay) s.logf("gemini: Accept error: %v; retrying in %v", err, tempDelay)
time.Sleep(tempDelay) time.Sleep(tempDelay)
continue continue
} }
@@ -135,22 +138,49 @@ func (s *Server) Serve(l net.Listener) error {
} }
func (s *Server) getCertificate(h *tls.ClientHelloInfo) (*tls.Certificate, error) { func (s *Server) getCertificate(h *tls.ClientHelloInfo) (*tls.Certificate, error) {
cert, err := s.Certificates.Lookup(h.ServerName) cert, err := s.getCertificateFor(h.ServerName)
switch err { if err != nil {
case ErrCertificateExpired, ErrCertificateUnknown: // Try wildcard
if s.CreateCertificate != nil { wildcard := strings.SplitN(h.ServerName, ".", 2)
cert, err := s.CreateCertificate(h.ServerName) if len(wildcard) == 2 {
if err == nil { cert, err = s.getCertificateFor("*." + wildcard[1])
s.Certificates.Add(h.ServerName, cert)
}
return &cert, err
} }
} }
return cert, err return cert, err
} }
func (s *Server) getCertificateFor(hostname string) (*tls.Certificate, error) {
if _, ok := s.hosts[hostname]; !ok {
return nil, errors.New("hostname not registered")
}
// 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 {
s.Certificates.Add(hostname, cert)
if err := s.Certificates.Write(hostname, cert); err != nil {
s.logf("gemini: Failed to write new certificate for %s: %s", hostname, err)
}
}
return &cert, err
}
return nil, errors.New("no certificate")
}
return &cert, nil
}
// respond responds to a connection. // respond responds to a connection.
func (s *Server) respond(conn net.Conn) { func (s *Server) respond(conn net.Conn) {
if d := s.ReadTimeout; d != 0 {
conn.SetReadDeadline(time.Now().Add(d))
}
if d := s.WriteTimeout; d != 0 {
conn.SetWriteDeadline(time.Now().Add(d))
}
r := bufio.NewReader(conn) r := bufio.NewReader(conn)
w := newResponseWriter(conn) w := newResponseWriter(conn)
// Read requested URL // Read requested URL
@@ -162,25 +192,39 @@ func (s *Server) respond(conn net.Conn) {
if b, err := r.ReadByte(); err != nil { if b, err := r.ReadByte(); err != nil {
return return
} else if b != '\n' { } else if b != '\n' {
w.WriteHeader(StatusBadRequest, "Bad request") w.WriteStatus(StatusBadRequest)
} }
// Trim carriage return // Trim carriage return
rawurl = rawurl[:len(rawurl)-1] rawurl = rawurl[:len(rawurl)-1]
// Ensure URL is valid // Ensure URL is valid
if len(rawurl) > 1024 { if len(rawurl) > 1024 {
w.WriteHeader(StatusBadRequest, "Bad request") w.WriteStatus(StatusBadRequest)
} else if url, err := url.Parse(rawurl); err != nil || url.User != nil { } else if url, err := url.Parse(rawurl); err != nil || url.User != nil {
// Note that we return an error status if User is specified in the URL // Note that we return an error status if User is specified in the URL
w.WriteHeader(StatusBadRequest, "Bad request") w.WriteStatus(StatusBadRequest)
} else { } else {
// If no scheme is specified, assume a default scheme of gemini:// // If no scheme is specified, assume a default scheme of gemini://
if url.Scheme == "" { if url.Scheme == "" {
url.Scheme = "gemini" url.Scheme = "gemini"
} }
// Store information about the TLS connection
connState := conn.(*tls.Conn).ConnectionState()
var cert *tls.Certificate
if len(connState.PeerCertificates) > 0 {
peerCert := connState.PeerCertificates[0]
// Store the TLS certificate
cert = &tls.Certificate{
Certificate: [][]byte{peerCert.Raw},
Leaf: peerCert,
}
}
req := &Request{ req := &Request{
URL: url, URL: url,
RemoteAddr: conn.RemoteAddr(), RemoteAddr: conn.RemoteAddr(),
TLS: conn.(*tls.Conn).ConnectionState(), TLS: connState,
Certificate: cert,
} }
resp := s.responder(req) resp := s.responder(req)
if resp != nil { if resp != nil {
@@ -194,24 +238,32 @@ func (s *Server) respond(conn net.Conn) {
} }
func (s *Server) responder(r *Request) Responder { func (s *Server) responder(r *Request) Responder {
if h, ok := s.responders[responderKey{r.URL.Scheme, r.URL.Hostname(), false}]; ok { if h, ok := s.responders[responderKey{r.URL.Scheme, r.URL.Hostname()}]; ok {
return h return h
} }
wildcard := strings.SplitN(r.URL.Hostname(), ".", 2) wildcard := strings.SplitN(r.URL.Hostname(), ".", 2)
if len(wildcard) == 2 { if len(wildcard) == 2 {
if h, ok := s.responders[responderKey{r.URL.Scheme, wildcard[1], true}]; ok { if h, ok := s.responders[responderKey{r.URL.Scheme, "*." + wildcard[1]}]; ok {
return h return h
} }
} }
return nil return nil
} }
func (s *Server) logf(format string, args ...interface{}) {
if s.ErrorLog != nil {
s.ErrorLog.Printf(format, args...)
} else {
log.Printf(format, args...)
}
}
// ResponseWriter is used by a Gemini handler to construct a Gemini response. // ResponseWriter is used by a Gemini handler to construct a Gemini response.
type ResponseWriter struct { type ResponseWriter struct {
b *bufio.Writer b *bufio.Writer
bodyAllowed bool bodyAllowed bool
wroteHeader bool wroteHeader bool
mimetype string mediatype string
} }
func newResponseWriter(conn net.Conn) *ResponseWriter { func newResponseWriter(conn net.Conn) *ResponseWriter {
@@ -244,32 +296,31 @@ func (w *ResponseWriter) WriteHeader(status Status, meta string) {
} }
// WriteStatus writes the response header with the given status code. // WriteStatus writes the response header with the given status code.
//
// WriteStatus is equivalent to WriteHeader(status, status.Message())
func (w *ResponseWriter) WriteStatus(status Status) { func (w *ResponseWriter) WriteStatus(status Status) {
w.WriteHeader(status, status.Message()) w.WriteHeader(status, status.Message())
} }
// SetMimetype sets the mimetype that will be written for a successful response. // SetMediaType sets the media type that will be written for a successful response.
// The provided mimetype will only be used if Write is called without calling
// WriteHeader.
// If the mimetype is not set, it will default to "text/gemini". // If the mimetype is not set, it will default to "text/gemini".
func (w *ResponseWriter) SetMimetype(mimetype string) { func (w *ResponseWriter) SetMediaType(mediatype string) {
w.mimetype = mimetype w.mediatype = mediatype
} }
// Write writes the response body. // Write writes the response body.
// If the response status does not allow for a response body, Write returns // If the response status does not allow for a response body, Write returns
// ErrBodyNotAllowed. // ErrBodyNotAllowed.
// //
// If WriteHeader has not yet been called, Write calls // If the response header has not yet been written, Write calls WriteHeader
// WriteHeader(StatusSuccess, mimetype) where mimetype is the mimetype set in // with StatusSuccess and the mimetype set in SetMimetype.
// SetMimetype. If no mimetype is set, a default of "text/gemini" will be used.
func (w *ResponseWriter) Write(b []byte) (int, error) { func (w *ResponseWriter) Write(b []byte) (int, error) {
if !w.wroteHeader { if !w.wroteHeader {
mimetype := w.mimetype mediatype := w.mediatype
if mimetype == "" { if mediatype == "" {
mimetype = "text/gemini" mediatype = "text/gemini"
} }
w.WriteHeader(StatusSuccess, mimetype) w.WriteHeader(StatusSuccess, mediatype)
} }
if !w.bodyAllowed { if !w.bodyAllowed {
return 0, ErrBodyNotAllowed return 0, ErrBodyNotAllowed
@@ -283,51 +334,29 @@ type Responder interface {
Respond(*ResponseWriter, *Request) Respond(*ResponseWriter, *Request)
} }
// Input returns the request query.
// If no input is provided, it responds with StatusInput.
func Input(w *ResponseWriter, r *Request, prompt string) (string, bool) {
if r.URL.ForceQuery || r.URL.RawQuery != "" {
query, err := url.QueryUnescape(r.URL.RawQuery)
return query, err == nil
}
w.WriteHeader(StatusInput, prompt)
return "", false
}
// SensitiveInput returns the request query.
// If no input is provided, it responds with StatusSensitiveInput.
func SensitiveInput(w *ResponseWriter, r *Request, prompt string) (string, bool) {
if r.URL.ForceQuery || r.URL.RawQuery != "" {
query, err := url.QueryUnescape(r.URL.RawQuery)
return query, err == nil
}
w.WriteHeader(StatusSensitiveInput, prompt)
return "", false
}
// Redirect replies to the request with a redirect to the given URL.
func Redirect(w *ResponseWriter, url string) {
w.WriteHeader(StatusRedirect, url)
}
// PermanentRedirect replies to the request with a permanent redirect to the given URL.
func PermanentRedirect(w *ResponseWriter, url string) {
w.WriteHeader(StatusRedirectPermanent, url)
}
// Certificate returns the request certificate. If one is not provided,
// it returns nil and responds with StatusCertificateRequired.
func Certificate(w *ResponseWriter, r *Request) (*x509.Certificate, bool) {
if len(r.TLS.PeerCertificates) == 0 {
w.WriteStatus(StatusCertificateRequired)
return nil, false
}
return r.TLS.PeerCertificates[0], true
}
// ResponderFunc is a wrapper around a bare function that implements Responder. // ResponderFunc is a wrapper around a bare function that implements Responder.
type ResponderFunc func(*ResponseWriter, *Request) type ResponderFunc func(*ResponseWriter, *Request)
func (f ResponderFunc) Respond(w *ResponseWriter, r *Request) { func (f ResponderFunc) Respond(w *ResponseWriter, r *Request) {
f(w, r) f(w, r)
} }
// Input returns the request query.
// If the query is invalid or no query is provided, ok will be false.
//
// Example:
//
// input, ok := gemini.Input(req)
// if !ok {
// w.WriteHeader(gemini.StatusInput, "Prompt")
// return
// }
// // ...
//
func Input(r *Request) (query string, ok bool) {
if r.URL.ForceQuery || r.URL.RawQuery != "" {
query, err := url.QueryUnescape(r.URL.RawQuery)
return query, err == nil
}
return "", false
}

View File

@@ -8,7 +8,7 @@ const (
StatusSensitiveInput Status = 11 StatusSensitiveInput Status = 11
StatusSuccess Status = 20 StatusSuccess Status = 20
StatusRedirect Status = 30 StatusRedirect Status = 30
StatusRedirectPermanent Status = 31 StatusPermanentRedirect Status = 31
StatusTemporaryFailure Status = 40 StatusTemporaryFailure Status = 40
StatusServerUnavailable Status = 41 StatusServerUnavailable Status = 41
StatusCGIError Status = 42 StatusCGIError Status = 42
@@ -52,7 +52,7 @@ func (s Status) Message() string {
return "Success" return "Success"
case StatusRedirect: case StatusRedirect:
return "Redirect" return "Redirect"
case StatusRedirectPermanent: case StatusPermanentRedirect:
return "Permanent redirect" return "Permanent redirect"
case StatusTemporaryFailure: case StatusTemporaryFailure:
return "Temporary failure" return "Temporary failure"

88
text.go
View File

@@ -87,58 +87,68 @@ func (l LineText) line() {}
// Text represents a Gemini text response. // Text represents a Gemini text response.
type Text []Line type Text []Line
// Parse parses Gemini text from the provided io.Reader. // ParseText parses Gemini text from the provided io.Reader.
func Parse(r io.Reader) Text { func ParseText(r io.Reader) Text {
const spacetab = " \t"
var t Text var t Text
ParseLines(r, func(line Line) {
t = append(t, line)
})
return t
}
// ParseLines parses Gemini text from the provided io.Reader.
// It calls handler with each line that it parses.
func ParseLines(r io.Reader, handler func(Line)) {
const spacetab = " \t"
var pre bool var pre bool
scanner := bufio.NewScanner(r) scanner := bufio.NewScanner(r)
for scanner.Scan() { for scanner.Scan() {
line := scanner.Text() var line Line
if strings.HasPrefix(line, "```") { text := scanner.Text()
if strings.HasPrefix(text, "```") {
pre = !pre pre = !pre
line = line[3:] text = text[3:]
t = append(t, LinePreformattingToggle(line)) line = LinePreformattingToggle(text)
} else if pre { } else if pre {
t = append(t, LinePreformattedText(line)) line = LinePreformattedText(text)
} else if strings.HasPrefix(line, "=>") { } else if strings.HasPrefix(text, "=>") {
line = line[2:] text = text[2:]
line = strings.TrimLeft(line, spacetab) text = strings.TrimLeft(text, spacetab)
split := strings.IndexAny(line, spacetab) split := strings.IndexAny(text, spacetab)
if split == -1 { if split == -1 {
// line is a URL // text is a URL
t = append(t, LineLink{URL: line}) line = LineLink{URL: text}
} else { } else {
url := line[:split] url := text[:split]
name := line[split:] name := text[split:]
name = strings.TrimLeft(name, spacetab) name = strings.TrimLeft(name, spacetab)
t = append(t, LineLink{url, name}) line = LineLink{url, name}
} }
} else if strings.HasPrefix(line, "*") { } else if strings.HasPrefix(text, "*") {
line = line[1:] text = text[1:]
line = strings.TrimLeft(line, spacetab) text = strings.TrimLeft(text, spacetab)
t = append(t, LineListItem(line)) line = LineListItem(text)
} else if strings.HasPrefix(line, "###") { } else if strings.HasPrefix(text, "###") {
line = line[3:] text = text[3:]
line = strings.TrimLeft(line, spacetab) text = strings.TrimLeft(text, spacetab)
t = append(t, LineHeading3(line)) line = LineHeading3(text)
} else if strings.HasPrefix(line, "##") { } else if strings.HasPrefix(text, "##") {
line = line[2:] text = text[2:]
line = strings.TrimLeft(line, spacetab) text = strings.TrimLeft(text, spacetab)
t = append(t, LineHeading2(line)) line = LineHeading2(text)
} else if strings.HasPrefix(line, "#") { } else if strings.HasPrefix(text, "#") {
line = line[1:] text = text[1:]
line = strings.TrimLeft(line, spacetab) text = strings.TrimLeft(text, spacetab)
t = append(t, LineHeading1(line)) line = LineHeading1(text)
} else if strings.HasPrefix(line, ">") { } else if strings.HasPrefix(text, ">") {
line = line[1:] text = text[1:]
line = strings.TrimLeft(line, spacetab) text = strings.TrimLeft(text, spacetab)
t = append(t, LineQuote(line)) line = LineQuote(text)
} else { } else {
t = append(t, LineText(line)) line = LineText(text)
} }
handler(line)
} }
return t
} }
// String writes the Gemini text response to a string and returns it. // String writes the Gemini text response to a string and returns it.

191
tofu.go
View File

@@ -3,45 +3,76 @@ package gemini
import ( import (
"bufio" "bufio"
"crypto/sha512" "crypto/sha512"
"crypto/x509"
"fmt" "fmt"
"io" "io"
"os" "os"
"path/filepath"
"strconv" "strconv"
"strings" "strings"
"time" "time"
) )
// Trust represents the trustworthiness of a certificate.
type Trust int
const (
TrustNone Trust = iota // The certificate is not trusted.
TrustOnce // The certificate is trusted once.
TrustAlways // The certificate is trusted always.
)
// KnownHosts represents a list of known hosts. // KnownHosts represents a list of known hosts.
// The zero value for KnownHosts is an empty list ready to use. // The zero value for KnownHosts is an empty list ready to use.
type KnownHosts struct { type KnownHosts struct {
hosts map[string]certInfo hosts map[string]Fingerprint
file *os.File out io.Writer
} }
// LoadDefault loads the known hosts from the default known hosts path, which is // SetOutput sets the output to which new known hosts will be written to.
// $XDG_DATA_HOME/gemini/known_hosts. func (k *KnownHosts) SetOutput(w io.Writer) {
// It creates the path and any of its parent directories if they do not exist. k.out = w
// KnownHosts will append to the file whenever a certificate is added. }
func (k *KnownHosts) LoadDefault() error {
path, err := defaultKnownHostsPath() // Add adds a known host to the list of known hosts.
if err != nil { func (k *KnownHosts) Add(hostname string, fingerprint Fingerprint) {
return err if k.hosts == nil {
k.hosts = map[string]Fingerprint{}
} }
return k.Load(path) k.hosts[hostname] = fingerprint
} }
// Load loads the known hosts from the provided path. // Lookup returns the fingerprint of the certificate corresponding to
// It creates the path and any of its parent directories if they do not exist. // the given hostname.
// KnownHosts will append to the file whenever a certificate is added. func (k *KnownHosts) Lookup(hostname string) (Fingerprint, bool) {
func (k *KnownHosts) Load(path string) error { c, ok := k.hosts[hostname]
if dir := filepath.Dir(path); dir != "." { return c, ok
err := os.MkdirAll(dir, 0755) }
if err != nil {
// Write writes a known hosts entry to the configured output.
func (k *KnownHosts) Write(hostname string, fingerprint Fingerprint) {
if k.out != nil {
k.writeKnownHost(k.out, hostname, fingerprint)
}
}
// WriteAll writes all of the known hosts to the provided io.Writer.
func (k *KnownHosts) WriteAll(w io.Writer) error {
for h, c := range k.hosts {
if _, err := k.writeKnownHost(w, h, c); err != nil {
return err return err
} }
} }
return nil
}
// writeKnownHost writes a known host to the provided io.Writer.
func (k *KnownHosts) writeKnownHost(w io.Writer, hostname string, f Fingerprint) (int, error) {
return fmt.Fprintf(w, "%s %s %s %d\n", hostname, f.Algorithm, f.Hex, f.Expires)
}
// Load loads the known hosts from the provided path.
// It creates the file if it does not exist.
// New known hosts will be appended to the file.
func (k *KnownHosts) Load(path string) error {
f, err := os.OpenFile(path, os.O_CREATE|os.O_RDONLY, 0644) f, err := os.OpenFile(path, os.O_CREATE|os.O_RDONLY, 0644)
if err != nil { if err != nil {
return err return err
@@ -53,66 +84,15 @@ func (k *KnownHosts) Load(path string) error {
if err != nil { if err != nil {
return err return err
} }
k.file = f k.out = f
return nil return nil
} }
// Add adds a certificate to the list of known hosts.
// If KnownHosts was loaded from a file, Add will append to the file.
func (k *KnownHosts) Add(hostname string, cert *x509.Certificate) {
k.add(hostname, cert, true)
}
// AddTemporary adds a certificate to the list of known hosts
// without writing it to the known hosts file.
func (k *KnownHosts) AddTemporary(hostname string, cert *x509.Certificate) {
k.add(hostname, cert, false)
}
func (k *KnownHosts) add(hostname string, cert *x509.Certificate, write bool) {
if k.hosts == nil {
k.hosts = map[string]certInfo{}
}
info := certInfo{
Algorithm: "SHA-512",
Fingerprint: Fingerprint(cert),
Expires: cert.NotAfter.Unix(),
}
k.hosts[hostname] = info
// Append to the file
if write && k.file != nil {
appendKnownHost(k.file, hostname, info)
}
}
// Lookup looks for the provided certificate in the list of known hosts.
// If the hostname is in the list, but the fingerprint differs,
// Lookup returns ErrCertificateNotTrusted.
// If the hostname is not in the list, Lookup returns ErrCertificateUnknown.
// If the certificate is found and the fingerprint matches, error will be nil.
func (k *KnownHosts) Lookup(hostname string, cert *x509.Certificate) error {
now := time.Now().Unix()
fingerprint := Fingerprint(cert)
if c, ok := k.hosts[hostname]; ok {
if c.Expires <= now {
// Certificate is expired
return ErrCertificateUnknown
}
if c.Fingerprint != fingerprint {
// Fingerprint does not match
return ErrCertificateNotTrusted
}
// Certificate is trusted
return nil
}
return ErrCertificateUnknown
}
// Parse parses the provided reader and adds the parsed known hosts to the list. // Parse parses the provided reader and adds the parsed known hosts to the list.
// Invalid lines are ignored. // Invalid entries are ignored.
func (k *KnownHosts) Parse(r io.Reader) { func (k *KnownHosts) Parse(r io.Reader) {
if k.hosts == nil { if k.hosts == nil {
k.hosts = map[string]certInfo{} k.hosts = map[string]Fingerprint{}
} }
scanner := bufio.NewScanner(r) scanner := bufio.NewScanner(r)
for scanner.Scan() { for scanner.Scan() {
@@ -128,39 +108,30 @@ func (k *KnownHosts) Parse(r io.Reader) {
continue continue
} }
fingerprint := parts[2] fingerprint := parts[2]
expires, err := strconv.ParseInt(parts[3], 10, 0) expires, err := strconv.ParseInt(parts[3], 10, 0)
if err != nil { if err != nil {
continue continue
} }
k.hosts[hostname] = certInfo{ k.hosts[hostname] = Fingerprint{
Algorithm: algorithm, Algorithm: algorithm,
Fingerprint: fingerprint, Hex: fingerprint,
Expires: expires, Expires: expires,
} }
} }
} }
// Write writes the known hosts to the provided io.Writer. // Fingerprint represents a fingerprint using a certain algorithm.
func (k *KnownHosts) Write(w io.Writer) { type Fingerprint struct {
for h, c := range k.hosts { Algorithm string // fingerprint algorithm e.g. SHA-512
appendKnownHost(w, h, c) Hex string // fingerprint in hexadecimal, with ':' between each octet
} Expires int64 // unix time of the fingerprint expiration date
} }
type certInfo struct { // NewFingerprint returns the SHA-512 fingerprint of the provided raw data.
Algorithm string // fingerprint algorithm e.g. SHA-512 func NewFingerprint(raw []byte, expires time.Time) Fingerprint {
Fingerprint string // fingerprint in hexadecimal, with ':' between each octet sum512 := sha512.Sum512(raw)
Expires int64 // unix time of certificate notAfter date
}
func appendKnownHost(w io.Writer, hostname string, c certInfo) (int, error) {
return fmt.Fprintf(w, "%s %s %s %d\n", hostname, c.Algorithm, c.Fingerprint, c.Expires)
}
// Fingerprint returns the SHA-512 fingerprint of the provided certificate.
func Fingerprint(cert *x509.Certificate) string {
sum512 := sha512.Sum512(cert.Raw)
var b strings.Builder var b strings.Builder
for i, f := range sum512 { for i, f := range sum512 {
if i > 0 { if i > 0 {
@@ -168,29 +139,9 @@ func Fingerprint(cert *x509.Certificate) string {
} }
fmt.Fprintf(&b, "%02X", f) fmt.Fprintf(&b, "%02X", f)
} }
return b.String() return Fingerprint{
} Algorithm: "SHA-512",
Hex: b.String(),
// defaultKnownHostsPath returns the default known_hosts path. Expires: expires.Unix(),
// The default path is $XDG_DATA_HOME/gemini/known_hosts
func defaultKnownHostsPath() (string, error) {
dataDir, err := userDataDir()
if err != nil {
return "", err
} }
return filepath.Join(dataDir, "gemini", "known_hosts"), nil
}
// userDataDir returns the user data directory.
func userDataDir() (string, error) {
dataDir, ok := os.LookupEnv("XDG_DATA_HOME")
if ok {
return dataDir, nil
}
home, err := os.UserHomeDir()
if err != nil {
return "", err
}
return filepath.Join(home, ".local", "share"), nil
} }