Compare commits
17 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
7fb1b6c6a4 | ||
|
|
0d3230a7d5 | ||
|
|
79b3b22e69 | ||
|
|
33c1dc435d | ||
|
|
dad8f38bfb | ||
|
|
8181b86759 | ||
|
|
65a5065250 | ||
|
|
b9cb7fe71d | ||
|
|
7d470c5fb1 | ||
|
|
42c95f8c8d | ||
|
|
a2fc1772bf | ||
|
|
63b9b484d1 | ||
|
|
ca8e0166fc | ||
|
|
14ef3be6fe | ||
|
|
3aa254870a | ||
|
|
a89065babb | ||
|
|
eb466ad02f |
48
cert.go
48
cert.go
@@ -6,17 +6,22 @@ import (
|
|||||||
"crypto/rand"
|
"crypto/rand"
|
||||||
"crypto/tls"
|
"crypto/tls"
|
||||||
"crypto/x509"
|
"crypto/x509"
|
||||||
|
"encoding/pem"
|
||||||
|
"log"
|
||||||
"math/big"
|
"math/big"
|
||||||
"net"
|
"net"
|
||||||
|
"os"
|
||||||
"path/filepath"
|
"path/filepath"
|
||||||
"strings"
|
"strings"
|
||||||
"time"
|
"time"
|
||||||
)
|
)
|
||||||
|
|
||||||
// CertificateStore maps hostnames to certificates.
|
// CertificateStore maps certificate scopes to certificates.
|
||||||
// The zero value of CertificateStore is an empty store ready to use.
|
// The zero value of CertificateStore is an empty store ready to use.
|
||||||
type CertificateStore struct {
|
type CertificateStore struct {
|
||||||
store map[string]tls.Certificate
|
store map[string]tls.Certificate
|
||||||
|
dir bool
|
||||||
|
path string
|
||||||
}
|
}
|
||||||
|
|
||||||
// Add adds a certificate for the given scope to the store.
|
// Add adds a certificate for the given scope to the store.
|
||||||
@@ -32,6 +37,15 @@ func (c *CertificateStore) Add(scope string, cert tls.Certificate) {
|
|||||||
cert.Leaf = parsed
|
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
|
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) {
|
func (c *CertificateStore) Lookup(scope string) (*tls.Certificate, error) {
|
||||||
cert, ok := c.store[scope]
|
cert, ok := c.store[scope]
|
||||||
if !ok {
|
if !ok {
|
||||||
return nil, ErrCertificateUnknown
|
return nil, ErrCertificateNotFound
|
||||||
}
|
}
|
||||||
// Ensure that the certificate is not expired
|
// Ensure that the certificate is not expired
|
||||||
if cert.Leaf != nil && cert.Leaf.NotAfter.Before(time.Now()) {
|
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.
|
// 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).
|
||||||
|
// New certificates will be written to this directory.
|
||||||
func (c *CertificateStore) Load(path string) error {
|
func (c *CertificateStore) Load(path string) error {
|
||||||
matches, err := filepath.Glob(filepath.Join(path, "*.crt"))
|
matches, err := filepath.Glob(filepath.Join(path, "*.crt"))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -67,6 +82,8 @@ func (c *CertificateStore) Load(path string) error {
|
|||||||
scope := strings.TrimSuffix(filepath.Base(crtPath), ".crt")
|
scope := strings.TrimSuffix(filepath.Base(crtPath), ".crt")
|
||||||
c.Add(scope, cert)
|
c.Add(scope, cert)
|
||||||
}
|
}
|
||||||
|
c.dir = true
|
||||||
|
c.path = path
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -133,3 +150,30 @@ func newX509KeyPair(options CertificateOptions) (*x509.Certificate, crypto.Priva
|
|||||||
}
|
}
|
||||||
return cert, priv, nil
|
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})
|
||||||
|
}
|
||||||
|
|||||||
61
client.go
61
client.go
@@ -8,6 +8,7 @@ import (
|
|||||||
"net/url"
|
"net/url"
|
||||||
"path"
|
"path"
|
||||||
"strings"
|
"strings"
|
||||||
|
"time"
|
||||||
)
|
)
|
||||||
|
|
||||||
// Client is a Gemini client.
|
// Client is a Gemini client.
|
||||||
@@ -18,6 +19,20 @@ type Client struct {
|
|||||||
// Certificates stores client-side certificates.
|
// Certificates stores client-side certificates.
|
||||||
Certificates CertificateStore
|
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.
|
// GetInput is called to retrieve input when the server requests it.
|
||||||
// If GetInput is nil or returns false, no input will be sent and
|
// If GetInput is nil or returns false, no input will be sent and
|
||||||
// the response will be returned.
|
// 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.
|
// the request will not be sent again and the response will be returned.
|
||||||
CreateCertificate func(hostname, path string) (tls.Certificate, error)
|
CreateCertificate func(hostname, path string) (tls.Certificate, error)
|
||||||
|
|
||||||
// TrustCertificate determines whether the client should trust
|
// TrustCertificate is called to determine whether the client
|
||||||
// the provided certificate.
|
// should trust a certificate it has not seen before.
|
||||||
// If the returned error is not nil, the connection will be aborted.
|
// If TrustCertificate is nil, the certificate will not be trusted
|
||||||
// If TrustCertificate is nil, the client will check KnownHosts
|
// and the connection will be aborted.
|
||||||
// for the certificate.
|
//
|
||||||
TrustCertificate func(hostname string, cert *x509.Certificate, knownHosts *KnownHosts) error
|
// If TrustCertificate returns TrustOnce, the certificate will be added
|
||||||
|
// to the client's list of known hosts.
|
||||||
|
// If TrustCertificate returns TrustAlways, the certificate will also be
|
||||||
|
// written to the known hosts file.
|
||||||
|
TrustCertificate func(hostname string, cert *x509.Certificate) Trust
|
||||||
}
|
}
|
||||||
|
|
||||||
// Get performs a Gemini request for the given url.
|
// Get performs a Gemini request for the given url.
|
||||||
@@ -72,7 +91,10 @@ func (c *Client) do(req *Request, via []*Request) (*Response, error) {
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
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
|
// Write the request
|
||||||
w := bufio.NewWriter(conn)
|
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 {
|
if err := verifyHostname(cert, hostname); err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
// Check that the client trusts the certificate
|
if c.InsecureSkipTrust {
|
||||||
var err error
|
return nil
|
||||||
if c.TrustCertificate != nil {
|
}
|
||||||
return c.TrustCertificate(hostname, cert, &c.KnownHosts)
|
// Check the known hosts
|
||||||
} else {
|
err := c.KnownHosts.Lookup(hostname, cert)
|
||||||
err = c.KnownHosts.Lookup(hostname, cert)
|
switch err {
|
||||||
|
case ErrCertificateExpired, ErrCertificateNotFound:
|
||||||
|
// See if the client trusts the certificate
|
||||||
|
if c.TrustCertificate != nil {
|
||||||
|
switch c.TrustCertificate(hostname, cert) {
|
||||||
|
case TrustOnce:
|
||||||
|
c.KnownHosts.AddTemporary(hostname, cert)
|
||||||
|
return nil
|
||||||
|
case TrustAlways:
|
||||||
|
c.KnownHosts.Add(hostname, cert)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return ErrCertificateNotTrusted
|
||||||
}
|
}
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|||||||
39
doc.go
39
doc.go
@@ -3,57 +3,30 @@ Package gemini implements the Gemini protocol.
|
|||||||
|
|
||||||
Get makes a Gemini request:
|
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")
|
resp, err := gemini.Get("gemini://example.com")
|
||||||
if err != nil {
|
if err != nil {
|
||||||
// handle error
|
// handle error
|
||||||
}
|
}
|
||||||
defer resp.Body.Close()
|
defer resp.Body.Close()
|
||||||
body, err := ioutil.ReadAll(resp.Body)
|
|
||||||
// ...
|
// ...
|
||||||
|
|
||||||
For control over client behavior, create a Client:
|
For control over client behavior, create a Client:
|
||||||
|
|
||||||
var client gemini.Client
|
client := &gemini.Client{}
|
||||||
resp, err := client.Get("gemini://example.com")
|
resp, err := client.Get("gemini://example.com")
|
||||||
if err != nil {
|
if err != nil {
|
||||||
// handle error
|
// handle error
|
||||||
}
|
}
|
||||||
// ...
|
// ...
|
||||||
|
|
||||||
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.
|
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")
|
err := server.Certificates.Load("/var/lib/gemini/certs")
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
|||||||
@@ -70,7 +70,7 @@ func login(w *gemini.ResponseWriter, r *gemini.Request) {
|
|||||||
sessions[fingerprint] = &session{
|
sessions[fingerprint] = &session{
|
||||||
username: username,
|
username: username,
|
||||||
}
|
}
|
||||||
gemini.Redirect(w, "/password")
|
w.WriteHeader(gemini.StatusRedirect, "/password")
|
||||||
}
|
}
|
||||||
|
|
||||||
func loginPassword(w *gemini.ResponseWriter, r *gemini.Request) {
|
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
|
expected := logins[session.username].password
|
||||||
if password == expected {
|
if password == expected {
|
||||||
session.authorized = true
|
session.authorized = true
|
||||||
gemini.Redirect(w, "/profile")
|
w.WriteHeader(gemini.StatusRedirect, "/profile")
|
||||||
} else {
|
} else {
|
||||||
gemini.SensitiveInput(w, r, "Wrong password. Try again")
|
gemini.SensitiveInput(w, r, "Wrong password. Try again")
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -8,43 +8,41 @@ import (
|
|||||||
"crypto/x509"
|
"crypto/x509"
|
||||||
"fmt"
|
"fmt"
|
||||||
"io/ioutil"
|
"io/ioutil"
|
||||||
|
"log"
|
||||||
"os"
|
"os"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"git.sr.ht/~adnano/go-gemini"
|
"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 (
|
var (
|
||||||
scanner = bufio.NewScanner(os.Stdin)
|
scanner = bufio.NewScanner(os.Stdin)
|
||||||
client = &gemini.Client{}
|
client = &gemini.Client{}
|
||||||
)
|
)
|
||||||
|
|
||||||
func init() {
|
func init() {
|
||||||
|
client.Timeout = 2 * time.Minute
|
||||||
client.KnownHosts.LoadDefault()
|
client.KnownHosts.LoadDefault()
|
||||||
client.TrustCertificate = func(hostname string, cert *x509.Certificate, knownHosts *gemini.KnownHosts) error {
|
client.TrustCertificate = func(hostname string, cert *x509.Certificate) gemini.Trust {
|
||||||
err := knownHosts.Lookup(hostname, cert)
|
fmt.Printf(trustPrompt, hostname, gemini.Fingerprint(cert))
|
||||||
if err != nil {
|
scanner.Scan()
|
||||||
switch err {
|
switch scanner.Text() {
|
||||||
case gemini.ErrCertificateNotTrusted:
|
case "t":
|
||||||
// Alert the user that the certificate is not trusted
|
return gemini.TrustAlways
|
||||||
fmt.Printf("Warning: Certificate for %s is not trusted!\n", hostname)
|
case "o":
|
||||||
fmt.Println("This could indicate a Man-in-the-Middle attack.")
|
return gemini.TrustOnce
|
||||||
case gemini.ErrCertificateUnknown:
|
default:
|
||||||
// Prompt the user to trust the certificate
|
return gemini.TrustNone
|
||||||
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
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
return err
|
|
||||||
}
|
}
|
||||||
client.CreateCertificate = func(hostname, path string) (tls.Certificate, error) {
|
client.CreateCertificate = func(hostname, path string) (tls.Certificate, error) {
|
||||||
fmt.Println("Generating client certificate for", hostname, path)
|
fmt.Println("Generating client certificate for", hostname, path)
|
||||||
@@ -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() {
|
func main() {
|
||||||
if len(os.Args) < 2 {
|
if len(os.Args) < 2 {
|
||||||
fmt.Printf("usage: %s gemini://... [host]", os.Args[0])
|
fmt.Printf("usage: %s gemini://... [host]", os.Args[0])
|
||||||
@@ -124,8 +74,20 @@ func main() {
|
|||||||
req.Host = os.Args[2]
|
req.Host = os.Args[2]
|
||||||
}
|
}
|
||||||
|
|
||||||
if err := doRequest(req); err != nil {
|
resp, err := client.Do(req)
|
||||||
|
if err != nil {
|
||||||
fmt.Println(err)
|
fmt.Println(err)
|
||||||
os.Exit(1)
|
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)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,14 +3,8 @@
|
|||||||
package main
|
package main
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"crypto"
|
|
||||||
"crypto/tls"
|
"crypto/tls"
|
||||||
"crypto/x509"
|
|
||||||
"encoding/pem"
|
|
||||||
"fmt"
|
|
||||||
"io"
|
|
||||||
"log"
|
"log"
|
||||||
"os"
|
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"git.sr.ht/~adnano/go-gemini"
|
"git.sr.ht/~adnano/go-gemini"
|
||||||
@@ -18,20 +12,16 @@ import (
|
|||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
var server gemini.Server
|
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 {
|
if err := server.Certificates.Load("/var/lib/gemini/certs"); err != nil {
|
||||||
log.Fatal(err)
|
log.Fatal(err)
|
||||||
}
|
}
|
||||||
server.CreateCertificate = func(hostname string) (tls.Certificate, error) {
|
server.CreateCertificate = func(hostname string) (tls.Certificate, error) {
|
||||||
fmt.Println("Generating certificate for", hostname)
|
return gemini.CreateCertificate(gemini.CertificateOptions{
|
||||||
cert, err := gemini.CreateCertificate(gemini.CertificateOptions{
|
|
||||||
DNSNames: []string{hostname},
|
DNSNames: []string{hostname},
|
||||||
Duration: time.Minute, // for testing purposes
|
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
|
var mux gemini.ServeMux
|
||||||
@@ -42,39 +32,3 @@ func main() {
|
|||||||
log.Fatal(err)
|
log.Fatal(err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// writeCertificate writes the provided certificate and private key
|
|
||||||
// to path.crt and path.key respectively.
|
|
||||||
func writeCertificate(path string, cert tls.Certificate) error {
|
|
||||||
// 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})
|
|
||||||
}
|
|
||||||
|
|||||||
25
gemini.go
25
gemini.go
@@ -1,11 +1,8 @@
|
|||||||
package gemini
|
package gemini
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"crypto/tls"
|
|
||||||
"crypto/x509"
|
|
||||||
"errors"
|
"errors"
|
||||||
"sync"
|
"sync"
|
||||||
"time"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
var crlf = []byte("\r\n")
|
var crlf = []byte("\r\n")
|
||||||
@@ -14,15 +11,15 @@ var crlf = []byte("\r\n")
|
|||||||
var (
|
var (
|
||||||
ErrInvalidURL = errors.New("gemini: invalid URL")
|
ErrInvalidURL = errors.New("gemini: invalid URL")
|
||||||
ErrInvalidResponse = errors.New("gemini: invalid response")
|
ErrInvalidResponse = errors.New("gemini: invalid response")
|
||||||
ErrCertificateUnknown = errors.New("gemini: unknown certificate")
|
|
||||||
ErrCertificateExpired = errors.New("gemini: certificate expired")
|
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")
|
ErrNotAFile = errors.New("gemini: not a file")
|
||||||
ErrNotAGeminiURL = errors.New("gemini: not a Gemini URL")
|
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")
|
ErrTooManyRedirects = errors.New("gemini: too many redirects")
|
||||||
ErrInputRequired = errors.New("gemini: input required")
|
ErrInputRequired = errors.New("gemini: input required")
|
||||||
ErrCertificateRequired = errors.New("gemini: certificate required")
|
|
||||||
)
|
)
|
||||||
|
|
||||||
// DefaultClient is the default client. It is used by Get and Do.
|
// 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.
|
// Get is a wrapper around DefaultClient.Get.
|
||||||
func Get(url string) (*Response, error) {
|
func Get(url string) (*Response, error) {
|
||||||
|
setupDefaultClientOnce()
|
||||||
return DefaultClient.Get(url)
|
return DefaultClient.Get(url)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -41,19 +39,14 @@ func Get(url string) (*Response, error) {
|
|||||||
//
|
//
|
||||||
// Do is a wrapper around DefaultClient.Do.
|
// Do is a wrapper around DefaultClient.Do.
|
||||||
func Do(req *Request) (*Response, error) {
|
func Do(req *Request) (*Response, error) {
|
||||||
|
setupDefaultClientOnce()
|
||||||
return DefaultClient.Do(req)
|
return DefaultClient.Do(req)
|
||||||
}
|
}
|
||||||
|
|
||||||
var defaultClientOnce sync.Once
|
var defaultClientOnce sync.Once
|
||||||
|
|
||||||
func init() {
|
func setupDefaultClientOnce() {
|
||||||
DefaultClient.TrustCertificate = func(hostname string, cert *x509.Certificate, knownHosts *KnownHosts) error {
|
defaultClientOnce.Do(func() {
|
||||||
defaultClientOnce.Do(func() { knownHosts.LoadDefault() })
|
DefaultClient.KnownHosts.LoadDefault()
|
||||||
return knownHosts.Lookup(hostname, cert)
|
})
|
||||||
}
|
|
||||||
DefaultClient.CreateCertificate = func(hostname, path string) (tls.Certificate, error) {
|
|
||||||
return CreateCertificate(CertificateOptions{
|
|
||||||
Duration: time.Hour,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
4
mux.go
4
mux.go
@@ -138,14 +138,14 @@ func (mux *ServeMux) Respond(w *ResponseWriter, r *Request) {
|
|||||||
// If the given path is /tree and its handler is not registered,
|
// If the given path is /tree and its handler is not registered,
|
||||||
// redirect for /tree/.
|
// redirect for /tree/.
|
||||||
if u, ok := mux.redirectToPathSlash(path, r.URL); ok {
|
if u, ok := mux.redirectToPathSlash(path, r.URL); ok {
|
||||||
Redirect(w, u.String())
|
w.WriteHeader(StatusRedirect, u.String())
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
if path != r.URL.Path {
|
if path != r.URL.Path {
|
||||||
u := *r.URL
|
u := *r.URL
|
||||||
u.Path = path
|
u.Path = path
|
||||||
Redirect(w, u.String())
|
w.WriteHeader(StatusRedirect, u.String())
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
13
response.go
13
response.go
@@ -2,14 +2,16 @@ package gemini
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"bufio"
|
"bufio"
|
||||||
|
"bytes"
|
||||||
"crypto/tls"
|
"crypto/tls"
|
||||||
"io"
|
"io"
|
||||||
|
"io/ioutil"
|
||||||
"strconv"
|
"strconv"
|
||||||
)
|
)
|
||||||
|
|
||||||
// Response is a Gemini response.
|
// Response is a Gemini response.
|
||||||
type Response struct {
|
type Response struct {
|
||||||
// Status represents the response status.
|
// Status contains the response status code.
|
||||||
Status Status
|
Status Status
|
||||||
|
|
||||||
// Meta contains more information related to the response status.
|
// Meta contains more information related to the response status.
|
||||||
@@ -19,9 +21,10 @@ type Response struct {
|
|||||||
Meta string
|
Meta string
|
||||||
|
|
||||||
// Body contains the response body for successful responses.
|
// Body contains the response body for successful responses.
|
||||||
|
// Body is guaranteed to be non-nil.
|
||||||
Body io.ReadCloser
|
Body io.ReadCloser
|
||||||
|
|
||||||
// Request is the request that was sent to obtain this Response.
|
// Request is the request that was sent to obtain this response.
|
||||||
Request *Request
|
Request *Request
|
||||||
|
|
||||||
// TLS contains information about the TLS connection on which the response
|
// 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 {
|
if len(meta) > 1024 {
|
||||||
return ErrInvalidResponse
|
return ErrInvalidResponse
|
||||||
}
|
}
|
||||||
|
// Default mime type of text/gemini; charset=utf-8
|
||||||
|
if statusClass == StatusClassSuccess && meta == "" {
|
||||||
|
meta = "text/gemini; charset=utf-8"
|
||||||
|
}
|
||||||
resp.Meta = meta
|
resp.Meta = meta
|
||||||
|
|
||||||
// Read terminating newline
|
// Read terminating newline
|
||||||
@@ -79,6 +86,8 @@ func (resp *Response) read(rc io.ReadCloser) error {
|
|||||||
|
|
||||||
if resp.Status.Class() == StatusClassSuccess {
|
if resp.Status.Class() == StatusClassSuccess {
|
||||||
resp.Body = newReadCloserBody(br, rc)
|
resp.Body = newReadCloserBody(br, rc)
|
||||||
|
} else {
|
||||||
|
resp.Body = ioutil.NopCloser(bytes.NewReader([]byte{}))
|
||||||
}
|
}
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|||||||
99
server.go
99
server.go
@@ -18,6 +18,13 @@ 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
|
||||||
|
|
||||||
|
// 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 contains the certificates used by the server.
|
||||||
Certificates CertificateStore
|
Certificates CertificateStore
|
||||||
|
|
||||||
@@ -27,25 +34,19 @@ type Server struct {
|
|||||||
|
|
||||||
// registered responders
|
// registered responders
|
||||||
responders map[responderKey]Responder
|
responders map[responderKey]Responder
|
||||||
|
hosts map[string]bool
|
||||||
}
|
}
|
||||||
|
|
||||||
type responderKey struct {
|
type responderKey struct {
|
||||||
scheme string
|
scheme string
|
||||||
hostname string
|
hostname string
|
||||||
wildcard bool
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Register registers a responder for the given pattern.
|
// Register registers a responder for the given pattern.
|
||||||
//
|
//
|
||||||
// Patterns must be in the form of hostname or scheme://hostname
|
// Patterns must be in the form of "hostname" or "scheme://hostname".
|
||||||
// (e.g. gemini://example.com).
|
// If no scheme is specified, a scheme of "gemini://" is implied.
|
||||||
// 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")
|
||||||
@@ -55,6 +56,7 @@ func (s *Server) Register(pattern string, responder Responder) {
|
|||||||
}
|
}
|
||||||
if s.responders == nil {
|
if s.responders == nil {
|
||||||
s.responders = map[responderKey]Responder{}
|
s.responders = map[responderKey]Responder{}
|
||||||
|
s.hosts = map[string]bool{}
|
||||||
}
|
}
|
||||||
|
|
||||||
split := strings.SplitN(pattern, "://", 2)
|
split := strings.SplitN(pattern, "://", 2)
|
||||||
@@ -66,16 +68,12 @@ func (s *Server) Register(pattern string, responder Responder) {
|
|||||||
key.scheme = "gemini"
|
key.scheme = "gemini"
|
||||||
key.hostname = split[0]
|
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 {
|
if _, ok := s.responders[key]; ok {
|
||||||
panic("gemini: multiple registrations for " + pattern)
|
panic("gemini: multiple registrations for " + pattern)
|
||||||
}
|
}
|
||||||
s.responders[key] = responder
|
s.responders[key] = responder
|
||||||
|
s.hosts[key.hostname] = true
|
||||||
}
|
}
|
||||||
|
|
||||||
// RegisterFunc registers a responder function for the given pattern.
|
// 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) {
|
func (s *Server) getCertificate(h *tls.ClientHelloInfo) (*tls.Certificate, error) {
|
||||||
cert, err := s.Certificates.Lookup(h.ServerName)
|
cert, err := s.getCertificateFor(h.ServerName)
|
||||||
switch err {
|
if err != nil {
|
||||||
case ErrCertificateExpired, ErrCertificateUnknown:
|
// Try wildcard
|
||||||
if s.CreateCertificate != nil {
|
wildcard := strings.SplitN(h.ServerName, ".", 2)
|
||||||
cert, err := s.CreateCertificate(h.ServerName)
|
if len(wildcard) == 2 {
|
||||||
if err == nil {
|
cert, err = s.getCertificateFor("*." + wildcard[1])
|
||||||
s.Certificates.Add(h.ServerName, cert)
|
|
||||||
}
|
|
||||||
return &cert, err
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return cert, err
|
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.
|
// respond responds to a connection.
|
||||||
func (s *Server) respond(conn net.Conn) {
|
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)
|
r := bufio.NewReader(conn)
|
||||||
w := newResponseWriter(conn)
|
w := newResponseWriter(conn)
|
||||||
// Read requested URL
|
// Read requested URL
|
||||||
@@ -162,16 +184,16 @@ func (s *Server) respond(conn net.Conn) {
|
|||||||
if b, err := r.ReadByte(); err != nil {
|
if b, err := r.ReadByte(); err != nil {
|
||||||
return
|
return
|
||||||
} else if b != '\n' {
|
} else if b != '\n' {
|
||||||
w.WriteHeader(StatusBadRequest, "Bad request")
|
w.WriteStatus(StatusBadRequest)
|
||||||
}
|
}
|
||||||
// Trim carriage return
|
// Trim carriage return
|
||||||
rawurl = rawurl[:len(rawurl)-1]
|
rawurl = rawurl[:len(rawurl)-1]
|
||||||
// Ensure URL is valid
|
// Ensure URL is valid
|
||||||
if len(rawurl) > 1024 {
|
if len(rawurl) > 1024 {
|
||||||
w.WriteHeader(StatusBadRequest, "Bad request")
|
w.WriteStatus(StatusBadRequest)
|
||||||
} else if url, err := url.Parse(rawurl); err != nil || url.User != nil {
|
} 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
|
// Note that we return an error status if User is specified in the URL
|
||||||
w.WriteHeader(StatusBadRequest, "Bad request")
|
w.WriteStatus(StatusBadRequest)
|
||||||
} else {
|
} else {
|
||||||
// If no scheme is specified, assume a default scheme of gemini://
|
// If no scheme is specified, assume a default scheme of gemini://
|
||||||
if url.Scheme == "" {
|
if url.Scheme == "" {
|
||||||
@@ -194,12 +216,12 @@ func (s *Server) respond(conn net.Conn) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (s *Server) responder(r *Request) Responder {
|
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
|
return h
|
||||||
}
|
}
|
||||||
wildcard := strings.SplitN(r.URL.Hostname(), ".", 2)
|
wildcard := strings.SplitN(r.URL.Hostname(), ".", 2)
|
||||||
if len(wildcard) == 2 {
|
if len(wildcard) == 2 {
|
||||||
if h, ok := s.responders[responderKey{r.URL.Scheme, wildcard[1], true}]; ok {
|
if h, ok := s.responders[responderKey{r.URL.Scheme, "*." + wildcard[1]}]; ok {
|
||||||
return h
|
return h
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -244,13 +266,13 @@ func (w *ResponseWriter) WriteHeader(status Status, meta string) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// WriteStatus writes the response header with the given status code.
|
// WriteStatus writes the response header with the given status code.
|
||||||
|
//
|
||||||
|
// WriteStatus is equivalent to WriteHeader(status, status.Message())
|
||||||
func (w *ResponseWriter) WriteStatus(status Status) {
|
func (w *ResponseWriter) WriteStatus(status Status) {
|
||||||
w.WriteHeader(status, status.Message())
|
w.WriteHeader(status, status.Message())
|
||||||
}
|
}
|
||||||
|
|
||||||
// SetMimetype sets the mimetype that will be written for a successful response.
|
// 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".
|
// If the mimetype is not set, it will default to "text/gemini".
|
||||||
func (w *ResponseWriter) SetMimetype(mimetype string) {
|
func (w *ResponseWriter) SetMimetype(mimetype string) {
|
||||||
w.mimetype = mimetype
|
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
|
// If the response status does not allow for a response body, Write returns
|
||||||
// ErrBodyNotAllowed.
|
// ErrBodyNotAllowed.
|
||||||
//
|
//
|
||||||
// If WriteHeader has not yet been called, Write calls
|
// If the response header has not yet been written, Write calls WriteHeader
|
||||||
// WriteHeader(StatusSuccess, mimetype) where mimetype is the mimetype set in
|
// with StatusSuccess and the mimetype set in SetMimetype.
|
||||||
// SetMimetype. If no mimetype is set, a default of "text/gemini" will be used.
|
|
||||||
func (w *ResponseWriter) Write(b []byte) (int, error) {
|
func (w *ResponseWriter) Write(b []byte) (int, error) {
|
||||||
if !w.wroteHeader {
|
if !w.wroteHeader {
|
||||||
mimetype := w.mimetype
|
mimetype := w.mimetype
|
||||||
@@ -305,16 +326,6 @@ func SensitiveInput(w *ResponseWriter, r *Request, prompt string) (string, bool)
|
|||||||
return "", false
|
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,
|
// Certificate returns the request certificate. If one is not provided,
|
||||||
// it returns nil and responds with StatusCertificateRequired.
|
// it returns nil and responds with StatusCertificateRequired.
|
||||||
func Certificate(w *ResponseWriter, r *Request) (*x509.Certificate, bool) {
|
func Certificate(w *ResponseWriter, r *Request) (*x509.Certificate, bool) {
|
||||||
|
|||||||
@@ -8,7 +8,7 @@ const (
|
|||||||
StatusSensitiveInput Status = 11
|
StatusSensitiveInput Status = 11
|
||||||
StatusSuccess Status = 20
|
StatusSuccess Status = 20
|
||||||
StatusRedirect Status = 30
|
StatusRedirect Status = 30
|
||||||
StatusRedirectPermanent Status = 31
|
StatusPermanentRedirect Status = 31
|
||||||
StatusTemporaryFailure Status = 40
|
StatusTemporaryFailure Status = 40
|
||||||
StatusServerUnavailable Status = 41
|
StatusServerUnavailable Status = 41
|
||||||
StatusCGIError Status = 42
|
StatusCGIError Status = 42
|
||||||
@@ -52,7 +52,7 @@ func (s Status) Message() string {
|
|||||||
return "Success"
|
return "Success"
|
||||||
case StatusRedirect:
|
case StatusRedirect:
|
||||||
return "Redirect"
|
return "Redirect"
|
||||||
case StatusRedirectPermanent:
|
case StatusPermanentRedirect:
|
||||||
return "Permanent redirect"
|
return "Permanent redirect"
|
||||||
case StatusTemporaryFailure:
|
case StatusTemporaryFailure:
|
||||||
return "Temporary failure"
|
return "Temporary failure"
|
||||||
|
|||||||
88
text.go
88
text.go
@@ -87,58 +87,68 @@ func (l LineText) line() {}
|
|||||||
// Text represents a Gemini text response.
|
// Text represents a Gemini text response.
|
||||||
type Text []Line
|
type Text []Line
|
||||||
|
|
||||||
// Parse parses Gemini text from the provided io.Reader.
|
// ParseText parses Gemini text from the provided io.Reader.
|
||||||
func Parse(r io.Reader) Text {
|
func ParseText(r io.Reader) Text {
|
||||||
const spacetab = " \t"
|
|
||||||
var t 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
|
var pre bool
|
||||||
scanner := bufio.NewScanner(r)
|
scanner := bufio.NewScanner(r)
|
||||||
for scanner.Scan() {
|
for scanner.Scan() {
|
||||||
line := scanner.Text()
|
var line Line
|
||||||
if strings.HasPrefix(line, "```") {
|
text := scanner.Text()
|
||||||
|
if strings.HasPrefix(text, "```") {
|
||||||
pre = !pre
|
pre = !pre
|
||||||
line = line[3:]
|
text = text[3:]
|
||||||
t = append(t, LinePreformattingToggle(line))
|
line = LinePreformattingToggle(text)
|
||||||
} else if pre {
|
} else if pre {
|
||||||
t = append(t, LinePreformattedText(line))
|
line = LinePreformattedText(text)
|
||||||
} else if strings.HasPrefix(line, "=>") {
|
} else if strings.HasPrefix(text, "=>") {
|
||||||
line = line[2:]
|
text = text[2:]
|
||||||
line = strings.TrimLeft(line, spacetab)
|
text = strings.TrimLeft(text, spacetab)
|
||||||
split := strings.IndexAny(line, spacetab)
|
split := strings.IndexAny(text, spacetab)
|
||||||
if split == -1 {
|
if split == -1 {
|
||||||
// line is a URL
|
// text is a URL
|
||||||
t = append(t, LineLink{URL: line})
|
line = LineLink{URL: text}
|
||||||
} else {
|
} else {
|
||||||
url := line[:split]
|
url := text[:split]
|
||||||
name := line[split:]
|
name := text[split:]
|
||||||
name = strings.TrimLeft(name, spacetab)
|
name = strings.TrimLeft(name, spacetab)
|
||||||
t = append(t, LineLink{url, name})
|
line = LineLink{url, name}
|
||||||
}
|
}
|
||||||
} else if strings.HasPrefix(line, "*") {
|
} else if strings.HasPrefix(text, "*") {
|
||||||
line = line[1:]
|
text = text[1:]
|
||||||
line = strings.TrimLeft(line, spacetab)
|
text = strings.TrimLeft(text, spacetab)
|
||||||
t = append(t, LineListItem(line))
|
line = LineListItem(text)
|
||||||
} else if strings.HasPrefix(line, "###") {
|
} else if strings.HasPrefix(text, "###") {
|
||||||
line = line[3:]
|
text = text[3:]
|
||||||
line = strings.TrimLeft(line, spacetab)
|
text = strings.TrimLeft(text, spacetab)
|
||||||
t = append(t, LineHeading3(line))
|
line = LineHeading3(text)
|
||||||
} else if strings.HasPrefix(line, "##") {
|
} else if strings.HasPrefix(text, "##") {
|
||||||
line = line[2:]
|
text = text[2:]
|
||||||
line = strings.TrimLeft(line, spacetab)
|
text = strings.TrimLeft(text, spacetab)
|
||||||
t = append(t, LineHeading2(line))
|
line = LineHeading2(text)
|
||||||
} else if strings.HasPrefix(line, "#") {
|
} else if strings.HasPrefix(text, "#") {
|
||||||
line = line[1:]
|
text = text[1:]
|
||||||
line = strings.TrimLeft(line, spacetab)
|
text = strings.TrimLeft(text, spacetab)
|
||||||
t = append(t, LineHeading1(line))
|
line = LineHeading1(text)
|
||||||
} else if strings.HasPrefix(line, ">") {
|
} else if strings.HasPrefix(text, ">") {
|
||||||
line = line[1:]
|
text = text[1:]
|
||||||
line = strings.TrimLeft(line, spacetab)
|
text = strings.TrimLeft(text, spacetab)
|
||||||
t = append(t, LineQuote(line))
|
line = LineQuote(text)
|
||||||
} else {
|
} 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.
|
// String writes the Gemini text response to a string and returns it.
|
||||||
|
|||||||
22
tofu.go
22
tofu.go
@@ -13,6 +13,15 @@ import (
|
|||||||
"time"
|
"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.
|
// KnownHosts represents a list of known hosts.
|
||||||
// The zero value for KnownHosts is an empty list ready to use.
|
// The zero value for KnownHosts is an empty list ready to use.
|
||||||
type KnownHosts struct {
|
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.
|
// Lookup looks for the provided certificate in the list of known hosts.
|
||||||
// If the hostname is in the list, but the fingerprint differs,
|
// If the hostname is not in the list, Lookup returns ErrCertificateNotFound.
|
||||||
// Lookup returns ErrCertificateNotTrusted.
|
// If the fingerprint doesn't match, Lookup returns ErrCertificateNotTrusted.
|
||||||
// If the hostname is not in the list, Lookup returns ErrCertificateUnknown.
|
// Otherwise, Lookup returns nil.
|
||||||
// If the certificate is found and the fingerprint matches, error will be nil.
|
|
||||||
func (k *KnownHosts) Lookup(hostname string, cert *x509.Certificate) error {
|
func (k *KnownHosts) Lookup(hostname string, cert *x509.Certificate) error {
|
||||||
now := time.Now().Unix()
|
now := time.Now().Unix()
|
||||||
fingerprint := Fingerprint(cert)
|
fingerprint := Fingerprint(cert)
|
||||||
if c, ok := k.hosts[hostname]; ok {
|
if c, ok := k.hosts[hostname]; ok {
|
||||||
if c.Expires <= now {
|
if c.Expires <= now {
|
||||||
// Certificate is expired
|
// Certificate is expired
|
||||||
return ErrCertificateUnknown
|
return ErrCertificateExpired
|
||||||
}
|
}
|
||||||
if c.Fingerprint != fingerprint {
|
if c.Fingerprint != fingerprint {
|
||||||
// Fingerprint does not match
|
// Fingerprint does not match
|
||||||
return ErrCertificateNotTrusted
|
return ErrCertificateNotTrusted
|
||||||
}
|
}
|
||||||
// Certificate is trusted
|
// Certificate is found
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
return ErrCertificateUnknown
|
return ErrCertificateNotFound
|
||||||
}
|
}
|
||||||
|
|
||||||
// Parse parses the provided reader and adds the parsed known hosts to the list.
|
// Parse parses the provided reader and adds the parsed known hosts to the list.
|
||||||
|
|||||||
Reference in New Issue
Block a user