17 Commits

Author SHA1 Message Date
Adnan Maolood
66e4dc86d5 Add optional host argument in examples/client.go 2020-10-28 16:50:17 -04:00
Adnan Maolood
5e4a38dccb Fix documentation 2020-10-28 16:04:14 -04:00
Adnan Maolood
b5fbd197a1 Update documentation 2020-10-28 16:02:04 -04:00
Adnan Maolood
34ae2a9066 Use strings.Builder in Fingerprint 2020-10-28 15:14:24 -04:00
Adnan Maolood
7f0b1fa8a1 Refactor server certificates 2020-10-28 15:03:54 -04:00
Adnan Maolood
32f22a3e2c Fix examples/cert.go 2020-10-28 13:47:52 -04:00
Adnan Maolood
fbd97a62de Refactor client certificates 2020-10-28 13:41:24 -04:00
Adnan Maolood
768664e0c5 Add ErrInputRequired and ErrCertificateRequired 2020-10-28 01:06:08 -04:00
Adnan Maolood
7a1a33513a Store a reference to the Request in Response 2020-10-28 00:21:27 -04:00
Adnan Maolood
e6072d8bbc Ensure absolute paths in client certificate store 2020-10-27 23:47:13 -04:00
Adnan Maolood
4c5167f590 Add Client.GetInput field 2020-10-27 23:35:22 -04:00
Adnan Maolood
d1dcf070ff Restrict client certificates to certain paths 2020-10-27 23:34:06 -04:00
Adnan Maolood
fc72224ce9 client: Follow redirects 2020-10-27 22:12:10 -04:00
Adnan Maolood
b84811668c Reject schemes other than gemini:// in NewRequest 2020-10-27 21:18:05 -04:00
Adnan Maolood
239ec885f7 Add (*Client).Get function 2020-10-27 19:22:34 -04:00
Adnan Maolood
12a9deb1a6 Make (*Response).Body an io.ReadCloser 2020-10-27 19:16:55 -04:00
Adnan Maolood
860a33f5a2 Fix examples 2020-10-27 14:17:14 -04:00
15 changed files with 709 additions and 651 deletions

46
cert.go
View File

