17 Commits

Author SHA1 Message Date
Adnan Maolood
7fb1b6c6a4 Update documentation 2020-11-01 00:10:30 -04:00
Adnan Maolood
0d3230a7d5 Rename InsecureTrustAlways to InsecureSkipTrust 2020-10-31 23:41:30 -04:00
Adnan Maolood
79b3b22e69 Update documentation 2020-10-31 23:05:31 -04:00
Adnan Maolood
33c1dc435d Guarantee that (*Response).Body is non-nil 2020-10-31 23:04:47 -04:00
Adnan Maolood
dad8f38bfb Fix examples/client.go 2020-10-31 22:50:42 -04:00
Adnan Maolood
8181b86759 Add option to skip trust checks 2020-10-31 22:45:21 -04:00
Adnan Maolood
65a5065250 Refactor client.TrustCertificate workflow 2020-10-31 22:34:51 -04:00
Adnan Maolood
b9cb7fe71d Update log.Printf calls 2020-10-31 21:33:59 -04:00
Adnan Maolood
7d470c5fb1 Implement Server read and write timeouts 2020-10-31 21:07:02 -04:00
Adnan Maolood
42c95f8c8d Implement Client connection timeout 2020-10-31 20:55:56 -04:00
Adnan Maolood
a2fc1772bf Set default mimetype if META is empty 2020-10-31 20:32:38 -04:00
Adnan Maolood
63b9b484d1 Remove Redirect and PermanentRedirect functions
Use (*ResponseWriter).WriteHeader instead.
2020-10-31 16:51:10 -04:00
Adnan Maolood
ca8e0166fc Add ErrCertificateNotFound 2020-10-31 16:45:38 -04:00
Adnan Maolood
14ef3be6fe server: Automatically write new certificates to disk 2020-10-31 16:33:56 -04:00
Adnan Maolood
3aa254870a Call CreateCertificate for missing certificates 2020-10-31 15:38:39 -04:00
Adnan Maolood
a89065babb Fix handling of wildcard hostnames 2020-10-31 15:11:05 -04:00
Adnan Maolood
eb466ad02f Add ParseLines function 2020-10-29 09:42:53 -04:00
13 changed files with 282 additions and 283 deletions

48
cert.go
View File

