Compare commits
87 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
31de8d49b0 | ||
|
|
2b17f3d8eb | ||
|
|
f36a1c5c87 | ||
|
|
af61c1b60a | ||
|
|
ad18ae601c | ||
|
|
8473f3b9d4 | ||
|
|
06c53cc5b1 | ||
|
|
4b643523fb | ||
|
|
79a4dfd43f | ||
|
|
14d89f304a | ||
|
|
7a00539f75 | ||
|
|
a0adc42c95 | ||
|
|
da8af5dbcb | ||
|
|
ced6b06d76 | ||
|
|
4a0f8e5e73 | ||
|
|
e701ceff71 | ||
|
|
1a3974b3a3 | ||
|
|
3fd55c5cee | ||
|
|
6f11910dff | ||
|
|
da3e9ac0fe | ||
|
|
9fe837ffac | ||
|
|
4b8bb16a3d | ||
|
|
95aff9c573 | ||
|
|
de042e4724 | ||
|
|
d78052ce08 | ||
|
|
1f2888c54a | ||
|
|
41d5f8d31b | ||
|
|
24026422b2 | ||
|
|
5e977250ec | ||
|
|
d8c5da1c7c | ||
|
|
d01d50ff1a | ||
|
|
3ed39e62d8 | ||
|
|
f2921a396f | ||
|
|
efef44c2f9 | ||
|
|
c8626bae17 | ||
|
|
48fa6a724e | ||
|
|
80ffa72863 | ||
|
|
61b417a5c4 | ||
|
|
a912ef996a | ||
|
|
d9a690a98f | ||
|
|
04bd0f4520 | ||
|
|
d34d5df89e | ||
|
|
decd72cc23 | ||
|
|
c329a2487e | ||
|
|
df1794c803 | ||
|
|
5af1acbd54 | ||
|
|
36c2086c82 | ||
|
|
d52d0af783 | ||
|
|
35836f2ff7 | ||
|
|
824887eab9 | ||
|
|
e2c907a7f6 | ||
|
|
a09cb5a23c | ||
|
|
7ca7053f66 | ||
|
|
ca35aadaea | ||
|
|
805a80dddf | ||
|
|
28c5c857dc | ||
|
|
176b260468 | ||
|
|
a1dd8de337 | ||
|
|
7be0715d39 | ||
|
|
4704b8fbcf | ||
|
|
aeafd57956 | ||
|
|
e687a05170 | ||
|
|
846fa2ac41 | ||
|
|
611a7d54c0 | ||
|
|
16739d20d0 | ||
|
|
24e488a4cb | ||
|
|
e0ac1685d2 | ||
|
|
82688746dd | ||
|
|
3b9cc7f168 | ||
|
|
3c7940f153 | ||
|
|
8ee55ee009 | ||
|
|
7ee0ea8b7f | ||
|
|
ab1db34f02 | ||
|
|
35e984fbba | ||
|
|
cab23032c0 | ||
|
|
4b653032e4 | ||
|
|
0c75e5d5ad | ||
|
|
f6b0443a62 | ||
|
|
3dee6dcff3 | ||
|
|
85f8e84bd5 | ||
|
|
9338681256 | ||
|
|
f2a1510375 | ||
|
|
46cbcfcaa4 | ||
|
|
76dfe257f1 | ||
|
|
5332dc6280 | ||
|
|
6b3cf1314b | ||
|
|
fe92db1e9c |
@@ -1,6 +1,6 @@
|
|||||||
# go-gemini
|
# go-gemini
|
||||||
|
|
||||||
[](https://godoc.org/git.sr.ht/~adnano/go-gemini)
|
[](https://godocs.io/git.sr.ht/~adnano/go-gemini)
|
||||||
|
|
||||||
Package gemini implements the [Gemini protocol](https://gemini.circumlunar.space) in Go.
|
Package gemini implements the [Gemini protocol](https://gemini.circumlunar.space) in Go.
|
||||||
|
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
package gemini
|
// Package certificate provides utility functions for TLS certificates.
|
||||||
|
package certificate
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"crypto"
|
"crypto"
|
||||||
@@ -15,22 +16,27 @@ import (
|
|||||||
"os"
|
"os"
|
||||||
"path/filepath"
|
"path/filepath"
|
||||||
"strings"
|
"strings"
|
||||||
|
"sync"
|
||||||
"time"
|
"time"
|
||||||
)
|
)
|
||||||
|
|
||||||
// CertificateStore maps certificate scopes to certificates.
|
// Dir represents a directory of certificates.
|
||||||
// The zero value of CertificateStore is an empty store ready to use.
|
// The zero value for Dir is an empty directory ready to use.
|
||||||
type CertificateStore struct {
|
//
|
||||||
store map[string]tls.Certificate
|
// Dir is safe for concurrent use by multiple goroutines.
|
||||||
dir bool
|
type Dir struct {
|
||||||
path string
|
certs map[string]tls.Certificate
|
||||||
|
path *string
|
||||||
|
mu sync.RWMutex
|
||||||
}
|
}
|
||||||
|
|
||||||
// Add adds a certificate for the given scope to the store.
|
// Add adds a certificate for the given scope to the directory.
|
||||||
// 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) error {
|
func (d *Dir) Add(scope string, cert tls.Certificate) error {
|
||||||
if c.store == nil {
|
d.mu.Lock()
|
||||||
c.store = map[string]tls.Certificate{}
|
defer d.mu.Unlock()
|
||||||
|
if d.certs == nil {
|
||||||
|
d.certs = map[string]tls.Certificate{}
|
||||||
}
|
}
|
||||||
// Parse certificate if not already parsed
|
// Parse certificate if not already parsed
|
||||||
if cert.Leaf == nil {
|
if cert.Leaf == nil {
|
||||||
@@ -39,31 +45,45 @@ func (c *CertificateStore) Add(scope string, cert tls.Certificate) error {
|
|||||||
cert.Leaf = parsed
|
cert.Leaf = parsed
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if c.dir {
|
|
||||||
// Write certificates
|
if d.path != nil {
|
||||||
certPath := filepath.Join(c.path, scope+".crt")
|
// Escape slash character
|
||||||
keyPath := filepath.Join(c.path, scope+".key")
|
scope = strings.ReplaceAll(scope, "/", ":")
|
||||||
if err := WriteCertificate(cert, certPath, keyPath); err != nil {
|
certPath := filepath.Join(*d.path, scope+".crt")
|
||||||
|
keyPath := filepath.Join(*d.path, scope+".key")
|
||||||
|
if err := Write(cert, certPath, keyPath); err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
c.store[scope] = cert
|
|
||||||
|
d.certs[scope] = cert
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// Lookup returns the certificate for the given scope.
|
// Lookup returns the certificate for the provided scope.
|
||||||
func (c *CertificateStore) Lookup(scope string) (tls.Certificate, bool) {
|
func (d *Dir) Lookup(scope string) (tls.Certificate, bool) {
|
||||||
cert, ok := c.store[scope]
|
d.mu.RLock()
|
||||||
|
defer d.mu.RUnlock()
|
||||||
|
cert, ok := d.certs[scope]
|
||||||
return cert, ok
|
return cert, ok
|
||||||
}
|
}
|
||||||
|
|
||||||
// Load loads certificates from the given path.
|
// Entries returns a map of hostnames to certificates.
|
||||||
// The path should lead to a directory containing certificates and private keys
|
func (d *Dir) Entries() map[string]tls.Certificate {
|
||||||
// in the form scope.crt and scope.key.
|
certs := map[string]tls.Certificate{}
|
||||||
// For example, the hostname "localhost" would have the corresponding files
|
for key := range d.certs {
|
||||||
// localhost.crt (certificate) and localhost.key (private key).
|
certs[key] = d.certs[key]
|
||||||
// New certificates will be written to this directory.
|
}
|
||||||
func (c *CertificateStore) Load(path string) error {
|
return certs
|
||||||
|
}
|
||||||
|
|
||||||
|
// Load loads certificates from the provided path.
|
||||||
|
// Add will write certificates to this path.
|
||||||
|
//
|
||||||
|
// The directory should contain certificates and private keys
|
||||||
|
// named scope.crt and scope.key respectively, where scope is
|
||||||
|
// the scope of the certificate.
|
||||||
|
func (d *Dir) Load(path string) error {
|
||||||
matches, err := filepath.Glob(filepath.Join(path, "*.crt"))
|
matches, err := filepath.Glob(filepath.Join(path, "*.crt"))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
@@ -75,24 +95,33 @@ func (c *CertificateStore) Load(path string) error {
|
|||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
scope := strings.TrimSuffix(filepath.Base(crtPath), ".crt")
|
scope := strings.TrimSuffix(filepath.Base(crtPath), ".crt")
|
||||||
c.Add(scope, cert)
|
// Unescape slash character
|
||||||
|
scope = strings.ReplaceAll(scope, ":", "/")
|
||||||
|
d.Add(scope, cert)
|
||||||
}
|
}
|
||||||
c.dir = true
|
d.SetPath(path)
|
||||||
c.path = path
|
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// CertificateOptions configures the creation of a certificate.
|
// SetPath sets the directory path.
|
||||||
type CertificateOptions struct {
|
// Add will write certificates to this path.
|
||||||
// Subject Alternate Name values.
|
func (d *Dir) SetPath(path string) {
|
||||||
// Should contain the IP addresses that the certificate is valid for.
|
d.mu.Lock()
|
||||||
IPAddresses []net.IP
|
defer d.mu.Unlock()
|
||||||
|
d.path = &path
|
||||||
|
}
|
||||||
|
|
||||||
|
// CreateOptions configures the creation of a TLS certificate.
|
||||||
|
type CreateOptions struct {
|
||||||
// Subject Alternate Name values.
|
// Subject Alternate Name values.
|
||||||
// Should contain the DNS names that this certificate is valid for.
|
// Should contain the DNS names that this certificate is valid for.
|
||||||
// E.g. example.com, *.example.com
|
// E.g. example.com, *.example.com
|
||||||
DNSNames []string
|
DNSNames []string
|
||||||
|
|
||||||
|
// Subject Alternate Name values.
|
||||||
|
// Should contain the IP addresses that the certificate is valid for.
|
||||||
|
IPAddresses []net.IP
|
||||||
|
|
||||||
// Subject specifies the certificate Subject.
|
// Subject specifies the certificate Subject.
|
||||||
//
|
//
|
||||||
// Subject.CommonName can contain the DNS name that this certificate
|
// Subject.CommonName can contain the DNS name that this certificate
|
||||||
@@ -109,8 +138,8 @@ type CertificateOptions struct {
|
|||||||
Ed25519 bool
|
Ed25519 bool
|
||||||
}
|
}
|
||||||
|
|
||||||
// CreateCertificate creates a new TLS certificate.
|
// Create creates a new TLS certificate.
|
||||||
func CreateCertificate(options CertificateOptions) (tls.Certificate, error) {
|
func Create(options CreateOptions) (tls.Certificate, error) {
|
||||||
crt, priv, err := newX509KeyPair(options)
|
crt, priv, err := newX509KeyPair(options)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return tls.Certificate{}, err
|
return tls.Certificate{}, err
|
||||||
@@ -123,7 +152,7 @@ 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 CreateOptions) (*x509.Certificate, crypto.PrivateKey, error) {
|
||||||
var pub crypto.PublicKey
|
var pub crypto.PublicKey
|
||||||
var priv crypto.PrivateKey
|
var priv crypto.PrivateKey
|
||||||
if options.Ed25519 {
|
if options.Ed25519 {
|
||||||
@@ -179,9 +208,9 @@ func newX509KeyPair(options CertificateOptions) (*x509.Certificate, crypto.Priva
|
|||||||
return cert, priv, nil
|
return cert, priv, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// WriteCertificate writes the provided certificate and private key
|
// Write writes the provided certificate and its private key
|
||||||
// to certPath and keyPath respectively.
|
// to certPath and keyPath respectively.
|
||||||
func WriteCertificate(cert tls.Certificate, certPath, keyPath string) error {
|
func Write(cert tls.Certificate, certPath, keyPath string) error {
|
||||||
certOut, err := os.OpenFile(certPath, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0600)
|
certOut, err := os.OpenFile(certPath, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0600)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
235
client.go
235
client.go
@@ -2,23 +2,27 @@ package gemini
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"bufio"
|
"bufio"
|
||||||
|
"context"
|
||||||
"crypto/tls"
|
"crypto/tls"
|
||||||
"crypto/x509"
|
"crypto/x509"
|
||||||
"errors"
|
"errors"
|
||||||
|
"fmt"
|
||||||
"net"
|
"net"
|
||||||
"net/url"
|
|
||||||
"path"
|
|
||||||
"strings"
|
"strings"
|
||||||
"time"
|
"time"
|
||||||
)
|
)
|
||||||
|
|
||||||
// Client is a Gemini client.
|
// Client is a Gemini client.
|
||||||
type Client struct {
|
type Client struct {
|
||||||
// KnownHosts is a list of known hosts.
|
// TrustCertificate is called to determine whether the client
|
||||||
KnownHosts KnownHosts
|
// should trust the certificate provided by the server.
|
||||||
|
// If TrustCertificate is nil, the client will accept any certificate.
|
||||||
// Certificates stores client-side certificates.
|
// If the returned error is not nil, the certificate will not be trusted
|
||||||
Certificates CertificateStore
|
// and the request will be aborted.
|
||||||
|
//
|
||||||
|
// For a basic trust on first use implementation, see (*KnownHosts).TOFU
|
||||||
|
// in the tofu submodule.
|
||||||
|
TrustCertificate func(hostname string, cert *x509.Certificate) error
|
||||||
|
|
||||||
// Timeout specifies a time limit for requests made by this
|
// Timeout specifies a time limit for requests made by this
|
||||||
// Client. The timeout includes connection time and reading
|
// Client. The timeout includes connection time and reading
|
||||||
@@ -27,41 +31,9 @@ type Client struct {
|
|||||||
//
|
//
|
||||||
// A Timeout of zero means no timeout.
|
// A Timeout of zero means no timeout.
|
||||||
Timeout time.Duration
|
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, 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)
|
|
||||||
|
|
||||||
// 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.
|
// Get performs a Gemini request for the given URL.
|
||||||
func (c *Client) Get(url string) (*Response, error) {
|
func (c *Client) Get(url string) (*Response, error) {
|
||||||
req, err := NewRequest(url)
|
req, err := NewRequest(url)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -72,132 +44,93 @@ 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) {
|
||||||
return c.do(req, nil)
|
// Extract hostname
|
||||||
}
|
colonPos := strings.LastIndex(req.Host, ":")
|
||||||
|
if colonPos == -1 {
|
||||||
|
colonPos = len(req.Host)
|
||||||
|
}
|
||||||
|
hostname := req.Host[:colonPos]
|
||||||
|
|
||||||
func (c *Client) do(req *Request, via []*Request) (*Response, error) {
|
|
||||||
// Connect to the host
|
// Connect to the host
|
||||||
config := &tls.Config{
|
config := &tls.Config{
|
||||||
InsecureSkipVerify: true,
|
InsecureSkipVerify: true,
|
||||||
MinVersion: tls.VersionTLS12,
|
MinVersion: tls.VersionTLS12,
|
||||||
GetClientCertificate: func(_ *tls.CertificateRequestInfo) (*tls.Certificate, error) {
|
GetClientCertificate: func(_ *tls.CertificateRequestInfo) (*tls.Certificate, error) {
|
||||||
return c.getClientCertificate(req)
|
if req.Certificate != nil {
|
||||||
|
return req.Certificate, nil
|
||||||
|
}
|
||||||
|
return &tls.Certificate{}, nil
|
||||||
},
|
},
|
||||||
VerifyConnection: func(cs tls.ConnectionState) error {
|
VerifyConnection: func(cs tls.ConnectionState) error {
|
||||||
return c.verifyConnection(req, cs)
|
return c.verifyConnection(req, cs)
|
||||||
},
|
},
|
||||||
|
ServerName: hostname,
|
||||||
}
|
}
|
||||||
conn, err := tls.Dial("tcp", req.Host, config)
|
// Set connection context
|
||||||
|
ctx := req.Context
|
||||||
|
if ctx == nil {
|
||||||
|
ctx = context.Background()
|
||||||
|
}
|
||||||
|
|
||||||
|
start := time.Now()
|
||||||
|
dialer := net.Dialer{
|
||||||
|
Timeout: c.Timeout,
|
||||||
|
}
|
||||||
|
|
||||||
|
netConn, err := dialer.DialContext(ctx, "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 c.Timeout != 0 {
|
||||||
conn.SetDeadline(time.Now().Add(d))
|
err := conn.SetDeadline(start.Add(c.Timeout))
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf(
|
||||||
|
"failed to set connection deadline: %w", err)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
resp, err := c.do(conn, req)
|
||||||
|
if err != nil {
|
||||||
|
// If we fail to perform the request/response we have
|
||||||
|
// to take responsibility for closing the connection.
|
||||||
|
_ = conn.Close()
|
||||||
|
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// Store connection state
|
||||||
|
resp.TLS = conn.ConnectionState()
|
||||||
|
|
||||||
|
return resp, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *Client) do(conn *tls.Conn, req *Request) (*Response, error) {
|
||||||
// Write the request
|
// Write the request
|
||||||
w := bufio.NewWriter(conn)
|
w := bufio.NewWriter(conn)
|
||||||
req.write(w)
|
|
||||||
|
err := req.Write(w)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf(
|
||||||
|
"failed to write request data: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
if err := w.Flush(); err != nil {
|
if err := w.Flush(); err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
// Read the response
|
// Read the response
|
||||||
resp := &Response{}
|
resp, err := ReadResponse(conn)
|
||||||
if err := resp.read(conn); err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
// Store connection state
|
|
||||||
resp.TLS = conn.ConnectionState()
|
|
||||||
|
|
||||||
switch {
|
|
||||||
case resp.Status == StatusCertificateRequired:
|
|
||||||
// Check to see if a certificate was already provided to prevent an infinite loop
|
|
||||||
if req.Certificate != nil {
|
|
||||||
return resp, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
hostname, path := req.URL.Hostname(), strings.TrimSuffix(req.URL.Path, "/")
|
|
||||||
if c.CreateCertificate != nil {
|
|
||||||
cert, err := c.CreateCertificate(hostname, path)
|
|
||||||
if err != nil {
|
|
||||||
return resp, err
|
|
||||||
}
|
|
||||||
c.Certificates.Add(hostname+path, cert)
|
|
||||||
req.Certificate = &cert
|
|
||||||
return c.do(req, via)
|
|
||||||
}
|
|
||||||
return resp, nil
|
|
||||||
|
|
||||||
case resp.Status.Class() == StatusClassInput:
|
|
||||||
if c.GetInput != nil {
|
|
||||||
input, ok := c.GetInput(resp.Meta, resp.Status == StatusSensitiveInput)
|
|
||||||
if ok {
|
|
||||||
req.URL.ForceQuery = true
|
|
||||||
req.URL.RawQuery = url.QueryEscape(input)
|
|
||||||
return c.do(req, via)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return resp, nil
|
|
||||||
|
|
||||||
case resp.Status.Class() == StatusClassRedirect:
|
|
||||||
if via == nil {
|
|
||||||
via = []*Request{}
|
|
||||||
}
|
|
||||||
via = append(via, req)
|
|
||||||
|
|
||||||
target, err := url.Parse(resp.Meta)
|
|
||||||
if err != nil {
|
|
||||||
return resp, err
|
|
||||||
}
|
|
||||||
|
|
||||||
target = req.URL.ResolveReference(target)
|
|
||||||
if target.Scheme != "" && target.Scheme != "gemini" {
|
|
||||||
return resp, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
redirect := NewRequestFromURL(target)
|
|
||||||
if c.CheckRedirect != nil {
|
|
||||||
if err := c.CheckRedirect(redirect, via); err != nil {
|
|
||||||
return resp, err
|
|
||||||
}
|
|
||||||
return c.do(redirect, via)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
resp.Request = req
|
|
||||||
return resp, nil
|
return resp, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c *Client) getClientCertificate(req *Request) (*tls.Certificate, error) {
|
|
||||||
// Request certificates have the highest precedence
|
|
||||||
if req.Certificate != nil {
|
|
||||||
return req.Certificate, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// Search recursively for the certificate
|
|
||||||
scope := req.URL.Hostname() + strings.TrimSuffix(req.URL.Path, "/")
|
|
||||||
for {
|
|
||||||
cert, 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)
|
|
||||||
if scope == "." {
|
|
||||||
break
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return &tls.Certificate{}, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *Client) verifyConnection(req *Request, cs tls.ConnectionState) error {
|
func (c *Client) verifyConnection(req *Request, cs tls.ConnectionState) error {
|
||||||
// Verify the hostname
|
// Verify the hostname
|
||||||
var hostname string
|
var hostname string
|
||||||
@@ -210,30 +143,14 @@ func (c *Client) verifyConnection(req *Request, cs tls.ConnectionState) error {
|
|||||||
if err := verifyHostname(cert, hostname); err != nil {
|
if err := verifyHostname(cert, hostname); err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
if c.InsecureSkipTrust {
|
// Check expiration date
|
||||||
return nil
|
if !time.Now().Before(cert.NotAfter) {
|
||||||
|
return errors.New("gemini: certificate expired")
|
||||||
}
|
}
|
||||||
|
|
||||||
// Check the known hosts
|
// See if the client trusts the certificate
|
||||||
knownHost, ok := c.KnownHosts.Lookup(hostname)
|
if c.TrustCertificate != nil {
|
||||||
if !ok || time.Now().Unix() >= knownHost.Expires {
|
return c.TrustCertificate(hostname, cert)
|
||||||
// See if the client trusts the certificate
|
|
||||||
if c.TrustCertificate != nil {
|
|
||||||
switch c.TrustCertificate(hostname, cert) {
|
|
||||||
case TrustOnce:
|
|
||||||
c.KnownHosts.AddTemporary(hostname, cert)
|
|
||||||
return nil
|
|
||||||
case TrustAlways:
|
|
||||||
c.KnownHosts.Add(hostname, cert)
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return errors.New("gemini: certificate not trusted")
|
|
||||||
}
|
}
|
||||||
|
return nil
|
||||||
fingerprint := NewFingerprint(cert)
|
|
||||||
if knownHost.Hex == fingerprint.Hex {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
return errors.New("gemini: fingerprint does not match")
|
|
||||||
}
|
}
|
||||||
|
|||||||
16
doc.go
16
doc.go
@@ -1,29 +1,21 @@
|
|||||||
/*
|
/*
|
||||||
Package gemini implements the Gemini protocol.
|
Package gemini implements the Gemini protocol.
|
||||||
|
|
||||||
Get makes a Gemini request:
|
Client is a Gemini client.
|
||||||
|
|
||||||
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{}
|
client := &gemini.Client{}
|
||||||
resp, err := client.Get("gemini://example.com")
|
resp, err := client.Get("gemini://example.com")
|
||||||
if err != nil {
|
if err != nil {
|
||||||
// handle error
|
// handle error
|
||||||
}
|
}
|
||||||
|
defer resp.Body.Close()
|
||||||
// ...
|
// ...
|
||||||
|
|
||||||
Server is a Gemini server.
|
Server is a Gemini server.
|
||||||
|
|
||||||
server := &gemini.Server{
|
server := &gemini.Server{
|
||||||
ReadTimeout: 10 * time.Second,
|
ReadTimeout: 10 * time.Second,
|
||||||
WriteTimeout: 10 * time.Second,
|
WriteTimeout: 10 * time.Second,
|
||||||
}
|
}
|
||||||
|
|
||||||
Servers should be configured with certificates:
|
Servers should be configured with certificates:
|
||||||
|
|||||||
134
examples/auth.go
134
examples/auth.go
@@ -3,6 +3,7 @@
|
|||||||
package main
|
package main
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"crypto/sha512"
|
||||||
"crypto/tls"
|
"crypto/tls"
|
||||||
"crypto/x509"
|
"crypto/x509"
|
||||||
"crypto/x509/pkix"
|
"crypto/x509/pkix"
|
||||||
@@ -11,44 +12,29 @@ import (
|
|||||||
"time"
|
"time"
|
||||||
|
|
||||||
"git.sr.ht/~adnano/go-gemini"
|
"git.sr.ht/~adnano/go-gemini"
|
||||||
|
"git.sr.ht/~adnano/go-gemini/certificate"
|
||||||
)
|
)
|
||||||
|
|
||||||
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) {
|
server.CreateCertificate = func(hostname string) (tls.Certificate, error) {
|
||||||
return gemini.CreateCertificate(gemini.CertificateOptions{
|
return certificate.Create(certificate.CreateOptions{
|
||||||
Subject: pkix.Name{
|
Subject: pkix.Name{
|
||||||
CommonName: hostname,
|
CommonName: hostname,
|
||||||
},
|
},
|
||||||
@@ -56,102 +42,50 @@ func main() {
|
|||||||
Duration: time.Hour,
|
Duration: time.Hour,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
server.Register("localhost", &mux)
|
server.Handle("localhost", &mux)
|
||||||
|
|
||||||
if err := server.ListenAndServe(); err != nil {
|
if err := server.ListenAndServe(); err != nil {
|
||||||
log.Fatal(err)
|
log.Fatal(err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func getSession(cert *x509.Certificate) (*session, bool) {
|
func fingerprint(cert *x509.Certificate) string {
|
||||||
fingerprint := gemini.NewFingerprint(cert)
|
b := sha512.Sum512(cert.Raw)
|
||||||
session, ok := sessions[fingerprint.Hex]
|
return string(b[:])
|
||||||
return session, ok
|
|
||||||
}
|
|
||||||
|
|
||||||
func login(w *gemini.ResponseWriter, r *gemini.Request) {
|
|
||||||
if r.Certificate == nil {
|
|
||||||
w.WriteStatus(gemini.StatusCertificateRequired)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
username, ok := gemini.Input(r)
|
|
||||||
if !ok {
|
|
||||||
w.WriteHeader(gemini.StatusInput, "Username")
|
|
||||||
return
|
|
||||||
}
|
|
||||||
fingerprint := gemini.NewFingerprint(r.Certificate.Leaf)
|
|
||||||
sessions[fingerprint.Hex] = &session{
|
|
||||||
username: username,
|
|
||||||
}
|
|
||||||
w.WriteHeader(gemini.StatusRedirect, "/password")
|
|
||||||
}
|
|
||||||
|
|
||||||
func loginPassword(w *gemini.ResponseWriter, r *gemini.Request) {
|
|
||||||
if r.Certificate == nil {
|
|
||||||
w.WriteStatus(gemini.StatusCertificateRequired)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
session, ok := getSession(r.Certificate.Leaf)
|
|
||||||
if !ok {
|
|
||||||
w.WriteStatus(gemini.StatusCertificateNotAuthorized)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
password, ok := gemini.Input(r)
|
|
||||||
if !ok {
|
|
||||||
w.WriteHeader(gemini.StatusSensitiveInput, "Password")
|
|
||||||
return
|
|
||||||
}
|
|
||||||
expected := logins[session.username].password
|
|
||||||
if password == expected {
|
|
||||||
session.authorized = true
|
|
||||||
w.WriteHeader(gemini.StatusRedirect, "/profile")
|
|
||||||
} else {
|
|
||||||
w.WriteHeader(gemini.StatusSensitiveInput, "Password")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func logout(w *gemini.ResponseWriter, r *gemini.Request) {
|
|
||||||
if r.Certificate == nil {
|
|
||||||
w.WriteStatus(gemini.StatusCertificateRequired)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
fingerprint := gemini.NewFingerprint(r.Certificate.Leaf)
|
|
||||||
delete(sessions, fingerprint.Hex)
|
|
||||||
fmt.Fprintln(w, "Successfully logged out.")
|
|
||||||
fmt.Fprintln(w, "=> / Index")
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func profile(w *gemini.ResponseWriter, r *gemini.Request) {
|
func profile(w *gemini.ResponseWriter, r *gemini.Request) {
|
||||||
if r.Certificate == nil {
|
if r.Certificate == nil {
|
||||||
w.WriteStatus(gemini.StatusCertificateRequired)
|
w.Status(gemini.StatusCertificateRequired)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
session, ok := getSession(r.Certificate.Leaf)
|
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) {
|
||||||
if r.Certificate == nil {
|
if r.Certificate == nil {
|
||||||
w.WriteStatus(gemini.StatusCertificateRequired)
|
w.Status(gemini.StatusCertificateRequired)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
session, ok := getSession(r.Certificate.Leaf)
|
|
||||||
|
username, err := gemini.QueryUnescape(r.URL.RawQuery)
|
||||||
|
if err != nil || username == "" {
|
||||||
|
w.Header(gemini.StatusInput, "Username")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
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]
|
user.Name = username
|
||||||
if !user.admin {
|
w.Header(gemini.StatusRedirect, "/")
|
||||||
w.WriteStatus(gemini.StatusCertificateNotAuthorized)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
fmt.Fprintln(w, "Welcome to the admin portal.")
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,5 +1,7 @@
|
|||||||
// +build ignore
|
// +build ignore
|
||||||
|
|
||||||
|
// This example illustrates a certificate generation tool.
|
||||||
|
|
||||||
package main
|
package main
|
||||||
|
|
||||||
import (
|
import (
|
||||||
@@ -9,7 +11,7 @@ import (
|
|||||||
"os"
|
"os"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"git.sr.ht/~adnano/go-gemini"
|
"git.sr.ht/~adnano/go-gemini/certificate"
|
||||||
)
|
)
|
||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
@@ -22,20 +24,20 @@ func main() {
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
log.Fatal(err)
|
log.Fatal(err)
|
||||||
}
|
}
|
||||||
options := gemini.CertificateOptions{
|
options := certificate.CreateOptions{
|
||||||
Subject: pkix.Name{
|
Subject: pkix.Name{
|
||||||
CommonName: host,
|
CommonName: host,
|
||||||
},
|
},
|
||||||
DNSNames: []string{host},
|
DNSNames: []string{host},
|
||||||
Duration: duration,
|
Duration: duration,
|
||||||
}
|
}
|
||||||
cert, err := gemini.CreateCertificate(options)
|
cert, err := certificate.Create(options)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Fatal(err)
|
log.Fatal(err)
|
||||||
}
|
}
|
||||||
certPath := host + ".crt"
|
certPath := host + ".crt"
|
||||||
keyPath := host + ".key"
|
keyPath := host + ".key"
|
||||||
if err := gemini.WriteCertificate(cert, certPath, keyPath); err != nil {
|
if err := certificate.Write(cert, certPath, keyPath); err != nil {
|
||||||
log.Fatal(err)
|
log.Fatal(err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,20 +1,49 @@
|
|||||||
// +build ignore
|
// +build ignore
|
||||||
|
|
||||||
|
// This example illustrates a Gemini client.
|
||||||
|
|
||||||
package main
|
package main
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"bufio"
|
"bufio"
|
||||||
"crypto/tls"
|
"bytes"
|
||||||
"crypto/x509"
|
"crypto/x509"
|
||||||
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
"io/ioutil"
|
"io/ioutil"
|
||||||
"log"
|
"log"
|
||||||
|
"net/url"
|
||||||
"os"
|
"os"
|
||||||
|
"path/filepath"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"git.sr.ht/~adnano/go-gemini"
|
"git.sr.ht/~adnano/go-gemini"
|
||||||
|
"git.sr.ht/~adnano/go-gemini/tofu"
|
||||||
|
"git.sr.ht/~adnano/go-xdg"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
var (
|
||||||
|
hosts tofu.KnownHosts
|
||||||
|
hostsfile *tofu.HostWriter
|
||||||
|
scanner *bufio.Scanner
|
||||||
|
)
|
||||||
|
|
||||||
|
func init() {
|
||||||
|
// Load known hosts file
|
||||||
|
path := filepath.Join(xdg.DataHome(), "gemini", "known_hosts")
|
||||||
|
err := hosts.Load(path)
|
||||||
|
if err != nil {
|
||||||
|
log.Fatal(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
hostsfile, err = tofu.NewHostsFile(path)
|
||||||
|
if err != nil {
|
||||||
|
log.Fatal(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
scanner = bufio.NewScanner(os.Stdin)
|
||||||
|
}
|
||||||
|
|
||||||
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:
|
||||||
%s
|
%s
|
||||||
|
|
||||||
@@ -24,49 +53,86 @@ Otherwise, this should be safe to trust.
|
|||||||
[t]rust always; trust [o]nce; [a]bort
|
[t]rust always; trust [o]nce; [a]bort
|
||||||
=> `
|
=> `
|
||||||
|
|
||||||
var (
|
func trustCertificate(hostname string, cert *x509.Certificate) error {
|
||||||
scanner = bufio.NewScanner(os.Stdin)
|
host := tofu.NewHost(hostname, cert.Raw, cert.NotAfter)
|
||||||
client = &gemini.Client{}
|
|
||||||
)
|
|
||||||
|
|
||||||
func init() {
|
knownHost, ok := hosts.Lookup(hostname)
|
||||||
client.Timeout = 30 * time.Second
|
if ok && time.Now().Before(knownHost.Expires) {
|
||||||
client.KnownHosts.LoadDefault()
|
// Check fingerprint
|
||||||
client.TrustCertificate = func(hostname string, cert *x509.Certificate) gemini.Trust {
|
if bytes.Equal(knownHost.Fingerprint, host.Fingerprint) {
|
||||||
fingerprint := gemini.NewFingerprint(cert)
|
return nil
|
||||||
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 errors.New("error: fingerprint does not match!")
|
||||||
}
|
}
|
||||||
client.CreateCertificate = func(hostname, path string) (tls.Certificate, error) {
|
|
||||||
fmt.Println("Generating client certificate for", hostname, path)
|
fmt.Printf(trustPrompt, hostname, host.Fingerprint)
|
||||||
return gemini.CreateCertificate(gemini.CertificateOptions{
|
scanner.Scan()
|
||||||
Duration: time.Hour,
|
switch scanner.Text() {
|
||||||
})
|
case "t":
|
||||||
|
hosts.Add(host)
|
||||||
|
hostsfile.WriteHost(host)
|
||||||
|
return nil
|
||||||
|
case "o":
|
||||||
|
hosts.Add(host)
|
||||||
|
return nil
|
||||||
|
default:
|
||||||
|
return errors.New("certificate not trusted")
|
||||||
}
|
}
|
||||||
client.GetInput = func(prompt string, sensitive bool) (string, bool) {
|
}
|
||||||
fmt.Printf("%s: ", prompt)
|
|
||||||
scanner.Scan()
|
func getInput(prompt string, sensitive bool) (input string, ok bool) {
|
||||||
return scanner.Text(), true
|
fmt.Printf("%s ", prompt)
|
||||||
|
scanner.Scan()
|
||||||
|
return scanner.Text(), true
|
||||||
|
}
|
||||||
|
|
||||||
|
func do(req *gemini.Request, via []*gemini.Request) (*gemini.Response, error) {
|
||||||
|
client := gemini.Client{
|
||||||
|
TrustCertificate: trustCertificate,
|
||||||
}
|
}
|
||||||
|
resp, err := client.Do(req)
|
||||||
|
if err != nil {
|
||||||
|
return resp, err
|
||||||
|
}
|
||||||
|
|
||||||
|
switch resp.Status.Class() {
|
||||||
|
case gemini.StatusClassInput:
|
||||||
|
input, ok := getInput(resp.Meta, resp.Status == gemini.StatusSensitiveInput)
|
||||||
|
if !ok {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
req.URL.ForceQuery = true
|
||||||
|
req.URL.RawQuery = gemini.QueryEscape(input)
|
||||||
|
return do(req, via)
|
||||||
|
|
||||||
|
case gemini.StatusClassRedirect:
|
||||||
|
via = append(via, req)
|
||||||
|
if len(via) > 5 {
|
||||||
|
return resp, errors.New("too many redirects")
|
||||||
|
}
|
||||||
|
|
||||||
|
target, err := url.Parse(resp.Meta)
|
||||||
|
if err != nil {
|
||||||
|
return resp, err
|
||||||
|
}
|
||||||
|
target = req.URL.ResolveReference(target)
|
||||||
|
redirect := *req
|
||||||
|
redirect.URL = target
|
||||||
|
return do(&redirect, via)
|
||||||
|
}
|
||||||
|
|
||||||
|
return resp, err
|
||||||
}
|
}
|
||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
if len(os.Args) < 2 {
|
if len(os.Args) < 2 {
|
||||||
fmt.Printf("usage: %s gemini://... [host]", os.Args[0])
|
fmt.Printf("usage: %s <url> [host]\n", os.Args[0])
|
||||||
os.Exit(1)
|
os.Exit(1)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Do the request
|
||||||
url := os.Args[1]
|
url := os.Args[1]
|
||||||
req, err := gemini.NewRequest(url)
|
req, err := gemini.NewRequest(url)
|
||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
fmt.Println(err)
|
fmt.Println(err)
|
||||||
os.Exit(1)
|
os.Exit(1)
|
||||||
@@ -74,14 +140,14 @@ func main() {
|
|||||||
if len(os.Args) == 3 {
|
if len(os.Args) == 3 {
|
||||||
req.Host = os.Args[2]
|
req.Host = os.Args[2]
|
||||||
}
|
}
|
||||||
|
resp, err := do(req, nil)
|
||||||
resp, err := client.Do(req)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
fmt.Println(err)
|
fmt.Println(err)
|
||||||
os.Exit(1)
|
os.Exit(1)
|
||||||
}
|
}
|
||||||
defer resp.Body.Close()
|
defer resp.Body.Close()
|
||||||
|
|
||||||
|
// Handle response
|
||||||
if resp.Status.Class() == gemini.StatusClassSuccess {
|
if resp.Status.Class() == gemini.StatusClassSuccess {
|
||||||
body, err := ioutil.ReadAll(resp.Body)
|
body, err := ioutil.ReadAll(resp.Body)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -89,6 +155,7 @@ func main() {
|
|||||||
}
|
}
|
||||||
fmt.Print(string(body))
|
fmt.Print(string(body))
|
||||||
} else {
|
} else {
|
||||||
fmt.Printf("request failed: %d %s: %s", resp.Status, resp.Status.Message(), resp.Meta)
|
fmt.Printf("%d %s\n", resp.Status, resp.Meta)
|
||||||
|
os.Exit(1)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
129
examples/html.go
129
examples/html.go
@@ -7,76 +7,77 @@ package main
|
|||||||
import (
|
import (
|
||||||
"fmt"
|
"fmt"
|
||||||
"html"
|
"html"
|
||||||
"strings"
|
"io"
|
||||||
|
"os"
|
||||||
|
|
||||||
"git.sr.ht/~adnano/go-gemini"
|
"git.sr.ht/~adnano/go-gemini"
|
||||||
)
|
)
|
||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
text := gemini.Text{
|
hw := HTMLWriter{
|
||||||
gemini.LineHeading1("Hello, world!"),
|
out: os.Stdout,
|
||||||
gemini.LineText("This is a gemini text document."),
|
|
||||||
}
|
}
|
||||||
|
gemini.ParseLines(os.Stdin, hw.Handle)
|
||||||
html := textToHTML(text)
|
hw.Finish()
|
||||||
fmt.Print(html)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// textToHTML returns the Gemini text response as HTML.
|
type HTMLWriter struct {
|
||||||
func textToHTML(text gemini.Text) string {
|
out io.Writer
|
||||||
var b strings.Builder
|
pre bool
|
||||||
var pre bool
|
list bool
|
||||||
var list bool
|
}
|
||||||
for _, l := range text {
|
|
||||||
if _, ok := l.(gemini.LineListItem); ok {
|
func (h *HTMLWriter) Handle(line gemini.Line) {
|
||||||
if !list {
|
if _, ok := line.(gemini.LineListItem); ok {
|
||||||
list = true
|
if !h.list {
|
||||||
fmt.Fprint(&b, "<ul>\n")
|
h.list = true
|
||||||
}
|
fmt.Fprint(h.out, "<ul>\n")
|
||||||
} else if list {
|
}
|
||||||
list = false
|
} else if h.list {
|
||||||
fmt.Fprint(&b, "</ul>\n")
|
h.list = false
|
||||||
}
|
fmt.Fprint(h.out, "</ul>\n")
|
||||||
switch l := l.(type) {
|
}
|
||||||
case gemini.LineLink:
|
switch line := line.(type) {
|
||||||
url := html.EscapeString(l.URL)
|
case gemini.LineLink:
|
||||||
name := html.EscapeString(l.Name)
|
url := html.EscapeString(line.URL)
|
||||||
if name == "" {
|
name := html.EscapeString(line.Name)
|
||||||
name = url
|
if name == "" {
|
||||||
}
|
name = url
|
||||||
fmt.Fprintf(&b, "<p><a href='%s'>%s</a></p>\n", url, name)
|
}
|
||||||
case gemini.LinePreformattingToggle:
|
fmt.Fprintf(h.out, "<p><a href='%s'>%s</a></p>\n", url, name)
|
||||||
pre = !pre
|
case gemini.LinePreformattingToggle:
|
||||||
if pre {
|
h.pre = !h.pre
|
||||||
fmt.Fprint(&b, "<pre>\n")
|
if h.pre {
|
||||||
} else {
|
fmt.Fprint(h.out, "<pre>\n")
|
||||||
fmt.Fprint(&b, "</pre>\n")
|
} else {
|
||||||
}
|
fmt.Fprint(h.out, "</pre>\n")
|
||||||
case gemini.LinePreformattedText:
|
}
|
||||||
fmt.Fprintf(&b, "%s\n", html.EscapeString(string(l)))
|
case gemini.LinePreformattedText:
|
||||||
case gemini.LineHeading1:
|
fmt.Fprintf(h.out, "%s\n", html.EscapeString(string(line)))
|
||||||
fmt.Fprintf(&b, "<h1>%s</h1>\n", html.EscapeString(string(l)))
|
case gemini.LineHeading1:
|
||||||
case gemini.LineHeading2:
|
fmt.Fprintf(h.out, "<h1>%s</h1>\n", html.EscapeString(string(line)))
|
||||||
fmt.Fprintf(&b, "<h2>%s</h2>\n", html.EscapeString(string(l)))
|
case gemini.LineHeading2:
|
||||||
case gemini.LineHeading3:
|
fmt.Fprintf(h.out, "<h2>%s</h2>\n", html.EscapeString(string(line)))
|
||||||
fmt.Fprintf(&b, "<h3>%s</h3>\n", html.EscapeString(string(l)))
|
case gemini.LineHeading3:
|
||||||
case gemini.LineListItem:
|
fmt.Fprintf(h.out, "<h3>%s</h3>\n", html.EscapeString(string(line)))
|
||||||
fmt.Fprintf(&b, "<li>%s</li>\n", html.EscapeString(string(l)))
|
case gemini.LineListItem:
|
||||||
case gemini.LineQuote:
|
fmt.Fprintf(h.out, "<li>%s</li>\n", html.EscapeString(string(line)))
|
||||||
fmt.Fprintf(&b, "<blockquote>%s</blockquote>\n", html.EscapeString(string(l)))
|
case gemini.LineQuote:
|
||||||
case gemini.LineText:
|
fmt.Fprintf(h.out, "<blockquote>%s</blockquote>\n", html.EscapeString(string(line)))
|
||||||
if l == "" {
|
case gemini.LineText:
|
||||||
fmt.Fprint(&b, "<br>\n")
|
if line == "" {
|
||||||
} else {
|
fmt.Fprint(h.out, "<br>\n")
|
||||||
fmt.Fprintf(&b, "<p>%s</p>\n", html.EscapeString(string(l)))
|
} else {
|
||||||
}
|
fmt.Fprintf(h.out, "<p>%s</p>\n", html.EscapeString(string(line)))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if pre {
|
}
|
||||||
fmt.Fprint(&b, "</pre>\n")
|
|
||||||
}
|
func (h *HTMLWriter) Finish() {
|
||||||
if list {
|
if h.pre {
|
||||||
fmt.Fprint(&b, "</ul>\n")
|
fmt.Fprint(h.out, "</pre>\n")
|
||||||
}
|
}
|
||||||
return b.String()
|
if h.list {
|
||||||
|
fmt.Fprint(h.out, "</ul>\n")
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,5 +1,7 @@
|
|||||||
// +build ignore
|
// +build ignore
|
||||||
|
|
||||||
|
// This example illustrates a Gemini server.
|
||||||
|
|
||||||
package main
|
package main
|
||||||
|
|
||||||
import (
|
import (
|
||||||
@@ -9,6 +11,7 @@ import (
|
|||||||
"time"
|
"time"
|
||||||
|
|
||||||
"git.sr.ht/~adnano/go-gemini"
|
"git.sr.ht/~adnano/go-gemini"
|
||||||
|
"git.sr.ht/~adnano/go-gemini/certificate"
|
||||||
)
|
)
|
||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
@@ -19,19 +22,19 @@ func main() {
|
|||||||
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 certificate.Create(certificate.CreateOptions{
|
||||||
Subject: pkix.Name{
|
Subject: pkix.Name{
|
||||||
CommonName: hostname,
|
CommonName: hostname,
|
||||||
},
|
},
|
||||||
DNSNames: []string{hostname},
|
DNSNames: []string{hostname},
|
||||||
Duration: time.Minute, // for testing purposes
|
Duration: 365 * 24 * time.Hour,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
var mux gemini.ServeMux
|
var mux gemini.ServeMux
|
||||||
mux.Handle("/", gemini.FileServer(gemini.Dir("/var/www")))
|
mux.Handle("/", gemini.FileServer(gemini.Dir("/var/www")))
|
||||||
|
|
||||||
server.Register("localhost", &mux)
|
server.Handle("localhost", &mux)
|
||||||
if err := server.ListenAndServe(); err != nil {
|
if err := server.ListenAndServe(); err != nil {
|
||||||
log.Fatal(err)
|
log.Fatal(err)
|
||||||
}
|
}
|
||||||
|
|||||||
71
examples/stream.go
Normal file
71
examples/stream.go
Normal file
@@ -0,0 +1,71 @@
|
|||||||
|
// +build ignore
|
||||||
|
|
||||||
|
// This example illustrates a streaming Gemini server.
|
||||||
|
|
||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"crypto/tls"
|
||||||
|
"crypto/x509/pkix"
|
||||||
|
"fmt"
|
||||||
|
"log"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"git.sr.ht/~adnano/go-gemini"
|
||||||
|
"git.sr.ht/~adnano/go-gemini/certificate"
|
||||||
|
)
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
var server gemini.Server
|
||||||
|
if err := server.Certificates.Load("/var/lib/gemini/certs"); err != nil {
|
||||||
|
log.Fatal(err)
|
||||||
|
}
|
||||||
|
server.CreateCertificate = func(hostname string) (tls.Certificate, error) {
|
||||||
|
return certificate.Create(certificate.CreateOptions{
|
||||||
|
Subject: pkix.Name{
|
||||||
|
CommonName: hostname,
|
||||||
|
},
|
||||||
|
DNSNames: []string{hostname},
|
||||||
|
Duration: 365 * 24 * time.Hour,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
server.HandleFunc("localhost", stream)
|
||||||
|
if err := server.ListenAndServe(); err != nil {
|
||||||
|
log.Fatal(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// stream writes an infinite stream to w.
|
||||||
|
func stream(w *gemini.ResponseWriter, r *gemini.Request) {
|
||||||
|
ch := make(chan string)
|
||||||
|
ctx, cancel := context.WithCancel(context.Background())
|
||||||
|
|
||||||
|
go func(ctx context.Context) {
|
||||||
|
for {
|
||||||
|
select {
|
||||||
|
case <-ctx.Done():
|
||||||
|
return
|
||||||
|
default:
|
||||||
|
ch <- fmt.Sprint(time.Now().UTC())
|
||||||
|
}
|
||||||
|
time.Sleep(time.Second)
|
||||||
|
}
|
||||||
|
// Close channel when finished.
|
||||||
|
// In this example this will never be reached.
|
||||||
|
close(ch)
|
||||||
|
}(ctx)
|
||||||
|
|
||||||
|
for {
|
||||||
|
s, ok := <-ch
|
||||||
|
if !ok {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
fmt.Fprintln(w, s)
|
||||||
|
if err := w.Flush(); err != nil {
|
||||||
|
cancel()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
27
fs.go
27
fs.go
@@ -14,7 +14,9 @@ func init() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// FileServer takes a filesystem and returns a Responder which uses that filesystem.
|
// FileServer takes a filesystem and returns a Responder which uses that filesystem.
|
||||||
// The returned Responder sanitizes paths before handling them.
|
// The returned Responder cleans paths before handling them.
|
||||||
|
//
|
||||||
|
// TODO: Use io/fs.FS when available.
|
||||||
func FileServer(fsys FS) Responder {
|
func FileServer(fsys FS) Responder {
|
||||||
return fsHandler{fsys}
|
return fsHandler{fsys}
|
||||||
}
|
}
|
||||||
@@ -27,23 +29,27 @@ func (fsh fsHandler) Respond(w *ResponseWriter, r *Request) {
|
|||||||
p := path.Clean(r.URL.Path)
|
p := path.Clean(r.URL.Path)
|
||||||
f, err := fsh.Open(p)
|
f, err := fsh.Open(p)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
w.WriteStatus(StatusNotFound)
|
w.Status(StatusNotFound)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
// Detect mimetype
|
// Detect mimetype
|
||||||
ext := path.Ext(p)
|
ext := path.Ext(p)
|
||||||
mimetype := mime.TypeByExtension(ext)
|
mimetype := mime.TypeByExtension(ext)
|
||||||
w.SetMimetype(mimetype)
|
w.Meta(mimetype)
|
||||||
// Copy file to response writer
|
// Copy file to response writer
|
||||||
io.Copy(w, f)
|
_, _ = io.Copy(w, f)
|
||||||
}
|
}
|
||||||
|
|
||||||
// TODO: replace with io/fs.FS when available
|
// FS represents a filesystem.
|
||||||
|
//
|
||||||
|
// TODO: Replace with io/fs.FS when available.
|
||||||
type FS interface {
|
type FS interface {
|
||||||
Open(name string) (File, error)
|
Open(name string) (File, error)
|
||||||
}
|
}
|
||||||
|
|
||||||
// TODO: replace with io/fs.File when available
|
// File represents a file.
|
||||||
|
//
|
||||||
|
// TODO: Replace with io/fs.File when available.
|
||||||
type File interface {
|
type File interface {
|
||||||
Stat() (os.FileInfo, error)
|
Stat() (os.FileInfo, error)
|
||||||
Read([]byte) (int, error)
|
Read([]byte) (int, error)
|
||||||
@@ -51,6 +57,8 @@ type File interface {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Dir implements FS using the native filesystem restricted to a specific directory.
|
// Dir implements FS using the native filesystem restricted to a specific directory.
|
||||||
|
//
|
||||||
|
// TODO: replace with os.DirFS when available.
|
||||||
type Dir string
|
type Dir string
|
||||||
|
|
||||||
// Open tries to open the file with the given name.
|
// Open tries to open the file with the given name.
|
||||||
@@ -62,19 +70,20 @@ func (d Dir) Open(name string) (File, error) {
|
|||||||
|
|
||||||
// ServeFile responds to the request with the contents of the named file
|
// ServeFile responds to the request with the contents of the named file
|
||||||
// or directory.
|
// or directory.
|
||||||
|
//
|
||||||
// TODO: Use io/fs.FS when available.
|
// TODO: Use io/fs.FS when available.
|
||||||
func ServeFile(w *ResponseWriter, fs FS, name string) {
|
func ServeFile(w *ResponseWriter, fs FS, name string) {
|
||||||
f, err := fs.Open(name)
|
f, err := fs.Open(name)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
w.WriteStatus(StatusNotFound)
|
w.Status(StatusNotFound)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
// Detect mimetype
|
// Detect mimetype
|
||||||
ext := path.Ext(name)
|
ext := path.Ext(name)
|
||||||
mimetype := mime.TypeByExtension(ext)
|
mimetype := mime.TypeByExtension(ext)
|
||||||
w.SetMimetype(mimetype)
|
w.Meta(mimetype)
|
||||||
// Copy file to response writer
|
// Copy file to response writer
|
||||||
io.Copy(w, f)
|
_, _ = io.Copy(w, f)
|
||||||
}
|
}
|
||||||
|
|
||||||
func openFile(p string) (File, error) {
|
func openFile(p string) (File, error) {
|
||||||
|
|||||||
25
gemini.go
25
gemini.go
@@ -2,7 +2,6 @@ package gemini
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"errors"
|
"errors"
|
||||||
"sync"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
var crlf = []byte("\r\n")
|
var crlf = []byte("\r\n")
|
||||||
@@ -10,29 +9,7 @@ var crlf = []byte("\r\n")
|
|||||||
// Errors.
|
// Errors.
|
||||||
var (
|
var (
|
||||||
ErrInvalidURL = errors.New("gemini: invalid URL")
|
ErrInvalidURL = errors.New("gemini: invalid URL")
|
||||||
|
ErrInvalidRequest = errors.New("gemini: invalid request")
|
||||||
ErrInvalidResponse = errors.New("gemini: invalid response")
|
ErrInvalidResponse = errors.New("gemini: invalid response")
|
||||||
ErrBodyNotAllowed = errors.New("gemini: response body not allowed")
|
ErrBodyNotAllowed = errors.New("gemini: response body not allowed")
|
||||||
)
|
)
|
||||||
|
|
||||||
// defaultClient is the default client. It is used by Get and Do.
|
|
||||||
var defaultClient Client
|
|
||||||
|
|
||||||
// Get performs a Gemini request for the given url.
|
|
||||||
func Get(url string) (*Response, error) {
|
|
||||||
setupDefaultClientOnce()
|
|
||||||
return defaultClient.Get(url)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Do performs a Gemini request and returns a Gemini response.
|
|
||||||
func Do(req *Request) (*Response, error) {
|
|
||||||
setupDefaultClientOnce()
|
|
||||||
return defaultClient.Do(req)
|
|
||||||
}
|
|
||||||
|
|
||||||
var defaultClientOnce sync.Once
|
|
||||||
|
|
||||||
func setupDefaultClientOnce() {
|
|
||||||
defaultClientOnce.Do(func() {
|
|
||||||
defaultClient.KnownHosts.LoadDefault()
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|||||||
6
mux.go
6
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,
|
// If the given path is /tree and its handler is not registered,
|
||||||
// redirect for /tree/.
|
// redirect for /tree/.
|
||||||
if u, ok := mux.redirectToPathSlash(path, r.URL); ok {
|
if u, ok := mux.redirectToPathSlash(path, r.URL); ok {
|
||||||
w.WriteHeader(StatusRedirect, u.String())
|
w.Header(StatusRedirect, u.String())
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
if path != r.URL.Path {
|
if path != r.URL.Path {
|
||||||
u := *r.URL
|
u := *r.URL
|
||||||
u.Path = path
|
u.Path = path
|
||||||
w.WriteHeader(StatusRedirect, u.String())
|
w.Header(StatusRedirect, u.String())
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -154,7 +154,7 @@ func (mux *ServeMux) Respond(w *ResponseWriter, r *Request) {
|
|||||||
|
|
||||||
resp := mux.match(path)
|
resp := mux.match(path)
|
||||||
if resp == nil {
|
if resp == nil {
|
||||||
w.WriteStatus(StatusNotFound)
|
w.Status(StatusNotFound)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
resp.Respond(w, r)
|
resp.Respond(w, r)
|
||||||
|
|||||||
18
query.go
Normal file
18
query.go
Normal file
@@ -0,0 +1,18 @@
|
|||||||
|
package gemini
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net/url"
|
||||||
|
"strings"
|
||||||
|
)
|
||||||
|
|
||||||
|
// QueryEscape 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)
|
||||||
|
}
|
||||||
48
request.go
48
request.go
@@ -2,7 +2,9 @@ package gemini
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"bufio"
|
"bufio"
|
||||||
|
"context"
|
||||||
"crypto/tls"
|
"crypto/tls"
|
||||||
|
"io"
|
||||||
"net"
|
"net"
|
||||||
"net/url"
|
"net/url"
|
||||||
)
|
)
|
||||||
@@ -14,11 +16,11 @@ type Request struct {
|
|||||||
|
|
||||||
// For client requests, Host specifies the host on which the URL is sought.
|
// For client requests, Host specifies the host on which the URL is sought.
|
||||||
// Host must contain a port.
|
// Host must contain a port.
|
||||||
|
//
|
||||||
// This field is ignored by the server.
|
// This field is ignored by the server.
|
||||||
Host string
|
Host string
|
||||||
|
|
||||||
// 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.
|
|
||||||
//
|
//
|
||||||
// On the server side, if the client provided a certificate then
|
// On the server side, if the client provided a certificate then
|
||||||
// Certificate.Leaf is guaranteed to be non-nil.
|
// Certificate.Leaf is guaranteed to be non-nil.
|
||||||
@@ -26,13 +28,19 @@ type Request struct {
|
|||||||
|
|
||||||
// RemoteAddr allows servers and other software to record the network
|
// RemoteAddr allows servers and other software to record the network
|
||||||
// address that sent the request.
|
// address that sent the request.
|
||||||
|
//
|
||||||
// This field is ignored by the client.
|
// This field is ignored by the client.
|
||||||
RemoteAddr net.Addr
|
RemoteAddr net.Addr
|
||||||
|
|
||||||
// TLS allows servers and other software to record information about the TLS
|
// TLS allows servers and other software to record information about the TLS
|
||||||
// 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.
|
||||||
|
// If Context is nil, the background context will be used.
|
||||||
|
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.
|
||||||
@@ -46,6 +54,9 @@ func NewRequest(rawurl string) (*Request, error) {
|
|||||||
|
|
||||||
// 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.
|
||||||
|
//
|
||||||
|
// Callers should be careful that the URL query is properly escaped.
|
||||||
|
// See the documentation for QueryEscape for more information.
|
||||||
func NewRequestFromURL(url *url.URL) *Request {
|
func NewRequestFromURL(url *url.URL) *Request {
|
||||||
host := url.Host
|
host := url.Host
|
||||||
if url.Port() == "" {
|
if url.Port() == "" {
|
||||||
@@ -57,8 +68,39 @@ func NewRequestFromURL(url *url.URL) *Request {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// write writes the Gemini request to the provided buffered writer.
|
// ReadRequest reads a Gemini request from the provided io.Reader
|
||||||
func (r *Request) write(w *bufio.Writer) error {
|
func ReadRequest(r io.Reader) (*Request, error) {
|
||||||
|
// Read URL
|
||||||
|
br := bufio.NewReader(r)
|
||||||
|
rawurl, err := br.ReadString('\r')
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
// Read terminating line feed
|
||||||
|
if b, err := br.ReadByte(); err != nil {
|
||||||
|
return nil, err
|
||||||
|
} else if b != '\n' {
|
||||||
|
return nil, ErrInvalidRequest
|
||||||
|
}
|
||||||
|
// Trim carriage return
|
||||||
|
rawurl = rawurl[:len(rawurl)-1]
|
||||||
|
// Validate URL
|
||||||
|
if len(rawurl) > 1024 {
|
||||||
|
return nil, ErrInvalidRequest
|
||||||
|
}
|
||||||
|
u, err := url.Parse(rawurl)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if u.User != nil {
|
||||||
|
// User is not allowed
|
||||||
|
return nil, ErrInvalidURL
|
||||||
|
}
|
||||||
|
return &Request{URL: u}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Write writes the Gemini request to the provided buffered writer.
|
||||||
|
func (r *Request) Write(w *bufio.Writer) error {
|
||||||
url := r.URL.String()
|
url := r.URL.String()
|
||||||
// User is invalid
|
// User is invalid
|
||||||
if r.URL.User != nil || len(url) > 1024 {
|
if r.URL.User != nil || len(url) > 1024 {
|
||||||
|
|||||||
139
response.go
139
response.go
@@ -2,10 +2,8 @@ package gemini
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"bufio"
|
"bufio"
|
||||||
"bytes"
|
|
||||||
"crypto/tls"
|
"crypto/tls"
|
||||||
"io"
|
"io"
|
||||||
"io/ioutil"
|
|
||||||
"strconv"
|
"strconv"
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -15,34 +13,35 @@ type Response struct {
|
|||||||
Status Status
|
Status Status
|
||||||
|
|
||||||
// Meta contains more information related to the response status.
|
// Meta contains more information related to the response status.
|
||||||
// For successful responses, Meta should contain the mimetype of the response.
|
// For successful responses, Meta should contain the media type of the response.
|
||||||
// For failure responses, Meta should contain a short description of the failure.
|
// For failure responses, Meta should contain a short description of the failure.
|
||||||
// Meta should not be longer than 1024 bytes.
|
// Meta should not be longer than 1024 bytes.
|
||||||
Meta string
|
Meta string
|
||||||
|
|
||||||
// Body contains the response body for successful responses.
|
// Body represents the response body.
|
||||||
// Body is guaranteed to be non-nil.
|
// Body is guaranteed to always be non-nil.
|
||||||
|
//
|
||||||
|
// The response body is streamed on demand as the Body field is read.
|
||||||
Body io.ReadCloser
|
Body io.ReadCloser
|
||||||
|
|
||||||
// Request is the request that was sent to obtain this response.
|
|
||||||
Request *Request
|
|
||||||
|
|
||||||
// TLS contains information about the TLS connection on which the response
|
// TLS contains information about the TLS connection on which the response
|
||||||
// was received.
|
// was received.
|
||||||
TLS tls.ConnectionState
|
TLS tls.ConnectionState
|
||||||
}
|
}
|
||||||
|
|
||||||
// read reads a Gemini response from the provided io.ReadCloser.
|
// ReadResponse reads a Gemini response from the provided io.ReadCloser.
|
||||||
func (resp *Response) read(rc io.ReadCloser) error {
|
func ReadResponse(rc io.ReadCloser) (*Response, error) {
|
||||||
|
resp := &Response{}
|
||||||
br := bufio.NewReader(rc)
|
br := bufio.NewReader(rc)
|
||||||
|
|
||||||
// Read the status
|
// Read the status
|
||||||
statusB := make([]byte, 2)
|
statusB := make([]byte, 2)
|
||||||
if _, err := br.Read(statusB); err != nil {
|
if _, err := br.Read(statusB); err != nil {
|
||||||
return err
|
return nil, err
|
||||||
}
|
}
|
||||||
status, err := strconv.Atoi(string(statusB))
|
status, err := strconv.Atoi(string(statusB))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return nil, err
|
||||||
}
|
}
|
||||||
resp.Status = Status(status)
|
resp.Status = Status(status)
|
||||||
|
|
||||||
@@ -50,26 +49,26 @@ func (resp *Response) read(rc io.ReadCloser) error {
|
|||||||
const minStatus, maxStatus = 1, 6
|
const minStatus, maxStatus = 1, 6
|
||||||
statusClass := resp.Status.Class()
|
statusClass := resp.Status.Class()
|
||||||
if statusClass < minStatus || statusClass > maxStatus {
|
if statusClass < minStatus || statusClass > maxStatus {
|
||||||
return ErrInvalidResponse
|
return nil, ErrInvalidResponse
|
||||||
}
|
}
|
||||||
|
|
||||||
// Read one space
|
// Read one space
|
||||||
if b, err := br.ReadByte(); err != nil {
|
if b, err := br.ReadByte(); err != nil {
|
||||||
return err
|
return nil, err
|
||||||
} else if b != ' ' {
|
} else if b != ' ' {
|
||||||
return ErrInvalidResponse
|
return nil, ErrInvalidResponse
|
||||||
}
|
}
|
||||||
|
|
||||||
// Read the meta
|
// Read the meta
|
||||||
meta, err := br.ReadString('\r')
|
meta, err := br.ReadString('\r')
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return nil, err
|
||||||
}
|
}
|
||||||
// Trim carriage return
|
// Trim carriage return
|
||||||
meta = meta[:len(meta)-1]
|
meta = meta[:len(meta)-1]
|
||||||
// Ensure meta is less than or equal to 1024 bytes
|
// Ensure meta is less than or equal to 1024 bytes
|
||||||
if len(meta) > 1024 {
|
if len(meta) > 1024 {
|
||||||
return ErrInvalidResponse
|
return nil, ErrInvalidResponse
|
||||||
}
|
}
|
||||||
// Default mime type of text/gemini; charset=utf-8
|
// Default mime type of text/gemini; charset=utf-8
|
||||||
if statusClass == StatusClassSuccess && meta == "" {
|
if statusClass == StatusClassSuccess && meta == "" {
|
||||||
@@ -79,16 +78,27 @@ func (resp *Response) read(rc io.ReadCloser) error {
|
|||||||
|
|
||||||
// Read terminating newline
|
// Read terminating newline
|
||||||
if b, err := br.ReadByte(); err != nil {
|
if b, err := br.ReadByte(); err != nil {
|
||||||
return err
|
return nil, err
|
||||||
} else if b != '\n' {
|
} else if b != '\n' {
|
||||||
return ErrInvalidResponse
|
return nil, ErrInvalidResponse
|
||||||
}
|
}
|
||||||
|
|
||||||
if resp.Status.Class() == StatusClassSuccess {
|
if resp.Status.Class() == StatusClassSuccess {
|
||||||
resp.Body = newReadCloserBody(br, rc)
|
resp.Body = newReadCloserBody(br, rc)
|
||||||
} else {
|
} else {
|
||||||
resp.Body = ioutil.NopCloser(bytes.NewReader([]byte{}))
|
resp.Body = nopReadCloser{}
|
||||||
|
rc.Close()
|
||||||
}
|
}
|
||||||
|
return resp, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
type nopReadCloser struct{}
|
||||||
|
|
||||||
|
func (nopReadCloser) Read(p []byte) (int, error) {
|
||||||
|
return 0, io.EOF
|
||||||
|
}
|
||||||
|
|
||||||
|
func (nopReadCloser) Close() error {
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -118,3 +128,92 @@ func (b *readCloserBody) Read(p []byte) (n int, err error) {
|
|||||||
}
|
}
|
||||||
return b.ReadCloser.Read(p)
|
return b.ReadCloser.Read(p)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ResponseWriter is used to construct a Gemini response.
|
||||||
|
type ResponseWriter struct {
|
||||||
|
b *bufio.Writer
|
||||||
|
status Status
|
||||||
|
meta string
|
||||||
|
setHeader bool
|
||||||
|
wroteHeader bool
|
||||||
|
bodyAllowed bool
|
||||||
|
}
|
||||||
|
|
||||||
|
// NewResponseWriter returns a ResponseWriter that uses the provided io.Writer.
|
||||||
|
func NewResponseWriter(w io.Writer) *ResponseWriter {
|
||||||
|
return &ResponseWriter{
|
||||||
|
b: bufio.NewWriter(w),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Header sets the response header.
|
||||||
|
func (w *ResponseWriter) Header(status Status, meta string) {
|
||||||
|
w.status = status
|
||||||
|
w.meta = meta
|
||||||
|
}
|
||||||
|
|
||||||
|
// Status sets the response status code.
|
||||||
|
// It also sets the response meta to status.Meta().
|
||||||
|
func (w *ResponseWriter) Status(status Status) {
|
||||||
|
w.status = status
|
||||||
|
w.meta = status.Meta()
|
||||||
|
}
|
||||||
|
|
||||||
|
// Meta sets the response meta.
|
||||||
|
//
|
||||||
|
// For successful responses, meta should contain the media type of the response.
|
||||||
|
// For failure responses, meta should contain a short description of the failure.
|
||||||
|
// The response meta should not be greater than 1024 bytes.
|
||||||
|
func (w *ResponseWriter) Meta(meta string) {
|
||||||
|
w.meta = meta
|
||||||
|
}
|
||||||
|
|
||||||
|
// Write writes data to the connection as part of the response body.
|
||||||
|
// If the response status does not allow for a response body, Write returns
|
||||||
|
// ErrBodyNotAllowed.
|
||||||
|
//
|
||||||
|
// Write writes the response header if it has not already been written.
|
||||||
|
// It writes a successful status code if one is not set.
|
||||||
|
func (w *ResponseWriter) Write(b []byte) (int, error) {
|
||||||
|
if !w.wroteHeader {
|
||||||
|
w.writeHeader(StatusSuccess)
|
||||||
|
}
|
||||||
|
if !w.bodyAllowed {
|
||||||
|
return 0, ErrBodyNotAllowed
|
||||||
|
}
|
||||||
|
return w.b.Write(b)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (w *ResponseWriter) writeHeader(defaultStatus Status) {
|
||||||
|
status := w.status
|
||||||
|
if status == 0 {
|
||||||
|
status = defaultStatus
|
||||||
|
}
|
||||||
|
|
||||||
|
meta := w.meta
|
||||||
|
if status.Class() == StatusClassSuccess {
|
||||||
|
w.bodyAllowed = true
|
||||||
|
|
||||||
|
if meta == "" {
|
||||||
|
meta = "text/gemini"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
w.b.WriteString(strconv.Itoa(int(status)))
|
||||||
|
w.b.WriteByte(' ')
|
||||||
|
w.b.WriteString(meta)
|
||||||
|
w.b.Write(crlf)
|
||||||
|
w.wroteHeader = true
|
||||||
|
}
|
||||||
|
|
||||||
|
// Flush writes any buffered data to the underlying io.Writer.
|
||||||
|
//
|
||||||
|
// Flush writes the response header if it has not already been written.
|
||||||
|
// It writes a failure status code if one is not set.
|
||||||
|
func (w *ResponseWriter) Flush() error {
|
||||||
|
if !w.wroteHeader {
|
||||||
|
w.writeHeader(StatusTemporaryFailure)
|
||||||
|
}
|
||||||
|
// Write errors from writeHeader will be returned here.
|
||||||
|
return w.b.Flush()
|
||||||
|
}
|
||||||
|
|||||||
181
server.go
181
server.go
@@ -1,15 +1,14 @@
|
|||||||
package gemini
|
package gemini
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"bufio"
|
|
||||||
"crypto/tls"
|
"crypto/tls"
|
||||||
"errors"
|
"errors"
|
||||||
"log"
|
"log"
|
||||||
"net"
|
"net"
|
||||||
"net/url"
|
|
||||||
"strconv"
|
|
||||||
"strings"
|
"strings"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
|
"git.sr.ht/~adnano/go-gemini/certificate"
|
||||||
)
|
)
|
||||||
|
|
||||||
// Server is a Gemini server.
|
// Server is a Gemini server.
|
||||||
@@ -26,7 +25,7 @@ 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 certificate.Dir
|
||||||
|
|
||||||
// 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.
|
||||||
@@ -47,12 +46,12 @@ type responderKey struct {
|
|||||||
hostname string
|
hostname string
|
||||||
}
|
}
|
||||||
|
|
||||||
// Register registers a responder for the given pattern.
|
// Handle registers a responder for the given pattern.
|
||||||
//
|
//
|
||||||
// Patterns must be in the form of "hostname" or "scheme://hostname".
|
// The pattern must be in the form of "hostname" or "scheme://hostname".
|
||||||
// If no scheme is specified, a scheme of "gemini://" is implied.
|
// If no scheme is specified, a scheme of "gemini://" is implied.
|
||||||
// Wildcard patterns are supported (e.g. "*.example.com").
|
// Wildcard patterns are supported (e.g. "*.example.com").
|
||||||
func (s *Server) Register(pattern string, responder Responder) {
|
func (s *Server) Handle(pattern string, responder Responder) {
|
||||||
if pattern == "" {
|
if pattern == "" {
|
||||||
panic("gemini: invalid pattern")
|
panic("gemini: invalid pattern")
|
||||||
}
|
}
|
||||||
@@ -81,9 +80,9 @@ func (s *Server) Register(pattern string, responder Responder) {
|
|||||||
s.hosts[key.hostname] = true
|
s.hosts[key.hostname] = true
|
||||||
}
|
}
|
||||||
|
|
||||||
// RegisterFunc registers a responder function for the given pattern.
|
// HandleFunc registers a responder function for the given pattern.
|
||||||
func (s *Server) RegisterFunc(pattern string, responder func(*ResponseWriter, *Request)) {
|
func (s *Server) HandleFunc(pattern string, responder func(*ResponseWriter, *Request)) {
|
||||||
s.Register(pattern, ResponderFunc(responder))
|
s.Handle(pattern, ResponderFunc(responder))
|
||||||
}
|
}
|
||||||
|
|
||||||
// ListenAndServe listens for requests at the server's configured address.
|
// ListenAndServe listens for requests at the server's configured address.
|
||||||
@@ -161,7 +160,7 @@ func (s *Server) getCertificateFor(hostname string) (*tls.Certificate, error) {
|
|||||||
cert, err := s.CreateCertificate(hostname)
|
cert, err := s.CreateCertificate(hostname)
|
||||||
if err == nil {
|
if err == nil {
|
||||||
if err := s.Certificates.Add(hostname, cert); err != nil {
|
if err := s.Certificates.Add(hostname, cert); err != nil {
|
||||||
s.logf("gemini: Failed to add new certificate for %s: %s", hostname, err)
|
s.logf("gemini: Failed to write new certificate for %s: %s", hostname, err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return &cert, err
|
return &cert, err
|
||||||
@@ -173,67 +172,45 @@ func (s *Server) getCertificateFor(hostname string) (*tls.Certificate, error) {
|
|||||||
|
|
||||||
// respond responds to a connection.
|
// respond responds to a connection.
|
||||||
func (s *Server) respond(conn net.Conn) {
|
func (s *Server) respond(conn net.Conn) {
|
||||||
|
defer conn.Close()
|
||||||
if d := s.ReadTimeout; d != 0 {
|
if d := s.ReadTimeout; d != 0 {
|
||||||
conn.SetReadDeadline(time.Now().Add(d))
|
_ = conn.SetReadDeadline(time.Now().Add(d))
|
||||||
}
|
}
|
||||||
if d := s.WriteTimeout; d != 0 {
|
if d := s.WriteTimeout; d != 0 {
|
||||||
conn.SetWriteDeadline(time.Now().Add(d))
|
_ = conn.SetWriteDeadline(time.Now().Add(d))
|
||||||
}
|
}
|
||||||
|
|
||||||
r := bufio.NewReader(conn)
|
w := NewResponseWriter(conn)
|
||||||
w := newResponseWriter(conn)
|
defer func() {
|
||||||
// Read requested URL
|
_ = w.Flush()
|
||||||
rawurl, err := r.ReadString('\r')
|
}()
|
||||||
|
|
||||||
|
req, err := ReadRequest(conn)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
w.Status(StatusBadRequest)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
// Read terminating line feed
|
|
||||||
if b, err := r.ReadByte(); err != nil {
|
|
||||||
return
|
|
||||||
} else if b != '\n' {
|
|
||||||
w.WriteStatus(StatusBadRequest)
|
|
||||||
}
|
|
||||||
// Trim carriage return
|
|
||||||
rawurl = rawurl[:len(rawurl)-1]
|
|
||||||
// Ensure URL is valid
|
|
||||||
if len(rawurl) > 1024 {
|
|
||||||
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.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
|
// Store information about the TLS connection
|
||||||
connState := conn.(*tls.Conn).ConnectionState()
|
if tlsConn, ok := conn.(*tls.Conn); ok {
|
||||||
var cert *tls.Certificate
|
req.TLS = tlsConn.ConnectionState()
|
||||||
if len(connState.PeerCertificates) > 0 {
|
if len(req.TLS.PeerCertificates) > 0 {
|
||||||
peerCert := connState.PeerCertificates[0]
|
peerCert := req.TLS.PeerCertificates[0]
|
||||||
// Store the TLS certificate
|
// Store the TLS certificate
|
||||||
cert = &tls.Certificate{
|
req.Certificate = &tls.Certificate{
|
||||||
Certificate: [][]byte{peerCert.Raw},
|
Certificate: [][]byte{peerCert.Raw},
|
||||||
Leaf: peerCert,
|
Leaf: peerCert,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
req := &Request{
|
|
||||||
URL: url,
|
|
||||||
RemoteAddr: conn.RemoteAddr(),
|
|
||||||
TLS: connState,
|
|
||||||
Certificate: cert,
|
|
||||||
}
|
|
||||||
resp := s.responder(req)
|
|
||||||
if resp != nil {
|
|
||||||
resp.Respond(w, req)
|
|
||||||
} else {
|
|
||||||
w.WriteStatus(StatusNotFound)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
w.b.Flush()
|
|
||||||
conn.Close()
|
resp := s.responder(req)
|
||||||
|
if resp == nil {
|
||||||
|
w.Status(StatusNotFound)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
resp.Respond(w, req)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *Server) responder(r *Request) Responder {
|
func (s *Server) responder(r *Request) Responder {
|
||||||
@@ -257,76 +234,6 @@ func (s *Server) logf(format string, args ...interface{}) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// ResponseWriter is used by a Gemini handler to construct a Gemini response.
|
|
||||||
type ResponseWriter struct {
|
|
||||||
b *bufio.Writer
|
|
||||||
bodyAllowed bool
|
|
||||||
wroteHeader bool
|
|
||||||
mimetype string
|
|
||||||
}
|
|
||||||
|
|
||||||
func newResponseWriter(conn net.Conn) *ResponseWriter {
|
|
||||||
return &ResponseWriter{
|
|
||||||
b: bufio.NewWriter(conn),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// WriteHeader writes the response header.
|
|
||||||
// If the header has already been written, WriteHeader does nothing.
|
|
||||||
//
|
|
||||||
// Meta contains more information related to the response status.
|
|
||||||
// For successful responses, Meta should contain the mimetype of the response.
|
|
||||||
// For failure responses, Meta should contain a short description of the failure.
|
|
||||||
// Meta should not be longer than 1024 bytes.
|
|
||||||
func (w *ResponseWriter) WriteHeader(status Status, meta string) {
|
|
||||||
if w.wroteHeader {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
w.b.WriteString(strconv.Itoa(int(status)))
|
|
||||||
w.b.WriteByte(' ')
|
|
||||||
w.b.WriteString(meta)
|
|
||||||
w.b.Write(crlf)
|
|
||||||
|
|
||||||
// Only allow body to be written on successful status codes.
|
|
||||||
if status.Class() == StatusClassSuccess {
|
|
||||||
w.bodyAllowed = true
|
|
||||||
}
|
|
||||||
w.wroteHeader = true
|
|
||||||
}
|
|
||||||
|
|
||||||
// WriteStatus writes the response header with the given status code.
|
|
||||||
//
|
|
||||||
// WriteStatus is equivalent to WriteHeader(status, status.Message())
|
|
||||||
func (w *ResponseWriter) WriteStatus(status Status) {
|
|
||||||
w.WriteHeader(status, status.Message())
|
|
||||||
}
|
|
||||||
|
|
||||||
// SetMimetype sets the mimetype that will be written for a successful response.
|
|
||||||
// If the mimetype is not set, it will default to "text/gemini".
|
|
||||||
func (w *ResponseWriter) SetMimetype(mimetype string) {
|
|
||||||
w.mimetype = mimetype
|
|
||||||
}
|
|
||||||
|
|
||||||
// Write writes the response body.
|
|
||||||
// If the response status does not allow for a response body, Write returns
|
|
||||||
// ErrBodyNotAllowed.
|
|
||||||
//
|
|
||||||
// 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"
|
|
||||||
}
|
|
||||||
w.WriteHeader(StatusSuccess, mimetype)
|
|
||||||
}
|
|
||||||
if !w.bodyAllowed {
|
|
||||||
return 0, ErrBodyNotAllowed
|
|
||||||
}
|
|
||||||
return w.b.Write(b)
|
|
||||||
}
|
|
||||||
|
|
||||||
// A Responder responds to a Gemini request.
|
// A Responder responds to a Gemini request.
|
||||||
type Responder interface {
|
type Responder interface {
|
||||||
// Respond accepts a Request and constructs a Response.
|
// Respond accepts a Request and constructs a Response.
|
||||||
@@ -339,23 +246,3 @@ type ResponderFunc func(*ResponseWriter, *Request)
|
|||||||
func (f ResponderFunc) Respond(w *ResponseWriter, r *Request) {
|
func (f ResponderFunc) Respond(w *ResponseWriter, r *Request) {
|
||||||
f(w, r)
|
f(w, r)
|
||||||
}
|
}
|
||||||
|
|
||||||
// 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
|
|
||||||
}
|
|
||||||
|
|||||||
16
status.go
16
status.go
@@ -41,19 +41,11 @@ func (s Status) Class() StatusClass {
|
|||||||
return StatusClass(s / 10)
|
return StatusClass(s / 10)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Message returns a status message corresponding to this status code.
|
// Meta returns a description of the status code appropriate for use in a response.
|
||||||
func (s Status) Message() string {
|
//
|
||||||
|
// Meta returns an empty string for input, success, and redirect status codes.
|
||||||
|
func (s Status) Meta() string {
|
||||||
switch s {
|
switch s {
|
||||||
case StatusInput:
|
|
||||||
return "Input"
|
|
||||||
case StatusSensitiveInput:
|
|
||||||
return "Sensitive input"
|
|
||||||
case StatusSuccess:
|
|
||||||
return "Success"
|
|
||||||
case StatusRedirect:
|
|
||||||
return "Redirect"
|
|
||||||
case StatusPermanentRedirect:
|
|
||||||
return "Permanent redirect"
|
|
||||||
case StatusTemporaryFailure:
|
case StatusTemporaryFailure:
|
||||||
return "Temporary failure"
|
return "Temporary failure"
|
||||||
case StatusServerUnavailable:
|
case StatusServerUnavailable:
|
||||||
|
|||||||
10
text.go
10
text.go
@@ -88,17 +88,17 @@ func (l LineText) line() {}
|
|||||||
type Text []Line
|
type Text []Line
|
||||||
|
|
||||||
// ParseText parses Gemini text from the provided io.Reader.
|
// ParseText parses Gemini text from the provided io.Reader.
|
||||||
func ParseText(r io.Reader) Text {
|
func ParseText(r io.Reader) (Text, error) {
|
||||||
var t Text
|
var t Text
|
||||||
ParseLines(r, func(line Line) {
|
err := ParseLines(r, func(line Line) {
|
||||||
t = append(t, line)
|
t = append(t, line)
|
||||||
})
|
})
|
||||||
return t
|
return t, err
|
||||||
}
|
}
|
||||||
|
|
||||||
// ParseLines parses Gemini text from the provided io.Reader.
|
// ParseLines parses Gemini text from the provided io.Reader.
|
||||||
// It calls handler with each line that it parses.
|
// It calls handler with each line that it parses.
|
||||||
func ParseLines(r io.Reader, handler func(Line)) {
|
func ParseLines(r io.Reader, handler func(Line)) error {
|
||||||
const spacetab = " \t"
|
const spacetab = " \t"
|
||||||
var pre bool
|
var pre bool
|
||||||
scanner := bufio.NewScanner(r)
|
scanner := bufio.NewScanner(r)
|
||||||
@@ -149,6 +149,8 @@ func ParseLines(r io.Reader, handler func(Line)) {
|
|||||||
}
|
}
|
||||||
handler(line)
|
handler(line)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
return scanner.Err()
|
||||||
}
|
}
|
||||||
|
|
||||||
// String writes the Gemini text response to a string and returns it.
|
// String writes the Gemini text response to a string and returns it.
|
||||||
|
|||||||
190
tofu.go
190
tofu.go
@@ -1,190 +0,0 @@
|
|||||||
package gemini
|
|
||||||
|
|
||||||
import (
|
|
||||||
"bufio"
|
|
||||||
"crypto/sha512"
|
|
||||||
"crypto/x509"
|
|
||||||
"fmt"
|
|
||||||
"io"
|
|
||||||
"os"
|
|
||||||
"path/filepath"
|
|
||||||
"strconv"
|
|
||||||
"strings"
|
|
||||||
)
|
|
||||||
|
|
||||||
// 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]Fingerprint
|
|
||||||
file *os.File
|
|
||||||
}
|
|
||||||
|
|
||||||
// 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
|
|
||||||
}
|
|
||||||
return k.Load(path)
|
|
||||||
}
|
|
||||||
|
|
||||||
// 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 {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
}
|
|
||||||
f, err := os.OpenFile(path, os.O_CREATE|os.O_RDONLY, 0644)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
k.Parse(f)
|
|
||||||
f.Close()
|
|
||||||
// Open the file for append-only use
|
|
||||||
f, err = os.OpenFile(path, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0644)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
k.file = 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]Fingerprint{}
|
|
||||||
}
|
|
||||||
fingerprint := NewFingerprint(cert)
|
|
||||||
k.hosts[hostname] = fingerprint
|
|
||||||
// Append to the file
|
|
||||||
if write && k.file != nil {
|
|
||||||
appendKnownHost(k.file, hostname, fingerprint)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// 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
|
|
||||||
}
|
|
||||||
|
|
||||||
// Parse parses the provided reader and adds the parsed known hosts to the list.
|
|
||||||
// Invalid lines are ignored.
|
|
||||||
func (k *KnownHosts) Parse(r io.Reader) {
|
|
||||||
if k.hosts == nil {
|
|
||||||
k.hosts = map[string]Fingerprint{}
|
|
||||||
}
|
|
||||||
scanner := bufio.NewScanner(r)
|
|
||||||
for scanner.Scan() {
|
|
||||||
text := scanner.Text()
|
|
||||||
parts := strings.Split(text, " ")
|
|
||||||
if len(parts) < 4 {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
|
|
||||||
hostname := parts[0]
|
|
||||||
algorithm := parts[1]
|
|
||||||
if algorithm != "SHA-512" {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
fingerprint := parts[2]
|
|
||||||
|
|
||||||
expires, err := strconv.ParseInt(parts[3], 10, 0)
|
|
||||||
if err != nil {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
|
|
||||||
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)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func appendKnownHost(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)
|
|
||||||
}
|
|
||||||
|
|
||||||
// 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
|
|
||||||
}
|
|
||||||
|
|
||||||
// NewFingerprint returns the SHA-512 fingerprint of the provided certificate.
|
|
||||||
func NewFingerprint(cert *x509.Certificate) Fingerprint {
|
|
||||||
sum512 := sha512.Sum512(cert.Raw)
|
|
||||||
var b strings.Builder
|
|
||||||
for i, f := range sum512 {
|
|
||||||
if i > 0 {
|
|
||||||
b.WriteByte(':')
|
|
||||||
}
|
|
||||||
fmt.Fprintf(&b, "%02X", f)
|
|
||||||
}
|
|
||||||
return Fingerprint{
|
|
||||||
Algorithm: "SHA-512",
|
|
||||||
Hex: b.String(),
|
|
||||||
Expires: cert.NotAfter.Unix(),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// 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 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
|
|
||||||
}
|
|
||||||
344
tofu/tofu.go
Normal file
344
tofu/tofu.go
Normal file
@@ -0,0 +1,344 @@
|
|||||||
|
// Package tofu implements trust on first use using hosts and fingerprints.
|
||||||
|
package tofu
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bufio"
|
||||||
|
"bytes"
|
||||||
|
"crypto/sha512"
|
||||||
|
"crypto/x509"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"os"
|
||||||
|
"sort"
|
||||||
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
"sync"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
// KnownHosts represents a list of known hosts.
|
||||||
|
// The zero value for KnownHosts represents an empty list ready to use.
|
||||||
|
//
|
||||||
|
// KnownHosts is safe for concurrent use by multiple goroutines.
|
||||||
|
type KnownHosts struct {
|
||||||
|
hosts map[string]Host
|
||||||
|
mu sync.RWMutex
|
||||||
|
}
|
||||||
|
|
||||||
|
// Add adds a host to the list of known hosts.
|
||||||
|
func (k *KnownHosts) Add(h Host) error {
|
||||||
|
k.mu.Lock()
|
||||||
|
defer k.mu.Unlock()
|
||||||
|
if k.hosts == nil {
|
||||||
|
k.hosts = map[string]Host{}
|
||||||
|
}
|
||||||
|
|
||||||
|
k.hosts[h.Hostname] = h
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Lookup returns the known host entry corresponding to the given hostname.
|
||||||
|
func (k *KnownHosts) Lookup(hostname string) (Host, bool) {
|
||||||
|
k.mu.RLock()
|
||||||
|
defer k.mu.RUnlock()
|
||||||
|
c, ok := k.hosts[hostname]
|
||||||
|
return c, ok
|
||||||
|
}
|
||||||
|
|
||||||
|
// Entries returns the known host entries sorted by hostname.
|
||||||
|
func (k *KnownHosts) Entries() []Host {
|
||||||
|
keys := make([]string, 0, len(k.hosts))
|
||||||
|
for key := range k.hosts {
|
||||||
|
keys = append(keys, key)
|
||||||
|
}
|
||||||
|
sort.Strings(keys)
|
||||||
|
|
||||||
|
hosts := make([]Host, 0, len(k.hosts))
|
||||||
|
for _, key := range keys {
|
||||||
|
hosts = append(hosts, k.hosts[key])
|
||||||
|
}
|
||||||
|
return hosts
|
||||||
|
}
|
||||||
|
|
||||||
|
// WriteTo writes the list of known hosts to the provided io.Writer.
|
||||||
|
func (k *KnownHosts) WriteTo(w io.Writer) (int64, error) {
|
||||||
|
k.mu.RLock()
|
||||||
|
defer k.mu.RUnlock()
|
||||||
|
|
||||||
|
var written int
|
||||||
|
|
||||||
|
bw := bufio.NewWriter(w)
|
||||||
|
for _, h := range k.hosts {
|
||||||
|
n, err := bw.WriteString(h.String())
|
||||||
|
written += n
|
||||||
|
if err != nil {
|
||||||
|
return int64(written), err
|
||||||
|
}
|
||||||
|
|
||||||
|
bw.WriteByte('\n')
|
||||||
|
written += 1
|
||||||
|
}
|
||||||
|
|
||||||
|
return int64(written), bw.Flush()
|
||||||
|
}
|
||||||
|
|
||||||
|
// Load loads the known hosts entries from the provided path.
|
||||||
|
func (k *KnownHosts) Load(path string) error {
|
||||||
|
f, err := os.Open(path)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
defer f.Close()
|
||||||
|
|
||||||
|
return k.Parse(f)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Parse parses the provided io.Reader and adds the parsed hosts to the list.
|
||||||
|
// Invalid entries are ignored.
|
||||||
|
//
|
||||||
|
// For more control over errors encountered during parsing, use bufio.Scanner
|
||||||
|
// in combination with ParseHost. For example:
|
||||||
|
//
|
||||||
|
// var knownHosts tofu.KnownHosts
|
||||||
|
// scanner := bufio.NewScanner(r)
|
||||||
|
// for scanner.Scan() {
|
||||||
|
// host, err := tofu.ParseHost(scanner.Bytes())
|
||||||
|
// if err != nil {
|
||||||
|
// // handle error
|
||||||
|
// } else {
|
||||||
|
// knownHosts.Add(host)
|
||||||
|
// }
|
||||||
|
// }
|
||||||
|
// err := scanner.Err()
|
||||||
|
// if err != nil {
|
||||||
|
// // handle error
|
||||||
|
// }
|
||||||
|
//
|
||||||
|
func (k *KnownHosts) Parse(r io.Reader) error {
|
||||||
|
k.mu.Lock()
|
||||||
|
defer k.mu.Unlock()
|
||||||
|
|
||||||
|
if k.hosts == nil {
|
||||||
|
k.hosts = map[string]Host{}
|
||||||
|
}
|
||||||
|
|
||||||
|
scanner := bufio.NewScanner(r)
|
||||||
|
for scanner.Scan() {
|
||||||
|
text := scanner.Bytes()
|
||||||
|
if len(text) == 0 {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
h, err := ParseHost(text)
|
||||||
|
if err != nil {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
k.hosts[h.Hostname] = h
|
||||||
|
}
|
||||||
|
|
||||||
|
return scanner.Err()
|
||||||
|
}
|
||||||
|
|
||||||
|
// TOFU implements basic trust on first use.
|
||||||
|
//
|
||||||
|
// If the host is not on file, it is added to the list.
|
||||||
|
// If the host on file is expired, it is replaced with the provided host.
|
||||||
|
// If the fingerprint does not match the one on file, an error is returned.
|
||||||
|
func (k *KnownHosts) TOFU(hostname string, cert *x509.Certificate) error {
|
||||||
|
host := NewHost(hostname, cert.Raw, cert.NotAfter)
|
||||||
|
|
||||||
|
knownHost, ok := k.Lookup(hostname)
|
||||||
|
if !ok || time.Now().After(knownHost.Expires) {
|
||||||
|
k.Add(host)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check fingerprint
|
||||||
|
if !bytes.Equal(knownHost.Fingerprint, host.Fingerprint) {
|
||||||
|
return fmt.Errorf("fingerprint for %q does not match", hostname)
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// HostWriter writes host entries to an io.WriteCloser.
|
||||||
|
//
|
||||||
|
// HostWriter is safe for concurrent use by multiple goroutines.
|
||||||
|
type HostWriter struct {
|
||||||
|
bw *bufio.Writer
|
||||||
|
cl io.Closer
|
||||||
|
mu sync.Mutex
|
||||||
|
}
|
||||||
|
|
||||||
|
// NewHostWriter returns a new host writer that writes to
|
||||||
|
// the provided io.WriteCloser.
|
||||||
|
func NewHostWriter(w io.WriteCloser) *HostWriter {
|
||||||
|
return &HostWriter{
|
||||||
|
bw: bufio.NewWriter(w),
|
||||||
|
cl: w,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// NewHostsFile returns a new host writer that appends to the file at the given path.
|
||||||
|
// The file is created if it does not exist.
|
||||||
|
func NewHostsFile(path string) (*HostWriter, error) {
|
||||||
|
f, err := os.OpenFile(path, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return NewHostWriter(f), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// WriteHost writes the host to the underlying io.Writer.
|
||||||
|
func (h *HostWriter) WriteHost(host Host) error {
|
||||||
|
h.mu.Lock()
|
||||||
|
defer h.mu.Unlock()
|
||||||
|
|
||||||
|
h.bw.WriteString(host.String())
|
||||||
|
h.bw.WriteByte('\n')
|
||||||
|
|
||||||
|
if err := h.bw.Flush(); err != nil {
|
||||||
|
return fmt.Errorf("failed to write host: %w", err)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Close closes the underlying io.Closer.
|
||||||
|
func (h *HostWriter) Close() error {
|
||||||
|
h.mu.Lock()
|
||||||
|
defer h.mu.Unlock()
|
||||||
|
return h.cl.Close()
|
||||||
|
}
|
||||||
|
|
||||||
|
// Host represents a host entry with a fingerprint using a certain algorithm.
|
||||||
|
type Host struct {
|
||||||
|
Hostname string // hostname
|
||||||
|
Algorithm string // fingerprint algorithm e.g. SHA-512
|
||||||
|
Fingerprint Fingerprint // fingerprint
|
||||||
|
Expires time.Time // unix time of the fingerprint expiration date
|
||||||
|
}
|
||||||
|
|
||||||
|
// NewHost returns a new host with a SHA-512 fingerprint of
|
||||||
|
// the provided raw data.
|
||||||
|
func NewHost(hostname string, raw []byte, expires time.Time) Host {
|
||||||
|
sum := sha512.Sum512(raw)
|
||||||
|
|
||||||
|
return Host{
|
||||||
|
Hostname: hostname,
|
||||||
|
Algorithm: "SHA-512",
|
||||||
|
Fingerprint: sum[:],
|
||||||
|
Expires: expires,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ParseHost parses a host from the provided text.
|
||||||
|
func ParseHost(text []byte) (Host, error) {
|
||||||
|
var h Host
|
||||||
|
err := h.UnmarshalText(text)
|
||||||
|
return h, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// String returns a string representation of the host.
|
||||||
|
func (h Host) String() string {
|
||||||
|
var b strings.Builder
|
||||||
|
b.WriteString(h.Hostname)
|
||||||
|
b.WriteByte(' ')
|
||||||
|
b.WriteString(h.Algorithm)
|
||||||
|
b.WriteByte(' ')
|
||||||
|
b.WriteString(h.Fingerprint.String())
|
||||||
|
b.WriteByte(' ')
|
||||||
|
b.WriteString(strconv.FormatInt(h.Expires.Unix(), 10))
|
||||||
|
return b.String()
|
||||||
|
}
|
||||||
|
|
||||||
|
// UnmarshalText unmarshals the host from the provided text.
|
||||||
|
func (h *Host) UnmarshalText(text []byte) error {
|
||||||
|
const format = "hostname algorithm hex-fingerprint expiry-unix-ts"
|
||||||
|
|
||||||
|
parts := bytes.Split(text, []byte(" "))
|
||||||
|
if len(parts) != 4 {
|
||||||
|
return fmt.Errorf(
|
||||||
|
"expected the format %q", format)
|
||||||
|
}
|
||||||
|
|
||||||
|
if len(parts[0]) == 0 {
|
||||||
|
return errors.New("empty hostname")
|
||||||
|
}
|
||||||
|
|
||||||
|
h.Hostname = string(parts[0])
|
||||||
|
|
||||||
|
algorithm := string(parts[1])
|
||||||
|
if algorithm != "SHA-512" {
|
||||||
|
return fmt.Errorf(
|
||||||
|
"unsupported algorithm %q", algorithm)
|
||||||
|
}
|
||||||
|
|
||||||
|
h.Algorithm = algorithm
|
||||||
|
|
||||||
|
fingerprint := make([]byte, 0, sha512.Size)
|
||||||
|
scanner := bufio.NewScanner(bytes.NewReader(parts[2]))
|
||||||
|
scanner.Split(scanFingerprint)
|
||||||
|
|
||||||
|
for scanner.Scan() {
|
||||||
|
b, err := strconv.ParseUint(scanner.Text(), 16, 8)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("failed to parse fingerprint hash: %w", err)
|
||||||
|
}
|
||||||
|
fingerprint = append(fingerprint, byte(b))
|
||||||
|
}
|
||||||
|
|
||||||
|
if len(fingerprint) != sha512.Size {
|
||||||
|
return fmt.Errorf("invalid fingerprint size %d, expected %d",
|
||||||
|
len(fingerprint), sha512.Size)
|
||||||
|
}
|
||||||
|
|
||||||
|
h.Fingerprint = fingerprint
|
||||||
|
|
||||||
|
unix, err := strconv.ParseInt(string(parts[3]), 10, 0)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf(
|
||||||
|
"invalid unix timestamp: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
h.Expires = time.Unix(unix, 0)
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func scanFingerprint(data []byte, atEOF bool) (advance int, token []byte, err error) {
|
||||||
|
if atEOF && len(data) == 0 {
|
||||||
|
return 0, nil, nil
|
||||||
|
}
|
||||||
|
if i := bytes.IndexByte(data, ':'); i >= 0 {
|
||||||
|
// We have a full newline-terminated line.
|
||||||
|
return i + 1, data[0:i], nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// If we're at EOF, we have a final, non-terminated hex byte
|
||||||
|
if atEOF {
|
||||||
|
return len(data), data, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Request more data.
|
||||||
|
return 0, nil, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Fingerprint represents a fingerprint.
|
||||||
|
type Fingerprint []byte
|
||||||
|
|
||||||
|
// String returns a string representation of the fingerprint.
|
||||||
|
func (f Fingerprint) String() string {
|
||||||
|
var sb strings.Builder
|
||||||
|
|
||||||
|
for i, b := range f {
|
||||||
|
if i > 0 {
|
||||||
|
sb.WriteByte(':')
|
||||||
|
}
|
||||||
|
|
||||||
|
fmt.Fprintf(&sb, "%02X", b)
|
||||||
|
}
|
||||||
|
|
||||||
|
return sb.String()
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user