Compare commits
48 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f6b0443a62 | ||
|
|
3dee6dcff3 | ||
|
|
85f8e84bd5 | ||
|
|
9338681256 | ||
|
|
f2a1510375 | ||
|
|
46cbcfcaa4 | ||
|
|
76dfe257f1 | ||
|
|
5332dc6280 | ||
|
|
6b3cf1314b | ||
|
|
fe92db1e9c | ||
|
|
ff6c95930b | ||
|
|
a5712c7705 | ||
|
|
520d0a7fb1 | ||
|
|
bf185e4091 | ||
|
|
8101fbe473 | ||
|
|
b76080c863 | ||
|
|
53390dad6b | ||
|
|
cec1f118fb | ||
|
|
95716296b4 | ||
|
|
1490bf6a75 | ||
|
|
610c6fc533 | ||
|
|
01670647d2 | ||
|
|
5b3194695f | ||
|
|
b6475aa7d9 | ||
|
|
cc372e8768 | ||
|
|
8e442146c3 | ||
|
|
e4dea6f2c8 | ||
|
|
b57ea57fec | ||
|
|
c3fc9a4e9f | ||
|
|
22d57dfc9e | ||
|
|
12bdb2f997 | ||
|
|
7fb1b6c6a4 | ||
|
|
0d3230a7d5 | ||
|
|
79b3b22e69 | ||
|
|
33c1dc435d | ||
|
|
dad8f38bfb | ||
|
|
8181b86759 | ||
|
|
65a5065250 | ||
|
|
b9cb7fe71d | ||
|
|
7d470c5fb1 | ||
|
|
42c95f8c8d | ||
|
|
a2fc1772bf | ||
|
|
63b9b484d1 | ||
|
|
ca8e0166fc | ||
|
|
14ef3be6fe | ||
|
|
3aa254870a | ||
|
|
a89065babb | ||
|
|
eb466ad02f |
123
cert.go
123
cert.go
@@ -2,21 +2,28 @@ package gemini
|
||||
|
||||
import (
|
||||
"crypto"
|
||||
"crypto/ecdsa"
|
||||
"crypto/ed25519"
|
||||
"crypto/elliptic"
|
||||
"crypto/rand"
|
||||
"crypto/tls"
|
||||
"crypto/x509"
|
||||
"crypto/x509/pkix"
|
||||
"encoding/pem"
|
||||
"math/big"
|
||||
"net"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
// CertificateStore maps hostnames to certificates.
|
||||
// CertificateStore maps certificate scopes to certificates.
|
||||
// The zero value of CertificateStore is an empty store ready to use.
|
||||
type CertificateStore struct {
|
||||
store map[string]tls.Certificate
|
||||
dir bool
|
||||
path string
|
||||
}
|
||||
|
||||
// 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
|
||||
}
|
||||
|
||||
// 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.
|
||||
func (c *CertificateStore) Lookup(scope string) (*tls.Certificate, error) {
|
||||
func (c *CertificateStore) Lookup(scope string) (tls.Certificate, bool) {
|
||||
cert, ok := c.store[scope]
|
||||
if !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
|
||||
return cert, ok
|
||||
}
|
||||
|
||||
// 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.
|
||||
// For example, the hostname "localhost" would have the corresponding files
|
||||
// localhost.crt (certificate) and localhost.key (private key).
|
||||
// New certificates will be written to this directory.
|
||||
func (c *CertificateStore) Load(path string) error {
|
||||
matches, err := filepath.Glob(filepath.Join(path, "*.crt"))
|
||||
if err != nil {
|
||||
@@ -67,14 +80,42 @@ func (c *CertificateStore) Load(path string) error {
|
||||
scope := strings.TrimSuffix(filepath.Base(crtPath), ".crt")
|
||||
c.Add(scope, cert)
|
||||
}
|
||||
c.dir = true
|
||||
c.path = path
|
||||
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 {
|
||||
// Subject Alternate Name values.
|
||||
// Should contain the IP addresses that the certificate is valid for.
|
||||
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.
|
||||
@@ -92,15 +133,27 @@ func CreateCertificate(options CertificateOptions) (tls.Certificate, error) {
|
||||
|
||||
// newX509KeyPair creates and returns a new certificate and private key.
|
||||
func newX509KeyPair(options CertificateOptions) (*x509.Certificate, crypto.PrivateKey, error) {
|
||||
// Generate an ED25519 private key
|
||||
_, priv, err := ed25519.GenerateKey(rand.Reader)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
var pub crypto.PublicKey
|
||||
var priv crypto.PrivateKey
|
||||
if options.Ed25519 {
|
||||
// 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
|
||||
// in the x509.Certificate template
|
||||
// ECDSA and Ed25519 keys should have the DigitalSignature KeyUsage bits
|
||||
// set in the x509.Certificate template
|
||||
keyUsage := x509.KeyUsageDigitalSignature
|
||||
|
||||
serialNumberLimit := new(big.Int).Lsh(big.NewInt(1), 128)
|
||||
@@ -121,9 +174,10 @@ func newX509KeyPair(options CertificateOptions) (*x509.Certificate, crypto.Priva
|
||||
BasicConstraintsValid: true,
|
||||
IPAddresses: options.IPAddresses,
|
||||
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 {
|
||||
return nil, nil, err
|
||||
}
|
||||
@@ -133,3 +187,30 @@ func newX509KeyPair(options CertificateOptions) (*x509.Certificate, crypto.Priva
|
||||
}
|
||||
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
107
client.go
@@ -4,10 +4,12 @@ import (
|
||||
"bufio"
|
||||
"crypto/tls"
|
||||
"crypto/x509"
|
||||
"errors"
|
||||
"net"
|
||||
"net/url"
|
||||
"path"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Client is a Gemini client.
|
||||
@@ -18,28 +20,45 @@ type Client struct {
|
||||
// Certificates stores client-side certificates.
|
||||
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.
|
||||
// If GetInput is nil or returns false, no input will be sent and
|
||||
// the response will be returned.
|
||||
GetInput func(prompt string, sensitive bool) (input string, ok bool)
|
||||
|
||||
// CheckRedirect determines whether to follow a redirect.
|
||||
// If CheckRedirect is nil, a default policy of no more than 5 consecutive
|
||||
// redirects will be enforced.
|
||||
// If CheckRedirect is nil, redirects will not be followed.
|
||||
CheckRedirect func(req *Request, via []*Request) error
|
||||
|
||||
// CreateCertificate is called to generate a certificate upon
|
||||
// the request of a server.
|
||||
// If CreateCertificate is nil or the returned error is not nil,
|
||||
// the request will not be sent again and the response will be returned.
|
||||
CreateCertificate func(hostname, path string) (tls.Certificate, error)
|
||||
CreateCertificate func(scope, path string) (tls.Certificate, error)
|
||||
|
||||
// TrustCertificate determines whether the client should trust
|
||||
// the provided certificate.
|
||||
// If the returned error is not nil, the connection will be aborted.
|
||||
// If TrustCertificate is nil, the client will check KnownHosts
|
||||
// for the certificate.
|
||||
TrustCertificate func(hostname string, cert *x509.Certificate, knownHosts *KnownHosts) error
|
||||
// TrustCertificate is called to determine whether the client
|
||||
// should trust a certificate it has not seen before.
|
||||
// If TrustCertificate is nil, the certificate will not be trusted
|
||||
// and the connection will be aborted.
|
||||
//
|
||||
// If TrustCertificate returns TrustOnce, the certificate will be added
|
||||
// to the client's list of known hosts.
|
||||
// If TrustCertificate returns TrustAlways, the certificate will also be
|
||||
// written to the known hosts file.
|
||||
TrustCertificate func(hostname string, cert *x509.Certificate) Trust
|
||||
}
|
||||
|
||||
// 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 {
|
||||
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
|
||||
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 {
|
||||
return nil, err
|
||||
}
|
||||
resp.Request = req
|
||||
// Store connection state
|
||||
resp.TLS = conn.ConnectionState()
|
||||
|
||||
@@ -103,9 +126,10 @@ func (c *Client) do(req *Request, via []*Request) (*Response, error) {
|
||||
return resp, err
|
||||
}
|
||||
c.Certificates.Add(hostname+path, cert)
|
||||
req.Certificate = &cert
|
||||
return c.do(req, via)
|
||||
}
|
||||
return resp, ErrCertificateRequired
|
||||
return resp, nil
|
||||
|
||||
case resp.Status.Class() == StatusClassInput:
|
||||
if c.GetInput != nil {
|
||||
@@ -116,7 +140,7 @@ func (c *Client) do(req *Request, via []*Request) (*Response, error) {
|
||||
return c.do(req, via)
|
||||
}
|
||||
}
|
||||
return resp, ErrInputRequired
|
||||
return resp, nil
|
||||
|
||||
case resp.Status.Class() == StatusClassRedirect:
|
||||
if via == nil {
|
||||
@@ -129,23 +153,16 @@ func (c *Client) do(req *Request, via []*Request) (*Response, error) {
|
||||
return resp, err
|
||||
}
|
||||
target = req.URL.ResolveReference(target)
|
||||
redirect, err := NewRequestFromURL(target)
|
||||
if err != nil {
|
||||
return resp, err
|
||||
}
|
||||
|
||||
redirect := NewRequestFromURL(target)
|
||||
if c.CheckRedirect != nil {
|
||||
if err := c.CheckRedirect(redirect, via); err != nil {
|
||||
return resp, err
|
||||
}
|
||||
} else if len(via) > 5 {
|
||||
// Default policy of no more than 5 redirects
|
||||
return resp, ErrTooManyRedirects
|
||||
return c.do(redirect, via)
|
||||
}
|
||||
return c.do(redirect, via)
|
||||
}
|
||||
|
||||
resp.Request = req
|
||||
return resp, nil
|
||||
}
|
||||
|
||||
@@ -158,11 +175,14 @@ func (c *Client) getClientCertificate(req *Request) (*tls.Certificate, error) {
|
||||
// Search recursively for the certificate
|
||||
scope := req.URL.Hostname() + strings.TrimSuffix(req.URL.Path, "/")
|
||||
for {
|
||||
cert, err := c.Certificates.Lookup(scope)
|
||||
if err == nil {
|
||||
return cert, err
|
||||
}
|
||||
if err == ErrCertificateExpired {
|
||||
cert, ok := c.Certificates.Lookup(scope)
|
||||
if ok {
|
||||
// Ensure that the certificate is not expired
|
||||
if cert.Leaf != nil && !time.Now().After(cert.Leaf.NotAfter) {
|
||||
// Store the certificate
|
||||
req.Certificate = &cert
|
||||
return &cert, nil
|
||||
}
|
||||
break
|
||||
}
|
||||
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 {
|
||||
return err
|
||||
}
|
||||
// Check that the client trusts the certificate
|
||||
var err error
|
||||
if c.TrustCertificate != nil {
|
||||
return c.TrustCertificate(hostname, cert, &c.KnownHosts)
|
||||
} else {
|
||||
err = c.KnownHosts.Lookup(hostname, cert)
|
||||
if c.InsecureSkipTrust {
|
||||
return nil
|
||||
}
|
||||
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
82
doc.go
@@ -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
|
||||
@@ -3,9 +3,12 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"crypto/tls"
|
||||
"crypto/x509"
|
||||
"crypto/x509/pkix"
|
||||
"fmt"
|
||||
"log"
|
||||
"time"
|
||||
|
||||
"git.sr.ht/~adnano/go-gemini"
|
||||
)
|
||||
@@ -44,6 +47,15 @@ func main() {
|
||||
if err := server.Certificates.Load("/var/lib/gemini/certs"); err != nil {
|
||||
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)
|
||||
|
||||
if err := server.ListenAndServe(); err != nil {
|
||||
@@ -51,68 +63,73 @@ func main() {
|
||||
}
|
||||
}
|
||||
|
||||
func getSession(crt *x509.Certificate) (*session, bool) {
|
||||
fingerprint := gemini.Fingerprint(crt)
|
||||
session, ok := sessions[fingerprint]
|
||||
func getSession(cert *x509.Certificate) (*session, bool) {
|
||||
fingerprint := gemini.NewFingerprint(cert.Raw, cert.NotAfter)
|
||||
session, ok := sessions[fingerprint.Hex]
|
||||
return session, ok
|
||||
}
|
||||
|
||||
func login(w *gemini.ResponseWriter, r *gemini.Request) {
|
||||
cert, ok := gemini.Certificate(w, r)
|
||||
if !ok {
|
||||
if r.Certificate == nil {
|
||||
w.WriteStatus(gemini.StatusCertificateRequired)
|
||||
return
|
||||
}
|
||||
username, ok := gemini.Input(w, r, "Username")
|
||||
username, ok := gemini.Input(r)
|
||||
if !ok {
|
||||
w.WriteHeader(gemini.StatusInput, "Username")
|
||||
return
|
||||
}
|
||||
fingerprint := gemini.Fingerprint(cert)
|
||||
sessions[fingerprint] = &session{
|
||||
cert := r.Certificate.Leaf
|
||||
fingerprint := gemini.NewFingerprint(cert.Raw, cert.NotAfter)
|
||||
sessions[fingerprint.Hex] = &session{
|
||||
username: username,
|
||||
}
|
||||
gemini.Redirect(w, "/password")
|
||||
w.WriteHeader(gemini.StatusRedirect, "/password")
|
||||
}
|
||||
|
||||
func loginPassword(w *gemini.ResponseWriter, r *gemini.Request) {
|
||||
cert, ok := gemini.Certificate(w, r)
|
||||
if !ok {
|
||||
if r.Certificate == nil {
|
||||
w.WriteStatus(gemini.StatusCertificateRequired)
|
||||
return
|
||||
}
|
||||
session, ok := getSession(cert)
|
||||
session, ok := getSession(r.Certificate.Leaf)
|
||||
if !ok {
|
||||
w.WriteStatus(gemini.StatusCertificateNotAuthorized)
|
||||
return
|
||||
}
|
||||
|
||||
password, ok := gemini.SensitiveInput(w, r, "Password")
|
||||
password, ok := gemini.Input(r)
|
||||
if !ok {
|
||||
w.WriteHeader(gemini.StatusSensitiveInput, "Password")
|
||||
return
|
||||
}
|
||||
expected := logins[session.username].password
|
||||
if password == expected {
|
||||
session.authorized = true
|
||||
gemini.Redirect(w, "/profile")
|
||||
w.WriteHeader(gemini.StatusRedirect, "/profile")
|
||||
} else {
|
||||
gemini.SensitiveInput(w, r, "Wrong password. Try again")
|
||||
w.WriteHeader(gemini.StatusSensitiveInput, "Password")
|
||||
}
|
||||
}
|
||||
|
||||
func logout(w *gemini.ResponseWriter, r *gemini.Request) {
|
||||
cert, ok := gemini.Certificate(w, r)
|
||||
if !ok {
|
||||
if r.Certificate == nil {
|
||||
w.WriteStatus(gemini.StatusCertificateRequired)
|
||||
return
|
||||
}
|
||||
fingerprint := gemini.Fingerprint(cert)
|
||||
delete(sessions, fingerprint)
|
||||
cert := r.Certificate.Leaf
|
||||
fingerprint := gemini.NewFingerprint(cert.Raw, cert.NotAfter)
|
||||
delete(sessions, fingerprint.Hex)
|
||||
fmt.Fprintln(w, "Successfully logged out.")
|
||||
fmt.Fprintln(w, "=> / Index")
|
||||
}
|
||||
|
||||
func profile(w *gemini.ResponseWriter, r *gemini.Request) {
|
||||
cert, ok := gemini.Certificate(w, r)
|
||||
if !ok {
|
||||
if r.Certificate == nil {
|
||||
w.WriteStatus(gemini.StatusCertificateRequired)
|
||||
return
|
||||
}
|
||||
session, ok := getSession(cert)
|
||||
session, ok := getSession(r.Certificate.Leaf)
|
||||
if !ok {
|
||||
w.WriteStatus(gemini.StatusCertificateNotAuthorized)
|
||||
return
|
||||
@@ -124,11 +141,11 @@ func profile(w *gemini.ResponseWriter, r *gemini.Request) {
|
||||
}
|
||||
|
||||
func admin(w *gemini.ResponseWriter, r *gemini.Request) {
|
||||
cert, ok := gemini.Certificate(w, r)
|
||||
if !ok {
|
||||
if r.Certificate == nil {
|
||||
w.WriteStatus(gemini.StatusCertificateRequired)
|
||||
return
|
||||
}
|
||||
session, ok := getSession(cert)
|
||||
session, ok := getSession(r.Certificate.Leaf)
|
||||
if !ok {
|
||||
w.WriteStatus(gemini.StatusCertificateNotAuthorized)
|
||||
return
|
||||
|
||||
@@ -3,10 +3,7 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"crypto/tls"
|
||||
"crypto/x509"
|
||||
"encoding/pem"
|
||||
"crypto/x509/pkix"
|
||||
"fmt"
|
||||
"log"
|
||||
"os"
|
||||
@@ -26,6 +23,9 @@ func main() {
|
||||
log.Fatal(err)
|
||||
}
|
||||
options := gemini.CertificateOptions{
|
||||
Subject: pkix.Name{
|
||||
CommonName: host,
|
||||
},
|
||||
DNSNames: []string{host},
|
||||
Duration: duration,
|
||||
}
|
||||
@@ -33,63 +33,9 @@ func main() {
|
||||
if err != nil {
|
||||
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)
|
||||
}
|
||||
}
|
||||
|
||||
// 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
|
||||
}
|
||||
|
||||
@@ -8,43 +8,44 @@ import (
|
||||
"crypto/x509"
|
||||
"fmt"
|
||||
"io/ioutil"
|
||||
"log"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"time"
|
||||
|
||||
"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 (
|
||||
scanner = bufio.NewScanner(os.Stdin)
|
||||
client = &gemini.Client{}
|
||||
)
|
||||
|
||||
func init() {
|
||||
client.KnownHosts.LoadDefault()
|
||||
client.TrustCertificate = func(hostname string, cert *x509.Certificate, knownHosts *gemini.KnownHosts) error {
|
||||
err := knownHosts.Lookup(hostname, cert)
|
||||
if err != nil {
|
||||
switch err {
|
||||
case gemini.ErrCertificateNotTrusted:
|
||||
// Alert the user that the certificate is not trusted
|
||||
fmt.Printf("Warning: Certificate for %s is not trusted!\n", hostname)
|
||||
fmt.Println("This could indicate a Man-in-the-Middle attack.")
|
||||
case gemini.ErrCertificateUnknown:
|
||||
// Prompt the user to trust the certificate
|
||||
trust := trustCertificate(cert)
|
||||
switch trust {
|
||||
case trustOnce:
|
||||
// Temporarily trust the certificate
|
||||
knownHosts.AddTemporary(hostname, cert)
|
||||
return nil
|
||||
case trustAlways:
|
||||
// Add the certificate to the known hosts file
|
||||
knownHosts.Add(hostname, cert)
|
||||
return nil
|
||||
}
|
||||
}
|
||||
client.Timeout = 30 * time.Second
|
||||
client.KnownHosts.Load(filepath.Join(xdg.DataHome(), "gemini", "known_hosts"))
|
||||
client.TrustCertificate = func(hostname string, cert *x509.Certificate) gemini.Trust {
|
||||
fingerprint := gemini.NewFingerprint(cert.Raw, cert.NotAfter)
|
||||
fmt.Printf(trustPrompt, hostname, fingerprint.Hex)
|
||||
scanner.Scan()
|
||||
switch scanner.Text() {
|
||||
case "t":
|
||||
return gemini.TrustAlways
|
||||
case "o":
|
||||
return gemini.TrustOnce
|
||||
default:
|
||||
return gemini.TrustNone
|
||||
}
|
||||
return err
|
||||
}
|
||||
client.CreateCertificate = func(hostname, path string) (tls.Certificate, error) {
|
||||
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() {
|
||||
if len(os.Args) < 2 {
|
||||
fmt.Printf("usage: %s gemini://... [host]", os.Args[0])
|
||||
@@ -124,8 +77,20 @@ func main() {
|
||||
req.Host = os.Args[2]
|
||||
}
|
||||
|
||||
if err := doRequest(req); err != nil {
|
||||
resp, err := client.Do(req)
|
||||
if err != nil {
|
||||
fmt.Println(err)
|
||||
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)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -37,11 +37,10 @@ func textToHTML(text gemini.Text) string {
|
||||
list = false
|
||||
fmt.Fprint(&b, "</ul>\n")
|
||||
}
|
||||
switch l.(type) {
|
||||
switch l := l.(type) {
|
||||
case gemini.LineLink:
|
||||
link := l.(gemini.LineLink)
|
||||
url := html.EscapeString(link.URL)
|
||||
name := html.EscapeString(link.Name)
|
||||
url := html.EscapeString(l.URL)
|
||||
name := html.EscapeString(l.Name)
|
||||
if name == "" {
|
||||
name = url
|
||||
}
|
||||
@@ -54,29 +53,22 @@ func textToHTML(text gemini.Text) string {
|
||||
fmt.Fprint(&b, "</pre>\n")
|
||||
}
|
||||
case gemini.LinePreformattedText:
|
||||
text := string(l.(gemini.LinePreformattedText))
|
||||
fmt.Fprintf(&b, "%s\n", html.EscapeString(text))
|
||||
fmt.Fprintf(&b, "%s\n", html.EscapeString(string(l)))
|
||||
case gemini.LineHeading1:
|
||||
text := string(l.(gemini.LineHeading1))
|
||||
fmt.Fprintf(&b, "<h1>%s</h1>\n", html.EscapeString(text))
|
||||
fmt.Fprintf(&b, "<h1>%s</h1>\n", html.EscapeString(string(l)))
|
||||
case gemini.LineHeading2:
|
||||
text := string(l.(gemini.LineHeading2))
|
||||
fmt.Fprintf(&b, "<h2>%s</h2>\n", html.EscapeString(text))
|
||||
fmt.Fprintf(&b, "<h2>%s</h2>\n", html.EscapeString(string(l)))
|
||||
case gemini.LineHeading3:
|
||||
text := string(l.(gemini.LineHeading3))
|
||||
fmt.Fprintf(&b, "<h3>%s</h3>\n", html.EscapeString(text))
|
||||
fmt.Fprintf(&b, "<h3>%s</h3>\n", html.EscapeString(string(l)))
|
||||
case gemini.LineListItem:
|
||||
text := string(l.(gemini.LineListItem))
|
||||
fmt.Fprintf(&b, "<li>%s</li>\n", html.EscapeString(text))
|
||||
fmt.Fprintf(&b, "<li>%s</li>\n", html.EscapeString(string(l)))
|
||||
case gemini.LineQuote:
|
||||
text := string(l.(gemini.LineQuote))
|
||||
fmt.Fprintf(&b, "<blockquote>%s</blockquote>\n", html.EscapeString(text))
|
||||
fmt.Fprintf(&b, "<blockquote>%s</blockquote>\n", html.EscapeString(string(l)))
|
||||
case gemini.LineText:
|
||||
text := string(l.(gemini.LineText))
|
||||
if text == "" {
|
||||
if l == "" {
|
||||
fmt.Fprint(&b, "<br>\n")
|
||||
} else {
|
||||
fmt.Fprintf(&b, "<p>%s</p>\n", html.EscapeString(text))
|
||||
fmt.Fprintf(&b, "<p>%s</p>\n", html.EscapeString(string(l)))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,14 +3,9 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"crypto"
|
||||
"crypto/tls"
|
||||
"crypto/x509"
|
||||
"encoding/pem"
|
||||
"fmt"
|
||||
"io"
|
||||
"crypto/x509/pkix"
|
||||
"log"
|
||||
"os"
|
||||
"time"
|
||||
|
||||
"git.sr.ht/~adnano/go-gemini"
|
||||
@@ -18,20 +13,19 @@ import (
|
||||
|
||||
func main() {
|
||||
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 {
|
||||
log.Fatal(err)
|
||||
}
|
||||
server.CreateCertificate = func(hostname string) (tls.Certificate, error) {
|
||||
fmt.Println("Generating certificate for", hostname)
|
||||
cert, err := gemini.CreateCertificate(gemini.CertificateOptions{
|
||||
return gemini.CreateCertificate(gemini.CertificateOptions{
|
||||
Subject: pkix.Name{
|
||||
CommonName: hostname,
|
||||
},
|
||||
DNSNames: []string{hostname},
|
||||
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
|
||||
@@ -42,39 +36,3 @@ func main() {
|
||||
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
8
fs.go
@@ -33,7 +33,7 @@ func (fsh fsHandler) Respond(w *ResponseWriter, r *Request) {
|
||||
// Detect mimetype
|
||||
ext := path.Ext(p)
|
||||
mimetype := mime.TypeByExtension(ext)
|
||||
w.SetMimetype(mimetype)
|
||||
w.SetMediaType(mimetype)
|
||||
// Copy file to response writer
|
||||
io.Copy(w, f)
|
||||
}
|
||||
@@ -72,7 +72,7 @@ func ServeFile(w *ResponseWriter, fs FS, name string) {
|
||||
// Detect mimetype
|
||||
ext := path.Ext(name)
|
||||
mimetype := mime.TypeByExtension(ext)
|
||||
w.SetMimetype(mimetype)
|
||||
w.SetMediaType(mimetype)
|
||||
// Copy file to response writer
|
||||
io.Copy(w, f)
|
||||
}
|
||||
@@ -96,9 +96,9 @@ func openFile(p string) (File, error) {
|
||||
if stat.Mode().IsRegular() {
|
||||
return f, nil
|
||||
}
|
||||
return nil, ErrNotAFile
|
||||
return nil, os.ErrNotExist
|
||||
} else if !stat.Mode().IsRegular() {
|
||||
return nil, ErrNotAFile
|
||||
return nil, os.ErrNotExist
|
||||
}
|
||||
}
|
||||
return f, nil
|
||||
|
||||
100
gemini.go
100
gemini.go
@@ -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
|
||||
|
||||
import (
|
||||
"crypto/tls"
|
||||
"crypto/x509"
|
||||
"errors"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
var crlf = []byte("\r\n")
|
||||
|
||||
// Errors.
|
||||
var (
|
||||
ErrInvalidURL = errors.New("gemini: invalid URL")
|
||||
ErrInvalidResponse = errors.New("gemini: invalid response")
|
||||
ErrCertificateUnknown = errors.New("gemini: unknown certificate")
|
||||
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")
|
||||
ErrInvalidURL = errors.New("gemini: invalid URL")
|
||||
ErrInvalidResponse = errors.New("gemini: invalid response")
|
||||
ErrBodyNotAllowed = errors.New("gemini: response body not allowed")
|
||||
)
|
||||
|
||||
// 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
4
mux.go
@@ -138,14 +138,14 @@ func (mux *ServeMux) Respond(w *ResponseWriter, r *Request) {
|
||||
// If the given path is /tree and its handler is not registered,
|
||||
// redirect for /tree/.
|
||||
if u, ok := mux.redirectToPathSlash(path, r.URL); ok {
|
||||
Redirect(w, u.String())
|
||||
w.WriteHeader(StatusRedirect, u.String())
|
||||
return
|
||||
}
|
||||
|
||||
if path != r.URL.Path {
|
||||
u := *r.URL
|
||||
u.Path = path
|
||||
Redirect(w, u.String())
|
||||
w.WriteHeader(StatusRedirect, u.String())
|
||||
return
|
||||
}
|
||||
|
||||
|
||||
13
request.go
13
request.go
@@ -19,7 +19,9 @@ type Request struct {
|
||||
|
||||
// Certificate specifies the TLS certificate to use for the request.
|
||||
// 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
|
||||
|
||||
// RemoteAddr allows servers and other software to record the network
|
||||
@@ -39,15 +41,12 @@ func NewRequest(rawurl string) (*Request, error) {
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return NewRequestFromURL(u)
|
||||
return NewRequestFromURL(u), nil
|
||||
}
|
||||
|
||||
// NewRequestFromURL returns a new request for the given URL.
|
||||
// The host is inferred from the URL.
|
||||
func NewRequestFromURL(url *url.URL) (*Request, error) {
|
||||
if url.Scheme != "" && url.Scheme != "gemini" {
|
||||
return nil, ErrNotAGeminiURL
|
||||
}
|
||||
func NewRequestFromURL(url *url.URL) *Request {
|
||||
host := url.Host
|
||||
if url.Port() == "" {
|
||||
host += ":1965"
|
||||
@@ -55,7 +54,7 @@ func NewRequestFromURL(url *url.URL) (*Request, error) {
|
||||
return &Request{
|
||||
URL: url,
|
||||
Host: host,
|
||||
}, nil
|
||||
}
|
||||
}
|
||||
|
||||
// write writes the Gemini request to the provided buffered writer.
|
||||
|
||||
@@ -9,7 +9,7 @@ import (
|
||||
|
||||
// Response is a Gemini response.
|
||||
type Response struct {
|
||||
// Status represents the response status.
|
||||
// Status contains the response status code.
|
||||
Status 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 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
|
||||
|
||||
// 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 {
|
||||
return ErrInvalidResponse
|
||||
}
|
||||
// Default mime type of text/gemini; charset=utf-8
|
||||
if statusClass == StatusClassSuccess && meta == "" {
|
||||
meta = "text/gemini; charset=utf-8"
|
||||
}
|
||||
resp.Meta = meta
|
||||
|
||||
// Read terminating newline
|
||||
|
||||
207
server.go
207
server.go
@@ -3,7 +3,7 @@ package gemini
|
||||
import (
|
||||
"bufio"
|
||||
"crypto/tls"
|
||||
"crypto/x509"
|
||||
"errors"
|
||||
"log"
|
||||
"net"
|
||||
"net/url"
|
||||
@@ -18,6 +18,13 @@ type Server struct {
|
||||
// If Addr is empty, the server will listen on the address ":1965".
|
||||
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 CertificateStore
|
||||
|
||||
@@ -25,27 +32,26 @@ type Server struct {
|
||||
// if the current one is expired or missing.
|
||||
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
|
||||
responders map[responderKey]Responder
|
||||
hosts map[string]bool
|
||||
}
|
||||
|
||||
type responderKey struct {
|
||||
scheme string
|
||||
hostname string
|
||||
wildcard bool
|
||||
}
|
||||
|
||||
// Register registers a responder for the given pattern.
|
||||
//
|
||||
// Patterns must be in the form of hostname or scheme://hostname
|
||||
// (e.g. gemini://example.com).
|
||||
// If no scheme is specified, a default scheme of gemini:// is assumed.
|
||||
//
|
||||
// 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)
|
||||
// Patterns must be in the form of "hostname" or "scheme://hostname".
|
||||
// If no scheme is specified, a scheme of "gemini://" is implied.
|
||||
// Wildcard patterns are supported (e.g. "*.example.com").
|
||||
func (s *Server) Register(pattern string, responder Responder) {
|
||||
if pattern == "" {
|
||||
panic("gemini: invalid pattern")
|
||||
@@ -55,6 +61,7 @@ func (s *Server) Register(pattern string, responder Responder) {
|
||||
}
|
||||
if s.responders == nil {
|
||||
s.responders = map[responderKey]Responder{}
|
||||
s.hosts = map[string]bool{}
|
||||
}
|
||||
|
||||
split := strings.SplitN(pattern, "://", 2)
|
||||
@@ -66,16 +73,12 @@ func (s *Server) Register(pattern string, responder Responder) {
|
||||
key.scheme = "gemini"
|
||||
key.hostname = split[0]
|
||||
}
|
||||
split = strings.SplitN(key.hostname, ".", 2)
|
||||
if len(split) == 2 && split[0] == "*" {
|
||||
key.hostname = split[1]
|
||||
key.wildcard = true
|
||||
}
|
||||
|
||||
if _, ok := s.responders[key]; ok {
|
||||
panic("gemini: multiple registrations for " + pattern)
|
||||
}
|
||||
s.responders[key] = responder
|
||||
s.hosts[key.hostname] = true
|
||||
}
|
||||
|
||||
// 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 {
|
||||
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)
|
||||
continue
|
||||
}
|
||||
@@ -135,22 +138,49 @@ func (s *Server) Serve(l net.Listener) error {
|
||||
}
|
||||
|
||||
func (s *Server) getCertificate(h *tls.ClientHelloInfo) (*tls.Certificate, error) {
|
||||
cert, err := s.Certificates.Lookup(h.ServerName)
|
||||
switch err {
|
||||
case ErrCertificateExpired, ErrCertificateUnknown:
|
||||
if s.CreateCertificate != nil {
|
||||
cert, err := s.CreateCertificate(h.ServerName)
|
||||
if err == nil {
|
||||
s.Certificates.Add(h.ServerName, cert)
|
||||
}
|
||||
return &cert, err
|
||||
cert, err := s.getCertificateFor(h.ServerName)
|
||||
if err != nil {
|
||||
// Try wildcard
|
||||
wildcard := strings.SplitN(h.ServerName, ".", 2)
|
||||
if len(wildcard) == 2 {
|
||||
cert, err = s.getCertificateFor("*." + wildcard[1])
|
||||
}
|
||||
}
|
||||
return cert, err
|
||||
}
|
||||
|
||||
func (s *Server) getCertificateFor(hostname string) (*tls.Certificate, error) {
|
||||
if _, ok := s.hosts[hostname]; !ok {
|
||||
return nil, 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.
|
||||
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)
|
||||
w := newResponseWriter(conn)
|
||||
// Read requested URL
|
||||
@@ -162,25 +192,39 @@ func (s *Server) respond(conn net.Conn) {
|
||||
if b, err := r.ReadByte(); err != nil {
|
||||
return
|
||||
} else if b != '\n' {
|
||||
w.WriteHeader(StatusBadRequest, "Bad request")
|
||||
w.WriteStatus(StatusBadRequest)
|
||||
}
|
||||
// Trim carriage return
|
||||
rawurl = rawurl[:len(rawurl)-1]
|
||||
// Ensure URL is valid
|
||||
if len(rawurl) > 1024 {
|
||||
w.WriteHeader(StatusBadRequest, "Bad request")
|
||||
w.WriteStatus(StatusBadRequest)
|
||||
} else if url, err := url.Parse(rawurl); err != nil || url.User != nil {
|
||||
// Note that we return an error status if User is specified in the URL
|
||||
w.WriteHeader(StatusBadRequest, "Bad request")
|
||||
w.WriteStatus(StatusBadRequest)
|
||||
} else {
|
||||
// If no scheme is specified, assume a default scheme of gemini://
|
||||
if url.Scheme == "" {
|
||||
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{
|
||||
URL: url,
|
||||
RemoteAddr: conn.RemoteAddr(),
|
||||
TLS: conn.(*tls.Conn).ConnectionState(),
|
||||
URL: url,
|
||||
RemoteAddr: conn.RemoteAddr(),
|
||||
TLS: connState,
|
||||
Certificate: cert,
|
||||
}
|
||||
resp := s.responder(req)
|
||||
if resp != nil {
|
||||
@@ -194,24 +238,32 @@ func (s *Server) respond(conn net.Conn) {
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
wildcard := strings.SplitN(r.URL.Hostname(), ".", 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 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.
|
||||
type ResponseWriter struct {
|
||||
b *bufio.Writer
|
||||
bodyAllowed bool
|
||||
wroteHeader bool
|
||||
mimetype string
|
||||
mediatype string
|
||||
}
|
||||
|
||||
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 is equivalent to WriteHeader(status, status.Message())
|
||||
func (w *ResponseWriter) WriteStatus(status Status) {
|
||||
w.WriteHeader(status, status.Message())
|
||||
}
|
||||
|
||||
// SetMimetype sets the mimetype that will be written for a successful response.
|
||||
// The provided mimetype will only be used if Write is called without calling
|
||||
// WriteHeader.
|
||||
// SetMediaType sets the media type that will be written for a successful response.
|
||||
// If the mimetype is not set, it will default to "text/gemini".
|
||||
func (w *ResponseWriter) SetMimetype(mimetype string) {
|
||||
w.mimetype = mimetype
|
||||
func (w *ResponseWriter) SetMediaType(mediatype string) {
|
||||
w.mediatype = mediatype
|
||||
}
|
||||
|
||||
// Write writes the response body.
|
||||
// If the response status does not allow for a response body, Write returns
|
||||
// ErrBodyNotAllowed.
|
||||
//
|
||||
// If WriteHeader has not yet been called, Write calls
|
||||
// WriteHeader(StatusSuccess, mimetype) where mimetype is the mimetype set in
|
||||
// SetMimetype. If no mimetype is set, a default of "text/gemini" will be used.
|
||||
// If the response header has not yet been written, Write calls WriteHeader
|
||||
// with StatusSuccess and the mimetype set in SetMimetype.
|
||||
func (w *ResponseWriter) Write(b []byte) (int, error) {
|
||||
if !w.wroteHeader {
|
||||
mimetype := w.mimetype
|
||||
if mimetype == "" {
|
||||
mimetype = "text/gemini"
|
||||
mediatype := w.mediatype
|
||||
if mediatype == "" {
|
||||
mediatype = "text/gemini"
|
||||
}
|
||||
w.WriteHeader(StatusSuccess, mimetype)
|
||||
w.WriteHeader(StatusSuccess, mediatype)
|
||||
}
|
||||
if !w.bodyAllowed {
|
||||
return 0, ErrBodyNotAllowed
|
||||
@@ -283,51 +334,29 @@ type Responder interface {
|
||||
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.
|
||||
type ResponderFunc func(*ResponseWriter, *Request)
|
||||
|
||||
func (f ResponderFunc) Respond(w *ResponseWriter, r *Request) {
|
||||
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
|
||||
}
|
||||
|
||||
@@ -8,7 +8,7 @@ const (
|
||||
StatusSensitiveInput Status = 11
|
||||
StatusSuccess Status = 20
|
||||
StatusRedirect Status = 30
|
||||
StatusRedirectPermanent Status = 31
|
||||
StatusPermanentRedirect Status = 31
|
||||
StatusTemporaryFailure Status = 40
|
||||
StatusServerUnavailable Status = 41
|
||||
StatusCGIError Status = 42
|
||||
@@ -52,7 +52,7 @@ func (s Status) Message() string {
|
||||
return "Success"
|
||||
case StatusRedirect:
|
||||
return "Redirect"
|
||||
case StatusRedirectPermanent:
|
||||
case StatusPermanentRedirect:
|
||||
return "Permanent redirect"
|
||||
case StatusTemporaryFailure:
|
||||
return "Temporary failure"
|
||||
|
||||
88
text.go
88
text.go
@@ -87,58 +87,68 @@ func (l LineText) line() {}
|
||||
// Text represents a Gemini text response.
|
||||
type Text []Line
|
||||
|
||||
// Parse parses Gemini text from the provided io.Reader.
|
||||
func Parse(r io.Reader) Text {
|
||||
const spacetab = " \t"
|
||||
// ParseText parses Gemini text from the provided io.Reader.
|
||||
func ParseText(r io.Reader) 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
|
||||
scanner := bufio.NewScanner(r)
|
||||
for scanner.Scan() {
|
||||
line := scanner.Text()
|
||||
if strings.HasPrefix(line, "```") {
|
||||
var line Line
|
||||
text := scanner.Text()
|
||||
if strings.HasPrefix(text, "```") {
|
||||
pre = !pre
|
||||
line = line[3:]
|
||||
t = append(t, LinePreformattingToggle(line))
|
||||
text = text[3:]
|
||||
line = LinePreformattingToggle(text)
|
||||
} else if pre {
|
||||
t = append(t, LinePreformattedText(line))
|
||||
} else if strings.HasPrefix(line, "=>") {
|
||||
line = line[2:]
|
||||
line = strings.TrimLeft(line, spacetab)
|
||||
split := strings.IndexAny(line, spacetab)
|
||||
line = LinePreformattedText(text)
|
||||
} else if strings.HasPrefix(text, "=>") {
|
||||
text = text[2:]
|
||||
text = strings.TrimLeft(text, spacetab)
|
||||
split := strings.IndexAny(text, spacetab)
|
||||
if split == -1 {
|
||||
// line is a URL
|
||||
t = append(t, LineLink{URL: line})
|
||||
// text is a URL
|
||||
line = LineLink{URL: text}
|
||||
} else {
|
||||
url := line[:split]
|
||||
name := line[split:]
|
||||
url := text[:split]
|
||||
name := text[split:]
|
||||
name = strings.TrimLeft(name, spacetab)
|
||||
t = append(t, LineLink{url, name})
|
||||
line = LineLink{url, name}
|
||||
}
|
||||
} else if strings.HasPrefix(line, "*") {
|
||||
line = line[1:]
|
||||
line = strings.TrimLeft(line, spacetab)
|
||||
t = append(t, LineListItem(line))
|
||||
} else if strings.HasPrefix(line, "###") {
|
||||
line = line[3:]
|
||||
line = strings.TrimLeft(line, spacetab)
|
||||
t = append(t, LineHeading3(line))
|
||||
} else if strings.HasPrefix(line, "##") {
|
||||
line = line[2:]
|
||||
line = strings.TrimLeft(line, spacetab)
|
||||
t = append(t, LineHeading2(line))
|
||||
} else if strings.HasPrefix(line, "#") {
|
||||
line = line[1:]
|
||||
line = strings.TrimLeft(line, spacetab)
|
||||
t = append(t, LineHeading1(line))
|
||||
} else if strings.HasPrefix(line, ">") {
|
||||
line = line[1:]
|
||||
line = strings.TrimLeft(line, spacetab)
|
||||
t = append(t, LineQuote(line))
|
||||
} else if strings.HasPrefix(text, "*") {
|
||||
text = text[1:]
|
||||
text = strings.TrimLeft(text, spacetab)
|
||||
line = LineListItem(text)
|
||||
} else if strings.HasPrefix(text, "###") {
|
||||
text = text[3:]
|
||||
text = strings.TrimLeft(text, spacetab)
|
||||
line = LineHeading3(text)
|
||||
} else if strings.HasPrefix(text, "##") {
|
||||
text = text[2:]
|
||||
text = strings.TrimLeft(text, spacetab)
|
||||
line = LineHeading2(text)
|
||||
} else if strings.HasPrefix(text, "#") {
|
||||
text = text[1:]
|
||||
text = strings.TrimLeft(text, spacetab)
|
||||
line = LineHeading1(text)
|
||||
} else if strings.HasPrefix(text, ">") {
|
||||
text = text[1:]
|
||||
text = strings.TrimLeft(text, spacetab)
|
||||
line = LineQuote(text)
|
||||
} 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.
|
||||
|
||||
191
tofu.go
191
tofu.go
@@ -3,45 +3,76 @@ package gemini
|
||||
import (
|
||||
"bufio"
|
||||
"crypto/sha512"
|
||||
"crypto/x509"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
"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.
|
||||
// The zero value for KnownHosts is an empty list ready to use.
|
||||
type KnownHosts struct {
|
||||
hosts map[string]certInfo
|
||||
file *os.File
|
||||
hosts map[string]Fingerprint
|
||||
out io.Writer
|
||||
}
|
||||
|
||||
// LoadDefault loads the known hosts from the default known hosts path, which is
|
||||
// $XDG_DATA_HOME/gemini/known_hosts.
|
||||
// It creates the path and any of its parent directories if they do not exist.
|
||||
// KnownHosts will append to the file whenever a certificate is added.
|
||||
func (k *KnownHosts) LoadDefault() error {
|
||||
path, err := defaultKnownHostsPath()
|
||||
if err != nil {
|
||||
return err
|
||||
// SetOutput sets the output to which new known hosts will be written to.
|
||||
func (k *KnownHosts) SetOutput(w io.Writer) {
|
||||
k.out = w
|
||||
}
|
||||
|
||||
// Add adds a known host to the list of known hosts.
|
||||
func (k *KnownHosts) Add(hostname string, fingerprint Fingerprint) {
|
||||
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.
|
||||
// It creates the path and any of its parent directories if they do not exist.
|
||||
// KnownHosts will append to the file whenever a certificate is added.
|
||||
func (k *KnownHosts) Load(path string) error {
|
||||
if dir := filepath.Dir(path); dir != "." {
|
||||
err := os.MkdirAll(dir, 0755)
|
||||
if err != nil {
|
||||
// Lookup returns the fingerprint of the certificate corresponding to
|
||||
// the given hostname.
|
||||
func (k *KnownHosts) Lookup(hostname string) (Fingerprint, bool) {
|
||||
c, ok := k.hosts[hostname]
|
||||
return c, ok
|
||||
}
|
||||
|
||||
// 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 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)
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -53,66 +84,15 @@ func (k *KnownHosts) Load(path string) error {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
k.file = f
|
||||
k.out = f
|
||||
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.
|
||||
// Invalid lines are ignored.
|
||||
// Invalid entries are ignored.
|
||||
func (k *KnownHosts) Parse(r io.Reader) {
|
||||
if k.hosts == nil {
|
||||
k.hosts = map[string]certInfo{}
|
||||
k.hosts = map[string]Fingerprint{}
|
||||
}
|
||||
scanner := bufio.NewScanner(r)
|
||||
for scanner.Scan() {
|
||||
@@ -128,39 +108,30 @@ func (k *KnownHosts) Parse(r io.Reader) {
|
||||
continue
|
||||
}
|
||||
fingerprint := parts[2]
|
||||
|
||||
expires, err := strconv.ParseInt(parts[3], 10, 0)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
|
||||
k.hosts[hostname] = certInfo{
|
||||
Algorithm: algorithm,
|
||||
Fingerprint: fingerprint,
|
||||
Expires: expires,
|
||||
k.hosts[hostname] = Fingerprint{
|
||||
Algorithm: algorithm,
|
||||
Hex: fingerprint,
|
||||
Expires: expires,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Write writes the known hosts to the provided io.Writer.
|
||||
func (k *KnownHosts) Write(w io.Writer) {
|
||||
for h, c := range k.hosts {
|
||||
appendKnownHost(w, h, c)
|
||||
}
|
||||
// Fingerprint represents a fingerprint using a certain algorithm.
|
||||
type Fingerprint struct {
|
||||
Algorithm string // fingerprint algorithm e.g. SHA-512
|
||||
Hex string // fingerprint in hexadecimal, with ':' between each octet
|
||||
Expires int64 // unix time of the fingerprint expiration date
|
||||
}
|
||||
|
||||
type certInfo struct {
|
||||
Algorithm string // fingerprint algorithm e.g. SHA-512
|
||||
Fingerprint string // fingerprint in hexadecimal, with ':' between each octet
|
||||
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)
|
||||
// NewFingerprint returns the SHA-512 fingerprint of the provided raw data.
|
||||
func NewFingerprint(raw []byte, expires time.Time) Fingerprint {
|
||||
sum512 := sha512.Sum512(raw)
|
||||
var b strings.Builder
|
||||
for i, f := range sum512 {
|
||||
if i > 0 {
|
||||
@@ -168,29 +139,9 @@ func Fingerprint(cert *x509.Certificate) string {
|
||||
}
|
||||
fmt.Fprintf(&b, "%02X", f)
|
||||
}
|
||||
return b.String()
|
||||
}
|
||||
|
||||
// defaultKnownHostsPath returns the default known_hosts path.
|
||||
// The default path is $XDG_DATA_HOME/gemini/known_hosts
|
||||
func defaultKnownHostsPath() (string, error) {
|
||||
dataDir, err := userDataDir()
|
||||
if err != nil {
|
||||
return "", err
|
||||
return Fingerprint{
|
||||
Algorithm: "SHA-512",
|
||||
Hex: b.String(),
|
||||
Expires: expires.Unix(),
|
||||
}
|
||||
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
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user