@@ -6,17 +6,22 @@ import (
"crypto/rand"
"crypto/tls"
"crypto/x509"
"encoding/pem"
"log"
"math/big"
"net"
"os"
"path/filepath"
"strings"
"time"
)
// CertificateStore maps hostnames to certificates.
// CertificateStore maps certificate scopes to certificates.
// The zero value of CertificateStore is an empty store ready to use.
type CertificateStore struct {
store map[string]tls.Certificate
dir bool
path string
}
// Add adds a certificate for the given scope to the store.
@@ -32,6 +37,15 @@ func (c *CertificateStore) Add(scope string, cert tls.Certificate) {
cert.Leaf = parsed
}
}
if c.dir {
// Write certificates
log.Printf("gemini: Writing certificate for %s to %s", scope, c.path)
certPath := filepath.Join(c.path, scope+".crt")
keyPath := filepath.Join(c.path, scope+".key")
if err := WriteCertificate(cert, certPath, keyPath); err != nil {
log.Printf("gemini: Failed to write certificate for %s: %s", scope, err)
}
}
c.store[scope] = cert
}
@@ -39,7 +53,7 @@ func (c *CertificateStore) Add(scope string, cert tls.Certificate) {
func (c *CertificateStore) Lookup(scope string) (*tls.Certificate, error) {
cert, ok := c.store[scope]
if !ok {
return nil, ErrCertificateUnknown
return nil, ErrCertificateNotFound
}
// Ensure that the certificate is not expired
if cert.Leaf != nil && cert.Leaf.NotAfter.Before(time.Now()) {
@@ -53,6 +67,7 @@ func (c *CertificateStore) Lookup(scope string) (*tls.Certificate, error) {
// in the form scope.crt and scope.key.
// For example, the hostname "localhost" would have the corresponding files
// localhost.crt (certificate) and localhost.key (private key).
// New certificates will be written to this directory.
func (c *CertificateStore) Load(path string) error {
matches, err := filepath.Glob(filepath.Join(path, "*.crt"))
if err != nil {
@@ -67,6 +82,8 @@ func (c *CertificateStore) Load(path string) error {
scope := strings.TrimSuffix(filepath.Base(crtPath), ".crt")
c.Add(scope, cert)
}
c.dir = true
c.path = path
return nil
}
@@ -133,3 +150,30 @@ func newX509KeyPair(options CertificateOptions) (*x509.Certificate, crypto.Priva
}
return cert, priv, nil
}
// WriteCertificate writes the provided certificate and private key
// to certPath and keyPath respectively.
func WriteCertificate(cert tls.Certificate, certPath, keyPath string) error {
certOut, err := os.OpenFile(certPath, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0600)
if err != nil {
return err
}
defer certOut.Close()
if err := pem.Encode(certOut, &pem.Block{
Type: "CERTIFICATE",
Bytes: cert.Leaf.Raw,
}); err != nil {
return err
}
keyOut, err := os.OpenFile(keyPath, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0600)
if err != nil {
return err
}
defer keyOut.Close()
privBytes, err := x509.MarshalPKCS8PrivateKey(cert.PrivateKey)
if err != nil {
return err
}
return pem.Encode(keyOut, &pem.Block{Type: "PRIVATE KEY", Bytes: privBytes})
}

View File

@@ -8,6 +8,7 @@ import (
"net/url"
"path"
"strings"
"time"
)
// Client is a Gemini client.
@@ -18,6 +19,20 @@ type Client struct {
// Certificates stores client-side certificates.
Certificates CertificateStore
// Timeout specifies a time limit for requests made by this
// Client. The timeout includes connection time and reading
// the response body. The timer remains running after
// Get and Do return and will interrupt reading of the Response.Body.
//
// A Timeout of zero means no timeout.
Timeout time.Duration
// InsecureSkipTrust specifies whether the client should trust
// any certificate it receives without checking KnownHosts
// or calling TrustCertificate.
// Use with caution.
InsecureSkipTrust bool
// GetInput is called to retrieve input when the server requests it.
// If GetInput is nil or returns false, no input will be sent and
// the response will be returned.
@@ -34,12 +49,16 @@ type Client struct {
// the request will not be sent again and the response will be returned.
CreateCertificate func(hostname, path string) (tls.Certificate, error)
// TrustCertificate determines whether the client should trust
// the provided certificate.
// If the returned error is not nil, the connection will be aborted.
// If TrustCertificate is nil, the client will check KnownHosts
// for the certificate.
TrustCertificate func(hostname string, cert *x509.Certificate, knownHosts *KnownHosts) error
// TrustCertificate is called to determine whether the client
// should trust a certificate it has not seen before.
// If TrustCertificate is nil, the certificate will not be trusted
// and the connection will be aborted.
//
// If TrustCertificate returns TrustOnce, the certificate will be added
// to the client's list of known hosts.
// If TrustCertificate returns TrustAlways, the certificate will also be
// written to the known hosts file.
TrustCertificate func(hostname string, cert *x509.Certificate) Trust
}
// Get performs a Gemini request for the given url.
@@ -72,7 +91,10 @@ func (c *Client) do(req *Request, via []*Request) (*Response, error) {
if err != nil {
return nil, err
}
// TODO: Set connection deadline
// Set connection deadline
if d := c.Timeout; d != 0 {
conn.SetDeadline(time.Now().Add(d))
}
// Write the request
w := bufio.NewWriter(conn)
@@ -186,12 +208,25 @@ func (c *Client) verifyConnection(req *Request, cs tls.ConnectionState) error {
if err := verifyHostname(cert, hostname); err != nil {
return err
}
// Check that the client trusts the certificate
var err error
if c.InsecureSkipTrust {
return nil
}
// Check the known hosts
err := c.KnownHosts.Lookup(hostname, cert)
switch err {
case ErrCertificateExpired, ErrCertificateNotFound:
// See if the client trusts the certificate
if c.TrustCertificate != nil {
return c.TrustCertificate(hostname, cert, &c.KnownHosts)
} else {
err = c.KnownHosts.Lookup(hostname, cert)
switch c.TrustCertificate(hostname, cert) {
case TrustOnce:
c.KnownHosts.AddTemporary(hostname, cert)
return nil
case TrustAlways:
c.KnownHosts.Add(hostname, cert)
return nil
}
}
return ErrCertificateNotTrusted
}
return err
}

39
doc.go
View File

@@ -3,57 +3,30 @@ Package gemini implements the Gemini protocol.
Get makes a Gemini request:
resp, err := gemini.Get("gemini://example.com")
if err != nil {
// handle error
}
// ...
The client must close the response body when finished with it:
resp, err := gemini.Get("gemini://example.com")
if err != nil {
// handle error
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
// ...
For control over client behavior, create a Client:
var client gemini.Client
client := &gemini.Client{}
resp, err := client.Get("gemini://example.com")
if err != nil {
// handle error
}
// ...
Clients can load their own list of known hosts:
err := client.KnownHosts.Load("path/to/my/known_hosts")
if err != nil {
// handle error
}
Clients can control when to trust certificates with TrustCertificate:
client.TrustCertificate = func(hostname string, cert *x509.Certificate, knownHosts *gemini.KnownHosts) error {
return knownHosts.Lookup(hostname, cert)
}
Clients can create client certificates upon the request of a server:
client.CreateCertificate = func(hostname, path string) (tls.Certificate, error) {
return gemini.CreateCertificate(gemini.CertificateOptions{
Duration: time.Hour,
})
}
Server is a Gemini server.
var server gemini.Server
server := &gemini.Server{
ReadTimeout: 10 * time.Second,
WriteTimeout: 10 * time.Second,
}
Servers must be configured with certificates:
Servers should be configured with certificates:
err := server.Certificates.Load("/var/lib/gemini/certs")
if err != nil {

View File

@@ -70,7 +70,7 @@ func login(w *gemini.ResponseWriter, r *gemini.Request) {
sessions[fingerprint] = &session{
username: username,
}
gemini.Redirect(w, "/password")
w.WriteHeader(gemini.StatusRedirect, "/password")
}
func loginPassword(w *gemini.ResponseWriter, r *gemini.Request) {
@@ -91,7 +91,7 @@ func loginPassword(w *gemini.ResponseWriter, r *gemini.Request) {
expected := logins[session.username].password
if password == expected {
session.authorized = true
gemini.Redirect(w, "/profile")
w.WriteHeader(gemini.StatusRedirect, "/profile")
} else {
gemini.SensitiveInput(w, r, "Wrong password. Try again")
}

View File

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

View File

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

View File

@@ -1,11 +1,8 @@
package gemini
import (
"crypto/tls"
"crypto/x509"
"errors"
"sync"
"time"
)
var crlf = []byte("\r\n")
@@ -14,15 +11,15 @@ var crlf = []byte("\r\n")
var (
ErrInvalidURL = errors.New("gemini: invalid URL")
ErrInvalidResponse = errors.New("gemini: invalid response")
ErrCertificateUnknown = errors.New("gemini: unknown certificate")
ErrCertificateExpired = errors.New("gemini: certificate expired")
ErrCertificateNotTrusted = errors.New("gemini: certificate is not trusted")
ErrCertificateNotFound = errors.New("gemini: certificate not found")
ErrCertificateNotTrusted = errors.New("gemini: certificate not trusted")
ErrCertificateRequired = errors.New("gemini: certificate required")
ErrNotAFile = errors.New("gemini: not a file")
ErrNotAGeminiURL = errors.New("gemini: not a Gemini URL")
ErrBodyNotAllowed = errors.New("gemini: response status code does not allow for body")
ErrTooManyRedirects = errors.New("gemini: too many redirects")
ErrInputRequired = errors.New("gemini: input required")
ErrCertificateRequired = errors.New("gemini: certificate required")
)
// DefaultClient is the default client. It is used by Get and Do.
@@ -34,6 +31,7 @@ var DefaultClient Client
//
// Get is a wrapper around DefaultClient.Get.
func Get(url string) (*Response, error) {
setupDefaultClientOnce()
return DefaultClient.Get(url)
}
@@ -41,19 +39,14 @@ func Get(url string) (*Response, error) {
//
// Do is a wrapper around DefaultClient.Do.
func Do(req *Request) (*Response, error) {
setupDefaultClientOnce()
return DefaultClient.Do(req)
}
var defaultClientOnce sync.Once
func init() {
DefaultClient.TrustCertificate = func(hostname string, cert *x509.Certificate, knownHosts *KnownHosts) error {
defaultClientOnce.Do(func() { knownHosts.LoadDefault() })
return knownHosts.Lookup(hostname, cert)
}
DefaultClient.CreateCertificate = func(hostname, path string) (tls.Certificate, error) {
return CreateCertificate(CertificateOptions{
Duration: time.Hour,
func setupDefaultClientOnce() {
defaultClientOnce.Do(func() {
DefaultClient.KnownHosts.LoadDefault()
})
}
}

4
mux.go
View File

@@ -138,14 +138,14 @@ func (mux *ServeMux) Respond(w *ResponseWriter, r *Request) {
// If the given path is /tree and its handler is not registered,
// redirect for /tree/.
if u, ok := mux.redirectToPathSlash(path, r.URL); ok {
Redirect(w, u.String())
w.WriteHeader(StatusRedirect, u.String())
return
}
if path != r.URL.Path {
u := *r.URL
u.Path = path
Redirect(w, u.String())
w.WriteHeader(StatusRedirect, u.String())
return
}

View File

@@ -2,14 +2,16 @@ package gemini
import (
"bufio"
"bytes"
"crypto/tls"
"io"
"io/ioutil"
"strconv"
)
// Response is a Gemini response.
type Response struct {
// Status represents the response status.
// Status contains the response status code.
Status Status
// Meta contains more information related to the response status.
@@ -19,9 +21,10 @@ type Response struct {
Meta string
// Body contains the response body for successful responses.
// Body is guaranteed to be non-nil.
Body io.ReadCloser
// Request is the request that was sent to obtain this Response.
// Request is the request that was sent to obtain this response.
Request *Request
// TLS contains information about the TLS connection on which the response
@@ -68,6 +71,10 @@ func (resp *Response) read(rc io.ReadCloser) error {
if len(meta) > 1024 {
return ErrInvalidResponse
}
// Default mime type of text/gemini; charset=utf-8
if statusClass == StatusClassSuccess && meta == "" {
meta = "text/gemini; charset=utf-8"
}
resp.Meta = meta
// Read terminating newline
@@ -79,6 +86,8 @@ func (resp *Response) read(rc io.ReadCloser) error {
if resp.Status.Class() == StatusClassSuccess {
resp.Body = newReadCloserBody(br, rc)
} else {
resp.Body = ioutil.NopCloser(bytes.NewReader([]byte{}))
}
return nil
}

View File

@@ -18,6 +18,13 @@ type Server struct {
// If Addr is empty, the server will listen on the address ":1965".
Addr string
// ReadTimeout is the maximum duration for reading a request.
ReadTimeout time.Duration
// WriteTimeout is the maximum duration before timing out
// writes of the response.
WriteTimeout time.Duration
// Certificates contains the certificates used by the server.
Certificates CertificateStore
@@ -27,25 +34,19 @@ type Server struct {
// registered responders
responders map[responderKey]Responder
hosts map[string]bool
}
type responderKey struct {
scheme string
hostname string
wildcard bool
}
// Register registers a responder for the given pattern.
//
// Patterns must be in the form of hostname or scheme://hostname
// (e.g. gemini://example.com).
// If no scheme is specified, a default scheme of gemini:// is assumed.
//
// Wildcard patterns are supported (e.g. *.example.com).
// To register a certificate for a wildcard hostname, call Certificates.Add:
//
// var s gemini.Server
// s.Certificates.Add("*.example.com", cert)
// Patterns must be in the form of "hostname" or "scheme://hostname".
// If no scheme is specified, a scheme of "gemini://" is implied.
// Wildcard patterns are supported (e.g. "*.example.com").
func (s *Server) Register(pattern string, responder Responder) {
if pattern == "" {
panic("gemini: invalid pattern")
@@ -55,6 +56,7 @@ func (s *Server) Register(pattern string, responder Responder) {
}
if s.responders == nil {
s.responders = map[responderKey]Responder{}
s.hosts = map[string]bool{}
}
split := strings.SplitN(pattern, "://", 2)
@@ -66,16 +68,12 @@ func (s *Server) Register(pattern string, responder Responder) {
key.scheme = "gemini"
key.hostname = split[0]
}
split = strings.SplitN(key.hostname, ".", 2)
if len(split) == 2 && split[0] == "*" {
key.hostname = split[1]
key.wildcard = true
}
if _, ok := s.responders[key]; ok {
panic("gemini: multiple registrations for " + pattern)
}
s.responders[key] = responder
s.hosts[key.hostname] = true
}
// RegisterFunc registers a responder function for the given pattern.
@@ -135,22 +133,46 @@ func (s *Server) Serve(l net.Listener) error {
}
func (s *Server) getCertificate(h *tls.ClientHelloInfo) (*tls.Certificate, error) {
cert, err := s.Certificates.Lookup(h.ServerName)
switch err {
case ErrCertificateExpired, ErrCertificateUnknown:
if s.CreateCertificate != nil {
cert, err := s.CreateCertificate(h.ServerName)
if err == nil {
s.Certificates.Add(h.ServerName, cert)
}
return &cert, err
cert, err := s.getCertificateFor(h.ServerName)
if err != nil {
// Try wildcard
wildcard := strings.SplitN(h.ServerName, ".", 2)
if len(wildcard) == 2 {
cert, err = s.getCertificateFor("*." + wildcard[1])
}
}
return cert, err
}
func (s *Server) getCertificateFor(hostname string) (*tls.Certificate, error) {
if _, ok := s.hosts[hostname]; !ok {
return nil, ErrCertificateNotFound
}
cert, err := s.Certificates.Lookup(hostname)
switch err {
case ErrCertificateNotFound, ErrCertificateExpired:
if s.CreateCertificate != nil {
cert, err := s.CreateCertificate(hostname)
if err == nil {
s.Certificates.Add(hostname, cert)
}
return &cert, err
}
}
return cert, err
}
// respond responds to a connection.
func (s *Server) respond(conn net.Conn) {
if d := s.ReadTimeout; d != 0 {
conn.SetReadDeadline(time.Now().Add(d))
}
if d := s.WriteTimeout; d != 0 {
conn.SetWriteDeadline(time.Now().Add(d))
}
r := bufio.NewReader(conn)
w := newResponseWriter(conn)
// Read requested URL
@@ -162,16 +184,16 @@ func (s *Server) respond(conn net.Conn) {
if b, err := r.ReadByte(); err != nil {
return
} else if b != '\n' {
w.WriteHeader(StatusBadRequest, "Bad request")
w.WriteStatus(StatusBadRequest)
}
// Trim carriage return
rawurl = rawurl[:len(rawurl)-1]
// Ensure URL is valid
if len(rawurl) > 1024 {
w.WriteHeader(StatusBadRequest, "Bad request")
w.WriteStatus(StatusBadRequest)
} else if url, err := url.Parse(rawurl); err != nil || url.User != nil {
// Note that we return an error status if User is specified in the URL
w.WriteHeader(StatusBadRequest, "Bad request")
w.WriteStatus(StatusBadRequest)
} else {
// If no scheme is specified, assume a default scheme of gemini://
if url.Scheme == "" {
@@ -194,12 +216,12 @@ func (s *Server) respond(conn net.Conn) {
}
func (s *Server) responder(r *Request) Responder {
if h, ok := s.responders[responderKey{r.URL.Scheme, r.URL.Hostname(), false}]; ok {
if h, ok := s.responders[responderKey{r.URL.Scheme, r.URL.Hostname()}]; ok {
return h
}
wildcard := strings.SplitN(r.URL.Hostname(), ".", 2)
if len(wildcard) == 2 {
if h, ok := s.responders[responderKey{r.URL.Scheme, wildcard[1], true}]; ok {
if h, ok := s.responders[responderKey{r.URL.Scheme, "*." + wildcard[1]}]; ok {
return h
}
}
@@ -244,13 +266,13 @@ func (w *ResponseWriter) WriteHeader(status Status, meta string) {
}
// WriteStatus writes the response header with the given status code.
//
// WriteStatus is equivalent to WriteHeader(status, status.Message())
func (w *ResponseWriter) WriteStatus(status Status) {
w.WriteHeader(status, status.Message())
}
// SetMimetype sets the mimetype that will be written for a successful response.
// The provided mimetype will only be used if Write is called without calling
// WriteHeader.
// If the mimetype is not set, it will default to "text/gemini".
func (w *ResponseWriter) SetMimetype(mimetype string) {
w.mimetype = mimetype
@@ -260,9 +282,8 @@ func (w *ResponseWriter) SetMimetype(mimetype string) {
// If the response status does not allow for a response body, Write returns
// ErrBodyNotAllowed.
//
// If WriteHeader has not yet been called, Write calls
// WriteHeader(StatusSuccess, mimetype) where mimetype is the mimetype set in
// SetMimetype. If no mimetype is set, a default of "text/gemini" will be used.
// If the response header has not yet been written, Write calls WriteHeader
// with StatusSuccess and the mimetype set in SetMimetype.
func (w *ResponseWriter) Write(b []byte) (int, error) {
if !w.wroteHeader {
mimetype := w.mimetype
@@ -305,16 +326,6 @@ func SensitiveInput(w *ResponseWriter, r *Request, prompt string) (string, bool)
return "", false
}
// Redirect replies to the request with a redirect to the given URL.
func Redirect(w *ResponseWriter, url string) {
w.WriteHeader(StatusRedirect, url)
}
// PermanentRedirect replies to the request with a permanent redirect to the given URL.
func PermanentRedirect(w *ResponseWriter, url string) {
w.WriteHeader(StatusRedirectPermanent, url)
}
// Certificate returns the request certificate. If one is not provided,
// it returns nil and responds with StatusCertificateRequired.
func Certificate(w *ResponseWriter, r *Request) (*x509.Certificate, bool) {

View File

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

88
text.go
View File

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

22
tofu.go
View File

@@ -13,6 +13,15 @@ import (
"time"
)
// Trust represents the trustworthiness of a certificate.
type Trust int
const (
TrustNone Trust = iota // The certificate is not trusted.
TrustOnce // The certificate is trusted once.
TrustAlways // The certificate is trusted always.
)
// KnownHosts represents a list of known hosts.
// The zero value for KnownHosts is an empty list ready to use.
type KnownHosts struct {
@@ -86,26 +95,25 @@ func (k *KnownHosts) add(hostname string, cert *x509.Certificate, write bool) {
}
// Lookup looks for the provided certificate in the list of known hosts.
// If the hostname is in the list, but the fingerprint differs,
// Lookup returns ErrCertificateNotTrusted.
// If the hostname is not in the list, Lookup returns ErrCertificateUnknown.
// If the certificate is found and the fingerprint matches, error will be nil.
// If the hostname is not in the list, Lookup returns ErrCertificateNotFound.
// If the fingerprint doesn't match, Lookup returns ErrCertificateNotTrusted.
// Otherwise, Lookup returns nil.
func (k *KnownHosts) Lookup(hostname string, cert *x509.Certificate) error {
now := time.Now().Unix()
fingerprint := Fingerprint(cert)
if c, ok := k.hosts[hostname]; ok {
if c.Expires <= now {
// Certificate is expired
return ErrCertificateUnknown
return ErrCertificateExpired
}
if c.Fingerprint != fingerprint {
// Fingerprint does not match
return ErrCertificateNotTrusted
}
// Certificate is trusted
// Certificate is found
return nil
}
return ErrCertificateUnknown
return ErrCertificateNotFound
}
// Parse parses the provided reader and adds the parsed known hosts to the list.