@@ -19,9 +19,9 @@ type CertificateStore struct {
store map[string]tls.Certificate store map[string]tls.Certificate
} }
// Add adds a certificate for the given hostname to the store. // Add adds a certificate for the given scope to the store.
// It tries to parse the certificate if it is not already parsed. // It tries to parse the certificate if it is not already parsed.
func (c *CertificateStore) Add(hostname string, cert tls.Certificate) { func (c *CertificateStore) Add(scope string, cert tls.Certificate) {
if c.store == nil { if c.store == nil {
c.store = map[string]tls.Certificate{} c.store = map[string]tls.Certificate{}
} }
@@ -32,12 +32,12 @@ func (c *CertificateStore) Add(hostname string, cert tls.Certificate) {
cert.Leaf = parsed cert.Leaf = parsed
} }
} }
c.store[hostname] = cert c.store[scope] = cert
} }
// Lookup returns the certificate for the given hostname. // Lookup returns the certificate for the given scope.
func (c *CertificateStore) Lookup(hostname string) (*tls.Certificate, error) { func (c *CertificateStore) Lookup(scope string) (*tls.Certificate, error) {
cert, ok := c.store[hostname] cert, ok := c.store[scope]
if !ok { if !ok {
return nil, ErrCertificateUnknown return nil, ErrCertificateUnknown
} }
@@ -50,7 +50,7 @@ func (c *CertificateStore) Lookup(hostname string) (*tls.Certificate, error) {
// Load loads certificates from the given path. // Load loads certificates from the given path.
// The path should lead to a directory containing certificates and private keys // The path should lead to a directory containing certificates and private keys
// in the form hostname.crt and hostname.key. // in the form scope.crt and scope.key.
// For example, the hostname "localhost" would have the corresponding files // For example, the hostname "localhost" would have the corresponding files
// localhost.crt (certificate) and localhost.key (private key). // localhost.crt (certificate) and localhost.key (private key).
func (c *CertificateStore) Load(path string) error { func (c *CertificateStore) Load(path string) error {
@@ -64,15 +64,22 @@ func (c *CertificateStore) Load(path string) error {
if err != nil { if err != nil {
continue continue
} }
hostname := strings.TrimSuffix(filepath.Base(crtPath), ".crt") scope := strings.TrimSuffix(filepath.Base(crtPath), ".crt")
c.Add(hostname, cert) c.Add(scope, cert)
} }
return nil return nil
} }
// NewCertificate creates and returns a new parsed certificate. // CertificateOptions configures how a certificate is created.
func NewCertificate(host string, duration time.Duration) (tls.Certificate, error) { type CertificateOptions struct {
crt, priv, err := newX509KeyPair(host, duration) IPAddresses []net.IP
DNSNames []string
Duration time.Duration
}
// CreateCertificate creates a new TLS certificate.
func CreateCertificate(options CertificateOptions) (tls.Certificate, error) {
crt, priv, err := newX509KeyPair(options)
if err != nil { if err != nil {
return tls.Certificate{}, err return tls.Certificate{}, err
} }
@@ -84,7 +91,7 @@ func NewCertificate(host string, duration time.Duration) (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(host string, duration time.Duration) (*x509.Certificate, crypto.PrivateKey, error) { func newX509KeyPair(options CertificateOptions) (*x509.Certificate, crypto.PrivateKey, error) {
// Generate an ED25519 private key // Generate an ED25519 private key
_, priv, err := ed25519.GenerateKey(rand.Reader) _, priv, err := ed25519.GenerateKey(rand.Reader)
if err != nil { if err != nil {
@@ -103,7 +110,7 @@ func newX509KeyPair(host string, duration time.Duration) (*x509.Certificate, cry
} }
notBefore := time.Now() notBefore := time.Now()
notAfter := notBefore.Add(duration) notAfter := notBefore.Add(options.Duration)
template := x509.Certificate{ template := x509.Certificate{
SerialNumber: serialNumber, SerialNumber: serialNumber,
@@ -112,15 +119,8 @@ func newX509KeyPair(host string, duration time.Duration) (*x509.Certificate, cry
KeyUsage: keyUsage, KeyUsage: keyUsage,
ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth}, ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
BasicConstraintsValid: true, BasicConstraintsValid: true,
} IPAddresses: options.IPAddresses,
DNSNames: options.DNSNames,
hosts := strings.Split(host, ",")
for _, h := range hosts {
if ip := net.ParseIP(h); ip != nil {
template.IPAddresses = append(template.IPAddresses, ip)
} else {
template.DNSNames = append(template.DNSNames, h)
}
} }
crt, err := x509.CreateCertificate(rand.Reader, &template, &template, public, priv) crt, err := x509.CreateCertificate(rand.Reader, &template, &template, public, priv)

195
client.go
View File

@@ -4,69 +4,75 @@ import (
"bufio" "bufio"
"crypto/tls" "crypto/tls"
"crypto/x509" "crypto/x509"
"net"
"net/url"
"path"
"strings"
) )
// Client represents a Gemini client. // Client is a Gemini client.
type Client struct { type Client struct {
// KnownHosts is a list of known hosts that the client trusts. // KnownHosts is a list of known hosts.
KnownHosts KnownHosts KnownHosts KnownHosts
// CertificateStore maps hostnames to certificates. // Certificates stores client-side certificates.
// It is used to determine which certificate to use when the server requests Certificates CertificateStore
// a certificate.
CertificateStore CertificateStore
// GetCertificate, if not nil, will be called when a server requests a certificate. // GetInput is called to retrieve input when the server requests it.
// The returned certificate will be used when sending the request again. // If GetInput is nil or returns false, no input will be sent and
// If the certificate is nil, the request will not be sent again and
// the response will be returned. // the response will be returned.
GetCertificate func(hostname string, store *CertificateStore) *tls.Certificate GetInput func(prompt string, sensitive bool) (input string, ok bool)
// TrustCertificate, if not nil, will be called to determine whether the // CheckRedirect determines whether to follow a redirect.
// client should trust the given certificate. // If CheckRedirect is nil, a default policy of no more than 5 consecutive
// If error is not nil, the connection will be aborted. // redirects will be enforced.
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 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 func(hostname string, cert *x509.Certificate, knownHosts *KnownHosts) error
} }
// Send sends a Gemini request and returns a Gemini response. // Get performs a Gemini request for the given url.
func (c *Client) Send(req *Request) (*Response, error) { func (c *Client) Get(url string) (*Response, error) {
req, err := NewRequest(url)
if err != nil {
return nil, err
}
return c.Do(req)
}
// Do performs a Gemini request and returns a Gemini response.
func (c *Client) Do(req *Request) (*Response, error) {
return c.do(req, nil)
}
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(info *tls.CertificateRequestInfo) (*tls.Certificate, error) { GetClientCertificate: func(_ *tls.CertificateRequestInfo) (*tls.Certificate, error) {
// Request certificates take precedence over client certificates return c.getClientCertificate(req)
if req.Certificate != nil {
return req.Certificate, nil
}
// If we have already stored the certificate, return it
if cert, err := c.CertificateStore.Lookup(hostname(req.Host)); err == nil {
return cert, nil
}
return &tls.Certificate{}, nil
}, },
VerifyConnection: func(cs tls.ConnectionState) error { VerifyConnection: func(cs tls.ConnectionState) error {
cert := cs.PeerCertificates[0] return c.verifyConnection(req, cs)
// Verify the hostname
if err := verifyHostname(cert, hostname(req.Host)); err != nil {
return err
}
// Check that the client trusts the certificate
if c.TrustCertificate == nil {
if err := c.KnownHosts.Lookup(hostname(req.Host), cert); err != nil {
return err
}
} else if err := c.TrustCertificate(hostname(req.Host), cert, &c.KnownHosts); err != nil {
return err
}
return nil
}, },
} }
conn, err := tls.Dial("tcp", req.Host, config) conn, err := tls.Dial("tcp", req.Host, config)
if err != nil { if err != nil {
return nil, err return nil, err
} }
defer conn.Close() // TODO: Set connection deadline
// Write the request // Write the request
w := bufio.NewWriter(conn) w := bufio.NewWriter(conn)
@@ -77,26 +83,115 @@ func (c *Client) Send(req *Request) (*Response, error) {
// Read the response // Read the response
resp := &Response{} resp := &Response{}
r := bufio.NewReader(conn) if err := resp.read(conn); err != nil {
if err := resp.read(r); err != nil {
return nil, err return nil, err
} }
// Store connection information // Store connection state
resp.TLS = conn.ConnectionState() resp.TLS = conn.ConnectionState()
// Resend the request with a certificate if the server responded switch {
// with CertificateRequired case resp.Status == StatusCertificateRequired:
if resp.Status == StatusCertificateRequired {
// Check to see if a certificate was already provided to prevent an infinite loop // Check to see if a certificate was already provided to prevent an infinite loop
if req.Certificate != nil { if req.Certificate != nil {
return resp, nil return resp, nil
} }
if c.GetCertificate != nil {
if cert := c.GetCertificate(hostname(req.Host), &c.CertificateStore); cert != nil { hostname, path := req.URL.Hostname(), strings.TrimSuffix(req.URL.Path, "/")
req.Certificate = cert if c.CreateCertificate != nil {
return c.Send(req) cert, err := c.CreateCertificate(hostname, path)
if err != nil {
return resp, err
}
c.Certificates.Add(hostname+path, cert)
return c.do(req, via)
}
return resp, ErrCertificateRequired
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, ErrInputRequired
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)
redirect, err := NewRequestFromURL(target)
if err != nil {
return resp, err
}
if c.CheckRedirect != nil {
if err := c.CheckRedirect(redirect, via); err != nil {
return resp, err
}
} else if len(via) > 5 {
// Default policy of no more than 5 redirects
return resp, ErrTooManyRedirects
}
return c.do(redirect, via)
} }
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, err := c.Certificates.Lookup(scope)
if err == nil {
return cert, err
}
if err == ErrCertificateExpired {
break
}
scope = path.Dir(scope)
if scope == "." {
break
}
}
return &tls.Certificate{}, nil
}
func (c *Client) verifyConnection(req *Request, cs tls.ConnectionState) error {
// Verify the hostname
var hostname string
if host, _, err := net.SplitHostPort(req.Host); err == nil {
hostname = host
} else {
hostname = req.Host
}
cert := cs.PeerCertificates[0]
if err := verifyHostname(cert, hostname); err != nil {
return err
}
// Check that the client trusts the certificate
var err error
if c.TrustCertificate != nil {
return c.TrustCertificate(hostname, cert, &c.KnownHosts)
} else {
err = c.KnownHosts.Lookup(hostname, cert)
}
return err
}

44
doc.go
View File

@@ -1,26 +1,34 @@
/* /*
Package gemini implements the Gemini protocol. Package gemini implements the Gemini protocol.
Send makes a Gemini request with the default client: Get makes a Gemini request:
req := gemini.NewRequest("gemini://example.com") resp, err := gemini.Get("gemini://example.com")
resp, err := gemini.Send(req)
if err != nil { if err != nil {
// handle error // handle error
} }
// ... // ...
For control over client behavior, create a custom Client: 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 var client gemini.Client
resp, err := client.Send(req) resp, err := client.Get("gemini://example.com")
if err != nil { if err != nil {
// handle error // handle error
} }
// ... // ...
The default client loads known hosts from "$XDG_DATA_HOME/gemini/known_hosts". Clients can load their own list of known hosts:
Custom clients can load their own list of known hosts:
err := client.KnownHosts.Load("path/to/my/known_hosts") err := client.KnownHosts.Load("path/to/my/known_hosts")
if err != nil { if err != nil {
@@ -33,22 +41,12 @@ Clients can control when to trust certificates with TrustCertificate:
return knownHosts.Lookup(hostname, cert) return knownHosts.Lookup(hostname, cert)
} }
If a server responds with StatusCertificateRequired, the default client will generate a certificate and resend the request with it. Custom clients can do so in GetCertificate: Clients can create client certificates upon the request of a server:
client.GetCertificate = func(hostname string, store *gemini.CertificateStore) *tls.Certificate { client.CreateCertificate = func(hostname, path string) (tls.Certificate, error) {
// If the certificate is in the store, return it return gemini.CreateCertificate(gemini.CertificateOptions{
if cert, err := store.Lookup(hostname); err == nil { Duration: time.Hour,
return &cert })
}
// Otherwise, generate a certificate
duration := time.Hour
cert, err := gemini.NewCertificate(hostname, duration)
if err != nil {
return nil
}
// Store and return the certificate
store.Add(hostname, cert)
return &cert
} }
Server is a Gemini server. Server is a Gemini server.
@@ -57,7 +55,7 @@ Server is a Gemini server.
Servers must be configured with certificates: Servers must be configured with certificates:
err := server.CertificateStore.Load("/var/lib/gemini/certs") err := server.Certificates.Load("/var/lib/gemini/certs")
if err != nil { if err != nil {
// handle error // handle error
} }

View File

@@ -7,7 +7,7 @@ import (
"fmt" "fmt"
"log" "log"
gmi "git.sr.ht/~adnano/go-gemini" "git.sr.ht/~adnano/go-gemini"
) )
type user struct { type user struct {
@@ -33,16 +33,15 @@ var (
) )
func main() { func main() {
var mux gmi.ServeMux var mux gemini.ServeMux
mux.HandleFunc("/", welcome) mux.HandleFunc("/", login)
mux.HandleFunc("/login", login) mux.HandleFunc("/password", loginPassword)
mux.HandleFunc("/login/password", loginPassword)
mux.HandleFunc("/profile", profile) mux.HandleFunc("/profile", profile)
mux.HandleFunc("/admin", admin) mux.HandleFunc("/admin", admin)
mux.HandleFunc("/logout", logout) mux.HandleFunc("/logout", logout)
var server gmi.Server var server gemini.Server
if err := server.CertificateStore.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.Register("localhost", &mux) server.Register("localhost", &mux)
@@ -53,74 +52,69 @@ func main() {
} }
func getSession(crt *x509.Certificate) (*session, bool) { func getSession(crt *x509.Certificate) (*session, bool) {
fingerprint := gmi.Fingerprint(crt) fingerprint := gemini.Fingerprint(crt)
session, ok := sessions[fingerprint] session, ok := sessions[fingerprint]
return session, ok return session, ok
} }
func welcome(w *gmi.ResponseWriter, r *gmi.Request) { func login(w *gemini.ResponseWriter, r *gemini.Request) {
fmt.Fprintln(w, "Welcome to this example.") cert, ok := gemini.Certificate(w, r)
fmt.Fprintln(w, "=> /login Login")
}
func login(w *gmi.ResponseWriter, r *gmi.Request) {
cert, ok := gmi.Certificate(w, r)
if !ok { if !ok {
return return
} }
username, ok := gmi.Input(w, r, "Username") username, ok := gemini.Input(w, r, "Username")
if !ok { if !ok {
return return
} }
fingerprint := gmi.Fingerprint(cert) fingerprint := gemini.Fingerprint(cert)
sessions[fingerprint] = &session{ sessions[fingerprint] = &session{
username: username, username: username,
} }
gmi.Redirect(w, r, "/login/password") gemini.Redirect(w, "/password")
} }
func loginPassword(w *gmi.ResponseWriter, r *gmi.Request) { func loginPassword(w *gemini.ResponseWriter, r *gemini.Request) {
cert, ok := gmi.Certificate(w, r) cert, ok := gemini.Certificate(w, r)
if !ok { if !ok {
return return
} }
session, ok := getSession(cert) session, ok := getSession(cert)
if !ok { if !ok {
gmi.CertificateNotAuthorized(w, r) w.WriteStatus(gemini.StatusCertificateNotAuthorized)
return return
} }
password, ok := gmi.SensitiveInput(w, r, "Password") password, ok := gemini.SensitiveInput(w, r, "Password")
if !ok { if !ok {
return return
} }
expected := logins[session.username].password expected := logins[session.username].password
if password == expected { if password == expected {
session.authorized = true session.authorized = true
gmi.Redirect(w, r, "/profile") gemini.Redirect(w, "/profile")
} else { } else {
gmi.SensitiveInput(w, r, "Wrong password. Try again") gemini.SensitiveInput(w, r, "Wrong password. Try again")
} }
} }
func logout(w *gmi.ResponseWriter, r *gmi.Request) { func logout(w *gemini.ResponseWriter, r *gemini.Request) {
cert, ok := gmi.Certificate(w, r) cert, ok := gemini.Certificate(w, r)
if !ok { if !ok {
return return
} }
fingerprint := gmi.Fingerprint(cert) fingerprint := gemini.Fingerprint(cert)
delete(sessions, fingerprint) delete(sessions, fingerprint)
fmt.Fprintln(w, "Successfully logged out.") fmt.Fprintln(w, "Successfully logged out.")
} }
func profile(w *gmi.ResponseWriter, r *gmi.Request) { func profile(w *gemini.ResponseWriter, r *gemini.Request) {
cert, ok := gmi.Certificate(w, r) cert, ok := gemini.Certificate(w, r)
if !ok { if !ok {
return return
} }
session, ok := getSession(cert) session, ok := getSession(cert)
if !ok { if !ok {
gmi.CertificateNotAuthorized(w, r) w.WriteStatus(gemini.StatusCertificateNotAuthorized)
return return
} }
user := logins[session.username] user := logins[session.username]
@@ -129,19 +123,19 @@ func profile(w *gmi.ResponseWriter, r *gmi.Request) {
fmt.Fprintln(w, "=> /logout Logout") fmt.Fprintln(w, "=> /logout Logout")
} }
func admin(w *gmi.ResponseWriter, r *gmi.Request) { func admin(w *gemini.ResponseWriter, r *gemini.Request) {
cert, ok := gmi.Certificate(w, r) cert, ok := gemini.Certificate(w, r)
if !ok { if !ok {
return return
} }
session, ok := getSession(cert) session, ok := getSession(cert)
if !ok { if !ok {
gmi.CertificateNotAuthorized(w, r) w.WriteStatus(gemini.StatusCertificateNotAuthorized)
return return
} }
user := logins[session.username] user := logins[session.username]
if !user.admin { if !user.admin {
gmi.CertificateNotAuthorized(w, r) w.WriteStatus(gemini.StatusCertificateNotAuthorized)
return return
} }
fmt.Fprintln(w, "Welcome to the admin portal.") fmt.Fprintln(w, "Welcome to the admin portal.")

View File

@@ -7,17 +7,29 @@ import (
"crypto/tls" "crypto/tls"
"crypto/x509" "crypto/x509"
"encoding/pem" "encoding/pem"
"fmt"
"log" "log"
"os" "os"
"time" "time"
gmi "git.sr.ht/~adnano/go-gemini" "git.sr.ht/~adnano/go-gemini"
) )
func main() { func main() {
host := "localhost" if len(os.Args) < 3 {
duration := 365 * 24 * time.Hour fmt.Printf("usage: %s [hostname] [duration]\n", os.Args[0])
cert, err := gmi.NewCertificate(host, duration) os.Exit(1)
}
host := os.Args[1]
duration, err := time.ParseDuration(os.Args[2])
if err != nil {
log.Fatal(err)
}
options := gemini.CertificateOptions{
DNSNames: []string{host},
Duration: duration,
}
cert, err := gemini.CreateCertificate(options)
if err != nil { if err != nil {
log.Fatal(err) log.Fatal(err)
} }

View File

@@ -7,30 +7,29 @@ import (
"crypto/tls" "crypto/tls"
"crypto/x509" "crypto/x509"
"fmt" "fmt"
"net/url" "io/ioutil"
"os" "os"
"time" "time"
gmi "git.sr.ht/~adnano/go-gemini" "git.sr.ht/~adnano/go-gemini"
) )
var ( var (
scanner = bufio.NewScanner(os.Stdin) scanner = bufio.NewScanner(os.Stdin)
client = &gmi.Client{} client = &gemini.Client{}
) )
func init() { func init() {
// Initialize the client client.KnownHosts.LoadDefault()
client.KnownHosts.LoadDefault() // Load known hosts client.TrustCertificate = func(hostname string, cert *x509.Certificate, knownHosts *gemini.KnownHosts) error {
client.TrustCertificate = func(hostname string, cert *x509.Certificate, knownHosts *gmi.KnownHosts) error {
err := knownHosts.Lookup(hostname, cert) err := knownHosts.Lookup(hostname, cert)
if err != nil { if err != nil {
switch err { switch err {
case gmi.ErrCertificateNotTrusted: case gemini.ErrCertificateNotTrusted:
// Alert the user that the certificate is not trusted // Alert the user that the certificate is not trusted
fmt.Printf("Warning: Certificate for %s is not trusted!\n", hostname) fmt.Printf("Warning: Certificate for %s is not trusted!\n", hostname)
fmt.Println("This could indicate a Man-in-the-Middle attack.") fmt.Println("This could indicate a Man-in-the-Middle attack.")
case gmi.ErrCertificateUnknown: case gemini.ErrCertificateUnknown:
// Prompt the user to trust the certificate // Prompt the user to trust the certificate
trust := trustCertificate(cert) trust := trustCertificate(cert)
switch trust { switch trust {
@@ -47,64 +46,35 @@ func init() {
} }
return err return err
} }
client.GetCertificate = func(hostname string, store *gmi.CertificateStore) *tls.Certificate { client.CreateCertificate = func(hostname, path string) (tls.Certificate, error) {
// If the certificate is in the store, return it fmt.Println("Generating client certificate for", hostname, path)
if cert, err := store.Lookup(hostname); err == nil { return gemini.CreateCertificate(gemini.CertificateOptions{
return cert Duration: time.Hour,
} })
// Otherwise, generate a certificate }
fmt.Println("Generating client certificate for", hostname) client.GetInput = func(prompt string, sensitive bool) (string, bool) {
duration := time.Hour fmt.Printf("%s: ", prompt)
cert, err := gmi.NewCertificate(hostname, duration) scanner.Scan()
if err != nil { return scanner.Text(), true
return nil
}
// Store and return the certificate
store.Add(hostname, cert)
return &cert
} }
} }
// sendRequest sends a request to the given URL. func doRequest(req *gemini.Request) error {
func sendRequest(req *gmi.Request) error { resp, err := client.Do(req)
resp, err := client.Send(req)
if err != nil { if err != nil {
return err return err
} }
// TODO: More fine-grained analysis of the status code. if resp.Status.Class() == gemini.StatusClassSuccess {
switch resp.Status / 10 { body, err := ioutil.ReadAll(resp.Body)
case gmi.StatusClassInput: resp.Body.Close()
fmt.Printf("%s: ", resp.Meta) if err != nil {
scanner.Scan() return err
req.URL.RawQuery = url.QueryEscape(scanner.Text()) }
return sendRequest(req) fmt.Print(string(body))
case gmi.StatusClassSuccess:
fmt.Print(string(resp.Body))
return nil return nil
case gmi.StatusClassRedirect:
fmt.Println("Redirecting to", resp.Meta)
target, err := url.Parse(resp.Meta)
if err != nil {
return err
}
// TODO: Prompt the user if the redirect is to another domain.
redirect, err := gmi.NewRequestFromURL(req.URL.ResolveReference(target))
if err != nil {
return err
}
return sendRequest(redirect)
case gmi.StatusClassTemporaryFailure:
return fmt.Errorf("Temporary failure: %s", resp.Meta)
case gmi.StatusClassPermanentFailure:
return fmt.Errorf("Permanent failure: %s", resp.Meta)
case gmi.StatusClassCertificateRequired:
// Note that this should not happen unless the server responds with
// CertificateRequired even after we send a certificate.
// CertificateNotAuthorized and CertificateNotValid are handled here.
return fmt.Errorf("Certificate required: %s", resp.Meta)
} }
panic("unreachable") return fmt.Errorf("request failed: %d %s: %s", resp.Status, resp.Status.Message(), resp.Meta)
} }
type trust int type trust int
@@ -125,7 +95,7 @@ Otherwise, this should be safe to trust.
=> ` => `
func trustCertificate(cert *x509.Certificate) trust { func trustCertificate(cert *x509.Certificate) trust {
fmt.Printf(trustPrompt, gmi.Fingerprint(cert)) fmt.Printf(trustPrompt, gemini.Fingerprint(cert))
scanner.Scan() scanner.Scan()
switch scanner.Text() { switch scanner.Text() {
case "t": case "t":
@@ -139,29 +109,22 @@ func trustCertificate(cert *x509.Certificate) trust {
func main() { func main() {
if len(os.Args) < 2 { if len(os.Args) < 2 {
fmt.Printf("usage: %s gemini://...", os.Args[0]) fmt.Printf("usage: %s gemini://... [host]", os.Args[0])
os.Exit(1) os.Exit(1)
} }
var host string
if len(os.Args) >= 3 {
host = os.Args[2]
}
url := os.Args[1] url := os.Args[1]
var req *gmi.Request req, err := gemini.NewRequest(url)
var err error
if host != "" {
req, err = gmi.NewRequestTo(url, host)
} else {
req, err = gmi.NewRequest(url)
}
if err != nil { if err != nil {
fmt.Println(err) fmt.Println(err)
os.Exit(1) os.Exit(1)
} }
if len(os.Args) == 3 {
req.Host = os.Args[2]
}
if err := sendRequest(req); err != nil { if err := doRequest(req); err != nil {
fmt.Println(err) fmt.Println(err)
os.Exit(1) os.Exit(1)
} }

View File

@@ -3,51 +3,39 @@
package main package main
import ( import (
"bytes" "crypto"
"crypto/tls" "crypto/tls"
"crypto/x509" "crypto/x509"
"encoding/pem" "encoding/pem"
"fmt"
"io"
"log" "log"
"os" "os"
"time" "time"
gmi "git.sr.ht/~adnano/go-gemini" "git.sr.ht/~adnano/go-gemini"
) )
func main() { func main() {
var server gmi.Server var server gemini.Server
if err := server.CertificateStore.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.GetCertificate = func(hostname string, store *gmi.CertificateStore) *tls.Certificate { server.CreateCertificate = func(hostname string) (tls.Certificate, error) {
cert, err := store.Lookup(hostname) fmt.Println("Generating certificate for", hostname)
if err != nil { cert, err := gemini.CreateCertificate(gemini.CertificateOptions{
switch err { DNSNames: []string{hostname},
case gmi.ErrCertificateExpired: Duration: time.Minute, // for testing purposes
// Generate a new certificate if the current one is expired. })
log.Print("Old certificate expired, creating new one") if err == nil {
fallthrough // Write the new certificate to disk
case gmi.ErrCertificateUnknown: err = writeCertificate("/var/lib/gemini/certs/"+hostname, cert)
// Generate a certificate if one does not exist.
cert, err := gmi.NewCertificate(hostname, time.Minute)
if err != nil {
// Failed to generate new certificate, abort
return nil
}
// Store and return the new certificate
err = writeCertificate("/var/lib/gemini/certs/"+hostname, cert)
if err != nil {
return nil
}
store.Add(hostname, cert)
return &cert
}
} }
return cert return cert, err
} }
var mux gmi.ServeMux var mux gemini.ServeMux
mux.Handle("/", gmi.FileServer(gmi.Dir("/var/www"))) mux.Handle("/", gemini.FileServer(gemini.Dir("/var/www")))
server.Register("localhost", &mux) server.Register("localhost", &mux)
if err := server.ListenAndServe(); err != nil { if err := server.ListenAndServe(); err != nil {
@@ -58,22 +46,13 @@ func main() {
// writeCertificate writes the provided certificate and private key // writeCertificate writes the provided certificate and private key
// to path.crt and path.key respectively. // to path.crt and path.key respectively.
func writeCertificate(path string, cert tls.Certificate) error { func writeCertificate(path string, cert tls.Certificate) error {
crt, err := marshalX509Certificate(cert.Leaf.Raw)
if err != nil {
return err
}
key, err := marshalPrivateKey(cert.PrivateKey)
if err != nil {
return err
}
// Write the certificate // Write the certificate
crtPath := path + ".crt" crtPath := path + ".crt"
crtOut, err := os.OpenFile(crtPath, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0600) crtOut, err := os.OpenFile(crtPath, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0600)
if err != nil { if err != nil {
return err return err
} }
if _, err := crtOut.Write(crt); err != nil { if err := marshalX509Certificate(crtOut, cert.Leaf.Raw); err != nil {
return err return err
} }
@@ -83,30 +62,19 @@ func writeCertificate(path string, cert tls.Certificate) error {
if err != nil { if err != nil {
return err return err
} }
if _, err := keyOut.Write(key); err != nil { return marshalPrivateKey(keyOut, cert.PrivateKey)
return err
}
return nil
} }
// marshalX509Certificate returns a PEM-encoded version of the given raw certificate. // marshalX509Certificate writes a PEM-encoded version of the given certificate.
func marshalX509Certificate(cert []byte) ([]byte, error) { func marshalX509Certificate(w io.Writer, cert []byte) error {
var b bytes.Buffer return pem.Encode(w, &pem.Block{Type: "CERTIFICATE", Bytes: cert})
if err := pem.Encode(&b, &pem.Block{Type: "CERTIFICATE", Bytes: cert}); err != nil {
return nil, err
}
return b.Bytes(), nil
} }
// marshalPrivateKey returns PEM encoded versions of the given certificate and private key. // marshalPrivateKey writes a PEM-encoded version of the given private key.
func marshalPrivateKey(priv interface{}) ([]byte, error) { func marshalPrivateKey(w io.Writer, priv crypto.PrivateKey) error {
var b bytes.Buffer
privBytes, err := x509.MarshalPKCS8PrivateKey(priv) privBytes, err := x509.MarshalPKCS8PrivateKey(priv)
if err != nil { if err != nil {
return nil, err return err
} }
if err := pem.Encode(&b, &pem.Block{Type: "PRIVATE KEY", Bytes: privBytes}); err != nil { return pem.Encode(w, &pem.Block{Type: "PRIVATE KEY", Bytes: privBytes})
return nil, err
}
return b.Bytes(), nil
} }

9
fs.go
View File

@@ -5,7 +5,6 @@ import (
"mime" "mime"
"os" "os"
"path" "path"
"path/filepath"
) )
func init() { func init() {
@@ -25,14 +24,14 @@ type fsHandler struct {
} }
func (fsh fsHandler) Respond(w *ResponseWriter, r *Request) { func (fsh fsHandler) Respond(w *ResponseWriter, r *Request) {
path := path.Clean(r.URL.Path) p := path.Clean(r.URL.Path)
f, err := fsh.Open(path) f, err := fsh.Open(p)
if err != nil { if err != nil {
w.WriteStatus(StatusNotFound) w.WriteStatus(StatusNotFound)
return return
} }
// Detect mimetype // Detect mimetype
ext := filepath.Ext(path) ext := path.Ext(p)
mimetype := mime.TypeByExtension(ext) mimetype := mime.TypeByExtension(ext)
w.SetMimetype(mimetype) w.SetMimetype(mimetype)
// Copy file to response writer // Copy file to response writer
@@ -71,7 +70,7 @@ func ServeFile(w *ResponseWriter, fs FS, name string) {
return return
} }
// Detect mimetype // Detect mimetype
ext := filepath.Ext(name) ext := path.Ext(name)
mimetype := mime.TypeByExtension(ext) mimetype := mime.TypeByExtension(ext)
w.SetMimetype(mimetype) w.SetMimetype(mimetype)
// Copy file to response writer // Copy file to response writer

138
gemini.go
View File

@@ -8,82 +8,7 @@ import (
"time" "time"
) )
// Status codes. var crlf = []byte("\r\n")
type Status int
const (
StatusInput Status = 10
StatusSensitiveInput Status = 11
StatusSuccess Status = 20
StatusRedirect Status = 30
StatusRedirectPermanent Status = 31
StatusTemporaryFailure Status = 40
StatusServerUnavailable Status = 41
StatusCGIError Status = 42
StatusProxyError Status = 43
StatusSlowDown Status = 44
StatusPermanentFailure Status = 50
StatusNotFound Status = 51
StatusGone Status = 52
StatusProxyRequestRefused Status = 53
StatusBadRequest Status = 59
StatusCertificateRequired Status = 60
StatusCertificateNotAuthorized Status = 61
StatusCertificateNotValid Status = 62
)
// Class returns the status class for this status code.
func (s Status) Class() StatusClass {
return StatusClass(s / 10)
}
// StatusMessage returns the status message corresponding to the provided
// status code.
// StatusMessage returns an empty string for input, successs, and redirect
// status codes.
func (s Status) Message() string {
switch s {
case StatusTemporaryFailure:
return "TemporaryFailure"
case StatusServerUnavailable:
return "Server unavailable"
case StatusCGIError:
return "CGI error"
case StatusProxyError:
return "Proxy error"
case StatusSlowDown:
return "Slow down"
case StatusPermanentFailure:
return "PermanentFailure"
case StatusNotFound:
return "Not found"
case StatusGone:
return "Gone"
case StatusProxyRequestRefused:
return "Proxy request refused"
case StatusBadRequest:
return "Bad request"
case StatusCertificateRequired:
return "Certificate required"
case StatusCertificateNotAuthorized:
return "Certificate not authorized"
case StatusCertificateNotValid:
return "Certificate not valid"
}
return ""
}
// Status code categories.
type StatusClass int
const (
StatusClassInput StatusClass = 1
StatusClassSuccess StatusClass = 2
StatusClassRedirect StatusClass = 3
StatusClassTemporaryFailure StatusClass = 4
StatusClassPermanentFailure StatusClass = 5
StatusClassCertificateRequired StatusClass = 6
)
// Errors. // Errors.
var ( var (
@@ -93,51 +18,42 @@ var (
ErrCertificateExpired = errors.New("gemini: certificate expired") ErrCertificateExpired = errors.New("gemini: certificate expired")
ErrCertificateNotTrusted = errors.New("gemini: certificate is not trusted") ErrCertificateNotTrusted = errors.New("gemini: certificate is not trusted")
ErrNotAFile = errors.New("gemini: not a file") 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") 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 Send. // DefaultClient is the default client. It is used by Get and Do.
// //
// On the first request, DefaultClient will load the default list of known hosts. // On the first request, DefaultClient loads the default list of known hosts.
var DefaultClient Client var DefaultClient Client
var ( // Get performs a Gemini request for the given url.
crlf = []byte("\r\n") //
) // Get is a wrapper around DefaultClient.Get.
func Get(url string) (*Response, error) {
return DefaultClient.Get(url)
}
// Do performs a Gemini request and returns a Gemini response.
//
// Do is a wrapper around DefaultClient.Do.
func Do(req *Request) (*Response, error) {
return DefaultClient.Do(req)
}
var defaultClientOnce sync.Once
func init() { func init() {
DefaultClient.TrustCertificate = func(hostname string, cert *x509.Certificate, knownHosts *KnownHosts) error { DefaultClient.TrustCertificate = func(hostname string, cert *x509.Certificate, knownHosts *KnownHosts) error {
// Load the hosts only once. This is so that the hosts don't have to be loaded defaultClientOnce.Do(func() { knownHosts.LoadDefault() })
// for those using their own clients.
setupDefaultClientOnce.Do(setupDefaultClient)
return knownHosts.Lookup(hostname, cert) return knownHosts.Lookup(hostname, cert)
} }
DefaultClient.GetCertificate = func(hostname string, store *CertificateStore) *tls.Certificate { DefaultClient.CreateCertificate = func(hostname, path string) (tls.Certificate, error) {
// If the certificate is in the store, return it return CreateCertificate(CertificateOptions{
if cert, err := store.Lookup(hostname); err == nil { Duration: time.Hour,
return cert })
}
// Otherwise, generate a certificate
duration := time.Hour
cert, err := NewCertificate(hostname, duration)
if err != nil {
return nil
}
// Store and return the certificate
store.Add(hostname, cert)
return &cert
} }
} }
var setupDefaultClientOnce sync.Once
func setupDefaultClient() {
DefaultClient.KnownHosts.LoadDefault()
}
// Send sends a Gemini request and returns a Gemini response.
//
// Send is a wrapper around DefaultClient.Send.
func Send(req *Request) (*Response, error) {
return DefaultClient.Send(req)
}

210
mux.go Normal file
View File

@@ -0,0 +1,210 @@
package gemini
import (
"net/url"
"path"
"sort"
"strings"
"sync"
)
// The following code is modified from the net/http package.
// Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// ServeMux is a Gemini request multiplexer.
// It matches the URL of each incoming request against a list of registered
// patterns and calls the handler for the pattern that
// most closely matches the URL.
//
// Patterns name fixed, rooted paths, like "/favicon.ico",
// or rooted subtrees, like "/images/" (note the trailing slash).
// Longer patterns take precedence over shorter ones, so that
// if there are handlers registered for both "/images/"
// and "/images/thumbnails/", the latter handler will be
// called for paths beginning "/images/thumbnails/" and the
// former will receive requests for any other paths in the
// "/images/" subtree.
//
// Note that since a pattern ending in a slash names a rooted subtree,
// the pattern "/" matches all paths not matched by other registered
// patterns, not just the URL with Path == "/".
//
// If a subtree has been registered and a request is received naming the
// subtree root without its trailing slash, ServeMux redirects that
// request to the subtree root (adding the trailing slash). This behavior can
// be overridden with a separate registration for the path without
// the trailing slash. For example, registering "/images/" causes ServeMux
// to redirect a request for "/images" to "/images/", unless "/images" has
// been registered separately.
//
// ServeMux also takes care of sanitizing the URL request path and
// redirecting any request containing . or .. elements or repeated slashes
// to an equivalent, cleaner URL.
type ServeMux struct {
mu sync.RWMutex
m map[string]muxEntry
es []muxEntry // slice of entries sorted from longest to shortest.
}
type muxEntry struct {
r Responder
pattern string
}
// cleanPath returns the canonical path for p, eliminating . and .. elements.
func cleanPath(p string) string {
if p == "" {
return "/"
}
if p[0] != '/' {
p = "/" + p
}
np := path.Clean(p)
// path.Clean removes trailing slash except for root;
// put the trailing slash back if necessary.
if p[len(p)-1] == '/' && np != "/" {
// Fast path for common case of p being the string we want:
if len(p) == len(np)+1 && strings.HasPrefix(p, np) {
np = p
} else {
np += "/"
}
}
return np
}
// Find a handler on a handler map given a path string.
// Most-specific (longest) pattern wins.
func (mux *ServeMux) match(path string) Responder {
// Check for exact match first.
v, ok := mux.m[path]
if ok {
return v.r
}
// Check for longest valid match. mux.es contains all patterns
// that end in / sorted from longest to shortest.
for _, e := range mux.es {
if strings.HasPrefix(path, e.pattern) {
return e.r
}
}
return nil
}
// redirectToPathSlash determines if the given path needs appending "/" to it.
// This occurs when a handler for path + "/" was already registered, but
// not for path itself. If the path needs appending to, it creates a new
// URL, setting the path to u.Path + "/" and returning true to indicate so.
func (mux *ServeMux) redirectToPathSlash(path string, u *url.URL) (*url.URL, bool) {
mux.mu.RLock()
shouldRedirect := mux.shouldRedirectRLocked(path)
mux.mu.RUnlock()
if !shouldRedirect {
return u, false
}
path = path + "/"
u = &url.URL{Path: path, RawQuery: u.RawQuery}
return u, true
}
// shouldRedirectRLocked reports whether the given path and host should be redirected to
// path+"/". This should happen if a handler is registered for path+"/" but
// not path -- see comments at ServeMux.
func (mux *ServeMux) shouldRedirectRLocked(path string) bool {
if _, exist := mux.m[path]; exist {
return false
}
n := len(path)
if n == 0 {
return false
}
if _, exist := mux.m[path+"/"]; exist {
return path[n-1] != '/'
}
return false
}
// Respond dispatches the request to the responder whose
// pattern most closely matches the request URL.
func (mux *ServeMux) Respond(w *ResponseWriter, r *Request) {
path := cleanPath(r.URL.Path)
// 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())
return
}
if path != r.URL.Path {
u := *r.URL
u.Path = path
Redirect(w, u.String())
return
}
mux.mu.RLock()
defer mux.mu.RUnlock()
resp := mux.match(path)
if resp == nil {
w.WriteStatus(StatusNotFound)
return
}
resp.Respond(w, r)
}
// Handle registers the responder for the given pattern.
// If a responder already exists for pattern, Handle panics.
func (mux *ServeMux) Handle(pattern string, responder Responder) {
mux.mu.Lock()
defer mux.mu.Unlock()
if pattern == "" {
panic("gemini: invalid pattern")
}
if responder == nil {
panic("gemini: nil responder")
}
if _, exist := mux.m[pattern]; exist {
panic("gemini: multiple registrations for " + pattern)
}
if mux.m == nil {
mux.m = make(map[string]muxEntry)
}
e := muxEntry{responder, pattern}
mux.m[pattern] = e
if pattern[len(pattern)-1] == '/' {
mux.es = appendSorted(mux.es, e)
}
}
func appendSorted(es []muxEntry, e muxEntry) []muxEntry {
n := len(es)
i := sort.Search(n, func(i int) bool {
return len(es[i].pattern) < len(e.pattern)
})
if i == n {
return append(es, e)
}
// we now know that i points at where we want to insert
es = append(es, muxEntry{}) // try to grow the slice in place, any entry works.
copy(es[i+1:], es[i:]) // move shorter entries down
es[i] = e
return es
}
// HandleFunc registers the responder function for the given pattern.
func (mux *ServeMux) HandleFunc(pattern string, responder func(*ResponseWriter, *Request)) {
if responder == nil {
panic("gemini: nil responder")
}
mux.Handle(pattern, ResponderFunc(responder))
}

View File

@@ -33,15 +33,6 @@ type Request struct {
TLS tls.ConnectionState TLS tls.ConnectionState
} }
// hostname returns the host without the port.
func hostname(host string) string {
hostname, _, err := net.SplitHostPort(host)
if err != nil {
return host
}
return hostname
}
// NewRequest returns a new request. The host is inferred from the URL. // NewRequest returns a new request. The host is inferred from the URL.
func NewRequest(rawurl string) (*Request, error) { func NewRequest(rawurl string) (*Request, error) {
u, err := url.Parse(rawurl) u, err := url.Parse(rawurl)
@@ -54,29 +45,16 @@ 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.
func NewRequestFromURL(url *url.URL) (*Request, error) { func NewRequestFromURL(url *url.URL) (*Request, error) {
// If there is no port, use the default port of 1965 if url.Scheme != "" && url.Scheme != "gemini" {
return nil, ErrNotAGeminiURL
}
host := url.Host host := url.Host
if url.Port() == "" { if url.Port() == "" {
host += ":1965" host += ":1965"
} }
return &Request{ return &Request{
Host: host,
URL: url, URL: url,
}, nil
}
// NewRequestTo returns a new request for the provided URL to the provided host.
// The host must contain a port.
func NewRequestTo(rawurl, host string) (*Request, error) {
u, err := url.Parse(rawurl)
if err != nil {
return nil, err
}
return &Request{
Host: host, Host: host,
URL: u,
}, nil }, nil
} }

View File

@@ -3,7 +3,7 @@ package gemini
import ( import (
"bufio" "bufio"
"crypto/tls" "crypto/tls"
"io/ioutil" "io"
"strconv" "strconv"
) )
@@ -18,19 +18,23 @@ type Response struct {
// 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. // Body contains the response body for successful responses.
Body []byte 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 buffered reader. // read reads a Gemini response from the provided io.ReadCloser.
func (resp *Response) read(r *bufio.Reader) error { func (resp *Response) read(rc io.ReadCloser) error {
br := bufio.NewReader(rc)
// Read the status // Read the status
statusB := make([]byte, 2) statusB := make([]byte, 2)
if _, err := r.Read(statusB); err != nil { if _, err := br.Read(statusB); err != nil {
return err return err
} }
status, err := strconv.Atoi(string(statusB)) status, err := strconv.Atoi(string(statusB))
@@ -47,14 +51,14 @@ func (resp *Response) read(r *bufio.Reader) error {
} }
// Read one space // Read one space
if b, err := r.ReadByte(); err != nil { if b, err := br.ReadByte(); err != nil {
return err return err
} else if b != ' ' { } else if b != ' ' {
return ErrInvalidResponse return ErrInvalidResponse
} }
// Read the meta // Read the meta
meta, err := r.ReadString('\r') meta, err := br.ReadString('\r')
if err != nil { if err != nil {
return err return err
} }
@@ -67,19 +71,41 @@ func (resp *Response) read(r *bufio.Reader) error {
resp.Meta = meta resp.Meta = meta
// Read terminating newline // Read terminating newline
if b, err := r.ReadByte(); err != nil { if b, err := br.ReadByte(); err != nil {
return err return err
} else if b != '\n' { } else if b != '\n' {
return ErrInvalidResponse return ErrInvalidResponse
} }
// Read response body
if resp.Status.Class() == StatusClassSuccess { if resp.Status.Class() == StatusClassSuccess {
var err error resp.Body = newReadCloserBody(br, rc)
resp.Body, err = ioutil.ReadAll(r)
if err != nil {
return err
}
} }
return nil return nil
} }
type readCloserBody struct {
br *bufio.Reader // used until empty
io.ReadCloser
}
func newReadCloserBody(br *bufio.Reader, rc io.ReadCloser) io.ReadCloser {
body := &readCloserBody{ReadCloser: rc}
if br.Buffered() != 0 {
body.br = br
}
return body
}
func (b *readCloserBody) Read(p []byte) (n int, err error) {
if b.br != nil {
if n := b.br.Buffered(); len(p) > n {
p = p[:n]
}
n, err = b.br.Read(p)
if b.br.Buffered() == 0 {
b.br = nil
}
return n, err
}
return b.ReadCloser.Read(p)
}

265
server.go
View File

@@ -7,11 +7,8 @@ import (
"log" "log"
"net" "net"
"net/url" "net/url"
"path"
"sort"
"strconv" "strconv"
"strings" "strings"
"sync"
"time" "time"
) )
@@ -21,13 +18,12 @@ type Server struct {
// If Addr is empty, the server will listen on the address ":1965". // If Addr is empty, the server will listen on the address ":1965".
Addr string Addr string
// CertificateStore contains the certificates used by the server. // Certificates contains the certificates used by the server.
CertificateStore CertificateStore Certificates CertificateStore
// GetCertificate, if not nil, will be called to retrieve the certificate // CreateCertificate, if not nil, will be called to create a new certificate
// to use for a given hostname. // if the current one is expired or missing.
// If the certificate is nil, the connection will be aborted. CreateCertificate func(hostname string) (tls.Certificate, error)
GetCertificate func(hostname string, store *CertificateStore) *tls.Certificate
// registered responders // registered responders
responders map[responderKey]Responder responders map[responderKey]Responder
@@ -40,9 +36,16 @@ type responderKey struct {
} }
// Register registers a responder for the given pattern. // Register registers a responder for the given pattern.
// Patterns must be in the form of scheme://hostname (e.g. gemini://example.com). //
// 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. // If no scheme is specified, a default scheme of gemini:// is assumed.
//
// Wildcard patterns are supported (e.g. *.example.com). // Wildcard patterns are supported (e.g. *.example.com).
// To register a certificate for a wildcard hostname, call Certificates.Add:
//
// var s gemini.Server
// s.Certificates.Add("*.example.com", cert)
func (s *Server) Register(pattern string, responder Responder) { func (s *Server) Register(pattern string, responder Responder) {
if pattern == "" { if pattern == "" {
panic("gemini: invalid pattern") panic("gemini: invalid pattern")
@@ -69,6 +72,9 @@ func (s *Server) Register(pattern string, responder Responder) {
key.wildcard = true key.wildcard = true
} }
if _, ok := s.responders[key]; ok {
panic("gemini: multiple registrations for " + pattern)
}
s.responders[key] = responder s.responders[key] = responder
} }
@@ -90,18 +96,11 @@ func (s *Server) ListenAndServe() error {
} }
defer ln.Close() defer ln.Close()
config := &tls.Config{ return s.Serve(tls.NewListener(ln, &tls.Config{
ClientAuth: tls.RequestClientCert, ClientAuth: tls.RequestClientCert,
MinVersion: tls.VersionTLS12, MinVersion: tls.VersionTLS12,
GetCertificate: func(h *tls.ClientHelloInfo) (*tls.Certificate, error) { GetCertificate: s.getCertificate,
if s.GetCertificate != nil { }))
return s.GetCertificate(h.ServerName, &s.CertificateStore), nil
}
return s.CertificateStore.Lookup(h.ServerName)
},
}
tlsListener := tls.NewListener(ln, config)
return s.Serve(tlsListener)
} }
// Serve listens for requests on the provided listener. // Serve listens for requests on the provided listener.
@@ -135,6 +134,21 @@ 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
}
}
return cert, err
}
// respond responds to a connection. // respond responds to a connection.
func (s *Server) respond(conn net.Conn) { func (s *Server) respond(conn net.Conn) {
r := bufio.NewReader(conn) r := bufio.NewReader(conn)
@@ -273,7 +287,8 @@ type Responder interface {
// If no input is provided, it responds with StatusInput. // If no input is provided, it responds with StatusInput.
func Input(w *ResponseWriter, r *Request, prompt string) (string, bool) { func Input(w *ResponseWriter, r *Request, prompt string) (string, bool) {
if r.URL.ForceQuery || r.URL.RawQuery != "" { if r.URL.ForceQuery || r.URL.RawQuery != "" {
return r.URL.RawQuery, true query, err := url.QueryUnescape(r.URL.RawQuery)
return query, err == nil
} }
w.WriteHeader(StatusInput, prompt) w.WriteHeader(StatusInput, prompt)
return "", false return "", false
@@ -283,7 +298,8 @@ func Input(w *ResponseWriter, r *Request, prompt string) (string, bool) {
// If no input is provided, it responds with StatusSensitiveInput. // If no input is provided, it responds with StatusSensitiveInput.
func SensitiveInput(w *ResponseWriter, r *Request, prompt string) (string, bool) { func SensitiveInput(w *ResponseWriter, r *Request, prompt string) (string, bool) {
if r.URL.ForceQuery || r.URL.RawQuery != "" { if r.URL.ForceQuery || r.URL.RawQuery != "" {
return r.URL.RawQuery, true query, err := url.QueryUnescape(r.URL.RawQuery)
return query, err == nil
} }
w.WriteHeader(StatusSensitiveInput, prompt) w.WriteHeader(StatusSensitiveInput, prompt)
return "", false return "", false
@@ -315,204 +331,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)
} }
// The following code is modified from the net/http package.
// Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// ServeMux is a Gemini request multiplexer.
// It matches the URL of each incoming request against a list of registered
// patterns and calls the handler for the pattern that
// most closely matches the URL.
//
// Patterns name fixed, rooted paths, like "/favicon.ico",
// or rooted subtrees, like "/images/" (note the trailing slash).
// Longer patterns take precedence over shorter ones, so that
// if there are handlers registered for both "/images/"
// and "/images/thumbnails/", the latter handler will be
// called for paths beginning "/images/thumbnails/" and the
// former will receive requests for any other paths in the
// "/images/" subtree.
//
// Note that since a pattern ending in a slash names a rooted subtree,
// the pattern "/" matches all paths not matched by other registered
// patterns, not just the URL with Path == "/".
//
// If a subtree has been registered and a request is received naming the
// subtree root without its trailing slash, ServeMux redirects that
// request to the subtree root (adding the trailing slash). This behavior can
// be overridden with a separate registration for the path without
// the trailing slash. For example, registering "/images/" causes ServeMux
// to redirect a request for "/images" to "/images/", unless "/images" has
// been registered separately.
//
// ServeMux also takes care of sanitizing the URL request path and
// redirecting any request containing . or .. elements or repeated slashes
// to an equivalent, cleaner URL.
type ServeMux struct {
mu sync.RWMutex
m map[string]muxEntry
es []muxEntry // slice of entries sorted from longest to shortest.
}
type muxEntry struct {
r Responder
pattern string
}
// cleanPath returns the canonical path for p, eliminating . and .. elements.
func cleanPath(p string) string {
if p == "" {
return "/"
}
if p[0] != '/' {
p = "/" + p
}
np := path.Clean(p)
// path.Clean removes trailing slash except for root;
// put the trailing slash back if necessary.
if p[len(p)-1] == '/' && np != "/" {
// Fast path for common case of p being the string we want:
if len(p) == len(np)+1 && strings.HasPrefix(p, np) {
np = p
} else {
np += "/"
}
}
return np
}
// Find a handler on a handler map given a path string.
// Most-specific (longest) pattern wins.
func (mux *ServeMux) match(path string) Responder {
// Check for exact match first.
v, ok := mux.m[path]
if ok {
return v.r
}
// Check for longest valid match. mux.es contains all patterns
// that end in / sorted from longest to shortest.
for _, e := range mux.es {
if strings.HasPrefix(path, e.pattern) {
return e.r
}
}
return nil
}
// redirectToPathSlash determines if the given path needs appending "/" to it.
// This occurs when a handler for path + "/" was already registered, but
// not for path itself. If the path needs appending to, it creates a new
// URL, setting the path to u.Path + "/" and returning true to indicate so.
func (mux *ServeMux) redirectToPathSlash(path string, u *url.URL) (*url.URL, bool) {
mux.mu.RLock()
shouldRedirect := mux.shouldRedirectRLocked(path)
mux.mu.RUnlock()
if !shouldRedirect {
return u, false
}
path = path + "/"
u = &url.URL{Path: path, RawQuery: u.RawQuery}
return u, true
}
// shouldRedirectRLocked reports whether the given path and host should be redirected to
// path+"/". This should happen if a handler is registered for path+"/" but
// not path -- see comments at ServeMux.
func (mux *ServeMux) shouldRedirectRLocked(path string) bool {
if _, exist := mux.m[path]; exist {
return false
}
n := len(path)
if n == 0 {
return false
}
if _, exist := mux.m[path+"/"]; exist {
return path[n-1] != '/'
}
return false
}
// Respond dispatches the request to the responder whose
// pattern most closely matches the request URL.
func (mux *ServeMux) Respond(w *ResponseWriter, r *Request) {
path := cleanPath(r.URL.Path)
// 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())
return
}
if path != r.URL.Path {
u := *r.URL
u.Path = path
Redirect(w, u.String())
return
}
mux.mu.RLock()
defer mux.mu.RUnlock()
resp := mux.match(path)
if resp == nil {
w.WriteStatus(StatusNotFound)
return
}
resp.Respond(w, r)
}
// Handle registers the responder for the given pattern.
// If a responder already exists for pattern, Handle panics.
func (mux *ServeMux) Handle(pattern string, responder Responder) {
mux.mu.Lock()
defer mux.mu.Unlock()
if pattern == "" {
panic("gemini: invalid pattern")
}
if responder == nil {
panic("gemini: nil responder")
}
if _, exist := mux.m[pattern]; exist {
panic("gemini: multiple registrations for " + pattern)
}
if mux.m == nil {
mux.m = make(map[string]muxEntry)
}
e := muxEntry{responder, pattern}
mux.m[pattern] = e
if pattern[len(pattern)-1] == '/' {
mux.es = appendSorted(mux.es, e)
}
}
func appendSorted(es []muxEntry, e muxEntry) []muxEntry {
n := len(es)
i := sort.Search(n, func(i int) bool {
return len(es[i].pattern) < len(e.pattern)
})
if i == n {
return append(es, e)
}
// we now know that i points at where we want to insert
es = append(es, muxEntry{}) // try to grow the slice in place, any entry works.
copy(es[i+1:], es[i:]) // move shorter entries down
es[i] = e
return es
}
// HandleFunc registers the responder function for the given pattern.
func (mux *ServeMux) HandleFunc(pattern string, responder func(*ResponseWriter, *Request)) {
if responder == nil {
panic("gemini: nil responder")
}
mux.Handle(pattern, ResponderFunc(responder))
}

85
status.go Normal file
View File

@@ -0,0 +1,85 @@
package gemini
// Status codes.
type Status int
const (
StatusInput Status = 10
StatusSensitiveInput Status = 11
StatusSuccess Status = 20
StatusRedirect Status = 30
StatusRedirectPermanent Status = 31
StatusTemporaryFailure Status = 40
StatusServerUnavailable Status = 41
StatusCGIError Status = 42
StatusProxyError Status = 43
StatusSlowDown Status = 44
StatusPermanentFailure Status = 50
StatusNotFound Status = 51
StatusGone Status = 52
StatusProxyRequestRefused Status = 53
StatusBadRequest Status = 59
StatusCertificateRequired Status = 60
StatusCertificateNotAuthorized Status = 61
StatusCertificateNotValid Status = 62
)
// Status code categories.
type StatusClass int
const (
StatusClassInput StatusClass = 1
StatusClassSuccess StatusClass = 2
StatusClassRedirect StatusClass = 3
StatusClassTemporaryFailure StatusClass = 4
StatusClassPermanentFailure StatusClass = 5
StatusClassCertificateRequired StatusClass = 6
)
// Class returns the status class for this status code.
func (s Status) Class() StatusClass {
return StatusClass(s / 10)
}
// Message returns a status message corresponding to this status code.
func (s Status) Message() string {
switch s {
case StatusInput:
return "Input"
case StatusSensitiveInput:
return "Sensitive input"
case StatusSuccess:
return "Success"
case StatusRedirect:
return "Redirect"
case StatusRedirectPermanent:
return "Permanent redirect"
case StatusTemporaryFailure:
return "Temporary failure"
case StatusServerUnavailable:
return "Server unavailable"
case StatusCGIError:
return "CGI error"
case StatusProxyError:
return "Proxy error"
case StatusSlowDown:
return "Slow down"
case StatusPermanentFailure:
return "Permanent failure"
case StatusNotFound:
return "Not found"
case StatusGone:
return "Gone"
case StatusProxyRequestRefused:
return "Proxy request refused"
case StatusBadRequest:
return "Bad request"
case StatusCertificateRequired:
return "Certificate required"
case StatusCertificateNotAuthorized:
return "Certificate not authorized"
case StatusCertificateNotValid:
return "Certificate not valid"
}
return ""
}

View File

@@ -2,7 +2,6 @@ package gemini
import ( import (
"bufio" "bufio"
"bytes"
"crypto/sha512" "crypto/sha512"
"crypto/x509" "crypto/x509"
"fmt" "fmt"
@@ -162,14 +161,14 @@ func appendKnownHost(w io.Writer, hostname string, c certInfo) (int, error) {
// Fingerprint returns the SHA-512 fingerprint of the provided certificate. // Fingerprint returns the SHA-512 fingerprint of the provided certificate.
func Fingerprint(cert *x509.Certificate) string { func Fingerprint(cert *x509.Certificate) string {
sum512 := sha512.Sum512(cert.Raw) sum512 := sha512.Sum512(cert.Raw)
var buf bytes.Buffer var b strings.Builder
for i, f := range sum512 { for i, f := range sum512 {
if i > 0 { if i > 0 {
fmt.Fprintf(&buf, ":") b.WriteByte(':')
} }
fmt.Fprintf(&buf, "%02X", f) fmt.Fprintf(&b, "%02X", f)
} }
return buf.String() return b.String()
} }
// defaultKnownHostsPath returns the default known_hosts path. // defaultKnownHostsPath returns the default known_hosts path.