Compare commits
45 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
611a7d54c0 | ||
|
|
16739d20d0 | ||
|
|
24e488a4cb | ||
|
|
e0ac1685d2 | ||
|
|
82688746dd | ||
|
|
3b9cc7f168 | ||
|
|
3c7940f153 | ||
|
|
8ee55ee009 | ||
|
|
7ee0ea8b7f | ||
|
|
ab1db34f02 | ||
|
|
35e984fbba | ||
|
|
cab23032c0 | ||
|
|
4b653032e4 | ||
|
|
0c75e5d5ad | ||
|
|
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 |
116
cert.go
116
cert.go
@@ -2,12 +2,14 @@ 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"
|
"encoding/pem"
|
||||||
"log"
|
|
||||||
"math/big"
|
"math/big"
|
||||||
"net"
|
"net"
|
||||||
"os"
|
"os"
|
||||||
@@ -16,19 +18,22 @@ import (
|
|||||||
"time"
|
"time"
|
||||||
)
|
)
|
||||||
|
|
||||||
// CertificateStore maps certificate scopes to certificates.
|
// CertificateDir maps certificate scopes to certificates.
|
||||||
// The zero value of CertificateStore is an empty store ready to use.
|
type CertificateStore map[string]tls.Certificate
|
||||||
type CertificateStore struct {
|
|
||||||
store map[string]tls.Certificate
|
// CertificateDir represents a certificate store optionally loaded from a directory.
|
||||||
dir bool
|
// The zero value of CertificateDir is an empty store ready to use.
|
||||||
path string
|
type CertificateDir struct {
|
||||||
|
CertificateStore
|
||||||
|
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.
|
||||||
// It tries to parse the certificate if it is not already parsed.
|
// It tries to parse the certificate if it is not already parsed.
|
||||||
func (c *CertificateStore) Add(scope string, cert tls.Certificate) {
|
func (c *CertificateDir) Add(scope string, cert tls.Certificate) {
|
||||||
if c.store == nil {
|
if c.CertificateStore == nil {
|
||||||
c.store = map[string]tls.Certificate{}
|
c.CertificateStore = CertificateStore{}
|
||||||
}
|
}
|
||||||
// Parse certificate if not already parsed
|
// Parse certificate if not already parsed
|
||||||
if cert.Leaf == nil {
|
if cert.Leaf == nil {
|
||||||
@@ -37,29 +42,27 @@ func (c *CertificateStore) Add(scope string, cert tls.Certificate) {
|
|||||||
cert.Leaf = parsed
|
cert.Leaf = parsed
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
c.CertificateStore[scope] = cert
|
||||||
|
}
|
||||||
|
|
||||||
|
// Write writes the provided certificate to the certificate directory.
|
||||||
|
func (c *CertificateDir) Write(scope string, cert tls.Certificate) error {
|
||||||
if c.dir {
|
if c.dir {
|
||||||
// Write certificates
|
// Escape slash character
|
||||||
log.Printf("gemini: Writing certificate for %s to %s", scope, c.path)
|
scope = strings.ReplaceAll(scope, "/", ":")
|
||||||
certPath := filepath.Join(c.path, scope+".crt")
|
certPath := filepath.Join(c.path, scope+".crt")
|
||||||
keyPath := filepath.Join(c.path, scope+".key")
|
keyPath := filepath.Join(c.path, scope+".key")
|
||||||
if err := WriteCertificate(cert, certPath, keyPath); err != nil {
|
if err := WriteCertificate(cert, certPath, keyPath); err != nil {
|
||||||
log.Printf("gemini: Failed to write certificate for %s: %s", scope, err)
|
return err
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
c.store[scope] = cert
|
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 *CertificateDir) Lookup(scope string) (tls.Certificate, bool) {
|
||||||
cert, ok := c.store[scope]
|
cert, ok := c.CertificateStore[scope]
|
||||||
if !ok {
|
return cert, ok
|
||||||
return nil, ErrCertificateNotFound
|
|
||||||
}
|
|
||||||
// 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.
|
||||||
@@ -68,7 +71,7 @@ func (c *CertificateStore) Lookup(scope string) (*tls.Certificate, error) {
|
|||||||
// 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.
|
// New certificates will be written to this directory.
|
||||||
func (c *CertificateStore) Load(path string) error {
|
func (c *CertificateDir) 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 {
|
||||||
return err
|
return err
|
||||||
@@ -80,6 +83,8 @@ func (c *CertificateStore) Load(path string) error {
|
|||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
scope := strings.TrimSuffix(filepath.Base(crtPath), ".crt")
|
scope := strings.TrimSuffix(filepath.Base(crtPath), ".crt")
|
||||||
|
// Unescape slash character
|
||||||
|
scope = strings.ReplaceAll(scope, ":", "/")
|
||||||
c.Add(scope, cert)
|
c.Add(scope, cert)
|
||||||
}
|
}
|
||||||
c.dir = true
|
c.dir = true
|
||||||
@@ -87,11 +92,37 @@ func (c *CertificateStore) Load(path string) error {
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// CertificateOptions configures how a certificate is created.
|
// SetDir sets the directory that new certificates will be written to.
|
||||||
|
func (c *CertificateDir) SetDir(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.
|
||||||
@@ -109,15 +140,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)
|
||||||
@@ -138,9 +181,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
|
||||||
}
|
}
|
||||||
|
|||||||
85
client.go
85
client.go
@@ -4,20 +4,24 @@ import (
|
|||||||
"bufio"
|
"bufio"
|
||||||
"crypto/tls"
|
"crypto/tls"
|
||||||
"crypto/x509"
|
"crypto/x509"
|
||||||
|
"errors"
|
||||||
"net"
|
"net"
|
||||||
"net/url"
|
"net/url"
|
||||||
"path"
|
"path"
|
||||||
"strings"
|
"strings"
|
||||||
|
"sync"
|
||||||
"time"
|
"time"
|
||||||
)
|
)
|
||||||
|
|
||||||
// Client is a Gemini client.
|
// Client is a Gemini client.
|
||||||
|
//
|
||||||
|
// Clients are safe for concurrent use by multiple goroutines.
|
||||||
type Client struct {
|
type Client struct {
|
||||||
// KnownHosts is a list of known hosts.
|
// KnownHosts is a list of known hosts.
|
||||||
KnownHosts KnownHosts
|
KnownHosts KnownHostsFile
|
||||||
|
|
||||||
// Certificates stores client-side certificates.
|
// Certificates stores client-side certificates.
|
||||||
Certificates CertificateStore
|
Certificates CertificateDir
|
||||||
|
|
||||||
// Timeout specifies a time limit for requests made by this
|
// Timeout specifies a time limit for requests made by this
|
||||||
// Client. The timeout includes connection time and reading
|
// Client. The timeout includes connection time and reading
|
||||||
@@ -39,15 +43,14 @@ type Client struct {
|
|||||||
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 is called to determine whether the client
|
// TrustCertificate is called to determine whether the client
|
||||||
// should trust a certificate it has not seen before.
|
// should trust a certificate it has not seen before.
|
||||||
@@ -59,6 +62,8 @@ type Client struct {
|
|||||||
// If TrustCertificate returns TrustAlways, the certificate will also be
|
// If TrustCertificate returns TrustAlways, the certificate will also be
|
||||||
// written to the known hosts file.
|
// written to the known hosts file.
|
||||||
TrustCertificate func(hostname string, cert *x509.Certificate) Trust
|
TrustCertificate func(hostname string, cert *x509.Certificate) Trust
|
||||||
|
|
||||||
|
mu sync.Mutex
|
||||||
}
|
}
|
||||||
|
|
||||||
// Get performs a Gemini request for the given url.
|
// Get performs a Gemini request for the given url.
|
||||||
@@ -72,10 +77,20 @@ func (c *Client) Get(url string) (*Response, error) {
|
|||||||
|
|
||||||
// Do performs a Gemini request and returns a Gemini response.
|
// Do performs a Gemini request and returns a Gemini response.
|
||||||
func (c *Client) Do(req *Request) (*Response, error) {
|
func (c *Client) Do(req *Request) (*Response, error) {
|
||||||
|
c.mu.Lock()
|
||||||
|
defer c.mu.Unlock()
|
||||||
|
|
||||||
return c.do(req, nil)
|
return c.do(req, nil)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c *Client) do(req *Request, via []*Request) (*Response, error) {
|
func (c *Client) do(req *Request, via []*Request) (*Response, error) {
|
||||||
|
// Extract hostname
|
||||||
|
colonPos := strings.LastIndex(req.Host, ":")
|
||||||
|
if colonPos == -1 {
|
||||||
|
colonPos = len(req.Host)
|
||||||
|
}
|
||||||
|
hostname := req.Host[:colonPos]
|
||||||
|
|
||||||
// Connect to the host
|
// Connect to the host
|
||||||
config := &tls.Config{
|
config := &tls.Config{
|
||||||
InsecureSkipVerify: true,
|
InsecureSkipVerify: true,
|
||||||
@@ -86,11 +101,13 @@ func (c *Client) do(req *Request, via []*Request) (*Response, error) {
|
|||||||
VerifyConnection: func(cs tls.ConnectionState) error {
|
VerifyConnection: func(cs tls.ConnectionState) error {
|
||||||
return c.verifyConnection(req, cs)
|
return c.verifyConnection(req, cs)
|
||||||
},
|
},
|
||||||
|
ServerName: hostname,
|
||||||
}
|
}
|
||||||
conn, err := tls.Dial("tcp", req.Host, config)
|
netConn, err := (&net.Dialer{}).DialContext(req.Context, "tcp", req.Host)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
conn := tls.Client(netConn, config)
|
||||||
// Set connection deadline
|
// Set connection deadline
|
||||||
if d := c.Timeout; d != 0 {
|
if d := c.Timeout; d != 0 {
|
||||||
conn.SetDeadline(time.Now().Add(d))
|
conn.SetDeadline(time.Now().Add(d))
|
||||||
@@ -108,6 +125,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()
|
||||||
|
|
||||||
@@ -125,20 +143,22 @@ 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)
|
||||||
|
c.Certificates.Write(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 {
|
||||||
input, ok := c.GetInput(resp.Meta, resp.Status == StatusSensitiveInput)
|
input, ok := c.GetInput(resp.Meta, resp.Status == StatusSensitiveInput)
|
||||||
if ok {
|
if ok {
|
||||||
req.URL.ForceQuery = true
|
req.URL.ForceQuery = true
|
||||||
req.URL.RawQuery = url.QueryEscape(input)
|
req.URL.RawQuery = QueryEscape(input)
|
||||||
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 {
|
||||||
@@ -151,23 +171,17 @@ 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)
|
||||||
|
redirect.Context = req.Context
|
||||||
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
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -180,11 +194,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)
|
||||||
@@ -211,22 +228,30 @@ func (c *Client) verifyConnection(req *Request, cs tls.ConnectionState) error {
|
|||||||
if c.InsecureSkipTrust {
|
if c.InsecureSkipTrust {
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// Check the known hosts
|
// Check the known hosts
|
||||||
err := c.KnownHosts.Lookup(hostname, cert)
|
knownHost, ok := c.KnownHosts.Lookup(hostname)
|
||||||
switch err {
|
if !ok || !time.Now().Before(knownHost.Expires) {
|
||||||
case ErrCertificateExpired, ErrCertificateNotFound:
|
|
||||||
// See if the client trusts the certificate
|
// See if the client trusts the certificate
|
||||||
if c.TrustCertificate != nil {
|
if c.TrustCertificate != nil {
|
||||||
switch c.TrustCertificate(hostname, cert) {
|
switch c.TrustCertificate(hostname, cert) {
|
||||||
case TrustOnce:
|
case TrustOnce:
|
||||||
c.KnownHosts.AddTemporary(hostname, cert)
|
fingerprint := NewFingerprint(cert.Raw, cert.NotAfter)
|
||||||
|
c.KnownHosts.Add(hostname, fingerprint)
|
||||||
return nil
|
return nil
|
||||||
case TrustAlways:
|
case TrustAlways:
|
||||||
c.KnownHosts.Add(hostname, cert)
|
fingerprint := NewFingerprint(cert.Raw, cert.NotAfter)
|
||||||
|
c.KnownHosts.Add(hostname, fingerprint)
|
||||||
|
c.KnownHosts.Write(hostname, fingerprint)
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return ErrCertificateNotTrusted
|
return errors.New("gemini: certificate not trusted")
|
||||||
}
|
}
|
||||||
return err
|
|
||||||
|
fingerprint := NewFingerprint(cert.Raw, cert.NotAfter)
|
||||||
|
if knownHost.Hex == fingerprint.Hex {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
return errors.New("gemini: fingerprint does not match")
|
||||||
}
|
}
|
||||||
|
|||||||
55
doc.go
55
doc.go
@@ -1,55 +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
|
|
||||||
}
|
|
||||||
defer resp.Body.Close()
|
|
||||||
// ...
|
|
||||||
|
|
||||||
For control over client behavior, create a Client:
|
|
||||||
|
|
||||||
client := &gemini.Client{}
|
|
||||||
resp, err := client.Get("gemini://example.com")
|
|
||||||
if err != nil {
|
|
||||||
// handle error
|
|
||||||
}
|
|
||||||
// ...
|
|
||||||
|
|
||||||
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
|
|
||||||
138
examples/auth.go
138
examples/auth.go
@@ -3,47 +3,44 @@
|
|||||||
package main
|
package main
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"crypto/sha512"
|
||||||
|
"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"
|
||||||
)
|
)
|
||||||
|
|
||||||
type user struct {
|
type User struct {
|
||||||
password string // TODO: use hashes
|
Name string
|
||||||
admin bool
|
|
||||||
}
|
|
||||||
|
|
||||||
type session struct {
|
|
||||||
username string
|
|
||||||
authorized bool // whether or not the password was supplied
|
|
||||||
}
|
}
|
||||||
|
|
||||||
var (
|
var (
|
||||||
// Map of usernames to user data
|
// Map of certificate hashes to users
|
||||||
logins = map[string]user{
|
users = map[string]*User{}
|
||||||
"admin": {"p@ssw0rd", true}, // NOTE: These are bad passwords!
|
|
||||||
"user1": {"password1", false},
|
|
||||||
"user2": {"password2", false},
|
|
||||||
}
|
|
||||||
|
|
||||||
// Map of certificate fingerprints to sessions
|
|
||||||
sessions = map[string]*session{}
|
|
||||||
)
|
)
|
||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
var mux gemini.ServeMux
|
var mux gemini.ServeMux
|
||||||
mux.HandleFunc("/", login)
|
mux.HandleFunc("/", profile)
|
||||||
mux.HandleFunc("/password", loginPassword)
|
mux.HandleFunc("/username", changeUsername)
|
||||||
mux.HandleFunc("/profile", profile)
|
|
||||||
mux.HandleFunc("/admin", admin)
|
|
||||||
mux.HandleFunc("/logout", logout)
|
|
||||||
|
|
||||||
var server gemini.Server
|
var server gemini.Server
|
||||||
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,92 +48,37 @@ func main() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func getSession(crt *x509.Certificate) (*session, bool) {
|
func fingerprint(cert *x509.Certificate) string {
|
||||||
fingerprint := gemini.Fingerprint(crt)
|
b := sha512.Sum512(cert.Raw)
|
||||||
session, ok := sessions[fingerprint]
|
return string(b[:])
|
||||||
return session, ok
|
|
||||||
}
|
|
||||||
|
|
||||||
func login(w *gemini.ResponseWriter, r *gemini.Request) {
|
|
||||||
cert, ok := gemini.Certificate(w, r)
|
|
||||||
if !ok {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
username, ok := gemini.Input(w, r, "Username")
|
|
||||||
if !ok {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
fingerprint := gemini.Fingerprint(cert)
|
|
||||||
sessions[fingerprint] = &session{
|
|
||||||
username: username,
|
|
||||||
}
|
|
||||||
w.WriteHeader(gemini.StatusRedirect, "/password")
|
|
||||||
}
|
|
||||||
|
|
||||||
func loginPassword(w *gemini.ResponseWriter, r *gemini.Request) {
|
|
||||||
cert, ok := gemini.Certificate(w, r)
|
|
||||||
if !ok {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
session, ok := getSession(cert)
|
|
||||||
if !ok {
|
|
||||||
w.WriteStatus(gemini.StatusCertificateNotAuthorized)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
password, ok := gemini.SensitiveInput(w, r, "Password")
|
|
||||||
if !ok {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
expected := logins[session.username].password
|
|
||||||
if password == expected {
|
|
||||||
session.authorized = true
|
|
||||||
w.WriteHeader(gemini.StatusRedirect, "/profile")
|
|
||||||
} else {
|
|
||||||
gemini.SensitiveInput(w, r, "Wrong password. Try again")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func logout(w *gemini.ResponseWriter, r *gemini.Request) {
|
|
||||||
cert, ok := gemini.Certificate(w, r)
|
|
||||||
if !ok {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
fingerprint := gemini.Fingerprint(cert)
|
|
||||||
delete(sessions, fingerprint)
|
|
||||||
fmt.Fprintln(w, "Successfully logged out.")
|
|
||||||
}
|
}
|
||||||
|
|
||||||
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)
|
fingerprint := fingerprint(r.Certificate.Leaf)
|
||||||
|
user, ok := users[fingerprint]
|
||||||
if !ok {
|
if !ok {
|
||||||
w.WriteStatus(gemini.StatusCertificateNotAuthorized)
|
user = &User{}
|
||||||
return
|
users[fingerprint] = user
|
||||||
}
|
}
|
||||||
user := logins[session.username]
|
fmt.Fprintln(w, "Username:", user.Name)
|
||||||
fmt.Fprintln(w, "Username:", session.username)
|
fmt.Fprintln(w, "=> /username Change username")
|
||||||
fmt.Fprintln(w, "Admin:", user.admin)
|
|
||||||
fmt.Fprintln(w, "=> /logout Logout")
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func admin(w *gemini.ResponseWriter, r *gemini.Request) {
|
func changeUsername(w *gemini.ResponseWriter, r *gemini.Request) {
|
||||||
cert, ok := gemini.Certificate(w, r)
|
if r.Certificate == nil {
|
||||||
|
w.WriteStatus(gemini.StatusCertificateRequired)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
username, ok := gemini.Input(r)
|
||||||
if !ok {
|
if !ok {
|
||||||
|
w.WriteHeader(gemini.StatusInput, "Username")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
session, ok := getSession(cert)
|
users[fingerprint(r.Certificate.Leaf)].Name = username
|
||||||
if !ok {
|
w.WriteHeader(gemini.StatusRedirect, "/")
|
||||||
w.WriteStatus(gemini.StatusCertificateNotAuthorized)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
user := logins[session.username]
|
|
||||||
if !user.admin {
|
|
||||||
w.WriteStatus(gemini.StatusCertificateNotAuthorized)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
fmt.Fprintln(w, "Welcome to the admin portal.")
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -10,9 +10,11 @@ import (
|
|||||||
"io/ioutil"
|
"io/ioutil"
|
||||||
"log"
|
"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:
|
const trustPrompt = `The certificate offered by %s is of unknown trust. Its fingerprint is:
|
||||||
@@ -30,10 +32,11 @@ var (
|
|||||||
)
|
)
|
||||||
|
|
||||||
func init() {
|
func init() {
|
||||||
client.Timeout = 2 * time.Minute
|
client.Timeout = 30 * time.Second
|
||||||
client.KnownHosts.LoadDefault()
|
client.KnownHosts.Load(filepath.Join(xdg.DataHome(), "gemini", "known_hosts"))
|
||||||
client.TrustCertificate = func(hostname string, cert *x509.Certificate) gemini.Trust {
|
client.TrustCertificate = func(hostname string, cert *x509.Certificate) gemini.Trust {
|
||||||
fmt.Printf(trustPrompt, hostname, gemini.Fingerprint(cert))
|
fingerprint := gemini.NewFingerprint(cert.Raw, cert.NotAfter)
|
||||||
|
fmt.Printf(trustPrompt, hostname, fingerprint.Hex)
|
||||||
scanner.Scan()
|
scanner.Scan()
|
||||||
switch scanner.Text() {
|
switch scanner.Text() {
|
||||||
case "t":
|
case "t":
|
||||||
@@ -79,9 +82,9 @@ func main() {
|
|||||||
fmt.Println(err)
|
fmt.Println(err)
|
||||||
os.Exit(1)
|
os.Exit(1)
|
||||||
}
|
}
|
||||||
defer resp.Body.Close()
|
|
||||||
|
|
||||||
if resp.Status.Class() == gemini.StatusClassSuccess {
|
if resp.Status.Class() == gemini.StatusClassSuccess {
|
||||||
|
defer resp.Body.Close()
|
||||||
body, err := ioutil.ReadAll(resp.Body)
|
body, err := ioutil.ReadAll(resp.Body)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Fatal(err)
|
log.Fatal(err)
|
||||||
|
|||||||
@@ -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)))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ package main
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"crypto/tls"
|
"crypto/tls"
|
||||||
|
"crypto/x509/pkix"
|
||||||
"log"
|
"log"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
@@ -12,15 +13,18 @@ import (
|
|||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
var server gemini.Server
|
var server gemini.Server
|
||||||
server.ReadTimeout = 1 * time.Minute
|
server.ReadTimeout = 30 * time.Second
|
||||||
server.WriteTimeout = 2 * time.Minute
|
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) {
|
||||||
return gemini.CreateCertificate(gemini.CertificateOptions{
|
return gemini.CreateCertificate(gemini.CertificateOptions{
|
||||||
|
Subject: pkix.Name{
|
||||||
|
CommonName: hostname,
|
||||||
|
},
|
||||||
DNSNames: []string{hostname},
|
DNSNames: []string{hostname},
|
||||||
Duration: time.Minute, // for testing purposes
|
Duration: 365 * 24 * time.Hour,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
8
fs.go
8
fs.go
@@ -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
|
||||||
|
|||||||
93
gemini.go
93
gemini.go
@@ -1,52 +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 (
|
||||||
"errors"
|
"errors"
|
||||||
"sync"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
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")
|
||||||
ErrCertificateExpired = errors.New("gemini: certificate expired")
|
ErrBodyNotAllowed = errors.New("gemini: response body not allowed")
|
||||||
ErrCertificateNotFound = errors.New("gemini: certificate not found")
|
|
||||||
ErrCertificateNotTrusted = errors.New("gemini: certificate not trusted")
|
|
||||||
ErrCertificateRequired = errors.New("gemini: certificate required")
|
|
||||||
ErrNotAFile = errors.New("gemini: not a file")
|
|
||||||
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")
|
|
||||||
)
|
)
|
||||||
|
|
||||||
// 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) {
|
|
||||||
setupDefaultClientOnce()
|
|
||||||
return DefaultClient.Get(url)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Do performs a Gemini request and returns a Gemini response.
|
|
||||||
//
|
|
||||||
// Do is a wrapper around DefaultClient.Do.
|
|
||||||
func Do(req *Request) (*Response, error) {
|
|
||||||
setupDefaultClientOnce()
|
|
||||||
return DefaultClient.Do(req)
|
|
||||||
}
|
|
||||||
|
|
||||||
var defaultClientOnce sync.Once
|
|
||||||
|
|
||||||
func setupDefaultClientOnce() {
|
|
||||||
defaultClientOnce.Do(func() {
|
|
||||||
DefaultClient.KnownHosts.LoadDefault()
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|||||||
17
query.go
Normal file
17
query.go
Normal file
@@ -0,0 +1,17 @@
|
|||||||
|
package gemini
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net/url"
|
||||||
|
"strings"
|
||||||
|
)
|
||||||
|
|
||||||
|
// QueryEscape properly escapes a string for use in a Gemini URL query.
|
||||||
|
// It is like url.PathEscape except that it also replaces plus signs with their percent-encoded counterpart.
|
||||||
|
func QueryEscape(query string) string {
|
||||||
|
return strings.ReplaceAll(url.PathEscape(query), "+", "%2B")
|
||||||
|
}
|
||||||
|
|
||||||
|
// QueryUnescape is identical to url.PathUnescape.
|
||||||
|
func QueryUnescape(query string) (string, error) {
|
||||||
|
return url.PathUnescape(query)
|
||||||
|
}
|
||||||
26
request.go
26
request.go
@@ -2,6 +2,7 @@ package gemini
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"bufio"
|
"bufio"
|
||||||
|
"context"
|
||||||
"crypto/tls"
|
"crypto/tls"
|
||||||
"net"
|
"net"
|
||||||
"net/url"
|
"net/url"
|
||||||
@@ -19,7 +20,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
|
||||||
@@ -31,6 +34,10 @@ type Request struct {
|
|||||||
// connection on which the request was received.
|
// connection on which the request was received.
|
||||||
// This field is ignored by the client.
|
// This field is ignored by the client.
|
||||||
TLS tls.ConnectionState
|
TLS tls.ConnectionState
|
||||||
|
|
||||||
|
// Context specifies the context to use for client requests.
|
||||||
|
// Context must not be nil.
|
||||||
|
Context context.Context
|
||||||
}
|
}
|
||||||
|
|
||||||
// NewRequest returns a new request. The host is inferred from the URL.
|
// NewRequest returns a new request. The host is inferred from the URL.
|
||||||
@@ -39,23 +46,24 @@ 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) {
|
//
|
||||||
if url.Scheme != "" && url.Scheme != "gemini" {
|
// Callers should be careful that the URL query is properly escaped.
|
||||||
return nil, ErrNotAGeminiURL
|
// See the documentation for QueryEscape for more information.
|
||||||
}
|
func NewRequestFromURL(url *url.URL) *Request {
|
||||||
host := url.Host
|
host := url.Host
|
||||||
if url.Port() == "" {
|
if url.Port() == "" {
|
||||||
host += ":1965"
|
host += ":1965"
|
||||||
}
|
}
|
||||||
return &Request{
|
return &Request{
|
||||||
URL: url,
|
URL: url,
|
||||||
Host: host,
|
Host: host,
|
||||||
}, nil
|
Context: context.Background(),
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// write writes the Gemini request to the provided buffered writer.
|
// write writes the Gemini request to the provided buffered writer.
|
||||||
|
|||||||
@@ -2,10 +2,8 @@ package gemini
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"bufio"
|
"bufio"
|
||||||
"bytes"
|
|
||||||
"crypto/tls"
|
"crypto/tls"
|
||||||
"io"
|
"io"
|
||||||
"io/ioutil"
|
|
||||||
"strconv"
|
"strconv"
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -21,7 +19,6 @@ type Response struct {
|
|||||||
Meta string
|
Meta string
|
||||||
|
|
||||||
// Body contains the response body for successful responses.
|
// Body contains the response body for successful responses.
|
||||||
// Body is guaranteed to be non-nil.
|
|
||||||
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.
|
||||||
@@ -86,8 +83,6 @@ func (resp *Response) read(rc io.ReadCloser) error {
|
|||||||
|
|
||||||
if resp.Status.Class() == StatusClassSuccess {
|
if resp.Status.Class() == StatusClassSuccess {
|
||||||
resp.Body = newReadCloserBody(br, rc)
|
resp.Body = newReadCloserBody(br, rc)
|
||||||
} else {
|
|
||||||
resp.Body = ioutil.NopCloser(bytes.NewReader([]byte{}))
|
|
||||||
}
|
}
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|||||||
123
server.go
123
server.go
@@ -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"
|
||||||
@@ -26,12 +26,17 @@ type Server struct {
|
|||||||
WriteTimeout time.Duration
|
WriteTimeout time.Duration
|
||||||
|
|
||||||
// Certificates contains the certificates used by the server.
|
// Certificates contains the certificates used by the server.
|
||||||
Certificates CertificateStore
|
Certificates CertificateDir
|
||||||
|
|
||||||
// CreateCertificate, if not nil, will be called to create a new certificate
|
// CreateCertificate, if not nil, will be called to create a new certificate
|
||||||
// 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
|
hosts map[string]bool
|
||||||
@@ -118,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
|
||||||
}
|
}
|
||||||
@@ -146,22 +151,25 @@ func (s *Server) getCertificate(h *tls.ClientHelloInfo) (*tls.Certificate, error
|
|||||||
|
|
||||||
func (s *Server) getCertificateFor(hostname string) (*tls.Certificate, error) {
|
func (s *Server) getCertificateFor(hostname string) (*tls.Certificate, error) {
|
||||||
if _, ok := s.hosts[hostname]; !ok {
|
if _, ok := s.hosts[hostname]; !ok {
|
||||||
return nil, ErrCertificateNotFound
|
return nil, errors.New("hostname not registered")
|
||||||
}
|
}
|
||||||
cert, err := s.Certificates.Lookup(hostname)
|
|
||||||
|
|
||||||
switch err {
|
// Generate a new certificate if it is missing or expired
|
||||||
case ErrCertificateNotFound, ErrCertificateExpired:
|
cert, ok := s.Certificates.Lookup(hostname)
|
||||||
|
if !ok || cert.Leaf != nil && cert.Leaf.NotAfter.Before(time.Now()) {
|
||||||
if s.CreateCertificate != nil {
|
if s.CreateCertificate != nil {
|
||||||
cert, err := s.CreateCertificate(hostname)
|
cert, err := s.CreateCertificate(hostname)
|
||||||
if err == nil {
|
if err == nil {
|
||||||
s.Certificates.Add(hostname, cert)
|
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 &cert, err
|
||||||
}
|
}
|
||||||
|
return nil, errors.New("no certificate")
|
||||||
}
|
}
|
||||||
|
return &cert, nil
|
||||||
return cert, err
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// respond responds to a connection.
|
// respond responds to a connection.
|
||||||
@@ -195,14 +203,23 @@ func (s *Server) respond(conn net.Conn) {
|
|||||||
// 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.WriteStatus(StatusBadRequest)
|
w.WriteStatus(StatusBadRequest)
|
||||||
} else {
|
} else {
|
||||||
// If no scheme is specified, assume a default scheme of gemini://
|
// Store information about the TLS connection
|
||||||
if url.Scheme == "" {
|
connState := conn.(*tls.Conn).ConnectionState()
|
||||||
url.Scheme = "gemini"
|
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 {
|
||||||
@@ -228,12 +245,20 @@ func (s *Server) responder(r *Request) Responder {
|
|||||||
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 {
|
||||||
@@ -272,10 +297,10 @@ 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.
|
||||||
// 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.
|
||||||
@@ -286,11 +311,11 @@ func (w *ResponseWriter) SetMimetype(mimetype string) {
|
|||||||
// with StatusSuccess and the mimetype set in SetMimetype.
|
// with StatusSuccess and the mimetype set in SetMimetype.
|
||||||
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
|
||||||
@@ -304,41 +329,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
|
|
||||||
}
|
|
||||||
|
|
||||||
// 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
|
||||||
|
}
|
||||||
|
|||||||
199
tofu.go
199
tofu.go
@@ -3,11 +3,9 @@ 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"
|
||||||
@@ -22,35 +20,62 @@ const (
|
|||||||
TrustAlways // The certificate is trusted always.
|
TrustAlways // The certificate is trusted always.
|
||||||
)
|
)
|
||||||
|
|
||||||
// KnownHosts represents a list of known hosts.
|
// KnownHosts maps hosts to fingerprints.
|
||||||
// The zero value for KnownHosts is an empty list ready to use.
|
type KnownHosts map[string]Fingerprint
|
||||||
type KnownHosts struct {
|
|
||||||
hosts map[string]certInfo
|
// KnownHostsFile represents a list of known hosts optionally loaded from a file.
|
||||||
file *os.File
|
// The zero value for KnownHostsFile represents an empty list ready to use.
|
||||||
|
type KnownHostsFile struct {
|
||||||
|
KnownHosts
|
||||||
|
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 *KnownHostsFile) 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 *KnownHostsFile) Add(hostname string, fingerprint Fingerprint) {
|
||||||
return err
|
if k.KnownHosts == nil {
|
||||||
|
k.KnownHosts = KnownHosts{}
|
||||||
}
|
}
|
||||||
return k.Load(path)
|
k.KnownHosts[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 *KnownHostsFile) Lookup(hostname string) (Fingerprint, bool) {
|
||||||
func (k *KnownHosts) Load(path string) error {
|
c, ok := k.KnownHosts[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 *KnownHostsFile) 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 *KnownHostsFile) WriteAll(w io.Writer) error {
|
||||||
|
for h, c := range k.KnownHosts {
|
||||||
|
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 *KnownHostsFile) 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.Unix())
|
||||||
|
}
|
||||||
|
|
||||||
|
// 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 *KnownHostsFile) 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
|
||||||
@@ -62,65 +87,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 not in the list, Lookup returns ErrCertificateNotFound.
|
|
||||||
// If the fingerprint doesn't match, Lookup returns ErrCertificateNotTrusted.
|
|
||||||
// Otherwise, Lookup returns 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 ErrCertificateExpired
|
|
||||||
}
|
|
||||||
if c.Fingerprint != fingerprint {
|
|
||||||
// Fingerprint does not match
|
|
||||||
return ErrCertificateNotTrusted
|
|
||||||
}
|
|
||||||
// Certificate is found
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
return ErrCertificateNotFound
|
|
||||||
}
|
|
||||||
|
|
||||||
// Parse parses the provided reader and adds the parsed known hosts to the list.
|
// Parse parses the provided reader and adds the parsed known hosts to the list.
|
||||||
// Invalid lines are ignored.
|
// Invalid entries are ignored.
|
||||||
func (k *KnownHosts) Parse(r io.Reader) {
|
func (k *KnownHostsFile) Parse(r io.Reader) {
|
||||||
if k.hosts == nil {
|
if k.KnownHosts == nil {
|
||||||
k.hosts = map[string]certInfo{}
|
k.KnownHosts = map[string]Fingerprint{}
|
||||||
}
|
}
|
||||||
scanner := bufio.NewScanner(r)
|
scanner := bufio.NewScanner(r)
|
||||||
for scanner.Scan() {
|
for scanner.Scan() {
|
||||||
@@ -135,40 +110,32 @@ func (k *KnownHosts) Parse(r io.Reader) {
|
|||||||
if algorithm != "SHA-512" {
|
if algorithm != "SHA-512" {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
fingerprint := parts[2]
|
hex := parts[2]
|
||||||
expires, err := strconv.ParseInt(parts[3], 10, 0)
|
|
||||||
|
unix, err := strconv.ParseInt(parts[3], 10, 0)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
|
expires := time.Unix(unix, 0)
|
||||||
|
|
||||||
k.hosts[hostname] = certInfo{
|
k.KnownHosts[hostname] = Fingerprint{
|
||||||
Algorithm: algorithm,
|
Algorithm: algorithm,
|
||||||
Fingerprint: fingerprint,
|
Hex: hex,
|
||||||
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 time.Time // 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 {
|
||||||
@@ -176,29 +143,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,
|
||||||
// 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
|
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user