Compare commits
297 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
21ad3a2ded | ||
|
|
2d7f28e152 | ||
|
|
1764e02d1e | ||
|
|
1bc5c68c3f | ||
|
|
867074d81b | ||
|
|
1da23ba07b | ||
|
|
cbfbeb6c22 | ||
|
|
c3418fdfed | ||
|
|
6181751e8d | ||
|
|
48c67bcead | ||
|
|
25f441f573 | ||
|
|
cb7879c966 | ||
|
|
19bfca1cc3 | ||
|
|
991b18d526 | ||
|
|
b66b287f94 | ||
|
|
bd29d76f66 | ||
|
|
1d20a6c3c8 | ||
|
|
6f46b2fa47 | ||
|
|
15385e3095 | ||
|
|
3101856afa | ||
|
|
094c16297b | ||
|
|
08f5ddd41a | ||
|
|
41c95add81 | ||
|
|
de339490f4 | ||
|
|
b488146cc6 | ||
|
|
069b473c28 | ||
|
|
2c2d74bcb2 | ||
|
|
3660698a4b | ||
|
|
526d232ab0 | ||
|
|
f08efa330f | ||
|
|
310bd16344 | ||
|
|
9eae88f00c | ||
|
|
b386a9ba41 | ||
|
|
f28a63ff0c | ||
|
|
d35dd3d867 | ||
|
|
75abb99518 | ||
|
|
e8d98ef4ec | ||
|
|
a65c3c3d4f | ||
|
|
64f9381bbc | ||
|
|
a34cf6dd1b | ||
|
|
b3e8d9ccf3 | ||
|
|
a7c449a3cf | ||
|
|
02bbedc330 | ||
|
|
5cf936d304 | ||
|
|
f1f933925c | ||
|
|
e1c04ee605 | ||
|
|
ae3fc2fc73 | ||
|
|
311233a012 | ||
|
|
c688defefd | ||
|
|
83c904913f | ||
|
|
833edaf63d | ||
|
|
d07e9d99d1 | ||
|
|
31e16d5a4c | ||
|
|
9974071657 | ||
|
|
09e3393e4c | ||
|
|
1aa85d0683 | ||
|
|
62e22b4cf2 | ||
|
|
eee7156b3a | ||
|
|
d8b5fa716a | ||
|
|
1080e95bb4 | ||
|
|
f722747abd | ||
|
|
4e25d2c3f9 | ||
|
|
5ab7617efd | ||
|
|
89f0b3f94b | ||
|
|
964c17b99f | ||
|
|
32f40523ed | ||
|
|
8190e819e8 | ||
|
|
871a8fe3d2 | ||
|
|
a4849c8eef | ||
|
|
f6bccb156a | ||
|
|
3c9c087a25 | ||
|
|
6de05c4b5d | ||
|
|
4c369072c8 | ||
|
|
27299f537d | ||
|
|
d61cf6318a | ||
|
|
99e6c37d92 | ||
|
|
31077afbbe | ||
|
|
3b8b5d6557 | ||
|
|
9aebcd362e | ||
|
|
35f7958083 | ||
|
|
c5b304216c | ||
|
|
118e019df0 | ||
|
|
2c64db3863 | ||
|
|
420f01da2a | ||
|
|
c3feafa90b | ||
|
|
0a3db2ce41 | ||
|
|
49dac34aff | ||
|
|
bb444fb364 | ||
|
|
a606c4fcc0 | ||
|
|
2ece48b019 | ||
|
|
a4b976c2dc | ||
|
|
b784442b6d | ||
|
|
57e541e103 | ||
|
|
c4c616518b | ||
|
|
352ad71af8 | ||
|
|
0722f4008a | ||
|
|
e3d48b2cad | ||
|
|
3fa55b52dd | ||
|
|
6c701ad9fe | ||
|
|
7084a226f4 | ||
|
|
f6505ae4c4 | ||
|
|
0c8c945eba | ||
|
|
7668345daa | ||
|
|
0baa66a4e7 | ||
|
|
d479c6391c | ||
|
|
423914d6e0 | ||
|
|
15f3e764c5 | ||
|
|
fadb2aed97 | ||
|
|
252fe678fd | ||
|
|
351fb92c7e | ||
|
|
2308c6407f | ||
|
|
8938038797 | ||
|
|
99a8f09c22 | ||
|
|
e9a68917c9 | ||
|
|
eca2afeb32 | ||
|
|
28b6232fbf | ||
|
|
3f4fd10b6d | ||
|
|
a7f958b20d | ||
|
|
0ab236c736 | ||
|
|
5922cff2e5 | ||
|
|
64dbb3eecb | ||
|
|
69674fcdd5 | ||
|
|
66e03ef1e4 | ||
|
|
76967dad2e | ||
|
|
2e149c9ccd | ||
|
|
229ebb4106 | ||
|
|
c70ef5c470 | ||
|
|
6928a1efef | ||
|
|
a80aae44a9 | ||
|
|
aab3ac4dfe | ||
|
|
a3a995df35 | ||
|
|
9ed2363b66 | ||
|
|
33a1fa4e0d | ||
|
|
7475687caa | ||
|
|
6edde376c4 | ||
|
|
f3cd70612b | ||
|
|
3d6ac90e08 | ||
|
|
b5a3c0adc5 | ||
|
|
f81c32a211 | ||
|
|
110c2de6de | ||
|
|
8543eca416 | ||
|
|
ec22e762c3 | ||
|
|
a3c1804395 | ||
|
|
fb9b50871c | ||
|
|
96dc161b4a | ||
|
|
246b252fd7 | ||
|
|
2e5569d5b5 | ||
|
|
8eccefb8c9 | ||
|
|
995769556c | ||
|
|
73bf1a31b0 | ||
|
|
fa7ec1ac87 | ||
|
|
e3d1fc2785 | ||
|
|
332dd253d0 | ||
|
|
d2001de5f3 | ||
|
|
cf995c86c9 | ||
|
|
dfa37aaeb8 | ||
|
|
7c1a5184c9 | ||
|
|
779be8b95b | ||
|
|
2157b35c0b | ||
|
|
1cb31e2d65 | ||
|
|
1d6cbddc5b | ||
|
|
a05fa6d6bd | ||
|
|
f158bb5f1d | ||
|
|
ec269c5c9d | ||
|
|
bf4959a8ba | ||
|
|
19678ef934 | ||
|
|
5a784693ef | ||
|
|
2c7f8273e9 | ||
|
|
96a84ddd38 | ||
|
|
3f2d540579 | ||
|
|
92e7a309c6 | ||
|
|
c5ccbf023a | ||
|
|
ff06e50df5 | ||
|
|
5ec8dea1ba | ||
|
|
46e10da3a8 | ||
|
|
41eec39a1d | ||
|
|
198a0b31c8 | ||
|
|
6f7c183662 | ||
|
|
20e1b14108 | ||
|
|
0c303588a4 | ||
|
|
37e5686764 | ||
|
|
7c703e95de | ||
|
|
595b0d0490 | ||
|
|
d2c70a33d5 | ||
|
|
79e0296bed | ||
|
|
f0e9150663 | ||
|
|
f4b80ef305 | ||
|
|
0e3b61ed00 | ||
|
|
f6824bd813 | ||
|
|
5ef5824d6f | ||
|
|
9bfb007581 | ||
|
|
7910ed433b | ||
|
|
29f2b3738d | ||
|
|
1f39cab063 | ||
|
|
62960266ac | ||
|
|
3efa17f6fb | ||
|
|
9e89b93bab | ||
|
|
31de8d49b0 | ||
|
|
2b17f3d8eb | ||
|
|
f36a1c5c87 | ||
|
|
af61c1b60a | ||
|
|
ad18ae601c | ||
|
|
8473f3b9d4 | ||
|
|
06c53cc5b1 | ||
|
|
4b643523fb | ||
|
|
79a4dfd43f | ||
|
|
14d89f304a | ||
|
|
7a00539f75 | ||
|
|
a0adc42c95 | ||
|
|
da8af5dbcb | ||
|
|
ced6b06d76 | ||
|
|
4a0f8e5e73 | ||
|
|
e701ceff71 | ||
|
|
1a3974b3a3 | ||
|
|
3fd55c5cee | ||
|
|
6f11910dff | ||
|
|
da3e9ac0fe | ||
|
|
9fe837ffac | ||
|
|
4b8bb16a3d | ||
|
|
95aff9c573 | ||
|
|
de042e4724 | ||
|
|
d78052ce08 | ||
|
|
1f2888c54a | ||
|
|
41d5f8d31b | ||
|
|
24026422b2 | ||
|
|
5e977250ec | ||
|
|
d8c5da1c7c | ||
|
|
d01d50ff1a | ||
|
|
3ed39e62d8 | ||
|
|
f2921a396f | ||
|
|
efef44c2f9 | ||
|
|
c8626bae17 | ||
|
|
48fa6a724e | ||
|
|
80ffa72863 | ||
|
|
61b417a5c4 | ||
|
|
a912ef996a | ||
|
|
d9a690a98f | ||
|
|
04bd0f4520 | ||
|
|
d34d5df89e | ||
|
|
decd72cc23 | ||
|
|
c329a2487e | ||
|
|
df1794c803 | ||
|
|
5af1acbd54 | ||
|
|
36c2086c82 | ||
|
|
d52d0af783 | ||
|
|
35836f2ff7 | ||
|
|
824887eab9 | ||
|
|
e2c907a7f6 | ||
|
|
a09cb5a23c | ||
|
|
7ca7053f66 | ||
|
|
ca35aadaea | ||
|
|
805a80dddf | ||
|
|
28c5c857dc | ||
|
|
176b260468 | ||
|
|
a1dd8de337 | ||
|
|
7be0715d39 | ||
|
|
4704b8fbcf | ||
|
|
aeafd57956 | ||
|
|
e687a05170 | ||
|
|
846fa2ac41 | ||
|
|
611a7d54c0 | ||
|
|
16739d20d0 | ||
|
|
24e488a4cb | ||
|
|
e0ac1685d2 | ||
|
|
82688746dd | ||
|
|
3b9cc7f168 | ||
|
|
3c7940f153 | ||
|
|
8ee55ee009 | ||
|
|
7ee0ea8b7f | ||
|
|
ab1db34f02 | ||
|
|
35e984fbba | ||
|
|
cab23032c0 | ||
|
|
4b653032e4 | ||
|
|
0c75e5d5ad | ||
|
|
f6b0443a62 | ||
|
|
3dee6dcff3 | ||
|
|
85f8e84bd5 | ||
|
|
9338681256 | ||
|
|
f2a1510375 | ||
|
|
46cbcfcaa4 | ||
|
|
76dfe257f1 | ||
|
|
5332dc6280 | ||
|
|
6b3cf1314b | ||
|
|
fe92db1e9c | ||
|
|
ff6c95930b | ||
|
|
a5712c7705 | ||
|
|
520d0a7fb1 | ||
|
|
bf185e4091 | ||
|
|
8101fbe473 | ||
|
|
b76080c863 | ||
|
|
53390dad6b | ||
|
|
cec1f118fb | ||
|
|
95716296b4 | ||
|
|
1490bf6a75 | ||
|
|
610c6fc533 | ||
|
|
01670647d2 | ||
|
|
5b3194695f |
9
.build.yml
Normal file
9
.build.yml
Normal file
@@ -0,0 +1,9 @@
|
|||||||
|
image: alpine/edge
|
||||||
|
packages:
|
||||||
|
- go
|
||||||
|
sources:
|
||||||
|
- https://git.sr.ht/~adnano/go-gemini
|
||||||
|
tasks:
|
||||||
|
- test: |
|
||||||
|
cd go-gemini
|
||||||
|
go test ./...
|
||||||
2
.gitignore
vendored
2
.gitignore
vendored
@@ -1,2 +0,0 @@
|
|||||||
*.crt
|
|
||||||
*.key
|
|
||||||
@@ -1,10 +1,12 @@
|
|||||||
# go-gemini
|
# go-gemini
|
||||||
|
|
||||||
[](https://godoc.org/git.sr.ht/~adnano/go-gemini)
|
[](https://godocs.io/git.sr.ht/~adnano/go-gemini) [](https://builds.sr.ht/~adnano/go-gemini?)
|
||||||
|
|
||||||
Package gemini implements the [Gemini protocol](https://gemini.circumlunar.space) in Go.
|
Package gemini implements the [Gemini protocol](https://gemini.circumlunar.space) in Go.
|
||||||
|
|
||||||
It aims to provide an API similar to that of net/http to make it easy to develop Gemini clients and servers.
|
It provides an API similar to that of net/http to make it easy to develop Gemini clients and servers.
|
||||||
|
|
||||||
|
Compatible with version v0.14.3 of the Gemini specification.
|
||||||
|
|
||||||
## Usage
|
## Usage
|
||||||
|
|
||||||
|
|||||||
179
cert.go
179
cert.go
@@ -1,179 +0,0 @@
|
|||||||
package gemini
|
|
||||||
|
|
||||||
import (
|
|
||||||
"crypto"
|
|
||||||
"crypto/ed25519"
|
|
||||||
"crypto/rand"
|
|
||||||
"crypto/tls"
|
|
||||||
"crypto/x509"
|
|
||||||
"encoding/pem"
|
|
||||||
"log"
|
|
||||||
"math/big"
|
|
||||||
"net"
|
|
||||||
"os"
|
|
||||||
"path/filepath"
|
|
||||||
"strings"
|
|
||||||
"time"
|
|
||||||
)
|
|
||||||
|
|
||||||
// CertificateStore maps certificate scopes to certificates.
|
|
||||||
// The zero value of CertificateStore is an empty store ready to use.
|
|
||||||
type CertificateStore struct {
|
|
||||||
store map[string]tls.Certificate
|
|
||||||
dir bool
|
|
||||||
path string
|
|
||||||
}
|
|
||||||
|
|
||||||
// Add adds a certificate for the given scope to the store.
|
|
||||||
// It tries to parse the certificate if it is not already parsed.
|
|
||||||
func (c *CertificateStore) Add(scope string, cert tls.Certificate) {
|
|
||||||
if c.store == nil {
|
|
||||||
c.store = map[string]tls.Certificate{}
|
|
||||||
}
|
|
||||||
// Parse certificate if not already parsed
|
|
||||||
if cert.Leaf == nil {
|
|
||||||
parsed, err := x509.ParseCertificate(cert.Certificate[0])
|
|
||||||
if err == nil {
|
|
||||||
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
|
|
||||||
}
|
|
||||||
|
|
||||||
// Lookup returns the certificate for the given scope.
|
|
||||||
func (c *CertificateStore) Lookup(scope string) (*tls.Certificate, error) {
|
|
||||||
cert, ok := c.store[scope]
|
|
||||||
if !ok {
|
|
||||||
return nil, ErrCertificateNotFound
|
|
||||||
}
|
|
||||||
// Ensure that the certificate is not expired
|
|
||||||
if cert.Leaf != nil && cert.Leaf.NotAfter.Before(time.Now()) {
|
|
||||||
return &cert, ErrCertificateExpired
|
|
||||||
}
|
|
||||||
return &cert, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// Load loads certificates from the given path.
|
|
||||||
// The path should lead to a directory containing certificates and private keys
|
|
||||||
// in the form scope.crt and scope.key.
|
|
||||||
// For example, the hostname "localhost" would have the corresponding files
|
|
||||||
// localhost.crt (certificate) and localhost.key (private key).
|
|
||||||
// New certificates will be written to this directory.
|
|
||||||
func (c *CertificateStore) Load(path string) error {
|
|
||||||
matches, err := filepath.Glob(filepath.Join(path, "*.crt"))
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
for _, crtPath := range matches {
|
|
||||||
keyPath := strings.TrimSuffix(crtPath, ".crt") + ".key"
|
|
||||||
cert, err := tls.LoadX509KeyPair(crtPath, keyPath)
|
|
||||||
if err != nil {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
scope := strings.TrimSuffix(filepath.Base(crtPath), ".crt")
|
|
||||||
c.Add(scope, cert)
|
|
||||||
}
|
|
||||||
c.dir = true
|
|
||||||
c.path = path
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// CertificateOptions configures how a certificate is created.
|
|
||||||
type CertificateOptions struct {
|
|
||||||
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 {
|
|
||||||
return tls.Certificate{}, err
|
|
||||||
}
|
|
||||||
var cert tls.Certificate
|
|
||||||
cert.Leaf = crt
|
|
||||||
cert.Certificate = append(cert.Certificate, crt.Raw)
|
|
||||||
cert.PrivateKey = priv
|
|
||||||
return cert, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// newX509KeyPair creates and returns a new certificate and private key.
|
|
||||||
func newX509KeyPair(options CertificateOptions) (*x509.Certificate, crypto.PrivateKey, error) {
|
|
||||||
// Generate an ED25519 private key
|
|
||||||
_, priv, err := ed25519.GenerateKey(rand.Reader)
|
|
||||||
if err != nil {
|
|
||||||
return nil, nil, err
|
|
||||||
}
|
|
||||||
public := priv.Public()
|
|
||||||
|
|
||||||
// ED25519 keys should have the DigitalSignature KeyUsage bits set
|
|
||||||
// in the x509.Certificate template
|
|
||||||
keyUsage := x509.KeyUsageDigitalSignature
|
|
||||||
|
|
||||||
serialNumberLimit := new(big.Int).Lsh(big.NewInt(1), 128)
|
|
||||||
serialNumber, err := rand.Int(rand.Reader, serialNumberLimit)
|
|
||||||
if err != nil {
|
|
||||||
return nil, nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
notBefore := time.Now()
|
|
||||||
notAfter := notBefore.Add(options.Duration)
|
|
||||||
|
|
||||||
template := x509.Certificate{
|
|
||||||
SerialNumber: serialNumber,
|
|
||||||
NotBefore: notBefore,
|
|
||||||
NotAfter: notAfter,
|
|
||||||
KeyUsage: keyUsage,
|
|
||||||
ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
|
|
||||||
BasicConstraintsValid: true,
|
|
||||||
IPAddresses: options.IPAddresses,
|
|
||||||
DNSNames: options.DNSNames,
|
|
||||||
}
|
|
||||||
|
|
||||||
crt, err := x509.CreateCertificate(rand.Reader, &template, &template, public, priv)
|
|
||||||
if err != nil {
|
|
||||||
return nil, nil, err
|
|
||||||
}
|
|
||||||
cert, err := x509.ParseCertificate(crt)
|
|
||||||
if err != nil {
|
|
||||||
return nil, nil, err
|
|
||||||
}
|
|
||||||
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})
|
|
||||||
}
|
|
||||||
142
certificate/create.go
Normal file
142
certificate/create.go
Normal file
@@ -0,0 +1,142 @@
|
|||||||
|
// Package certificate provides functions for creating and storing TLS certificates.
|
||||||
|
package certificate
|
||||||
|
|
||||||
|
import (
|
||||||
|
"crypto"
|
||||||
|
"crypto/ecdsa"
|
||||||
|
"crypto/ed25519"
|
||||||
|
"crypto/elliptic"
|
||||||
|
"crypto/rand"
|
||||||
|
"crypto/tls"
|
||||||
|
"crypto/x509"
|
||||||
|
"crypto/x509/pkix"
|
||||||
|
"encoding/pem"
|
||||||
|
"math/big"
|
||||||
|
"net"
|
||||||
|
"os"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
// CreateOptions configures the creation of a TLS certificate.
|
||||||
|
type CreateOptions struct {
|
||||||
|
// Subject Alternate Name values.
|
||||||
|
// Should contain the DNS names that this certificate is valid for.
|
||||||
|
// E.g. example.com, *.example.com
|
||||||
|
DNSNames []string
|
||||||
|
|
||||||
|
// Subject Alternate Name values.
|
||||||
|
// Should contain the IP addresses that the certificate is valid for.
|
||||||
|
IPAddresses []net.IP
|
||||||
|
|
||||||
|
// Subject specifies the certificate Subject.
|
||||||
|
//
|
||||||
|
// Subject.CommonName can contain the DNS name that this certificate
|
||||||
|
// is valid for. Server certificates should specify both a Subject
|
||||||
|
// and a Subject Alternate Name.
|
||||||
|
Subject pkix.Name
|
||||||
|
|
||||||
|
// Duration specifies the amount of time that the certificate is valid for.
|
||||||
|
Duration time.Duration
|
||||||
|
|
||||||
|
// Ed25519 specifies whether to generate an Ed25519 key pair.
|
||||||
|
// If false, an ECDSA key will be generated instead.
|
||||||
|
// Ed25519 is not as widely supported as ECDSA.
|
||||||
|
Ed25519 bool
|
||||||
|
}
|
||||||
|
|
||||||
|
// Create creates a new TLS certificate.
|
||||||
|
func Create(options CreateOptions) (tls.Certificate, error) {
|
||||||
|
crt, priv, err := newX509KeyPair(options)
|
||||||
|
if err != nil {
|
||||||
|
return tls.Certificate{}, err
|
||||||
|
}
|
||||||
|
var cert tls.Certificate
|
||||||
|
cert.Leaf = crt
|
||||||
|
cert.Certificate = append(cert.Certificate, crt.Raw)
|
||||||
|
cert.PrivateKey = priv
|
||||||
|
return cert, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// newX509KeyPair creates and returns a new certificate and private key.
|
||||||
|
func newX509KeyPair(options CreateOptions) (*x509.Certificate, crypto.PrivateKey, error) {
|
||||||
|
var pub crypto.PublicKey
|
||||||
|
var priv crypto.PrivateKey
|
||||||
|
if options.Ed25519 {
|
||||||
|
// Generate an Ed25519 private key
|
||||||
|
var err error
|
||||||
|
pub, priv, err = ed25519.GenerateKey(rand.Reader)
|
||||||
|
if err != nil {
|
||||||
|
return nil, nil, err
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
// Generate an ECDSA private key
|
||||||
|
private, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
|
||||||
|
if err != nil {
|
||||||
|
return nil, nil, err
|
||||||
|
}
|
||||||
|
priv = private
|
||||||
|
pub = &private.PublicKey
|
||||||
|
}
|
||||||
|
|
||||||
|
// ECDSA and Ed25519 keys should have the DigitalSignature KeyUsage bits
|
||||||
|
// set in the x509.Certificate template
|
||||||
|
keyUsage := x509.KeyUsageDigitalSignature
|
||||||
|
|
||||||
|
serialNumberLimit := new(big.Int).Lsh(big.NewInt(1), 128)
|
||||||
|
serialNumber, err := rand.Int(rand.Reader, serialNumberLimit)
|
||||||
|
if err != nil {
|
||||||
|
return nil, nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
notBefore := time.Now()
|
||||||
|
notAfter := notBefore.Add(options.Duration)
|
||||||
|
|
||||||
|
template := x509.Certificate{
|
||||||
|
SerialNumber: serialNumber,
|
||||||
|
NotBefore: notBefore,
|
||||||
|
NotAfter: notAfter,
|
||||||
|
KeyUsage: keyUsage,
|
||||||
|
ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
|
||||||
|
BasicConstraintsValid: true,
|
||||||
|
IPAddresses: options.IPAddresses,
|
||||||
|
DNSNames: options.DNSNames,
|
||||||
|
Subject: options.Subject,
|
||||||
|
}
|
||||||
|
|
||||||
|
crt, err := x509.CreateCertificate(rand.Reader, &template, &template, pub, priv)
|
||||||
|
if err != nil {
|
||||||
|
return nil, nil, err
|
||||||
|
}
|
||||||
|
cert, err := x509.ParseCertificate(crt)
|
||||||
|
if err != nil {
|
||||||
|
return nil, nil, err
|
||||||
|
}
|
||||||
|
return cert, priv, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Write writes the provided certificate and its private key
|
||||||
|
// to certPath and keyPath respectively.
|
||||||
|
func Write(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})
|
||||||
|
}
|
||||||
174
certificate/store.go
Normal file
174
certificate/store.go
Normal file
@@ -0,0 +1,174 @@
|
|||||||
|
package certificate
|
||||||
|
|
||||||
|
import (
|
||||||
|
"crypto/tls"
|
||||||
|
"crypto/x509"
|
||||||
|
"crypto/x509/pkix"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"path/filepath"
|
||||||
|
"strings"
|
||||||
|
"sync"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
// A Store represents a certificate store.
|
||||||
|
// It generates certificates as needed and automatically rotates expired certificates.
|
||||||
|
// The zero value for Store is an empty store ready to use.
|
||||||
|
//
|
||||||
|
// Certificate scopes must be registered with Register before calling Get or Load.
|
||||||
|
// This prevents the Store from creating or loading unnecessary certificates.
|
||||||
|
//
|
||||||
|
// Store is safe for concurrent use by multiple goroutines.
|
||||||
|
type Store struct {
|
||||||
|
// CreateCertificate, if not nil, is called to create a new certificate
|
||||||
|
// to replace a missing or expired certificate. If CreateCertificate
|
||||||
|
// is nil, a certificate with a duration of 1 year will be created.
|
||||||
|
// The provided scope is suitable for use in a certificate's DNSNames.
|
||||||
|
CreateCertificate func(scope string) (tls.Certificate, error)
|
||||||
|
|
||||||
|
certs map[string]tls.Certificate
|
||||||
|
path string
|
||||||
|
mu sync.RWMutex
|
||||||
|
}
|
||||||
|
|
||||||
|
// Register registers the provided scope with the certificate store.
|
||||||
|
// The scope can either be a hostname or a wildcard pattern (e.g. "*.example.com").
|
||||||
|
// To accept all hostnames, use the special pattern "*".
|
||||||
|
func (s *Store) Register(scope string) {
|
||||||
|
s.mu.Lock()
|
||||||
|
defer s.mu.Unlock()
|
||||||
|
if s.certs == nil {
|
||||||
|
s.certs = make(map[string]tls.Certificate)
|
||||||
|
}
|
||||||
|
s.certs[scope] = tls.Certificate{}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Add adds a certificate with the given scope to the certificate store.
|
||||||
|
// If a certificate for the given scope already exists, Add will overwrite it.
|
||||||
|
func (s *Store) Add(scope string, cert tls.Certificate) error {
|
||||||
|
s.mu.Lock()
|
||||||
|
defer s.mu.Unlock()
|
||||||
|
if s.certs == nil {
|
||||||
|
s.certs = make(map[string]tls.Certificate)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Parse certificate if not already parsed
|
||||||
|
if cert.Leaf == nil {
|
||||||
|
parsed, err := x509.ParseCertificate(cert.Certificate[0])
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
cert.Leaf = parsed
|
||||||
|
}
|
||||||
|
|
||||||
|
if s.path != "" {
|
||||||
|
certPath := filepath.Join(s.path, scope+".crt")
|
||||||
|
keyPath := filepath.Join(s.path, scope+".key")
|
||||||
|
if err := Write(cert, certPath, keyPath); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
s.certs[scope] = cert
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Get retrieves a certificate for the given hostname.
|
||||||
|
// If no matching scope has been registered, Get returns an error.
|
||||||
|
// Get generates new certificates as needed and rotates expired certificates.
|
||||||
|
//
|
||||||
|
// Get is suitable for use in a gemini.Server's GetCertificate field.
|
||||||
|
func (s *Store) Get(hostname string) (*tls.Certificate, error) {
|
||||||
|
s.mu.RLock()
|
||||||
|
defer s.mu.RUnlock()
|
||||||
|
cert, ok := s.certs[hostname]
|
||||||
|
if !ok {
|
||||||
|
// Try wildcard
|
||||||
|
wildcard := strings.SplitN(hostname, ".", 2)
|
||||||
|
if len(wildcard) == 2 {
|
||||||
|
hostname = "*." + wildcard[1]
|
||||||
|
cert, ok = s.certs[hostname]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if !ok {
|
||||||
|
// Try "*"
|
||||||
|
cert, ok = s.certs["*"]
|
||||||
|
}
|
||||||
|
if !ok {
|
||||||
|
return nil, errors.New("unrecognized scope")
|
||||||
|
}
|
||||||
|
|
||||||
|
// If the certificate is empty or expired, generate a new one.
|
||||||
|
if cert.Leaf == nil || cert.Leaf.NotAfter.Before(time.Now()) {
|
||||||
|
var err error
|
||||||
|
cert, err = s.createCertificate(hostname)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if err := s.Add(hostname, cert); err != nil {
|
||||||
|
return nil, fmt.Errorf("failed to add certificate for %s: %w", hostname, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return &cert, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Store) createCertificate(scope string) (tls.Certificate, error) {
|
||||||
|
if s.CreateCertificate != nil {
|
||||||
|
return s.CreateCertificate(scope)
|
||||||
|
}
|
||||||
|
return Create(CreateOptions{
|
||||||
|
DNSNames: []string{scope},
|
||||||
|
Subject: pkix.Name{
|
||||||
|
CommonName: scope,
|
||||||
|
},
|
||||||
|
Duration: 365 * 24 * time.Hour,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// Load loads certificates from the provided path.
|
||||||
|
// New certificates will be written to this path.
|
||||||
|
// The path should lead to a directory containing certificates
|
||||||
|
// and private keys named "scope.crt" and "scope.key" respectively,
|
||||||
|
// where "scope" is the scope of the certificate.
|
||||||
|
// Certificates with scopes that have not been registered will be ignored.
|
||||||
|
func (s *Store) Load(path string) error {
|
||||||
|
matches, err := filepath.Glob(filepath.Join(path, "*.crt"))
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
for _, crtPath := range matches {
|
||||||
|
scope := strings.TrimSuffix(filepath.Base(crtPath), ".crt")
|
||||||
|
if _, ok := s.certs[scope]; !ok {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
keyPath := strings.TrimSuffix(crtPath, ".crt") + ".key"
|
||||||
|
cert, err := tls.LoadX509KeyPair(crtPath, keyPath)
|
||||||
|
if err != nil {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
s.Add(scope, cert)
|
||||||
|
}
|
||||||
|
s.SetPath(path)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Entries returns a map of scopes to certificates.
|
||||||
|
func (s *Store) Entries() map[string]tls.Certificate {
|
||||||
|
s.mu.RLock()
|
||||||
|
defer s.mu.RUnlock()
|
||||||
|
certs := make(map[string]tls.Certificate)
|
||||||
|
for key := range s.certs {
|
||||||
|
certs[key] = s.certs[key]
|
||||||
|
}
|
||||||
|
return certs
|
||||||
|
}
|
||||||
|
|
||||||
|
// SetPath sets the path that new certificates will be written to.
|
||||||
|
func (s *Store) SetPath(path string) {
|
||||||
|
s.mu.Lock()
|
||||||
|
defer s.mu.Unlock()
|
||||||
|
s.path = path
|
||||||
|
}
|
||||||
361
client.go
361
client.go
@@ -1,234 +1,223 @@
|
|||||||
package gemini
|
package gemini
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"bufio"
|
"context"
|
||||||
"crypto/tls"
|
"crypto/tls"
|
||||||
"crypto/x509"
|
"crypto/x509"
|
||||||
"net"
|
"net"
|
||||||
"net/url"
|
"net/url"
|
||||||
"path"
|
|
||||||
"strings"
|
|
||||||
"time"
|
"time"
|
||||||
|
"unicode/utf8"
|
||||||
|
|
||||||
|
"golang.org/x/net/idna"
|
||||||
)
|
)
|
||||||
|
|
||||||
// Client is a Gemini client.
|
// A Client is a Gemini client. Its zero value is a usable client.
|
||||||
type Client struct {
|
type Client struct {
|
||||||
// KnownHosts is a list of known hosts.
|
// TrustCertificate is called to determine whether the client should
|
||||||
KnownHosts KnownHosts
|
// trust the certificate provided by the server.
|
||||||
|
// If TrustCertificate is nil or returns nil, the client will accept
|
||||||
// Certificates stores client-side certificates.
|
// any certificate. Otherwise, the certificate will not be trusted
|
||||||
Certificates CertificateStore
|
// and the request will be aborted.
|
||||||
|
|
||||||
// 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.
|
// See the tofu submodule for an implementation of trust on first use.
|
||||||
Timeout time.Duration
|
TrustCertificate func(hostname string, cert *x509.Certificate) error
|
||||||
|
|
||||||
// InsecureSkipTrust specifies whether the client should trust
|
// DialContext specifies the dial function for creating TCP connections.
|
||||||
// any certificate it receives without checking KnownHosts
|
// If DialContext is nil, the client dials using package net.
|
||||||
// or calling TrustCertificate.
|
DialContext func(ctx context.Context, network, addr string) (net.Conn, error)
|
||||||
// Use with caution.
|
|
||||||
InsecureSkipTrust bool
|
|
||||||
|
|
||||||
// GetInput is called to retrieve input when the server requests it.
|
|
||||||
// If GetInput is nil or returns false, no input will be sent and
|
|
||||||
// the response will be returned.
|
|
||||||
GetInput func(prompt string, sensitive bool) (input string, ok bool)
|
|
||||||
|
|
||||||
// CheckRedirect determines whether to follow a redirect.
|
|
||||||
// If CheckRedirect is nil, a default policy of no more than 5 consecutive
|
|
||||||
// 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 is called to determine whether the client
|
|
||||||
// should trust a certificate it has not seen before.
|
|
||||||
// If TrustCertificate is nil, the certificate will not be trusted
|
|
||||||
// and the connection will be aborted.
|
|
||||||
//
|
|
||||||
// If TrustCertificate returns TrustOnce, the certificate will be added
|
|
||||||
// to the client's list of known hosts.
|
|
||||||
// If TrustCertificate returns TrustAlways, the certificate will also be
|
|
||||||
// written to the known hosts file.
|
|
||||||
TrustCertificate func(hostname string, cert *x509.Certificate) Trust
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Get performs a Gemini request for the given url.
|
// Get sends a Gemini request for the given URL.
|
||||||
func (c *Client) Get(url string) (*Response, error) {
|
// The context controls the entire lifetime of a request and its response:
|
||||||
|
// obtaining a connection, sending the request, and reading the response
|
||||||
|
// header and body.
|
||||||
|
//
|
||||||
|
// An error is returned if there was a Gemini protocol error.
|
||||||
|
// A non-2x status code doesn't cause an error.
|
||||||
|
//
|
||||||
|
// If the returned error is nil, the user is expected to close the Response.
|
||||||
|
//
|
||||||
|
// For more control over requests, use NewRequest and Client.Do.
|
||||||
|
func (c *Client) Get(ctx context.Context, url string) (*Response, error) {
|
||||||
req, err := NewRequest(url)
|
req, err := NewRequest(url)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
return c.Do(req)
|
return c.Do(ctx, req)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Do performs a Gemini request and returns a Gemini response.
|
// Do sends a Gemini request and returns a Gemini response.
|
||||||
func (c *Client) Do(req *Request) (*Response, error) {
|
// The context controls the entire lifetime of a request and its response:
|
||||||
return c.do(req, nil)
|
// obtaining a connection, sending the request, and reading the response
|
||||||
}
|
// header and body.
|
||||||
|
//
|
||||||
func (c *Client) do(req *Request, via []*Request) (*Response, error) {
|
// An error is returned if there was a Gemini protocol error.
|
||||||
// Connect to the host
|
// A non-2x status code doesn't cause an error.
|
||||||
config := &tls.Config{
|
//
|
||||||
InsecureSkipVerify: true,
|
// If the returned error is nil, the user is expected to close the Response.
|
||||||
MinVersion: tls.VersionTLS12,
|
func (c *Client) Do(ctx context.Context, req *Request) (*Response, error) {
|
||||||
GetClientCertificate: func(_ *tls.CertificateRequestInfo) (*tls.Certificate, error) {
|
if ctx == nil {
|
||||||
return c.getClientCertificate(req)
|
panic("nil context")
|
||||||
},
|
|
||||||
VerifyConnection: func(cs tls.ConnectionState) error {
|
|
||||||
return c.verifyConnection(req, cs)
|
|
||||||
},
|
|
||||||
}
|
}
|
||||||
conn, err := tls.Dial("tcp", req.Host, config)
|
|
||||||
|
// Punycode request URL host
|
||||||
|
host, port := splitHostPort(req.URL.Host)
|
||||||
|
punycode, err := punycodeHostname(host)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
// Set connection deadline
|
if host != punycode {
|
||||||
if d := c.Timeout; d != 0 {
|
host = punycode
|
||||||
conn.SetDeadline(time.Now().Add(d))
|
|
||||||
|
// Copy the URL and update the host
|
||||||
|
u := new(url.URL)
|
||||||
|
*u = *req.URL
|
||||||
|
u.Host = net.JoinHostPort(host, port)
|
||||||
|
|
||||||
|
// Use the new URL in the request so that the server gets
|
||||||
|
// the punycoded hostname
|
||||||
|
r := new(Request)
|
||||||
|
*r = *req
|
||||||
|
r.URL = u
|
||||||
|
req = r
|
||||||
|
}
|
||||||
|
|
||||||
|
// Use request host if provided
|
||||||
|
if req.Host != "" {
|
||||||
|
host, port = splitHostPort(req.Host)
|
||||||
|
host, err = punycodeHostname(host)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
addr := net.JoinHostPort(host, port)
|
||||||
|
|
||||||
|
// Connect to the host
|
||||||
|
conn, err := c.dialContext(ctx, "tcp", addr)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// Setup TLS
|
||||||
|
conn = tls.Client(conn, &tls.Config{
|
||||||
|
InsecureSkipVerify: true,
|
||||||
|
MinVersion: tls.VersionTLS12,
|
||||||
|
GetClientCertificate: func(_ *tls.CertificateRequestInfo) (*tls.Certificate, error) {
|
||||||
|
if req.Certificate != nil {
|
||||||
|
return req.Certificate, nil
|
||||||
|
}
|
||||||
|
return &tls.Certificate{}, nil
|
||||||
|
},
|
||||||
|
VerifyConnection: func(cs tls.ConnectionState) error {
|
||||||
|
return c.verifyConnection(cs, host)
|
||||||
|
},
|
||||||
|
ServerName: host,
|
||||||
|
})
|
||||||
|
|
||||||
|
type result struct {
|
||||||
|
resp *Response
|
||||||
|
err error
|
||||||
|
}
|
||||||
|
|
||||||
|
res := make(chan result, 1)
|
||||||
|
go func() {
|
||||||
|
resp, err := c.do(ctx, conn, req)
|
||||||
|
res <- result{resp, err}
|
||||||
|
}()
|
||||||
|
|
||||||
|
select {
|
||||||
|
case <-ctx.Done():
|
||||||
|
conn.Close()
|
||||||
|
return nil, ctx.Err()
|
||||||
|
case r := <-res:
|
||||||
|
return r.resp, r.err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *Client) do(ctx context.Context, conn net.Conn, req *Request) (*Response, error) {
|
||||||
|
ctx, cancel := context.WithCancel(ctx)
|
||||||
|
done := ctx.Done()
|
||||||
|
w := &contextWriter{
|
||||||
|
ctx: ctx,
|
||||||
|
done: done,
|
||||||
|
cancel: cancel,
|
||||||
|
wc: conn,
|
||||||
|
}
|
||||||
|
rc := &contextReader{
|
||||||
|
ctx: ctx,
|
||||||
|
done: done,
|
||||||
|
cancel: cancel,
|
||||||
|
rc: conn,
|
||||||
}
|
}
|
||||||
|
|
||||||
// Write the request
|
// Write the request
|
||||||
w := bufio.NewWriter(conn)
|
if err := req.Write(w); err != nil {
|
||||||
req.write(w)
|
|
||||||
if err := w.Flush(); err != nil {
|
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
// Read the response
|
// Read the response
|
||||||
resp := &Response{}
|
resp, err := ReadResponse(rc)
|
||||||
if err := resp.read(conn); err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
// Store connection state
|
resp.conn = conn
|
||||||
resp.TLS = conn.ConnectionState()
|
|
||||||
|
|
||||||
switch {
|
|
||||||
case resp.Status == StatusCertificateRequired:
|
|
||||||
// Check to see if a certificate was already provided to prevent an infinite loop
|
|
||||||
if req.Certificate != nil {
|
|
||||||
return resp, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
hostname, path := req.URL.Hostname(), strings.TrimSuffix(req.URL.Path, "/")
|
|
||||||
if c.CreateCertificate != nil {
|
|
||||||
cert, err := c.CreateCertificate(hostname, path)
|
|
||||||
if err != nil {
|
|
||||||
return resp, err
|
|
||||||
}
|
|
||||||
c.Certificates.Add(hostname+path, cert)
|
|
||||||
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) {
|
func (c *Client) dialContext(ctx context.Context, network, addr string) (net.Conn, error) {
|
||||||
// Request certificates have the highest precedence
|
if c.DialContext != nil {
|
||||||
if req.Certificate != nil {
|
return c.DialContext(ctx, network, addr)
|
||||||
return req.Certificate, nil
|
|
||||||
}
|
}
|
||||||
|
return (&net.Dialer{}).DialContext(ctx, network, addr)
|
||||||
// Search recursively for the certificate
|
|
||||||
scope := req.URL.Hostname() + strings.TrimSuffix(req.URL.Path, "/")
|
|
||||||
for {
|
|
||||||
cert, err := c.Certificates.Lookup(scope)
|
|
||||||
if err == nil {
|
|
||||||
// Store the certificate
|
|
||||||
req.Certificate = cert
|
|
||||||
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 {
|
func (c *Client) verifyConnection(cs tls.ConnectionState, hostname string) 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]
|
cert := cs.PeerCertificates[0]
|
||||||
|
// Verify hostname
|
||||||
if err := verifyHostname(cert, hostname); err != nil {
|
if err := verifyHostname(cert, hostname); err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
if c.InsecureSkipTrust {
|
// Check expiration date
|
||||||
return nil
|
if !time.Now().Before(cert.NotAfter) {
|
||||||
|
return ErrCertificateExpired
|
||||||
}
|
}
|
||||||
// Check the known hosts
|
// See if the client trusts the certificate
|
||||||
err := c.KnownHosts.Lookup(hostname, cert)
|
if c.TrustCertificate != nil {
|
||||||
switch err {
|
return c.TrustCertificate(hostname, cert)
|
||||||
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 nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func splitHostPort(hostport string) (host, port string) {
|
||||||
|
var err error
|
||||||
|
host, port, err = net.SplitHostPort(hostport)
|
||||||
|
if err != nil {
|
||||||
|
// Likely no port
|
||||||
|
host = hostport
|
||||||
|
port = "1965"
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
func isASCII(s string) bool {
|
||||||
|
for i := 0; i < len(s); i++ {
|
||||||
|
if s[i] >= utf8.RuneSelf {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
// punycodeHostname returns the punycoded version of hostname.
|
||||||
|
func punycodeHostname(hostname string) (string, error) {
|
||||||
|
if net.ParseIP(hostname) != nil {
|
||||||
|
return hostname, nil
|
||||||
|
}
|
||||||
|
if isASCII(hostname) {
|
||||||
|
return hostname, nil
|
||||||
|
}
|
||||||
|
return idna.Lookup.ToASCII(hostname)
|
||||||
}
|
}
|
||||||
|
|||||||
42
doc.go
42
doc.go
@@ -1,53 +1,53 @@
|
|||||||
/*
|
/*
|
||||||
Package gemini implements the Gemini protocol.
|
Package gemini provides Gemini client and server implementations.
|
||||||
|
|
||||||
Get makes a Gemini request:
|
Client is a Gemini client.
|
||||||
|
|
||||||
resp, err := gemini.Get("gemini://example.com")
|
client := &gemini.Client{}
|
||||||
|
ctx := context.Background()
|
||||||
|
resp, err := client.Get(ctx, "gemini://example.com")
|
||||||
if err != nil {
|
if err != nil {
|
||||||
// handle error
|
// handle error
|
||||||
}
|
}
|
||||||
defer resp.Body.Close()
|
defer resp.Body.Close()
|
||||||
// ...
|
// ...
|
||||||
|
|
||||||
For control over client behavior, create a Client:
|
|
||||||
|
|
||||||
client := &gemini.Client{}
|
|
||||||
resp, err := client.Get("gemini://example.com")
|
|
||||||
if err != nil {
|
|
||||||
// handle error
|
|
||||||
}
|
|
||||||
// ...
|
|
||||||
|
|
||||||
Server is a Gemini server.
|
Server is a Gemini server.
|
||||||
|
|
||||||
server := &gemini.Server{
|
server := &gemini.Server{
|
||||||
ReadTimeout: 10 * time.Second,
|
ReadTimeout: 10 * time.Second,
|
||||||
WriteTimeout: 10 * time.Second,
|
WriteTimeout: 10 * time.Second,
|
||||||
}
|
}
|
||||||
|
|
||||||
Servers should be configured with certificates:
|
Servers should be configured with certificates:
|
||||||
|
|
||||||
err := server.Certificates.Load("/var/lib/gemini/certs")
|
certificates := &certificate.Store{}
|
||||||
|
certificates.Register("localhost")
|
||||||
|
err := certificates.Load("/var/lib/gemini/certs")
|
||||||
if err != nil {
|
if err != nil {
|
||||||
// handle error
|
// handle error
|
||||||
}
|
}
|
||||||
|
server.GetCertificate = certificates.Get
|
||||||
|
|
||||||
Servers can accept requests for multiple hosts and schemes:
|
ServeMux is a Gemini request multiplexer.
|
||||||
|
ServeMux can handle requests for multiple hosts and schemes.
|
||||||
|
|
||||||
server.RegisterFunc("example.com", func(w *gemini.ResponseWriter, r *gemini.Request) {
|
mux := &gemini.ServeMux{}
|
||||||
|
mux.HandleFunc("example.com", func(ctx context.Context, w gemini.ResponseWriter, r *gemini.Request) {
|
||||||
fmt.Fprint(w, "Welcome to example.com")
|
fmt.Fprint(w, "Welcome to example.com")
|
||||||
})
|
})
|
||||||
server.RegisterFunc("example.org", func(w *gemini.ResponseWriter, r *gemini.Request) {
|
mux.HandleFunc("example.org/about.gmi", func(ctx context.Context, w gemini.ResponseWriter, r *gemini.Request) {
|
||||||
fmt.Fprint(w, "Welcome to example.org")
|
fmt.Fprint(w, "About example.org")
|
||||||
})
|
})
|
||||||
server.RegisterFunc("http://example.net", func(w *gemini.ResponseWriter, r *gemini.Request) {
|
mux.HandleFunc("http://example.net", func(ctx context.Context, w gemini.ResponseWriter, r *gemini.Request) {
|
||||||
fmt.Fprint(w, "Proxied content from http://example.net")
|
fmt.Fprint(w, "Proxied content from http://example.net")
|
||||||
})
|
})
|
||||||
|
server.Handler = mux
|
||||||
|
|
||||||
To start the server, call ListenAndServe:
|
To start the server, call ListenAndServe:
|
||||||
|
|
||||||
err := server.ListenAndServe()
|
ctx := context.Background()
|
||||||
|
err := server.ListenAndServe(ctx)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
// handle error
|
// handle error
|
||||||
}
|
}
|
||||||
|
|||||||
168
examples/auth.go
168
examples/auth.go
@@ -3,150 +3,88 @@
|
|||||||
package main
|
package main
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"crypto/tls"
|
"context"
|
||||||
|
"crypto/sha512"
|
||||||
"crypto/x509"
|
"crypto/x509"
|
||||||
"fmt"
|
"fmt"
|
||||||
"log"
|
"log"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"git.sr.ht/~adnano/go-gemini"
|
"git.sr.ht/~adnano/go-gemini"
|
||||||
|
"git.sr.ht/~adnano/go-gemini/certificate"
|
||||||
)
|
)
|
||||||
|
|
||||||
type user struct {
|
type User struct {
|
||||||
password string // TODO: use hashes
|
Name string
|
||||||
admin bool
|
|
||||||
}
|
|
||||||
|
|
||||||
type session struct {
|
|
||||||
username string
|
|
||||||
authorized bool // whether or not the password was supplied
|
|
||||||
}
|
}
|
||||||
|
|
||||||
var (
|
var (
|
||||||
// Map of usernames to user data
|
// Map of certificate hashes to users
|
||||||
logins = map[string]user{
|
users = map[string]*User{}
|
||||||
"admin": {"p@ssw0rd", true}, // NOTE: These are bad passwords!
|
|
||||||
"user1": {"password1", false},
|
|
||||||
"user2": {"password2", false},
|
|
||||||
}
|
|
||||||
|
|
||||||
// Map of certificate fingerprints to sessions
|
|
||||||
sessions = map[string]*session{}
|
|
||||||
)
|
)
|
||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
var mux gemini.ServeMux
|
certificates := &certificate.Store{}
|
||||||
mux.HandleFunc("/", login)
|
certificates.Register("localhost")
|
||||||
mux.HandleFunc("/password", loginPassword)
|
if err := certificates.Load("/var/lib/gemini/certs"); err != nil {
|
||||||
mux.HandleFunc("/profile", profile)
|
|
||||||
mux.HandleFunc("/admin", admin)
|
|
||||||
mux.HandleFunc("/logout", logout)
|
|
||||||
|
|
||||||
var server gemini.Server
|
|
||||||
if err := server.Certificates.Load("/var/lib/gemini/certs"); err != nil {
|
|
||||||
log.Fatal(err)
|
log.Fatal(err)
|
||||||
}
|
}
|
||||||
server.CreateCertificate = func(hostname string) (tls.Certificate, error) {
|
|
||||||
return gemini.CreateCertificate(gemini.CertificateOptions{
|
|
||||||
DNSNames: []string{hostname},
|
|
||||||
Duration: time.Hour,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
server.Register("localhost", &mux)
|
|
||||||
|
|
||||||
if err := server.ListenAndServe(); err != nil {
|
mux := &gemini.ServeMux{}
|
||||||
|
mux.HandleFunc("/", profile)
|
||||||
|
mux.HandleFunc("/username", changeUsername)
|
||||||
|
|
||||||
|
server := &gemini.Server{
|
||||||
|
Handler: mux,
|
||||||
|
ReadTimeout: 30 * time.Second,
|
||||||
|
WriteTimeout: 1 * time.Minute,
|
||||||
|
GetCertificate: certificates.Get,
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := server.ListenAndServe(context.Background()); err != nil {
|
||||||
log.Fatal(err)
|
log.Fatal(err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func getSession(cert *x509.Certificate) (*session, bool) {
|
func fingerprint(cert *x509.Certificate) string {
|
||||||
fingerprint := gemini.Fingerprint(cert)
|
b := sha512.Sum512(cert.Raw)
|
||||||
session, ok := sessions[fingerprint]
|
return string(b[:])
|
||||||
return session, ok
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func login(w *gemini.ResponseWriter, r *gemini.Request) {
|
func profile(ctx context.Context, w gemini.ResponseWriter, r *gemini.Request) {
|
||||||
if r.Certificate == nil {
|
tls := r.TLS()
|
||||||
w.WriteStatus(gemini.StatusCertificateRequired)
|
if len(tls.PeerCertificates) == 0 {
|
||||||
|
w.WriteHeader(gemini.StatusCertificateRequired, "Certificate required")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
username, ok := gemini.Input(r)
|
fingerprint := fingerprint(tls.PeerCertificates[0])
|
||||||
|
user, ok := users[fingerprint]
|
||||||
if !ok {
|
if !ok {
|
||||||
|
user = &User{}
|
||||||
|
users[fingerprint] = user
|
||||||
|
}
|
||||||
|
fmt.Fprintln(w, "Username:", user.Name)
|
||||||
|
fmt.Fprintln(w, "=> /username Change username")
|
||||||
|
}
|
||||||
|
|
||||||
|
func changeUsername(ctx context.Context, w gemini.ResponseWriter, r *gemini.Request) {
|
||||||
|
tls := r.TLS()
|
||||||
|
if len(tls.PeerCertificates) == 0 {
|
||||||
|
w.WriteHeader(gemini.StatusCertificateRequired, "Certificate required")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
username, err := gemini.QueryUnescape(r.URL.RawQuery)
|
||||||
|
if err != nil || username == "" {
|
||||||
w.WriteHeader(gemini.StatusInput, "Username")
|
w.WriteHeader(gemini.StatusInput, "Username")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
fingerprint := gemini.Fingerprint(r.Certificate.Leaf)
|
fingerprint := fingerprint(tls.PeerCertificates[0])
|
||||||
sessions[fingerprint] = &session{
|
user, ok := users[fingerprint]
|
||||||
username: username,
|
|
||||||
}
|
|
||||||
w.WriteHeader(gemini.StatusRedirect, "/password")
|
|
||||||
}
|
|
||||||
|
|
||||||
func loginPassword(w *gemini.ResponseWriter, r *gemini.Request) {
|
|
||||||
if r.Certificate == nil {
|
|
||||||
w.WriteStatus(gemini.StatusCertificateRequired)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
session, ok := getSession(r.Certificate.Leaf)
|
|
||||||
if !ok {
|
if !ok {
|
||||||
w.WriteStatus(gemini.StatusCertificateNotAuthorized)
|
user = &User{}
|
||||||
return
|
users[fingerprint] = user
|
||||||
}
|
|
||||||
|
|
||||||
password, ok := gemini.Input(r)
|
|
||||||
if !ok {
|
|
||||||
w.WriteHeader(gemini.StatusSensitiveInput, "Password")
|
|
||||||
return
|
|
||||||
}
|
|
||||||
expected := logins[session.username].password
|
|
||||||
if password == expected {
|
|
||||||
session.authorized = true
|
|
||||||
w.WriteHeader(gemini.StatusRedirect, "/profile")
|
|
||||||
} else {
|
|
||||||
w.WriteHeader(gemini.StatusSensitiveInput, "Wrong password. Try again")
|
|
||||||
}
|
}
|
||||||
}
|
user.Name = username
|
||||||
|
w.WriteHeader(gemini.StatusRedirect, "/")
|
||||||
func logout(w *gemini.ResponseWriter, r *gemini.Request) {
|
|
||||||
if r.Certificate == nil {
|
|
||||||
w.WriteStatus(gemini.StatusCertificateRequired)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
fingerprint := gemini.Fingerprint(r.Certificate.Leaf)
|
|
||||||
delete(sessions, fingerprint)
|
|
||||||
fmt.Fprintln(w, "Successfully logged out.")
|
|
||||||
}
|
|
||||||
|
|
||||||
func profile(w *gemini.ResponseWriter, r *gemini.Request) {
|
|
||||||
if r.Certificate == nil {
|
|
||||||
w.WriteStatus(gemini.StatusCertificateRequired)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
session, ok := getSession(r.Certificate.Leaf)
|
|
||||||
if !ok {
|
|
||||||
w.WriteStatus(gemini.StatusCertificateNotAuthorized)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
user := logins[session.username]
|
|
||||||
fmt.Fprintln(w, "Username:", session.username)
|
|
||||||
fmt.Fprintln(w, "Admin:", user.admin)
|
|
||||||
fmt.Fprintln(w, "=> /logout Logout")
|
|
||||||
}
|
|
||||||
|
|
||||||
func admin(w *gemini.ResponseWriter, r *gemini.Request) {
|
|
||||||
if r.Certificate == nil {
|
|
||||||
w.WriteStatus(gemini.StatusCertificateRequired)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
session, ok := getSession(r.Certificate.Leaf)
|
|
||||||
if !ok {
|
|
||||||
w.WriteStatus(gemini.StatusCertificateNotAuthorized)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
user := logins[session.username]
|
|
||||||
if !user.admin {
|
|
||||||
w.WriteStatus(gemini.StatusCertificateNotAuthorized)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
fmt.Fprintln(w, "Welcome to the admin portal.")
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,14 +1,17 @@
|
|||||||
// +build ignore
|
// +build ignore
|
||||||
|
|
||||||
|
// This example illustrates a certificate generation tool.
|
||||||
|
|
||||||
package main
|
package main
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"crypto/x509/pkix"
|
||||||
"fmt"
|
"fmt"
|
||||||
"log"
|
"log"
|
||||||
"os"
|
"os"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"git.sr.ht/~adnano/go-gemini"
|
"git.sr.ht/~adnano/go-gemini/certificate"
|
||||||
)
|
)
|
||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
@@ -21,17 +24,20 @@ func main() {
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
log.Fatal(err)
|
log.Fatal(err)
|
||||||
}
|
}
|
||||||
options := gemini.CertificateOptions{
|
options := certificate.CreateOptions{
|
||||||
|
Subject: pkix.Name{
|
||||||
|
CommonName: host,
|
||||||
|
},
|
||||||
DNSNames: []string{host},
|
DNSNames: []string{host},
|
||||||
Duration: duration,
|
Duration: duration,
|
||||||
}
|
}
|
||||||
cert, err := gemini.CreateCertificate(options)
|
cert, err := certificate.Create(options)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Fatal(err)
|
log.Fatal(err)
|
||||||
}
|
}
|
||||||
certPath := host + ".crt"
|
certPath := host + ".crt"
|
||||||
keyPath := host + ".key"
|
keyPath := host + ".key"
|
||||||
if err := gemini.WriteCertificate(cert, certPath, keyPath); err != nil {
|
if err := certificate.Write(cert, certPath, keyPath); err != nil {
|
||||||
log.Fatal(err)
|
log.Fatal(err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,20 +1,56 @@
|
|||||||
// +build ignore
|
// +build ignore
|
||||||
|
|
||||||
|
// This example illustrates a Gemini client.
|
||||||
|
|
||||||
package main
|
package main
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"bufio"
|
"bufio"
|
||||||
"crypto/tls"
|
"bytes"
|
||||||
|
"context"
|
||||||
"crypto/x509"
|
"crypto/x509"
|
||||||
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
"io/ioutil"
|
"io"
|
||||||
"log"
|
"log"
|
||||||
|
"net/url"
|
||||||
"os"
|
"os"
|
||||||
|
"path/filepath"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"git.sr.ht/~adnano/go-gemini"
|
"git.sr.ht/~adnano/go-gemini"
|
||||||
|
"git.sr.ht/~adnano/go-gemini/tofu"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
var (
|
||||||
|
hosts tofu.KnownHosts
|
||||||
|
hostsfile *tofu.HostWriter
|
||||||
|
scanner *bufio.Scanner
|
||||||
|
)
|
||||||
|
|
||||||
|
func xdgDataHome() string {
|
||||||
|
if s, ok := os.LookupEnv("XDG_DATA_HOME"); ok {
|
||||||
|
return s
|
||||||
|
}
|
||||||
|
return filepath.Join(os.Getenv("HOME"), ".local", "share")
|
||||||
|
}
|
||||||
|
|
||||||
|
func init() {
|
||||||
|
// Load known hosts file
|
||||||
|
path := filepath.Join(xdgDataHome(), "gemini", "known_hosts")
|
||||||
|
err := hosts.Load(path)
|
||||||
|
if err != nil {
|
||||||
|
log.Fatal(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
hostsfile, err = tofu.OpenHostsFile(path)
|
||||||
|
if err != nil {
|
||||||
|
log.Fatal(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
scanner = bufio.NewScanner(os.Stdin)
|
||||||
|
}
|
||||||
|
|
||||||
const trustPrompt = `The certificate offered by %s is of unknown trust. Its fingerprint is:
|
const trustPrompt = `The certificate offered by %s is of unknown trust. Its fingerprint is:
|
||||||
%s
|
%s
|
||||||
|
|
||||||
@@ -24,48 +60,87 @@ Otherwise, this should be safe to trust.
|
|||||||
[t]rust always; trust [o]nce; [a]bort
|
[t]rust always; trust [o]nce; [a]bort
|
||||||
=> `
|
=> `
|
||||||
|
|
||||||
var (
|
func trustCertificate(hostname string, cert *x509.Certificate) error {
|
||||||
scanner = bufio.NewScanner(os.Stdin)
|
host := tofu.NewHost(hostname, cert.Raw, cert.NotAfter)
|
||||||
client = &gemini.Client{}
|
|
||||||
)
|
|
||||||
|
|
||||||
func init() {
|
knownHost, ok := hosts.Lookup(hostname)
|
||||||
client.Timeout = 30 * time.Second
|
if ok && time.Now().Before(knownHost.Expires) {
|
||||||
client.KnownHosts.LoadDefault()
|
// Check fingerprint
|
||||||
client.TrustCertificate = func(hostname string, cert *x509.Certificate) gemini.Trust {
|
if bytes.Equal(knownHost.Fingerprint, host.Fingerprint) {
|
||||||
fmt.Printf(trustPrompt, hostname, gemini.Fingerprint(cert))
|
return nil
|
||||||
scanner.Scan()
|
|
||||||
switch scanner.Text() {
|
|
||||||
case "t":
|
|
||||||
return gemini.TrustAlways
|
|
||||||
case "o":
|
|
||||||
return gemini.TrustOnce
|
|
||||||
default:
|
|
||||||
return gemini.TrustNone
|
|
||||||
}
|
}
|
||||||
|
return errors.New("error: fingerprint does not match!")
|
||||||
}
|
}
|
||||||
client.CreateCertificate = func(hostname, path string) (tls.Certificate, error) {
|
|
||||||
fmt.Println("Generating client certificate for", hostname, path)
|
fmt.Printf(trustPrompt, hostname, host.Fingerprint)
|
||||||
return gemini.CreateCertificate(gemini.CertificateOptions{
|
scanner.Scan()
|
||||||
Duration: time.Hour,
|
switch scanner.Text() {
|
||||||
})
|
case "t":
|
||||||
|
hosts.Add(host)
|
||||||
|
hostsfile.WriteHost(host)
|
||||||
|
return nil
|
||||||
|
case "o":
|
||||||
|
hosts.Add(host)
|
||||||
|
return nil
|
||||||
|
default:
|
||||||
|
return errors.New("certificate not trusted")
|
||||||
}
|
}
|
||||||
client.GetInput = func(prompt string, sensitive bool) (string, bool) {
|
}
|
||||||
fmt.Printf("%s: ", prompt)
|
|
||||||
scanner.Scan()
|
func getInput(prompt string, sensitive bool) (input string, ok bool) {
|
||||||
return scanner.Text(), true
|
fmt.Printf("%s ", prompt)
|
||||||
|
scanner.Scan()
|
||||||
|
return scanner.Text(), true
|
||||||
|
}
|
||||||
|
|
||||||
|
func do(req *gemini.Request, via []*gemini.Request) (*gemini.Response, error) {
|
||||||
|
client := gemini.Client{
|
||||||
|
TrustCertificate: trustCertificate,
|
||||||
}
|
}
|
||||||
|
ctx := context.Background()
|
||||||
|
resp, err := client.Do(ctx, req)
|
||||||
|
if err != nil {
|
||||||
|
return resp, err
|
||||||
|
}
|
||||||
|
|
||||||
|
switch resp.Status.Class() {
|
||||||
|
case gemini.StatusInput:
|
||||||
|
input, ok := getInput(resp.Meta, resp.Status == gemini.StatusSensitiveInput)
|
||||||
|
if !ok {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
req.URL.ForceQuery = true
|
||||||
|
req.URL.RawQuery = gemini.QueryEscape(input)
|
||||||
|
return do(req, via)
|
||||||
|
|
||||||
|
case gemini.StatusRedirect:
|
||||||
|
via = append(via, req)
|
||||||
|
if len(via) > 5 {
|
||||||
|
return resp, errors.New("too many redirects")
|
||||||
|
}
|
||||||
|
|
||||||
|
target, err := url.Parse(resp.Meta)
|
||||||
|
if err != nil {
|
||||||
|
return resp, err
|
||||||
|
}
|
||||||
|
target = req.URL.ResolveReference(target)
|
||||||
|
redirect := *req
|
||||||
|
redirect.URL = target
|
||||||
|
return do(&redirect, via)
|
||||||
|
}
|
||||||
|
|
||||||
|
return resp, err
|
||||||
}
|
}
|
||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
if len(os.Args) < 2 {
|
if len(os.Args) < 2 {
|
||||||
fmt.Printf("usage: %s gemini://... [host]", os.Args[0])
|
fmt.Printf("usage: %s <url> [host]\n", os.Args[0])
|
||||||
os.Exit(1)
|
os.Exit(1)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Do the request
|
||||||
url := os.Args[1]
|
url := os.Args[1]
|
||||||
req, err := gemini.NewRequest(url)
|
req, err := gemini.NewRequest(url)
|
||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
fmt.Println(err)
|
fmt.Println(err)
|
||||||
os.Exit(1)
|
os.Exit(1)
|
||||||
@@ -73,21 +148,21 @@ func main() {
|
|||||||
if len(os.Args) == 3 {
|
if len(os.Args) == 3 {
|
||||||
req.Host = os.Args[2]
|
req.Host = os.Args[2]
|
||||||
}
|
}
|
||||||
|
resp, err := do(req, nil)
|
||||||
resp, err := client.Do(req)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
fmt.Println(err)
|
fmt.Println(err)
|
||||||
os.Exit(1)
|
os.Exit(1)
|
||||||
}
|
}
|
||||||
defer resp.Body.Close()
|
defer resp.Body.Close()
|
||||||
|
|
||||||
if resp.Status.Class() == gemini.StatusClassSuccess {
|
// Handle response
|
||||||
body, err := ioutil.ReadAll(resp.Body)
|
if resp.Status.Class() == gemini.StatusSuccess {
|
||||||
|
_, err := io.Copy(os.Stdout, resp.Body)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Fatal(err)
|
log.Fatal(err)
|
||||||
}
|
}
|
||||||
fmt.Print(string(body))
|
|
||||||
} else {
|
} else {
|
||||||
fmt.Printf("request failed: %d %s: %s", resp.Status, resp.Status.Message(), resp.Meta)
|
fmt.Printf("%d %s\n", resp.Status, resp.Meta)
|
||||||
|
os.Exit(1)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
129
examples/html.go
129
examples/html.go
@@ -7,76 +7,77 @@ package main
|
|||||||
import (
|
import (
|
||||||
"fmt"
|
"fmt"
|
||||||
"html"
|
"html"
|
||||||
"strings"
|
"io"
|
||||||
|
"os"
|
||||||
|
|
||||||
"git.sr.ht/~adnano/go-gemini"
|
"git.sr.ht/~adnano/go-gemini"
|
||||||
)
|
)
|
||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
text := gemini.Text{
|
hw := HTMLWriter{
|
||||||
gemini.LineHeading1("Hello, world!"),
|
out: os.Stdout,
|
||||||
gemini.LineText("This is a gemini text document."),
|
|
||||||
}
|
}
|
||||||
|
gemini.ParseLines(os.Stdin, hw.Handle)
|
||||||
html := textToHTML(text)
|
hw.Finish()
|
||||||
fmt.Print(html)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// textToHTML returns the Gemini text response as HTML.
|
type HTMLWriter struct {
|
||||||
func textToHTML(text gemini.Text) string {
|
out io.Writer
|
||||||
var b strings.Builder
|
pre bool
|
||||||
var pre bool
|
list bool
|
||||||
var list bool
|
}
|
||||||
for _, l := range text {
|
|
||||||
if _, ok := l.(gemini.LineListItem); ok {
|
func (h *HTMLWriter) Handle(line gemini.Line) {
|
||||||
if !list {
|
if _, ok := line.(gemini.LineListItem); ok {
|
||||||
list = true
|
if !h.list {
|
||||||
fmt.Fprint(&b, "<ul>\n")
|
h.list = true
|
||||||
}
|
fmt.Fprint(h.out, "<ul>\n")
|
||||||
} else if list {
|
}
|
||||||
list = false
|
} else if h.list {
|
||||||
fmt.Fprint(&b, "</ul>\n")
|
h.list = false
|
||||||
}
|
fmt.Fprint(h.out, "</ul>\n")
|
||||||
switch l := l.(type) {
|
}
|
||||||
case gemini.LineLink:
|
switch line := line.(type) {
|
||||||
url := html.EscapeString(l.URL)
|
case gemini.LineLink:
|
||||||
name := html.EscapeString(l.Name)
|
url := html.EscapeString(line.URL)
|
||||||
if name == "" {
|
name := html.EscapeString(line.Name)
|
||||||
name = url
|
if name == "" {
|
||||||
}
|
name = url
|
||||||
fmt.Fprintf(&b, "<p><a href='%s'>%s</a></p>\n", url, name)
|
}
|
||||||
case gemini.LinePreformattingToggle:
|
fmt.Fprintf(h.out, "<p><a href='%s'>%s</a></p>\n", url, name)
|
||||||
pre = !pre
|
case gemini.LinePreformattingToggle:
|
||||||
if pre {
|
h.pre = !h.pre
|
||||||
fmt.Fprint(&b, "<pre>\n")
|
if h.pre {
|
||||||
} else {
|
fmt.Fprint(h.out, "<pre>\n")
|
||||||
fmt.Fprint(&b, "</pre>\n")
|
} else {
|
||||||
}
|
fmt.Fprint(h.out, "</pre>\n")
|
||||||
case gemini.LinePreformattedText:
|
}
|
||||||
fmt.Fprintf(&b, "%s\n", html.EscapeString(string(l)))
|
case gemini.LinePreformattedText:
|
||||||
case gemini.LineHeading1:
|
fmt.Fprintf(h.out, "%s\n", html.EscapeString(string(line)))
|
||||||
fmt.Fprintf(&b, "<h1>%s</h1>\n", html.EscapeString(string(l)))
|
case gemini.LineHeading1:
|
||||||
case gemini.LineHeading2:
|
fmt.Fprintf(h.out, "<h1>%s</h1>\n", html.EscapeString(string(line)))
|
||||||
fmt.Fprintf(&b, "<h2>%s</h2>\n", html.EscapeString(string(l)))
|
case gemini.LineHeading2:
|
||||||
case gemini.LineHeading3:
|
fmt.Fprintf(h.out, "<h2>%s</h2>\n", html.EscapeString(string(line)))
|
||||||
fmt.Fprintf(&b, "<h3>%s</h3>\n", html.EscapeString(string(l)))
|
case gemini.LineHeading3:
|
||||||
case gemini.LineListItem:
|
fmt.Fprintf(h.out, "<h3>%s</h3>\n", html.EscapeString(string(line)))
|
||||||
fmt.Fprintf(&b, "<li>%s</li>\n", html.EscapeString(string(l)))
|
case gemini.LineListItem:
|
||||||
case gemini.LineQuote:
|
fmt.Fprintf(h.out, "<li>%s</li>\n", html.EscapeString(string(line)))
|
||||||
fmt.Fprintf(&b, "<blockquote>%s</blockquote>\n", html.EscapeString(string(l)))
|
case gemini.LineQuote:
|
||||||
case gemini.LineText:
|
fmt.Fprintf(h.out, "<blockquote>%s</blockquote>\n", html.EscapeString(string(line)))
|
||||||
if l == "" {
|
case gemini.LineText:
|
||||||
fmt.Fprint(&b, "<br>\n")
|
if line == "" {
|
||||||
} else {
|
fmt.Fprint(h.out, "<br>\n")
|
||||||
fmt.Fprintf(&b, "<p>%s</p>\n", html.EscapeString(string(l)))
|
} else {
|
||||||
}
|
fmt.Fprintf(h.out, "<p>%s</p>\n", html.EscapeString(string(line)))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if pre {
|
}
|
||||||
fmt.Fprint(&b, "</pre>\n")
|
|
||||||
}
|
func (h *HTMLWriter) Finish() {
|
||||||
if list {
|
if h.pre {
|
||||||
fmt.Fprint(&b, "</ul>\n")
|
fmt.Fprint(h.out, "</pre>\n")
|
||||||
}
|
}
|
||||||
return b.String()
|
if h.list {
|
||||||
|
fmt.Fprint(h.out, "</ul>\n")
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,34 +1,104 @@
|
|||||||
// +build ignore
|
// +build ignore
|
||||||
|
|
||||||
|
// This example illustrates a Gemini server.
|
||||||
|
|
||||||
package main
|
package main
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"crypto/tls"
|
"context"
|
||||||
"log"
|
"log"
|
||||||
|
"os"
|
||||||
|
"os/signal"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"git.sr.ht/~adnano/go-gemini"
|
"git.sr.ht/~adnano/go-gemini"
|
||||||
|
"git.sr.ht/~adnano/go-gemini/certificate"
|
||||||
)
|
)
|
||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
var server gemini.Server
|
certificates := &certificate.Store{}
|
||||||
server.ReadTimeout = 30 * time.Second
|
certificates.Register("localhost")
|
||||||
server.WriteTimeout = 1 * time.Minute
|
if err := certificates.Load("/var/lib/gemini/certs"); err != nil {
|
||||||
if err := server.Certificates.Load("/var/lib/gemini/certs"); err != nil {
|
|
||||||
log.Fatal(err)
|
log.Fatal(err)
|
||||||
}
|
}
|
||||||
server.CreateCertificate = func(hostname string) (tls.Certificate, error) {
|
|
||||||
return gemini.CreateCertificate(gemini.CertificateOptions{
|
mux := &gemini.ServeMux{}
|
||||||
DNSNames: []string{hostname},
|
mux.Handle("/", gemini.FileServer(os.DirFS("/var/www")))
|
||||||
Duration: time.Minute, // for testing purposes
|
|
||||||
})
|
server := &gemini.Server{
|
||||||
|
Handler: logMiddleware(mux),
|
||||||
|
ReadTimeout: 30 * time.Second,
|
||||||
|
WriteTimeout: 1 * time.Minute,
|
||||||
|
GetCertificate: certificates.Get,
|
||||||
}
|
}
|
||||||
|
|
||||||
var mux gemini.ServeMux
|
// Listen for interrupt signal
|
||||||
mux.Handle("/", gemini.FileServer(gemini.Dir("/var/www")))
|
c := make(chan os.Signal, 1)
|
||||||
|
signal.Notify(c, os.Interrupt)
|
||||||
|
|
||||||
server.Register("localhost", &mux)
|
errch := make(chan error)
|
||||||
if err := server.ListenAndServe(); err != nil {
|
go func() {
|
||||||
|
ctx := context.Background()
|
||||||
|
errch <- server.ListenAndServe(ctx)
|
||||||
|
}()
|
||||||
|
|
||||||
|
select {
|
||||||
|
case err := <-errch:
|
||||||
log.Fatal(err)
|
log.Fatal(err)
|
||||||
|
case <-c:
|
||||||
|
// Shutdown the server
|
||||||
|
log.Println("Shutting down...")
|
||||||
|
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
|
||||||
|
defer cancel()
|
||||||
|
err := server.Shutdown(ctx)
|
||||||
|
if err != nil {
|
||||||
|
log.Fatal(err)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func logMiddleware(h gemini.Handler) gemini.Handler {
|
||||||
|
return gemini.HandlerFunc(func(ctx context.Context, w gemini.ResponseWriter, r *gemini.Request) {
|
||||||
|
lw := &logResponseWriter{rw: w}
|
||||||
|
h.ServeGemini(ctx, lw, r)
|
||||||
|
host := r.TLS().ServerName
|
||||||
|
log.Printf("gemini: %s %q %d %d", host, r.URL, lw.status, lw.wrote)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
type logResponseWriter struct {
|
||||||
|
rw gemini.ResponseWriter
|
||||||
|
status gemini.Status
|
||||||
|
meta string
|
||||||
|
mediatype string
|
||||||
|
wroteHeader bool
|
||||||
|
wrote int
|
||||||
|
}
|
||||||
|
|
||||||
|
func (w *logResponseWriter) SetMediaType(mediatype string) {
|
||||||
|
w.mediatype = mediatype
|
||||||
|
}
|
||||||
|
|
||||||
|
func (w *logResponseWriter) Write(b []byte) (int, error) {
|
||||||
|
if !w.wroteHeader {
|
||||||
|
w.WriteHeader(gemini.StatusSuccess, w.mediatype)
|
||||||
|
}
|
||||||
|
n, err := w.rw.Write(b)
|
||||||
|
w.wrote += n
|
||||||
|
return n, err
|
||||||
|
}
|
||||||
|
|
||||||
|
func (w *logResponseWriter) WriteHeader(status gemini.Status, meta string) {
|
||||||
|
if w.wroteHeader {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
w.status = status
|
||||||
|
w.meta = meta
|
||||||
|
w.wroteHeader = true
|
||||||
|
w.rw.WriteHeader(status, meta)
|
||||||
|
w.wrote += len(meta) + 5
|
||||||
|
}
|
||||||
|
|
||||||
|
func (w *logResponseWriter) Flush() error {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|||||||
54
examples/stream.go
Normal file
54
examples/stream.go
Normal file
@@ -0,0 +1,54 @@
|
|||||||
|
// +build ignore
|
||||||
|
|
||||||
|
// This example illustrates a streaming Gemini server.
|
||||||
|
|
||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"fmt"
|
||||||
|
"log"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"git.sr.ht/~adnano/go-gemini"
|
||||||
|
"git.sr.ht/~adnano/go-gemini/certificate"
|
||||||
|
)
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
certificates := &certificate.Store{}
|
||||||
|
certificates.Register("localhost")
|
||||||
|
if err := certificates.Load("/var/lib/gemini/certs"); err != nil {
|
||||||
|
log.Fatal(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
mux := &gemini.ServeMux{}
|
||||||
|
mux.HandleFunc("/", stream)
|
||||||
|
|
||||||
|
server := &gemini.Server{
|
||||||
|
Handler: mux,
|
||||||
|
ReadTimeout: 30 * time.Second,
|
||||||
|
WriteTimeout: 1 * time.Minute,
|
||||||
|
GetCertificate: certificates.Get,
|
||||||
|
}
|
||||||
|
|
||||||
|
ctx := context.Background()
|
||||||
|
if err := server.ListenAndServe(ctx); err != nil {
|
||||||
|
log.Fatal(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// stream writes an infinite stream to w.
|
||||||
|
func stream(ctx context.Context, w gemini.ResponseWriter, r *gemini.Request) {
|
||||||
|
for {
|
||||||
|
select {
|
||||||
|
case <-ctx.Done():
|
||||||
|
return
|
||||||
|
default:
|
||||||
|
}
|
||||||
|
fmt.Fprintln(w, time.Now().UTC())
|
||||||
|
if err := w.Flush(); err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
time.Sleep(time.Second)
|
||||||
|
}
|
||||||
|
}
|
||||||
264
fs.go
264
fs.go
@@ -1,105 +1,213 @@
|
|||||||
|
// +build go1.16
|
||||||
|
|
||||||
package gemini
|
package gemini
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
"io"
|
"io"
|
||||||
|
"io/fs"
|
||||||
"mime"
|
"mime"
|
||||||
"os"
|
"net/url"
|
||||||
"path"
|
"path"
|
||||||
|
"sort"
|
||||||
|
"strings"
|
||||||
)
|
)
|
||||||
|
|
||||||
func init() {
|
// FileServer returns a handler that serves Gemini requests with the contents
|
||||||
// Add Gemini mime types
|
// of the provided file system.
|
||||||
mime.AddExtensionType(".gmi", "text/gemini")
|
//
|
||||||
mime.AddExtensionType(".gemini", "text/gemini")
|
// To use the operating system's file system implementation, use os.DirFS:
|
||||||
|
//
|
||||||
|
// gemini.FileServer(os.DirFS("/tmp"))
|
||||||
|
func FileServer(fsys fs.FS) Handler {
|
||||||
|
return fileServer{fsys}
|
||||||
}
|
}
|
||||||
|
|
||||||
// FileServer takes a filesystem and returns a Responder which uses that filesystem.
|
type fileServer struct {
|
||||||
// The returned Responder sanitizes paths before handling them.
|
fs.FS
|
||||||
func FileServer(fsys FS) Responder {
|
|
||||||
return fsHandler{fsys}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
type fsHandler struct {
|
func (fs fileServer) ServeGemini(ctx context.Context, w ResponseWriter, r *Request) {
|
||||||
FS
|
serveFile(w, r, fs, path.Clean(r.URL.Path), true)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (fsh fsHandler) Respond(w *ResponseWriter, r *Request) {
|
// ServeContent replies to the request using the content in the
|
||||||
p := path.Clean(r.URL.Path)
|
// provided Reader. The main benefit of ServeContent over io.Copy
|
||||||
f, err := fsh.Open(p)
|
// is that it sets the MIME type of the response.
|
||||||
if err != nil {
|
//
|
||||||
w.WriteStatus(StatusNotFound)
|
// ServeContent tries to deduce the type from name's file extension.
|
||||||
return
|
// The name is otherwise unused; it is never sent in the response.
|
||||||
}
|
func ServeContent(w ResponseWriter, r *Request, name string, content io.Reader) {
|
||||||
// Detect mimetype
|
serveContent(w, name, content)
|
||||||
ext := path.Ext(p)
|
}
|
||||||
|
|
||||||
|
func serveContent(w ResponseWriter, name string, content io.Reader) {
|
||||||
|
// Detect mimetype from file extension
|
||||||
|
ext := path.Ext(name)
|
||||||
mimetype := mime.TypeByExtension(ext)
|
mimetype := mime.TypeByExtension(ext)
|
||||||
w.SetMimetype(mimetype)
|
w.SetMediaType(mimetype)
|
||||||
// Copy file to response writer
|
io.Copy(w, content)
|
||||||
io.Copy(w, f)
|
|
||||||
}
|
|
||||||
|
|
||||||
// TODO: replace with io/fs.FS when available
|
|
||||||
type FS interface {
|
|
||||||
Open(name string) (File, error)
|
|
||||||
}
|
|
||||||
|
|
||||||
// TODO: replace with io/fs.File when available
|
|
||||||
type File interface {
|
|
||||||
Stat() (os.FileInfo, error)
|
|
||||||
Read([]byte) (int, error)
|
|
||||||
Close() error
|
|
||||||
}
|
|
||||||
|
|
||||||
// Dir implements FS using the native filesystem restricted to a specific directory.
|
|
||||||
type Dir string
|
|
||||||
|
|
||||||
// Open tries to open the file with the given name.
|
|
||||||
// If the file is a directory, it tries to open the index file in that directory.
|
|
||||||
func (d Dir) Open(name string) (File, error) {
|
|
||||||
p := path.Join(string(d), name)
|
|
||||||
return openFile(p)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// ServeFile responds to the request with the contents of the named file
|
// ServeFile responds to the request with the contents of the named file
|
||||||
// or directory.
|
// or directory.
|
||||||
// TODO: Use io/fs.FS when available.
|
//
|
||||||
func ServeFile(w *ResponseWriter, fs FS, name string) {
|
// If the provided file or directory name is a relative path, it is interpreted
|
||||||
f, err := fs.Open(name)
|
// relative to the current directory and may ascend to parent directories. If
|
||||||
if err != nil {
|
// the provided name is constructed from user input, it should be sanitized
|
||||||
w.WriteStatus(StatusNotFound)
|
// before calling ServeFile.
|
||||||
|
//
|
||||||
|
// As a precaution, ServeFile will reject requests where r.URL.Path contains a
|
||||||
|
// ".." path element; this protects against callers who might unsafely use
|
||||||
|
// path.Join on r.URL.Path without sanitizing it and then use that
|
||||||
|
// path.Join result as the name argument.
|
||||||
|
//
|
||||||
|
// As another special case, ServeFile redirects any request where r.URL.Path
|
||||||
|
// ends in "/index.gmi" to the same path, without the final "index.gmi". To
|
||||||
|
// avoid such redirects either modify the path or use ServeContent.
|
||||||
|
//
|
||||||
|
// Outside of those two special cases, ServeFile does not use r.URL.Path for
|
||||||
|
// selecting the file or directory to serve; only the file or directory
|
||||||
|
// provided in the name argument is used.
|
||||||
|
func ServeFile(w ResponseWriter, r *Request, fsys fs.FS, name string) {
|
||||||
|
if containsDotDot(r.URL.Path) {
|
||||||
|
// Too many programs use r.URL.Path to construct the argument to
|
||||||
|
// serveFile. Reject the request under the assumption that happened
|
||||||
|
// here and ".." may not be wanted.
|
||||||
|
// Note that name might not contain "..", for example if code (still
|
||||||
|
// incorrectly) used path.Join(myDir, r.URL.Path).
|
||||||
|
w.WriteHeader(StatusBadRequest, "invalid URL path")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
// Detect mimetype
|
serveFile(w, r, fsys, name, false)
|
||||||
ext := path.Ext(name)
|
|
||||||
mimetype := mime.TypeByExtension(ext)
|
|
||||||
w.SetMimetype(mimetype)
|
|
||||||
// Copy file to response writer
|
|
||||||
io.Copy(w, f)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func openFile(p string) (File, error) {
|
func containsDotDot(v string) bool {
|
||||||
f, err := os.OpenFile(p, os.O_RDONLY, 0644)
|
if !strings.Contains(v, "..") {
|
||||||
if err != nil {
|
return false
|
||||||
return nil, err
|
|
||||||
}
|
}
|
||||||
|
for _, ent := range strings.FieldsFunc(v, isSlashRune) {
|
||||||
if stat, err := f.Stat(); err == nil {
|
if ent == ".." {
|
||||||
if stat.IsDir() {
|
return true
|
||||||
f, err := os.Open(path.Join(p, "index.gmi"))
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
stat, err := f.Stat()
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
if stat.Mode().IsRegular() {
|
|
||||||
return f, nil
|
|
||||||
}
|
|
||||||
return nil, ErrNotAFile
|
|
||||||
} else if !stat.Mode().IsRegular() {
|
|
||||||
return nil, ErrNotAFile
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return f, nil
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
func isSlashRune(r rune) bool { return r == '/' || r == '\\' }
|
||||||
|
|
||||||
|
func serveFile(w ResponseWriter, r *Request, fsys fs.FS, name string, redirect bool) {
|
||||||
|
const indexPage = "/index.gmi"
|
||||||
|
|
||||||
|
// Redirect .../index.gmi to .../
|
||||||
|
if strings.HasSuffix(r.URL.Path, indexPage) {
|
||||||
|
w.WriteHeader(StatusPermanentRedirect, "./")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if name == "/" {
|
||||||
|
name = "."
|
||||||
|
} else {
|
||||||
|
name = strings.Trim(name, "/")
|
||||||
|
}
|
||||||
|
|
||||||
|
f, err := fsys.Open(name)
|
||||||
|
if err != nil {
|
||||||
|
w.WriteHeader(toGeminiError(err))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
defer f.Close()
|
||||||
|
|
||||||
|
stat, err := f.Stat()
|
||||||
|
if err != nil {
|
||||||
|
w.WriteHeader(toGeminiError(err))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// Redirect to canonical path
|
||||||
|
if redirect {
|
||||||
|
url := r.URL.Path
|
||||||
|
if stat.IsDir() {
|
||||||
|
// Add trailing slash
|
||||||
|
if url[len(url)-1] != '/' {
|
||||||
|
w.WriteHeader(StatusPermanentRedirect, path.Base(url)+"/")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
// Remove trailing slash
|
||||||
|
if url[len(url)-1] == '/' {
|
||||||
|
w.WriteHeader(StatusPermanentRedirect, "../"+path.Base(url))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if stat.IsDir() {
|
||||||
|
// Redirect if the directory name doesn't end in a slash
|
||||||
|
url := r.URL.Path
|
||||||
|
if url[len(url)-1] != '/' {
|
||||||
|
w.WriteHeader(StatusRedirect, path.Base(url)+"/")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// Use contents of index.gmi if present
|
||||||
|
index, err := fsys.Open(path.Join(name, indexPage))
|
||||||
|
if err == nil {
|
||||||
|
defer index.Close()
|
||||||
|
istat, err := index.Stat()
|
||||||
|
if err == nil {
|
||||||
|
f = index
|
||||||
|
stat = istat
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if stat.IsDir() {
|
||||||
|
// Failed to find index file
|
||||||
|
dirList(w, f)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
serveContent(w, name, f)
|
||||||
|
}
|
||||||
|
|
||||||
|
func dirList(w ResponseWriter, f fs.File) {
|
||||||
|
var entries []fs.DirEntry
|
||||||
|
var err error
|
||||||
|
d, ok := f.(fs.ReadDirFile)
|
||||||
|
if ok {
|
||||||
|
entries, err = d.ReadDir(-1)
|
||||||
|
}
|
||||||
|
if !ok || err != nil {
|
||||||
|
w.WriteHeader(StatusTemporaryFailure, "Error reading directory")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
sort.Slice(entries, func(i, j int) bool {
|
||||||
|
return entries[i].Name() < entries[j].Name()
|
||||||
|
})
|
||||||
|
|
||||||
|
for _, entry := range entries {
|
||||||
|
name := entry.Name()
|
||||||
|
if entry.IsDir() {
|
||||||
|
name += "/"
|
||||||
|
}
|
||||||
|
link := LineLink{
|
||||||
|
Name: name,
|
||||||
|
URL: (&url.URL{Path: name}).EscapedPath(),
|
||||||
|
}
|
||||||
|
fmt.Fprintln(w, link.String())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func toGeminiError(err error) (status Status, meta string) {
|
||||||
|
if errors.Is(err, fs.ErrNotExist) {
|
||||||
|
return StatusNotFound, "Not found"
|
||||||
|
}
|
||||||
|
if errors.Is(err, fs.ErrPermission) {
|
||||||
|
return StatusNotFound, "Forbidden"
|
||||||
|
}
|
||||||
|
return StatusTemporaryFailure, "Internal server error"
|
||||||
}
|
}
|
||||||
|
|||||||
50
gemini.go
50
gemini.go
@@ -2,45 +2,25 @@ package gemini
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"errors"
|
"errors"
|
||||||
"sync"
|
"mime"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
func init() {
|
||||||
|
// Add Gemini mime types
|
||||||
|
mime.AddExtensionType(".gmi", "text/gemini")
|
||||||
|
mime.AddExtensionType(".gemini", "text/gemini")
|
||||||
|
}
|
||||||
|
|
||||||
var crlf = []byte("\r\n")
|
var crlf = []byte("\r\n")
|
||||||
|
|
||||||
// Errors.
|
// Errors.
|
||||||
var (
|
var (
|
||||||
ErrInvalidURL = errors.New("gemini: invalid URL")
|
ErrInvalidRequest = errors.New("gemini: invalid request")
|
||||||
ErrInvalidResponse = errors.New("gemini: invalid response")
|
ErrInvalidResponse = errors.New("gemini: invalid response")
|
||||||
ErrCertificateExpired = errors.New("gemini: certificate expired")
|
|
||||||
ErrCertificateNotFound = errors.New("gemini: certificate not found")
|
ErrCertificateExpired = errors.New("gemini: certificate expired")
|
||||||
ErrCertificateNotTrusted = errors.New("gemini: certificate not trusted")
|
|
||||||
ErrCertificateRequired = errors.New("gemini: certificate required")
|
// ErrBodyNotAllowed is returned by ResponseWriter.Write calls
|
||||||
ErrNotAFile = errors.New("gemini: not a file")
|
// when the response status code does not permit a body.
|
||||||
ErrNotAGeminiURL = errors.New("gemini: not a Gemini URL")
|
ErrBodyNotAllowed = errors.New("gemini: response status code does not allow 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")
|
|
||||||
)
|
)
|
||||||
|
|
||||||
// defaultClient is the default client. It is used by Get and Do.
|
|
||||||
var defaultClient Client
|
|
||||||
|
|
||||||
// Get performs a Gemini request for the given url.
|
|
||||||
func Get(url string) (*Response, error) {
|
|
||||||
setupDefaultClientOnce()
|
|
||||||
return defaultClient.Get(url)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Do performs a Gemini request and returns a Gemini response.
|
|
||||||
func Do(req *Request) (*Response, error) {
|
|
||||||
setupDefaultClientOnce()
|
|
||||||
return defaultClient.Do(req)
|
|
||||||
}
|
|
||||||
|
|
||||||
var defaultClientOnce sync.Once
|
|
||||||
|
|
||||||
func setupDefaultClientOnce() {
|
|
||||||
defaultClientOnce.Do(func() {
|
|
||||||
defaultClient.KnownHosts.LoadDefault()
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|||||||
2
go.mod
2
go.mod
@@ -1,3 +1,5 @@
|
|||||||
module git.sr.ht/~adnano/go-gemini
|
module git.sr.ht/~adnano/go-gemini
|
||||||
|
|
||||||
go 1.15
|
go 1.15
|
||||||
|
|
||||||
|
require golang.org/x/net v0.0.0-20210119194325-5f4716e94777
|
||||||
|
|||||||
7
go.sum
Normal file
7
go.sum
Normal file
@@ -0,0 +1,7 @@
|
|||||||
|
golang.org/x/net v0.0.0-20210119194325-5f4716e94777 h1:003p0dJM77cxMSyCPFphvZf/Y5/NXf5fzg6ufd1/Oew=
|
||||||
|
golang.org/x/net v0.0.0-20210119194325-5f4716e94777/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg=
|
||||||
|
golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||||
|
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
|
||||||
|
golang.org/x/text v0.3.3 h1:cokOdA+Jmi5PJGXLlLllQSgYigAEfHXJAERHVMaCc2k=
|
||||||
|
golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
|
||||||
|
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
|
||||||
155
handler.go
Normal file
155
handler.go
Normal file
@@ -0,0 +1,155 @@
|
|||||||
|
package gemini
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"context"
|
||||||
|
"io"
|
||||||
|
"net/url"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
// A Handler responds to a Gemini request.
|
||||||
|
//
|
||||||
|
// ServeGemini should write the response header and data to the ResponseWriter
|
||||||
|
// and then return. Returning signals that the request is finished; it is not
|
||||||
|
// valid to use the ResponseWriter after or concurrently with the completion
|
||||||
|
// of the ServeGemini call.
|
||||||
|
//
|
||||||
|
// The provided context is canceled when the client's connection is closed
|
||||||
|
// or the ServeGemini method returns.
|
||||||
|
//
|
||||||
|
// Handlers should not modify the provided Request.
|
||||||
|
type Handler interface {
|
||||||
|
ServeGemini(context.Context, ResponseWriter, *Request)
|
||||||
|
}
|
||||||
|
|
||||||
|
// The HandlerFunc type is an adapter to allow the use of ordinary functions
|
||||||
|
// as Gemini handlers. If f is a function with the appropriate signature,
|
||||||
|
// HandlerFunc(f) is a Handler that calls f.
|
||||||
|
type HandlerFunc func(context.Context, ResponseWriter, *Request)
|
||||||
|
|
||||||
|
// ServeGemini calls f(ctx, w, r).
|
||||||
|
func (f HandlerFunc) ServeGemini(ctx context.Context, w ResponseWriter, r *Request) {
|
||||||
|
f(ctx, w, r)
|
||||||
|
}
|
||||||
|
|
||||||
|
// StatusHandler returns a request handler that responds to each request
|
||||||
|
// with the provided status code and meta.
|
||||||
|
func StatusHandler(status Status, meta string) Handler {
|
||||||
|
return HandlerFunc(func(ctx context.Context, w ResponseWriter, r *Request) {
|
||||||
|
w.WriteHeader(status, meta)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// NotFoundHandler returns a simple request handler that replies to each
|
||||||
|
// request with a “51 Not found” reply.
|
||||||
|
func NotFoundHandler() Handler {
|
||||||
|
return StatusHandler(StatusNotFound, "Not found")
|
||||||
|
}
|
||||||
|
|
||||||
|
// StripPrefix returns a handler that serves Gemini requests by removing the
|
||||||
|
// given prefix from the request URL's Path (and RawPath if set) and invoking
|
||||||
|
// the handler h. StripPrefix handles a request for a path that doesn't begin
|
||||||
|
// with prefix by replying with a Gemini 51 not found error. The prefix must
|
||||||
|
// match exactly: if the prefix in the request contains escaped characters the
|
||||||
|
// reply is also a Gemini 51 not found error.
|
||||||
|
func StripPrefix(prefix string, h Handler) Handler {
|
||||||
|
if prefix == "" {
|
||||||
|
return h
|
||||||
|
}
|
||||||
|
return HandlerFunc(func(ctx context.Context, w ResponseWriter, r *Request) {
|
||||||
|
p := strings.TrimPrefix(r.URL.Path, prefix)
|
||||||
|
rp := strings.TrimPrefix(r.URL.RawPath, prefix)
|
||||||
|
if len(p) < len(r.URL.Path) && (r.URL.RawPath == "" || len(rp) < len(r.URL.RawPath)) {
|
||||||
|
r2 := new(Request)
|
||||||
|
*r2 = *r
|
||||||
|
r2.URL = new(url.URL)
|
||||||
|
*r2.URL = *r.URL
|
||||||
|
r2.URL.Path = p
|
||||||
|
r2.URL.RawPath = rp
|
||||||
|
h.ServeGemini(ctx, w, r2)
|
||||||
|
} else {
|
||||||
|
w.WriteHeader(StatusNotFound, "Not found")
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// TimeoutHandler returns a Handler that runs h with the given time limit.
|
||||||
|
//
|
||||||
|
// The new Handler calls h.ServeGemini to handle each request, but
|
||||||
|
// if a call runs for longer than its time limit, the handler responds with a
|
||||||
|
// 40 Temporary Failure error. After such a timeout, writes by h to
|
||||||
|
// its ResponseWriter will return context.DeadlineExceeded.
|
||||||
|
func TimeoutHandler(h Handler, dt time.Duration) Handler {
|
||||||
|
return &timeoutHandler{
|
||||||
|
h: h,
|
||||||
|
dt: dt,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
type timeoutHandler struct {
|
||||||
|
h Handler
|
||||||
|
dt time.Duration
|
||||||
|
}
|
||||||
|
|
||||||
|
func (t *timeoutHandler) ServeGemini(ctx context.Context, w ResponseWriter, r *Request) {
|
||||||
|
ctx, cancel := context.WithTimeout(ctx, t.dt)
|
||||||
|
defer cancel()
|
||||||
|
|
||||||
|
buf := &bytes.Buffer{}
|
||||||
|
tw := &timeoutWriter{
|
||||||
|
wr: &contextWriter{
|
||||||
|
ctx: ctx,
|
||||||
|
cancel: cancel,
|
||||||
|
done: ctx.Done(),
|
||||||
|
wc: nopCloser{buf},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
done := make(chan struct{})
|
||||||
|
go func() {
|
||||||
|
t.h.ServeGemini(ctx, tw, r)
|
||||||
|
close(done)
|
||||||
|
}()
|
||||||
|
|
||||||
|
select {
|
||||||
|
case <-done:
|
||||||
|
w.WriteHeader(tw.status, tw.meta)
|
||||||
|
w.Write(buf.Bytes())
|
||||||
|
case <-ctx.Done():
|
||||||
|
w.WriteHeader(StatusTemporaryFailure, "Timeout")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
type timeoutWriter struct {
|
||||||
|
wr io.Writer
|
||||||
|
status Status
|
||||||
|
meta string
|
||||||
|
mediatype string
|
||||||
|
wroteHeader bool
|
||||||
|
}
|
||||||
|
|
||||||
|
func (w *timeoutWriter) SetMediaType(mediatype string) {
|
||||||
|
w.mediatype = mediatype
|
||||||
|
}
|
||||||
|
|
||||||
|
func (w *timeoutWriter) Write(b []byte) (int, error) {
|
||||||
|
if !w.wroteHeader {
|
||||||
|
w.WriteHeader(StatusSuccess, w.mediatype)
|
||||||
|
}
|
||||||
|
return w.wr.Write(b)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (w *timeoutWriter) WriteHeader(status Status, meta string) {
|
||||||
|
if w.wroteHeader {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
w.status = status
|
||||||
|
w.meta = meta
|
||||||
|
w.wroteHeader = true
|
||||||
|
}
|
||||||
|
|
||||||
|
func (w *timeoutWriter) Flush() error {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
104
io.go
Normal file
104
io.go
Normal file
@@ -0,0 +1,104 @@
|
|||||||
|
package gemini
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bufio"
|
||||||
|
"context"
|
||||||
|
"io"
|
||||||
|
)
|
||||||
|
|
||||||
|
type contextReader struct {
|
||||||
|
ctx context.Context
|
||||||
|
done <-chan struct{}
|
||||||
|
cancel func()
|
||||||
|
rc io.ReadCloser
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *contextReader) Read(p []byte) (int, error) {
|
||||||
|
select {
|
||||||
|
case <-r.done:
|
||||||
|
r.rc.Close()
|
||||||
|
return 0, r.ctx.Err()
|
||||||
|
default:
|
||||||
|
}
|
||||||
|
n, err := r.rc.Read(p)
|
||||||
|
if err != nil {
|
||||||
|
r.cancel()
|
||||||
|
}
|
||||||
|
return n, err
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *contextReader) Close() error {
|
||||||
|
r.cancel()
|
||||||
|
return r.rc.Close()
|
||||||
|
}
|
||||||
|
|
||||||
|
type contextWriter struct {
|
||||||
|
ctx context.Context
|
||||||
|
done <-chan struct{}
|
||||||
|
cancel func()
|
||||||
|
wc io.WriteCloser
|
||||||
|
}
|
||||||
|
|
||||||
|
func (w *contextWriter) Write(b []byte) (int, error) {
|
||||||
|
select {
|
||||||
|
case <-w.done:
|
||||||
|
w.wc.Close()
|
||||||
|
return 0, w.ctx.Err()
|
||||||
|
default:
|
||||||
|
}
|
||||||
|
n, err := w.wc.Write(b)
|
||||||
|
if err != nil {
|
||||||
|
w.cancel()
|
||||||
|
}
|
||||||
|
return n, err
|
||||||
|
}
|
||||||
|
|
||||||
|
func (w *contextWriter) Close() error {
|
||||||
|
w.cancel()
|
||||||
|
return w.wc.Close()
|
||||||
|
}
|
||||||
|
|
||||||
|
type nopCloser struct {
|
||||||
|
io.Writer
|
||||||
|
}
|
||||||
|
|
||||||
|
func (nopCloser) Close() error {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
type nopReadCloser struct{}
|
||||||
|
|
||||||
|
func (nopReadCloser) Read(p []byte) (int, error) {
|
||||||
|
return 0, io.EOF
|
||||||
|
}
|
||||||
|
|
||||||
|
func (nopReadCloser) Close() error {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
type bufReadCloser struct {
|
||||||
|
br *bufio.Reader // used until empty
|
||||||
|
io.ReadCloser
|
||||||
|
}
|
||||||
|
|
||||||
|
func newBufReadCloser(br *bufio.Reader, rc io.ReadCloser) io.ReadCloser {
|
||||||
|
body := &bufReadCloser{ReadCloser: rc}
|
||||||
|
if br.Buffered() != 0 {
|
||||||
|
body.br = br
|
||||||
|
}
|
||||||
|
return body
|
||||||
|
}
|
||||||
|
|
||||||
|
func (b *bufReadCloser) 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)
|
||||||
|
}
|
||||||
207
mux.go
207
mux.go
@@ -1,6 +1,8 @@
|
|||||||
package gemini
|
package gemini
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"context"
|
||||||
|
"net"
|
||||||
"net/url"
|
"net/url"
|
||||||
"path"
|
"path"
|
||||||
"sort"
|
"sort"
|
||||||
@@ -8,12 +10,6 @@ import (
|
|||||||
"sync"
|
"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.
|
// ServeMux is a Gemini request multiplexer.
|
||||||
// It matches the URL of each incoming request against a list of registered
|
// It matches the URL of each incoming request against a list of registered
|
||||||
// patterns and calls the handler for the pattern that
|
// patterns and calls the handler for the pattern that
|
||||||
@@ -32,6 +28,32 @@ import (
|
|||||||
// the pattern "/" matches all paths not matched by other registered
|
// the pattern "/" matches all paths not matched by other registered
|
||||||
// patterns, not just the URL with Path == "/".
|
// patterns, not just the URL with Path == "/".
|
||||||
//
|
//
|
||||||
|
// Patterns may also contain schemes and hostnames.
|
||||||
|
// Wildcard patterns can be used to match multiple hostnames (e.g. "*.example.com").
|
||||||
|
//
|
||||||
|
// The following are examples of valid patterns, along with the scheme,
|
||||||
|
// hostname, and path that they match.
|
||||||
|
//
|
||||||
|
// Pattern │ Scheme │ Hostname │ Path
|
||||||
|
// ─────────────────────────────┼────────┼──────────┼─────────────
|
||||||
|
// /file │ gemini │ * │ /file
|
||||||
|
// /directory/ │ gemini │ * │ /directory/*
|
||||||
|
// hostname/file │ gemini │ hostname │ /file
|
||||||
|
// hostname/directory/ │ gemini │ hostname │ /directory/*
|
||||||
|
// scheme://hostname/file │ scheme │ hostname │ /file
|
||||||
|
// scheme://hostname/directory/ │ scheme │ hostname │ /directory/*
|
||||||
|
// //hostname/file │ * │ hostname │ /file
|
||||||
|
// //hostname/directory/ │ * │ hostname │ /directory/*
|
||||||
|
// scheme:///file │ scheme │ * │ /file
|
||||||
|
// scheme:///directory/ │ scheme │ * │ /directory/*
|
||||||
|
// ///file │ * │ * │ /file
|
||||||
|
// ///directory/ │ * │ * │ /directory/*
|
||||||
|
//
|
||||||
|
// A pattern without a hostname will match any hostname.
|
||||||
|
// If a pattern begins with "//", it will match any scheme.
|
||||||
|
// Otherwise, a pattern with no scheme is treated as though it has a
|
||||||
|
// scheme of "gemini".
|
||||||
|
//
|
||||||
// If a subtree has been registered and a request is received naming the
|
// If a subtree has been registered and a request is received naming the
|
||||||
// subtree root without its trailing slash, ServeMux redirects that
|
// subtree root without its trailing slash, ServeMux redirects that
|
||||||
// request to the subtree root (adding the trailing slash). This behavior can
|
// request to the subtree root (adding the trailing slash). This behavior can
|
||||||
@@ -45,13 +67,19 @@ import (
|
|||||||
// to an equivalent, cleaner URL.
|
// to an equivalent, cleaner URL.
|
||||||
type ServeMux struct {
|
type ServeMux struct {
|
||||||
mu sync.RWMutex
|
mu sync.RWMutex
|
||||||
m map[string]muxEntry
|
m map[muxKey]Handler
|
||||||
es []muxEntry // slice of entries sorted from longest to shortest.
|
es []muxEntry // slice of entries sorted from longest to shortest
|
||||||
|
}
|
||||||
|
|
||||||
|
type muxKey struct {
|
||||||
|
scheme string
|
||||||
|
host string
|
||||||
|
path string
|
||||||
}
|
}
|
||||||
|
|
||||||
type muxEntry struct {
|
type muxEntry struct {
|
||||||
r Responder
|
handler Handler
|
||||||
pattern string
|
key muxKey
|
||||||
}
|
}
|
||||||
|
|
||||||
// cleanPath returns the canonical path for p, eliminating . and .. elements.
|
// cleanPath returns the canonical path for p, eliminating . and .. elements.
|
||||||
@@ -78,18 +106,25 @@ func cleanPath(p string) string {
|
|||||||
|
|
||||||
// Find a handler on a handler map given a path string.
|
// Find a handler on a handler map given a path string.
|
||||||
// Most-specific (longest) pattern wins.
|
// Most-specific (longest) pattern wins.
|
||||||
func (mux *ServeMux) match(path string) Responder {
|
func (mux *ServeMux) match(key muxKey) Handler {
|
||||||
// Check for exact match first.
|
// Check for exact match first.
|
||||||
v, ok := mux.m[path]
|
if r, ok := mux.m[key]; ok {
|
||||||
if ok {
|
return r
|
||||||
return v.r
|
} else if r, ok := mux.m[muxKey{"", key.host, key.path}]; ok {
|
||||||
|
return r
|
||||||
|
} else if r, ok := mux.m[muxKey{key.scheme, "", key.path}]; ok {
|
||||||
|
return r
|
||||||
|
} else if r, ok := mux.m[muxKey{"", "", key.path}]; ok {
|
||||||
|
return r
|
||||||
}
|
}
|
||||||
|
|
||||||
// Check for longest valid match. mux.es contains all patterns
|
// Check for longest valid match. mux.es contains all patterns
|
||||||
// that end in / sorted from longest to shortest.
|
// that end in / sorted from longest to shortest.
|
||||||
for _, e := range mux.es {
|
for _, e := range mux.es {
|
||||||
if strings.HasPrefix(path, e.pattern) {
|
if (e.key.scheme == "" || key.scheme == e.key.scheme) &&
|
||||||
return e.r
|
(e.key.host == "" || key.host == e.key.host) &&
|
||||||
|
strings.HasPrefix(key.path, e.key.path) {
|
||||||
|
return e.handler
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return nil
|
return nil
|
||||||
@@ -99,89 +134,144 @@ func (mux *ServeMux) match(path string) Responder {
|
|||||||
// This occurs when a handler for path + "/" was already registered, but
|
// 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
|
// 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.
|
// 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) {
|
func (mux *ServeMux) redirectToPathSlash(key muxKey, u *url.URL) (*url.URL, bool) {
|
||||||
mux.mu.RLock()
|
mux.mu.RLock()
|
||||||
shouldRedirect := mux.shouldRedirectRLocked(path)
|
shouldRedirect := mux.shouldRedirectRLocked(key)
|
||||||
mux.mu.RUnlock()
|
mux.mu.RUnlock()
|
||||||
if !shouldRedirect {
|
if !shouldRedirect {
|
||||||
return u, false
|
return u, false
|
||||||
}
|
}
|
||||||
path = path + "/"
|
return u.ResolveReference(&url.URL{Path: key.path + "/"}), true
|
||||||
u = &url.URL{Path: path, RawQuery: u.RawQuery}
|
|
||||||
return u, true
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// shouldRedirectRLocked reports whether the given path and host should be redirected to
|
// shouldRedirectRLocked reports whether the given path and host should be redirected to
|
||||||
// path+"/". This should happen if a handler is registered for path+"/" but
|
// path+"/". This should happen if a handler is registered for path+"/" but
|
||||||
// not path -- see comments at ServeMux.
|
// not path -- see comments at ServeMux.
|
||||||
func (mux *ServeMux) shouldRedirectRLocked(path string) bool {
|
func (mux *ServeMux) shouldRedirectRLocked(key muxKey) bool {
|
||||||
if _, exist := mux.m[path]; exist {
|
if _, exist := mux.m[key]; exist {
|
||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
|
|
||||||
n := len(path)
|
n := len(key.path)
|
||||||
if n == 0 {
|
if n == 0 {
|
||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
if _, exist := mux.m[path+"/"]; exist {
|
if _, exist := mux.m[muxKey{key.scheme, key.host, key.path + "/"}]; exist {
|
||||||
return path[n-1] != '/'
|
return key.path[n-1] != '/'
|
||||||
}
|
}
|
||||||
|
|
||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
|
|
||||||
// Respond dispatches the request to the responder whose
|
func getWildcard(hostname string) (string, bool) {
|
||||||
// pattern most closely matches the request URL.
|
if net.ParseIP(hostname) == nil {
|
||||||
func (mux *ServeMux) Respond(w *ResponseWriter, r *Request) {
|
split := strings.SplitN(hostname, ".", 2)
|
||||||
|
if len(split) == 2 {
|
||||||
|
return "*." + split[1], true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return "", false
|
||||||
|
}
|
||||||
|
|
||||||
|
// Handler returns the handler to use for the given request, consulting
|
||||||
|
// r.URL.Scheme, r.URL.Host, and r.URL.Path. It always returns a non-nil handler. If
|
||||||
|
// the path is not in its canonical form, the handler will be an
|
||||||
|
// internally-generated handler that redirects to the canonical path. If the
|
||||||
|
// host contains a port, it is ignored when matching handlers.
|
||||||
|
func (mux *ServeMux) Handler(r *Request) Handler {
|
||||||
|
scheme := r.URL.Scheme
|
||||||
|
host := r.URL.Hostname()
|
||||||
path := cleanPath(r.URL.Path)
|
path := cleanPath(r.URL.Path)
|
||||||
|
|
||||||
// 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(muxKey{scheme, host, path}, r.URL); ok {
|
||||||
w.WriteHeader(StatusRedirect, u.String())
|
return StatusHandler(StatusPermanentRedirect, u.String())
|
||||||
return
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if path != r.URL.Path {
|
if path != r.URL.Path {
|
||||||
u := *r.URL
|
u := *r.URL
|
||||||
u.Path = path
|
u.Path = path
|
||||||
w.WriteHeader(StatusRedirect, u.String())
|
return StatusHandler(StatusPermanentRedirect, u.String())
|
||||||
return
|
|
||||||
}
|
}
|
||||||
|
|
||||||
mux.mu.RLock()
|
mux.mu.RLock()
|
||||||
defer mux.mu.RUnlock()
|
defer mux.mu.RUnlock()
|
||||||
|
|
||||||
resp := mux.match(path)
|
h := mux.match(muxKey{scheme, host, path})
|
||||||
if resp == nil {
|
if h == nil {
|
||||||
w.WriteStatus(StatusNotFound)
|
// Try wildcard
|
||||||
return
|
if wildcard, ok := getWildcard(host); ok {
|
||||||
|
h = mux.match(muxKey{scheme, wildcard, path})
|
||||||
|
}
|
||||||
}
|
}
|
||||||
resp.Respond(w, r)
|
if h == nil {
|
||||||
|
h = NotFoundHandler()
|
||||||
|
}
|
||||||
|
return h
|
||||||
}
|
}
|
||||||
|
|
||||||
// Handle registers the responder for the given pattern.
|
// ServeGemini dispatches the request to the handler whose
|
||||||
// If a responder already exists for pattern, Handle panics.
|
// pattern most closely matches the request URL.
|
||||||
func (mux *ServeMux) Handle(pattern string, responder Responder) {
|
func (mux *ServeMux) ServeGemini(ctx context.Context, w ResponseWriter, r *Request) {
|
||||||
mux.mu.Lock()
|
h := mux.Handler(r)
|
||||||
defer mux.mu.Unlock()
|
h.ServeGemini(ctx, w, r)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Handle registers the handler for the given pattern.
|
||||||
|
// If a handler already exists for pattern, Handle panics.
|
||||||
|
func (mux *ServeMux) Handle(pattern string, handler Handler) {
|
||||||
if pattern == "" {
|
if pattern == "" {
|
||||||
panic("gemini: invalid pattern")
|
panic("gemini: invalid pattern")
|
||||||
}
|
}
|
||||||
if responder == nil {
|
if handler == nil {
|
||||||
panic("gemini: nil responder")
|
panic("gemini: nil handler")
|
||||||
}
|
}
|
||||||
if _, exist := mux.m[pattern]; exist {
|
|
||||||
|
mux.mu.Lock()
|
||||||
|
defer mux.mu.Unlock()
|
||||||
|
|
||||||
|
var key muxKey
|
||||||
|
if strings.HasPrefix(pattern, "//") {
|
||||||
|
// match any scheme
|
||||||
|
key.scheme = ""
|
||||||
|
pattern = pattern[2:]
|
||||||
|
} else {
|
||||||
|
// extract scheme
|
||||||
|
cut := strings.Index(pattern, "://")
|
||||||
|
if cut == -1 {
|
||||||
|
// default scheme of gemini
|
||||||
|
key.scheme = "gemini"
|
||||||
|
} else {
|
||||||
|
key.scheme = pattern[:cut]
|
||||||
|
pattern = pattern[cut+3:]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// extract hostname and path
|
||||||
|
cut := strings.Index(pattern, "/")
|
||||||
|
if cut == -1 {
|
||||||
|
key.host = pattern
|
||||||
|
key.path = "/"
|
||||||
|
} else {
|
||||||
|
key.host = pattern[:cut]
|
||||||
|
key.path = pattern[cut:]
|
||||||
|
}
|
||||||
|
|
||||||
|
// strip port from hostname
|
||||||
|
if hostname, _, err := net.SplitHostPort(key.host); err == nil {
|
||||||
|
key.host = hostname
|
||||||
|
}
|
||||||
|
|
||||||
|
if _, exist := mux.m[key]; exist {
|
||||||
panic("gemini: multiple registrations for " + pattern)
|
panic("gemini: multiple registrations for " + pattern)
|
||||||
}
|
}
|
||||||
|
|
||||||
if mux.m == nil {
|
if mux.m == nil {
|
||||||
mux.m = make(map[string]muxEntry)
|
mux.m = make(map[muxKey]Handler)
|
||||||
}
|
}
|
||||||
e := muxEntry{responder, pattern}
|
mux.m[key] = handler
|
||||||
mux.m[pattern] = e
|
e := muxEntry{handler, key}
|
||||||
if pattern[len(pattern)-1] == '/' {
|
if key.path[len(key.path)-1] == '/' {
|
||||||
mux.es = appendSorted(mux.es, e)
|
mux.es = appendSorted(mux.es, e)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -189,7 +279,9 @@ func (mux *ServeMux) Handle(pattern string, responder Responder) {
|
|||||||
func appendSorted(es []muxEntry, e muxEntry) []muxEntry {
|
func appendSorted(es []muxEntry, e muxEntry) []muxEntry {
|
||||||
n := len(es)
|
n := len(es)
|
||||||
i := sort.Search(n, func(i int) bool {
|
i := sort.Search(n, func(i int) bool {
|
||||||
return len(es[i].pattern) < len(e.pattern)
|
return len(es[i].key.scheme) < len(e.key.scheme) ||
|
||||||
|
len(es[i].key.host) < len(es[i].key.host) ||
|
||||||
|
len(es[i].key.path) < len(e.key.path)
|
||||||
})
|
})
|
||||||
if i == n {
|
if i == n {
|
||||||
return append(es, e)
|
return append(es, e)
|
||||||
@@ -201,10 +293,7 @@ func appendSorted(es []muxEntry, e muxEntry) []muxEntry {
|
|||||||
return es
|
return es
|
||||||
}
|
}
|
||||||
|
|
||||||
// HandleFunc registers the responder function for the given pattern.
|
// HandleFunc registers the handler function for the given pattern.
|
||||||
func (mux *ServeMux) HandleFunc(pattern string, responder func(*ResponseWriter, *Request)) {
|
func (mux *ServeMux) HandleFunc(pattern string, handler HandlerFunc) {
|
||||||
if responder == nil {
|
mux.Handle(pattern, handler)
|
||||||
panic("gemini: nil responder")
|
|
||||||
}
|
|
||||||
mux.Handle(pattern, ResponderFunc(responder))
|
|
||||||
}
|
}
|
||||||
|
|||||||
315
mux_test.go
Normal file
315
mux_test.go
Normal file
@@ -0,0 +1,315 @@
|
|||||||
|
package gemini
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"net/url"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
type nopHandler struct{}
|
||||||
|
|
||||||
|
func (*nopHandler) ServeGemini(context.Context, ResponseWriter, *Request) {}
|
||||||
|
|
||||||
|
func TestServeMuxMatch(t *testing.T) {
|
||||||
|
type Match struct {
|
||||||
|
URL string
|
||||||
|
Ok bool
|
||||||
|
}
|
||||||
|
|
||||||
|
tests := []struct {
|
||||||
|
Pattern string
|
||||||
|
Matches []Match
|
||||||
|
}{
|
||||||
|
{
|
||||||
|
// scheme: gemini, hostname: *, path: /*
|
||||||
|
Pattern: "/",
|
||||||
|
Matches: []Match{
|
||||||
|
{"gemini://example.com/path", true},
|
||||||
|
{"gemini://example.com/", true},
|
||||||
|
{"gemini://example.com/path.gmi", true},
|
||||||
|
{"gemini://example.com/path/", true},
|
||||||
|
{"gemini://example.org/path", true},
|
||||||
|
{"http://example.com/path", false},
|
||||||
|
{"http://example.org/path", false},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
// scheme: gemini, hostname: *, path: /path
|
||||||
|
Pattern: "/path",
|
||||||
|
Matches: []Match{
|
||||||
|
{"gemini://example.com/path", true},
|
||||||
|
{"gemini://example.com/", false},
|
||||||
|
{"gemini://example.com/path.gmi", false},
|
||||||
|
{"gemini://example.com/path/", false},
|
||||||
|
{"gemini://example.org/path", true},
|
||||||
|
{"http://example.com/path", false},
|
||||||
|
{"http://example.org/path", false},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
// scheme: gemini, hostname: *, path: /subtree/*
|
||||||
|
Pattern: "/subtree/",
|
||||||
|
Matches: []Match{
|
||||||
|
{"gemini://example.com/subtree/", true},
|
||||||
|
{"gemini://example.com/subtree/nested/", true},
|
||||||
|
{"gemini://example.com/subtree/nested/file", true},
|
||||||
|
{"gemini://example.org/subtree/", true},
|
||||||
|
{"gemini://example.org/subtree/nested/", true},
|
||||||
|
{"gemini://example.org/subtree/nested/file", true},
|
||||||
|
{"gemini://example.com/subtree", false},
|
||||||
|
{"gemini://www.example.com/subtree/", true},
|
||||||
|
{"http://example.com/subtree/", false},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
// scheme: gemini, hostname: example.com, path: /*
|
||||||
|
Pattern: "example.com",
|
||||||
|
Matches: []Match{
|
||||||
|
{"gemini://example.com/path", true},
|
||||||
|
{"gemini://example.com/", true},
|
||||||
|
{"gemini://example.com/path.gmi", true},
|
||||||
|
{"gemini://example.com/path/", true},
|
||||||
|
{"gemini://example.org/path", false},
|
||||||
|
{"http://example.com/path", false},
|
||||||
|
{"http://example.org/path", false},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
// scheme: gemini, hostname: example.com, path: /path
|
||||||
|
Pattern: "example.com/path",
|
||||||
|
Matches: []Match{
|
||||||
|
{"gemini://example.com/path", true},
|
||||||
|
{"gemini://example.com/", false},
|
||||||
|
{"gemini://example.com/path.gmi", false},
|
||||||
|
{"gemini://example.com/path/", false},
|
||||||
|
{"gemini://example.org/path", false},
|
||||||
|
{"http://example.com/path", false},
|
||||||
|
{"http://example.org/path", false},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
// scheme: gemini, hostname: example.com, path: /subtree/*
|
||||||
|
Pattern: "example.com/subtree/",
|
||||||
|
Matches: []Match{
|
||||||
|
{"gemini://example.com/subtree/", true},
|
||||||
|
{"gemini://example.com/subtree/nested/", true},
|
||||||
|
{"gemini://example.com/subtree/nested/file", true},
|
||||||
|
{"gemini://example.org/subtree/", false},
|
||||||
|
{"gemini://example.org/subtree/nested/", false},
|
||||||
|
{"gemini://example.org/subtree/nested/file", false},
|
||||||
|
{"gemini://example.com/subtree", false},
|
||||||
|
{"gemini://www.example.com/subtree/", false},
|
||||||
|
{"http://example.com/subtree/", false},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
// scheme: http, hostname: example.com, path: /*
|
||||||
|
Pattern: "http://example.com",
|
||||||
|
Matches: []Match{
|
||||||
|
{"http://example.com/path", true},
|
||||||
|
{"http://example.com/", true},
|
||||||
|
{"http://example.com/path.gmi", true},
|
||||||
|
{"http://example.com/path/", true},
|
||||||
|
{"http://example.org/path", false},
|
||||||
|
{"gemini://example.com/path", false},
|
||||||
|
{"gemini://example.org/path", false},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
// scheme: http, hostname: example.com, path: /path
|
||||||
|
Pattern: "http://example.com/path",
|
||||||
|
Matches: []Match{
|
||||||
|
{"http://example.com/path", true},
|
||||||
|
{"http://example.com/", false},
|
||||||
|
{"http://example.com/path.gmi", false},
|
||||||
|
{"http://example.com/path/", false},
|
||||||
|
{"http://example.org/path", false},
|
||||||
|
{"gemini://example.com/path", false},
|
||||||
|
{"gemini://example.org/path", false},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
// scheme: http, hostname: example.com, path: /subtree/*
|
||||||
|
Pattern: "http://example.com/subtree/",
|
||||||
|
Matches: []Match{
|
||||||
|
{"http://example.com/subtree/", true},
|
||||||
|
{"http://example.com/subtree/nested/", true},
|
||||||
|
{"http://example.com/subtree/nested/file", true},
|
||||||
|
{"http://example.org/subtree/", false},
|
||||||
|
{"http://example.org/subtree/nested/", false},
|
||||||
|
{"http://example.org/subtree/nested/file", false},
|
||||||
|
{"http://example.com/subtree", false},
|
||||||
|
{"http://www.example.com/subtree/", false},
|
||||||
|
{"gemini://example.com/subtree/", false},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
// scheme: *, hostname: example.com, path: /*
|
||||||
|
Pattern: "//example.com",
|
||||||
|
Matches: []Match{
|
||||||
|
{"gemini://example.com/path", true},
|
||||||
|
{"gemini://example.com/", true},
|
||||||
|
{"gemini://example.com/path.gmi", true},
|
||||||
|
{"gemini://example.com/path/", true},
|
||||||
|
{"gemini://example.org/path", false},
|
||||||
|
{"http://example.com/path", true},
|
||||||
|
{"http://example.org/path", false},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
// scheme: *, hostname: example.com, path: /path
|
||||||
|
Pattern: "//example.com/path",
|
||||||
|
Matches: []Match{
|
||||||
|
{"gemini://example.com/path", true},
|
||||||
|
{"gemini://example.com/", false},
|
||||||
|
{"gemini://example.com/path.gmi", false},
|
||||||
|
{"gemini://example.com/path/", false},
|
||||||
|
{"gemini://example.org/path", false},
|
||||||
|
{"http://example.com/path", true},
|
||||||
|
{"http://example.org/path", false},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
// scheme: *, hostname: example.com, path: /subtree/*
|
||||||
|
Pattern: "//example.com/subtree/",
|
||||||
|
Matches: []Match{
|
||||||
|
{"gemini://example.com/subtree/", true},
|
||||||
|
{"gemini://example.com/subtree/nested/", true},
|
||||||
|
{"gemini://example.com/subtree/nested/file", true},
|
||||||
|
{"gemini://example.org/subtree/", false},
|
||||||
|
{"gemini://example.org/subtree/nested/", false},
|
||||||
|
{"gemini://example.org/subtree/nested/file", false},
|
||||||
|
{"gemini://example.com/subtree", false},
|
||||||
|
{"gemini://www.example.com/subtree/", false},
|
||||||
|
{"http://example.com/subtree/", true},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
// scheme: http, hostname: *, path: /*
|
||||||
|
Pattern: "http://",
|
||||||
|
Matches: []Match{
|
||||||
|
{"http://example.com/path", true},
|
||||||
|
{"http://example.com/", true},
|
||||||
|
{"http://example.com/path.gmi", true},
|
||||||
|
{"http://example.com/path/", true},
|
||||||
|
{"http://example.org/path", true},
|
||||||
|
{"gemini://example.com/path", false},
|
||||||
|
{"gemini://example.org/path", false},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
// scheme: http, hostname: *, path: /path
|
||||||
|
Pattern: "http:///path",
|
||||||
|
Matches: []Match{
|
||||||
|
{"http://example.com/path", true},
|
||||||
|
{"http://example.com/", false},
|
||||||
|
{"http://example.com/path.gmi", false},
|
||||||
|
{"http://example.com/path/", false},
|
||||||
|
{"http://example.org/path", true},
|
||||||
|
{"gemini://example.com/path", false},
|
||||||
|
{"gemini://example.org/path", false},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
// scheme: http, hostname: *, path: /subtree/*
|
||||||
|
Pattern: "http:///subtree/",
|
||||||
|
Matches: []Match{
|
||||||
|
{"http://example.com/subtree/", true},
|
||||||
|
{"http://example.com/subtree/nested/", true},
|
||||||
|
{"http://example.com/subtree/nested/file", true},
|
||||||
|
{"http://example.org/subtree/", true},
|
||||||
|
{"http://example.org/subtree/nested/", true},
|
||||||
|
{"http://example.org/subtree/nested/file", true},
|
||||||
|
{"http://example.com/subtree", false},
|
||||||
|
{"http://www.example.com/subtree/", true},
|
||||||
|
{"gemini://example.com/subtree/", false},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
// scheme: *, hostname: *, path: /*
|
||||||
|
Pattern: "//",
|
||||||
|
Matches: []Match{
|
||||||
|
{"gemini://example.com/path", true},
|
||||||
|
{"gemini://example.com/", true},
|
||||||
|
{"gemini://example.com/path.gmi", true},
|
||||||
|
{"gemini://example.com/path/", true},
|
||||||
|
{"gemini://example.org/path", true},
|
||||||
|
{"http://example.com/path", true},
|
||||||
|
{"http://example.org/path", true},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
// scheme: *, hostname: *, path: /path
|
||||||
|
Pattern: "///path",
|
||||||
|
Matches: []Match{
|
||||||
|
{"gemini://example.com/path", true},
|
||||||
|
{"gemini://example.com/", false},
|
||||||
|
{"gemini://example.com/path.gmi", false},
|
||||||
|
{"gemini://example.com/path/", false},
|
||||||
|
{"gemini://example.org/path", true},
|
||||||
|
{"http://example.com/path", true},
|
||||||
|
{"http://example.org/path", true},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
// scheme: *, hostname: *, path: /subtree/*
|
||||||
|
Pattern: "///subtree/",
|
||||||
|
Matches: []Match{
|
||||||
|
{"gemini://example.com/subtree/", true},
|
||||||
|
{"gemini://example.com/subtree/nested/", true},
|
||||||
|
{"gemini://example.com/subtree/nested/file", true},
|
||||||
|
{"gemini://example.org/subtree/", true},
|
||||||
|
{"gemini://example.org/subtree/nested/", true},
|
||||||
|
{"gemini://example.org/subtree/nested/file", true},
|
||||||
|
{"gemini://example.com/subtree", false},
|
||||||
|
{"gemini://www.example.com/subtree/", true},
|
||||||
|
{"http://example.com/subtree/", true},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
// scheme: gemini, hostname: *.example.com, path: /*
|
||||||
|
Pattern: "*.example.com",
|
||||||
|
Matches: []Match{
|
||||||
|
{"gemini://mail.example.com/", true},
|
||||||
|
{"gemini://www.example.com/index.gmi", true},
|
||||||
|
{"gemini://example.com/", false},
|
||||||
|
{"gemini://a.b.example.com/", false},
|
||||||
|
{"http://www.example.com/", false},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
// scheme: http, hostname: *.example.com, path: /*
|
||||||
|
Pattern: "http://*.example.com",
|
||||||
|
Matches: []Match{
|
||||||
|
{"http://mail.example.com/", true},
|
||||||
|
{"http://www.example.com/index.gmi", true},
|
||||||
|
{"http://example.com/", false},
|
||||||
|
{"http://a.b.example.com/", false},
|
||||||
|
{"gemini://www.example.com/", false},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
for i, test := range tests {
|
||||||
|
h := &nopHandler{}
|
||||||
|
var mux ServeMux
|
||||||
|
mux.Handle(test.Pattern, h)
|
||||||
|
|
||||||
|
for _, match := range tests[i].Matches {
|
||||||
|
u, err := url.Parse(match.URL)
|
||||||
|
if err != nil {
|
||||||
|
panic(err)
|
||||||
|
}
|
||||||
|
got := mux.Handler(&Request{URL: u})
|
||||||
|
if match.Ok {
|
||||||
|
if h != got {
|
||||||
|
t.Errorf("expected %s to match %s", test.Pattern, match.URL)
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
if h == got {
|
||||||
|
t.Errorf("expected %s not to match %s", test.Pattern, match.URL)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
19
query.go
Normal file
19
query.go
Normal file
@@ -0,0 +1,19 @@
|
|||||||
|
package gemini
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net/url"
|
||||||
|
"strings"
|
||||||
|
)
|
||||||
|
|
||||||
|
// QueryEscape escapes a string for use in a Gemini URL query.
|
||||||
|
// It is like url.PathEscape except that it also replaces plus signs
|
||||||
|
// with their percent-encoded counterpart.
|
||||||
|
func QueryEscape(query string) string {
|
||||||
|
return strings.ReplaceAll(url.PathEscape(query), "+", "%2B")
|
||||||
|
}
|
||||||
|
|
||||||
|
// QueryUnescape unescapes a Gemini URL query.
|
||||||
|
// It is identical to url.PathUnescape.
|
||||||
|
func QueryUnescape(query string) (string, error) {
|
||||||
|
return url.PathUnescape(query)
|
||||||
|
}
|
||||||
110
request.go
110
request.go
@@ -3,75 +3,107 @@ package gemini
|
|||||||
import (
|
import (
|
||||||
"bufio"
|
"bufio"
|
||||||
"crypto/tls"
|
"crypto/tls"
|
||||||
|
"io"
|
||||||
"net"
|
"net"
|
||||||
"net/url"
|
"net/url"
|
||||||
)
|
)
|
||||||
|
|
||||||
// Request represents a Gemini request.
|
// A Request represents a Gemini request received by a server or to be sent
|
||||||
|
// by a client.
|
||||||
type Request struct {
|
type Request struct {
|
||||||
// URL specifies the URL being requested.
|
// URL specifies the URL being requested.
|
||||||
URL *url.URL
|
URL *url.URL
|
||||||
|
|
||||||
// For client requests, Host specifies the host on which the URL is sought.
|
// For client requests, Host optionally specifies the server to
|
||||||
// Host must contain a port.
|
// connect to. It may be of the form "host" or "host:port".
|
||||||
// This field is ignored by the server.
|
// If empty, the value of URL.Host is used.
|
||||||
|
// For international domain names, Host may be in Punycode or
|
||||||
|
// Unicode form. Use golang.org/x/net/idna to convert it to
|
||||||
|
// either format if needed.
|
||||||
|
// This field is ignored by the Gemini server.
|
||||||
Host string
|
Host string
|
||||||
|
|
||||||
// Certificate specifies the TLS certificate to use for the request.
|
// For client requests, Certificate optionally specifies the
|
||||||
// Request certificates take precedence over client certificates.
|
// TLS certificate to present to the other side of the connection.
|
||||||
//
|
// This field is ignored by the Gemini server.
|
||||||
// On the server side, if the client provided a certificate then
|
|
||||||
// Certificate.Leaf is guaranteed to be non-nil.
|
|
||||||
Certificate *tls.Certificate
|
Certificate *tls.Certificate
|
||||||
|
|
||||||
// RemoteAddr allows servers and other software to record the network
|
conn net.Conn
|
||||||
// address that sent the request.
|
|
||||||
// This field is ignored by the client.
|
|
||||||
RemoteAddr net.Addr
|
|
||||||
|
|
||||||
// TLS allows servers and other software to record information about the TLS
|
|
||||||
// connection on which the request was received.
|
|
||||||
// This field is ignored by the client.
|
|
||||||
TLS tls.ConnectionState
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// NewRequest returns a new request. The host is inferred from the URL.
|
// NewRequest returns a new request.
|
||||||
|
// The returned Request is suitable for use with Client.Do.
|
||||||
|
//
|
||||||
|
// Callers should be careful that the URL query is properly escaped.
|
||||||
|
// See the documentation for QueryEscape for more information.
|
||||||
func NewRequest(rawurl string) (*Request, error) {
|
func NewRequest(rawurl string) (*Request, error) {
|
||||||
u, err := url.Parse(rawurl)
|
u, err := url.Parse(rawurl)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
return NewRequestFromURL(u)
|
return &Request{URL: u}, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// NewRequestFromURL returns a new request for the given URL.
|
// ReadRequest reads and parses an incoming request from r.
|
||||||
// The host is inferred from the URL.
|
//
|
||||||
func NewRequestFromURL(url *url.URL) (*Request, error) {
|
// ReadRequest is a low-level function and should only be used
|
||||||
if url.Scheme != "" && url.Scheme != "gemini" {
|
// for specialized applications; most code should use the Server
|
||||||
return nil, ErrNotAGeminiURL
|
// to read requests and handle them via the Handler interface.
|
||||||
|
func ReadRequest(r io.Reader) (*Request, error) {
|
||||||
|
// Read URL
|
||||||
|
r = io.LimitReader(r, 1026)
|
||||||
|
br := bufio.NewReaderSize(r, 1026)
|
||||||
|
rawurl, err := br.ReadString('\r')
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
}
|
}
|
||||||
host := url.Host
|
// Read terminating line feed
|
||||||
if url.Port() == "" {
|
if b, err := br.ReadByte(); err != nil {
|
||||||
host += ":1965"
|
return nil, err
|
||||||
|
} else if b != '\n' {
|
||||||
|
return nil, ErrInvalidRequest
|
||||||
}
|
}
|
||||||
return &Request{
|
// Trim carriage return
|
||||||
URL: url,
|
rawurl = rawurl[:len(rawurl)-1]
|
||||||
Host: host,
|
// Validate URL
|
||||||
}, nil
|
if len(rawurl) > 1024 {
|
||||||
|
return nil, ErrInvalidRequest
|
||||||
|
}
|
||||||
|
u, err := url.Parse(rawurl)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return &Request{URL: u}, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// write writes the Gemini request to the provided buffered writer.
|
// Write writes a Gemini request in wire format.
|
||||||
func (r *Request) write(w *bufio.Writer) error {
|
// This method consults the request URL only.
|
||||||
|
func (r *Request) Write(w io.Writer) error {
|
||||||
|
bw := bufio.NewWriterSize(w, 1026)
|
||||||
url := r.URL.String()
|
url := r.URL.String()
|
||||||
// User is invalid
|
if len(url) > 1024 {
|
||||||
if r.URL.User != nil || len(url) > 1024 {
|
return ErrInvalidRequest
|
||||||
return ErrInvalidURL
|
|
||||||
}
|
}
|
||||||
if _, err := w.WriteString(url); err != nil {
|
if _, err := bw.WriteString(url); err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
if _, err := w.Write(crlf); err != nil {
|
if _, err := bw.Write(crlf); err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
return bw.Flush()
|
||||||
|
}
|
||||||
|
|
||||||
|
// Conn returns the network connection on which the request was received.
|
||||||
|
func (r *Request) Conn() net.Conn {
|
||||||
|
return r.conn
|
||||||
|
}
|
||||||
|
|
||||||
|
// TLS returns information about the TLS connection on which the
|
||||||
|
// request was received.
|
||||||
|
func (r *Request) TLS() *tls.ConnectionState {
|
||||||
|
if tlsConn, ok := r.conn.(*tls.Conn); ok {
|
||||||
|
state := tlsConn.ConnectionState()
|
||||||
|
return &state
|
||||||
|
}
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|||||||
132
request_test.go
Normal file
132
request_test.go
Normal file
@@ -0,0 +1,132 @@
|
|||||||
|
package gemini
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bufio"
|
||||||
|
"io"
|
||||||
|
"net/url"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
// 1024 bytes
|
||||||
|
const maxURL = "gemini://example.net/xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
|
||||||
|
|
||||||
|
func TestReadRequest(t *testing.T) {
|
||||||
|
tests := []struct {
|
||||||
|
Raw string
|
||||||
|
URL *url.URL
|
||||||
|
Err error
|
||||||
|
}{
|
||||||
|
{
|
||||||
|
Raw: "gemini://example.com\r\n",
|
||||||
|
URL: &url.URL{
|
||||||
|
Scheme: "gemini",
|
||||||
|
Host: "example.com",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
Raw: "http://example.org/path/?query#fragment\r\n",
|
||||||
|
URL: &url.URL{
|
||||||
|
Scheme: "http",
|
||||||
|
Host: "example.org",
|
||||||
|
Path: "/path/",
|
||||||
|
RawQuery: "query",
|
||||||
|
Fragment: "fragment",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
Raw: "\r\n",
|
||||||
|
URL: &url.URL{},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
Raw: "gemini://example.com\n",
|
||||||
|
Err: io.EOF,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
Raw: "gemini://example.com",
|
||||||
|
Err: io.EOF,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
// 1030 bytes
|
||||||
|
Raw: maxURL + "xxxxxx",
|
||||||
|
Err: io.EOF,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
// 1027 bytes
|
||||||
|
Raw: maxURL + "x" + "\r\n",
|
||||||
|
Err: io.EOF,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
// 1024 bytes
|
||||||
|
Raw: maxURL[:len(maxURL)-2] + "\r\n",
|
||||||
|
URL: &url.URL{
|
||||||
|
Scheme: "gemini",
|
||||||
|
Host: "example.net",
|
||||||
|
Path: maxURL[len("gemini://example.net") : len(maxURL)-2],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, test := range tests {
|
||||||
|
t.Logf("%#v", test.Raw)
|
||||||
|
req, err := ReadRequest(strings.NewReader(test.Raw))
|
||||||
|
if err != test.Err {
|
||||||
|
t.Errorf("expected err = %v, got %v", test.Err, err)
|
||||||
|
}
|
||||||
|
if req == nil && test.URL != nil {
|
||||||
|
t.Errorf("expected url = %s, got nil", test.URL)
|
||||||
|
} else if req != nil && test.URL == nil {
|
||||||
|
t.Errorf("expected req = nil, got %v", req)
|
||||||
|
} else if req != nil && *req.URL != *test.URL {
|
||||||
|
t.Errorf("expected url = %v, got %v", *test.URL, *req.URL)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func newRequest(rawurl string) *Request {
|
||||||
|
req, err := NewRequest(rawurl)
|
||||||
|
if err != nil {
|
||||||
|
panic(err)
|
||||||
|
}
|
||||||
|
return req
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestWriteRequest(t *testing.T) {
|
||||||
|
tests := []struct {
|
||||||
|
Req *Request
|
||||||
|
Raw string
|
||||||
|
Err error
|
||||||
|
}{
|
||||||
|
{
|
||||||
|
Req: newRequest("gemini://example.com"),
|
||||||
|
Raw: "gemini://example.com\r\n",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
Req: newRequest("gemini://example.com/path/?query#fragment"),
|
||||||
|
Raw: "gemini://example.com/path/?query#fragment\r\n",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
Req: newRequest(maxURL),
|
||||||
|
Raw: maxURL + "\r\n",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
Req: newRequest(maxURL + "x"),
|
||||||
|
Err: ErrInvalidRequest,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, test := range tests {
|
||||||
|
t.Logf("%s", test.Req.URL)
|
||||||
|
var b strings.Builder
|
||||||
|
bw := bufio.NewWriter(&b)
|
||||||
|
err := test.Req.Write(bw)
|
||||||
|
if err != test.Err {
|
||||||
|
t.Errorf("expected err = %v, got %v", test.Err, err)
|
||||||
|
}
|
||||||
|
bw.Flush()
|
||||||
|
got := b.String()
|
||||||
|
if got != test.Raw {
|
||||||
|
t.Errorf("expected %#v, got %#v", test.Raw, got)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
207
response.go
207
response.go
@@ -2,119 +2,206 @@ package gemini
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"bufio"
|
"bufio"
|
||||||
"bytes"
|
|
||||||
"crypto/tls"
|
"crypto/tls"
|
||||||
"io"
|
"io"
|
||||||
"io/ioutil"
|
"net"
|
||||||
"strconv"
|
"strconv"
|
||||||
)
|
)
|
||||||
|
|
||||||
// Response is a Gemini response.
|
// The default media type for responses.
|
||||||
|
const defaultMediaType = "text/gemini; charset=utf-8"
|
||||||
|
|
||||||
|
// Response represents the response from a Gemini request.
|
||||||
|
//
|
||||||
|
// The Client returns Responses from servers once the response
|
||||||
|
// header has been received. The response body is streamed on demand
|
||||||
|
// as the Body field is read.
|
||||||
type Response struct {
|
type Response struct {
|
||||||
// Status contains the response status code.
|
// Status is the response status code.
|
||||||
Status Status
|
Status Status
|
||||||
|
|
||||||
// Meta contains more information related to the response status.
|
// Meta returns the response meta.
|
||||||
// For successful responses, Meta should contain the mimetype of the response.
|
// For successful responses, the meta should contain the media type of the response.
|
||||||
// For failure responses, Meta should contain a short description of the failure.
|
// For failure responses, the meta should contain a short description of the failure.
|
||||||
// Meta should not be longer than 1024 bytes.
|
|
||||||
Meta string
|
Meta string
|
||||||
|
|
||||||
// Body contains the response body for successful responses.
|
// Body represents the response body.
|
||||||
// Body is guaranteed to be non-nil.
|
//
|
||||||
|
// The response body is streamed on demand as the Body field
|
||||||
|
// is read. If the network connection fails or the server
|
||||||
|
// terminates the response, Body.Read calls return an error.
|
||||||
|
//
|
||||||
|
// The Gemini client guarantees that Body is always
|
||||||
|
// non-nil, even on responses without a body or responses with
|
||||||
|
// a zero-length body. It is the caller's responsibility to
|
||||||
|
// close Body.
|
||||||
Body io.ReadCloser
|
Body io.ReadCloser
|
||||||
|
|
||||||
// Request is the request that was sent to obtain this response.
|
conn net.Conn
|
||||||
Request *Request
|
|
||||||
|
|
||||||
// TLS contains information about the TLS connection on which the response
|
|
||||||
// was received.
|
|
||||||
TLS tls.ConnectionState
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// read reads a Gemini response from the provided io.ReadCloser.
|
// ReadResponse reads a Gemini response from the provided io.ReadCloser.
|
||||||
func (resp *Response) read(rc io.ReadCloser) error {
|
func ReadResponse(r io.ReadCloser) (*Response, error) {
|
||||||
br := bufio.NewReader(rc)
|
resp := &Response{}
|
||||||
|
br := bufio.NewReader(r)
|
||||||
|
|
||||||
// Read the status
|
// Read the status
|
||||||
statusB := make([]byte, 2)
|
statusB := make([]byte, 2)
|
||||||
if _, err := br.Read(statusB); err != nil {
|
if _, err := br.Read(statusB); err != nil {
|
||||||
return err
|
return nil, err
|
||||||
}
|
}
|
||||||
status, err := strconv.Atoi(string(statusB))
|
status, err := strconv.Atoi(string(statusB))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return nil, ErrInvalidResponse
|
||||||
}
|
}
|
||||||
resp.Status = Status(status)
|
resp.Status = Status(status)
|
||||||
|
|
||||||
// Disregard invalid status codes
|
|
||||||
const minStatus, maxStatus = 1, 6
|
|
||||||
statusClass := resp.Status.Class()
|
|
||||||
if statusClass < minStatus || statusClass > maxStatus {
|
|
||||||
return ErrInvalidResponse
|
|
||||||
}
|
|
||||||
|
|
||||||
// Read one space
|
// Read one space
|
||||||
if b, err := br.ReadByte(); err != nil {
|
if b, err := br.ReadByte(); err != nil {
|
||||||
return err
|
return nil, err
|
||||||
} else if b != ' ' {
|
} else if b != ' ' {
|
||||||
return ErrInvalidResponse
|
return nil, ErrInvalidResponse
|
||||||
}
|
}
|
||||||
|
|
||||||
// Read the meta
|
// Read the meta
|
||||||
meta, err := br.ReadString('\r')
|
meta, err := br.ReadString('\r')
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return nil, err
|
||||||
}
|
}
|
||||||
// Trim carriage return
|
// Trim carriage return
|
||||||
meta = meta[:len(meta)-1]
|
meta = meta[:len(meta)-1]
|
||||||
// Ensure meta is less than or equal to 1024 bytes
|
// Ensure meta is less than or equal to 1024 bytes
|
||||||
if len(meta) > 1024 {
|
if len(meta) > 1024 {
|
||||||
return ErrInvalidResponse
|
return nil, ErrInvalidResponse
|
||||||
}
|
}
|
||||||
// Default mime type of text/gemini; charset=utf-8
|
if resp.Status.Class() == StatusSuccess && meta == "" {
|
||||||
if statusClass == StatusClassSuccess && meta == "" {
|
// Use default media type
|
||||||
meta = "text/gemini; charset=utf-8"
|
meta = defaultMediaType
|
||||||
}
|
}
|
||||||
resp.Meta = meta
|
resp.Meta = meta
|
||||||
|
|
||||||
// Read terminating newline
|
// Read terminating newline
|
||||||
if b, err := br.ReadByte(); err != nil {
|
if b, err := br.ReadByte(); err != nil {
|
||||||
return err
|
return nil, err
|
||||||
} else if b != '\n' {
|
} else if b != '\n' {
|
||||||
return ErrInvalidResponse
|
return nil, ErrInvalidResponse
|
||||||
}
|
}
|
||||||
|
|
||||||
if resp.Status.Class() == StatusClassSuccess {
|
if resp.Status.Class() == StatusSuccess {
|
||||||
resp.Body = newReadCloserBody(br, rc)
|
resp.Body = newBufReadCloser(br, r)
|
||||||
} else {
|
} else {
|
||||||
resp.Body = ioutil.NopCloser(bytes.NewReader([]byte{}))
|
resp.Body = nopReadCloser{}
|
||||||
|
r.Close()
|
||||||
|
}
|
||||||
|
return resp, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Conn returns the network connection on which the response was received.
|
||||||
|
func (r *Response) Conn() net.Conn {
|
||||||
|
return r.conn
|
||||||
|
}
|
||||||
|
|
||||||
|
// TLS returns information about the TLS connection on which the
|
||||||
|
// response was received.
|
||||||
|
func (r *Response) TLS() *tls.ConnectionState {
|
||||||
|
if tlsConn, ok := r.conn.(*tls.Conn); ok {
|
||||||
|
state := tlsConn.ConnectionState()
|
||||||
|
return &state
|
||||||
}
|
}
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
type readCloserBody struct {
|
// A ResponseWriter interface is used by a Gemini handler to construct
|
||||||
br *bufio.Reader // used until empty
|
// a Gemini response.
|
||||||
io.ReadCloser
|
//
|
||||||
|
// A ResponseWriter may not be used after the Handler.ServeGemini method
|
||||||
|
// has returned.
|
||||||
|
type ResponseWriter interface {
|
||||||
|
// SetMediaType sets the media type that will be sent by Write for a
|
||||||
|
// successful response. If no media type is set, a default of
|
||||||
|
// "text/gemini; charset=utf-8" will be used.
|
||||||
|
//
|
||||||
|
// Setting the media type after a call to Write or WriteHeader has
|
||||||
|
// no effect.
|
||||||
|
SetMediaType(mediatype string)
|
||||||
|
|
||||||
|
// Write writes the data to the connection as part of a Gemini response.
|
||||||
|
//
|
||||||
|
// If WriteHeader has not yet been called, Write calls WriteHeader with
|
||||||
|
// StatusSuccess and the media type set in SetMediaType before writing the data.
|
||||||
|
// If no media type was set, Write uses a default media type of
|
||||||
|
// "text/gemini; charset=utf-8".
|
||||||
|
Write([]byte) (int, error)
|
||||||
|
|
||||||
|
// WriteHeader sends a Gemini response header with the provided
|
||||||
|
// status code and meta.
|
||||||
|
//
|
||||||
|
// If WriteHeader is not called explicitly, the first call to Write
|
||||||
|
// will trigger an implicit call to WriteHeader with a successful
|
||||||
|
// status code and the media type set in SetMediaType.
|
||||||
|
//
|
||||||
|
// The provided code must be a valid Gemini status code.
|
||||||
|
// The provided meta must not be longer than 1024 bytes.
|
||||||
|
// Only one header may be written.
|
||||||
|
WriteHeader(status Status, meta string)
|
||||||
|
|
||||||
|
// Flush sends any buffered data to the client.
|
||||||
|
Flush() error
|
||||||
}
|
}
|
||||||
|
|
||||||
func newReadCloserBody(br *bufio.Reader, rc io.ReadCloser) io.ReadCloser {
|
type responseWriter struct {
|
||||||
body := &readCloserBody{ReadCloser: rc}
|
bw *bufio.Writer
|
||||||
if br.Buffered() != 0 {
|
cl io.Closer
|
||||||
body.br = br
|
mediatype string
|
||||||
}
|
wroteHeader bool
|
||||||
return body
|
bodyAllowed bool
|
||||||
}
|
}
|
||||||
|
|
||||||
func (b *readCloserBody) Read(p []byte) (n int, err error) {
|
func newResponseWriter(w io.Writer) *responseWriter {
|
||||||
if b.br != nil {
|
return &responseWriter{
|
||||||
if n := b.br.Buffered(); len(p) > n {
|
bw: bufio.NewWriter(w),
|
||||||
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)
|
}
|
||||||
|
|
||||||
|
func (w *responseWriter) SetMediaType(mediatype string) {
|
||||||
|
w.mediatype = mediatype
|
||||||
|
}
|
||||||
|
|
||||||
|
func (w *responseWriter) Write(b []byte) (int, error) {
|
||||||
|
if !w.wroteHeader {
|
||||||
|
meta := w.mediatype
|
||||||
|
if meta == "" {
|
||||||
|
// Use default media type
|
||||||
|
meta = defaultMediaType
|
||||||
|
}
|
||||||
|
w.WriteHeader(StatusSuccess, meta)
|
||||||
|
}
|
||||||
|
if !w.bodyAllowed {
|
||||||
|
return 0, ErrBodyNotAllowed
|
||||||
|
}
|
||||||
|
return w.bw.Write(b)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (w *responseWriter) WriteHeader(status Status, meta string) {
|
||||||
|
if w.wroteHeader {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if status.Class() == StatusSuccess {
|
||||||
|
w.bodyAllowed = true
|
||||||
|
}
|
||||||
|
|
||||||
|
w.bw.WriteString(strconv.Itoa(int(status)))
|
||||||
|
w.bw.WriteByte(' ')
|
||||||
|
w.bw.WriteString(meta)
|
||||||
|
w.bw.Write(crlf)
|
||||||
|
w.wroteHeader = true
|
||||||
|
}
|
||||||
|
|
||||||
|
func (w *responseWriter) Flush() error {
|
||||||
|
if !w.wroteHeader {
|
||||||
|
w.WriteHeader(StatusTemporaryFailure, "Temporary failure")
|
||||||
|
}
|
||||||
|
// Write errors from WriteHeader will be returned here.
|
||||||
|
return w.bw.Flush()
|
||||||
}
|
}
|
||||||
|
|||||||
126
response_test.go
Normal file
126
response_test.go
Normal file
@@ -0,0 +1,126 @@
|
|||||||
|
package gemini
|
||||||
|
|
||||||
|
import (
|
||||||
|
"io"
|
||||||
|
"io/ioutil"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestReadWriteResponse(t *testing.T) {
|
||||||
|
tests := []struct {
|
||||||
|
Raw string
|
||||||
|
Status Status
|
||||||
|
Meta string
|
||||||
|
Body string
|
||||||
|
Err error
|
||||||
|
SkipWrite bool
|
||||||
|
}{
|
||||||
|
{
|
||||||
|
Raw: "20 text/gemini\r\nHello, world!\nWelcome to my capsule.",
|
||||||
|
Status: 20,
|
||||||
|
Meta: "text/gemini",
|
||||||
|
Body: "Hello, world!\nWelcome to my capsule.",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
Raw: "10 Search query\r\n",
|
||||||
|
Status: 10,
|
||||||
|
Meta: "Search query",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
Raw: "30 /redirect\r\n",
|
||||||
|
Status: 30,
|
||||||
|
Meta: "/redirect",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
Raw: "31 /redirect\r\nThis body is ignored.",
|
||||||
|
Status: 31,
|
||||||
|
Meta: "/redirect",
|
||||||
|
SkipWrite: true, // skip write test since result won't match Raw
|
||||||
|
},
|
||||||
|
{
|
||||||
|
Raw: "99 Unknown status code\r\n",
|
||||||
|
Status: 99,
|
||||||
|
Meta: "Unknown status code",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
Raw: "\r\n",
|
||||||
|
Err: ErrInvalidResponse,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
Raw: "\n",
|
||||||
|
Err: ErrInvalidResponse,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
Raw: "1 Bad response\r\n",
|
||||||
|
Err: ErrInvalidResponse,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
Raw: "",
|
||||||
|
Err: io.EOF,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
Raw: "10 Search query",
|
||||||
|
Err: io.EOF,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
Raw: "20 text/gemini\nHello, world!",
|
||||||
|
Err: io.EOF,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
Raw: "20 text/gemini\rHello, world!",
|
||||||
|
Err: ErrInvalidResponse,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
Raw: "20 text/gemini\r",
|
||||||
|
Err: io.EOF,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
Raw: "abcdefghijklmnopqrstuvwxyz",
|
||||||
|
Err: ErrInvalidResponse,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, test := range tests {
|
||||||
|
t.Logf("%#v", test.Raw)
|
||||||
|
resp, err := ReadResponse(ioutil.NopCloser(strings.NewReader(test.Raw)))
|
||||||
|
if err != test.Err {
|
||||||
|
t.Errorf("expected err = %v, got %v", test.Err, err)
|
||||||
|
}
|
||||||
|
if test.Err != nil {
|
||||||
|
// No response
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if resp.Status != test.Status {
|
||||||
|
t.Errorf("expected status = %d, got %d", test.Status, resp.Status)
|
||||||
|
}
|
||||||
|
if resp.Meta != test.Meta {
|
||||||
|
t.Errorf("expected meta = %s, got %s", test.Meta, resp.Meta)
|
||||||
|
}
|
||||||
|
b, _ := ioutil.ReadAll(resp.Body)
|
||||||
|
body := string(b)
|
||||||
|
if body != test.Body {
|
||||||
|
t.Errorf("expected body = %#v, got %#v", test.Body, body)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, test := range tests {
|
||||||
|
if test.Err != nil || test.SkipWrite {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
var b strings.Builder
|
||||||
|
w := newResponseWriter(nopCloser{&b})
|
||||||
|
w.WriteHeader(test.Status, test.Meta)
|
||||||
|
io.Copy(w, strings.NewReader(test.Body))
|
||||||
|
if err := w.Flush(); err != nil {
|
||||||
|
t.Error(err)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
got := b.String()
|
||||||
|
if got != test.Raw {
|
||||||
|
t.Errorf("expected %#v, got %#v", test.Raw, got)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
571
server.go
571
server.go
@@ -1,109 +1,267 @@
|
|||||||
package gemini
|
package gemini
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"bufio"
|
"context"
|
||||||
"crypto/tls"
|
"crypto/tls"
|
||||||
|
"errors"
|
||||||
"log"
|
"log"
|
||||||
"net"
|
"net"
|
||||||
"net/url"
|
"sync"
|
||||||
"strconv"
|
|
||||||
"strings"
|
|
||||||
"time"
|
"time"
|
||||||
)
|
)
|
||||||
|
|
||||||
// Server is a Gemini server.
|
// A Server defines parameters for running a Gemini server. The zero value for
|
||||||
|
// Server is a valid configuration.
|
||||||
type Server struct {
|
type Server struct {
|
||||||
// Addr specifies the address that the server should listen on.
|
// Addr optionally specifies the TCP address for the server to listen on,
|
||||||
// If Addr is empty, the server will listen on the address ":1965".
|
// in the form "host:port". If empty, ":1965" (port 1965) is used.
|
||||||
|
// See net.Dial for details of the address format.
|
||||||
Addr string
|
Addr string
|
||||||
|
|
||||||
// ReadTimeout is the maximum duration for reading a request.
|
// The Handler to invoke.
|
||||||
|
Handler Handler
|
||||||
|
|
||||||
|
// ReadTimeout is the maximum duration for reading the entire
|
||||||
|
// request.
|
||||||
|
//
|
||||||
|
// A ReadTimeout of zero means no timeout.
|
||||||
ReadTimeout time.Duration
|
ReadTimeout time.Duration
|
||||||
|
|
||||||
// WriteTimeout is the maximum duration before timing out
|
// WriteTimeout is the maximum duration before timing out
|
||||||
// writes of the response.
|
// writes of the response.
|
||||||
|
//
|
||||||
|
// A WriteTimeout of zero means no timeout.
|
||||||
WriteTimeout time.Duration
|
WriteTimeout time.Duration
|
||||||
|
|
||||||
// Certificates contains the certificates used by the server.
|
// GetCertificate returns a TLS certificate based on the given
|
||||||
Certificates CertificateStore
|
// hostname.
|
||||||
|
//
|
||||||
|
// If GetCertificate is nil or returns nil, then no certificate
|
||||||
|
// will be used and the connection will be aborted.
|
||||||
|
//
|
||||||
|
// See the certificate submodule for a certificate store that creates
|
||||||
|
// and rotates certificates as needed.
|
||||||
|
GetCertificate func(hostname string) (*tls.Certificate, error)
|
||||||
|
|
||||||
// CreateCertificate, if not nil, will be called to create a new certificate
|
// ErrorLog specifies an optional logger for errors accepting connections,
|
||||||
// if the current one is expired or missing.
|
// unexpected behavior from handlers, and underlying file system errors.
|
||||||
CreateCertificate func(hostname string) (tls.Certificate, error)
|
// If nil, logging is done via the log package's standard logger.
|
||||||
|
ErrorLog interface {
|
||||||
|
Printf(format string, v ...interface{})
|
||||||
|
}
|
||||||
|
|
||||||
// registered responders
|
listeners map[*net.Listener]context.CancelFunc
|
||||||
responders map[responderKey]Responder
|
conns map[*net.Conn]context.CancelFunc
|
||||||
hosts map[string]bool
|
closed bool // true if Close or Shutdown called
|
||||||
|
shutdown bool // true if Shutdown called
|
||||||
|
doneChan chan struct{}
|
||||||
|
mu sync.Mutex
|
||||||
}
|
}
|
||||||
|
|
||||||
type responderKey struct {
|
func (srv *Server) isClosed() bool {
|
||||||
scheme string
|
srv.mu.Lock()
|
||||||
hostname string
|
defer srv.mu.Unlock()
|
||||||
|
return srv.closed
|
||||||
}
|
}
|
||||||
|
|
||||||
// Register registers a responder for the given pattern.
|
// done returns a channel that's closed when the server is closed and
|
||||||
|
// all listeners and connections are closed.
|
||||||
|
func (srv *Server) done() chan struct{} {
|
||||||
|
srv.mu.Lock()
|
||||||
|
defer srv.mu.Unlock()
|
||||||
|
return srv.doneLocked()
|
||||||
|
}
|
||||||
|
|
||||||
|
func (srv *Server) doneLocked() chan struct{} {
|
||||||
|
if srv.doneChan == nil {
|
||||||
|
srv.doneChan = make(chan struct{})
|
||||||
|
}
|
||||||
|
return srv.doneChan
|
||||||
|
}
|
||||||
|
|
||||||
|
// tryCloseDone closes srv.done() if the server is closed and
|
||||||
|
// there are no active listeners or connections.
|
||||||
|
func (srv *Server) tryCloseDone() {
|
||||||
|
srv.mu.Lock()
|
||||||
|
defer srv.mu.Unlock()
|
||||||
|
srv.tryCloseDoneLocked()
|
||||||
|
}
|
||||||
|
|
||||||
|
func (srv *Server) tryCloseDoneLocked() {
|
||||||
|
if !srv.closed {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if len(srv.listeners) == 0 && len(srv.conns) == 0 {
|
||||||
|
ch := srv.doneLocked()
|
||||||
|
select {
|
||||||
|
case <-ch:
|
||||||
|
default:
|
||||||
|
close(ch)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Close immediately closes all active net.Listeners and connections.
|
||||||
|
// For a graceful shutdown, use Shutdown.
|
||||||
|
func (srv *Server) Close() error {
|
||||||
|
srv.mu.Lock()
|
||||||
|
{
|
||||||
|
if srv.closed {
|
||||||
|
srv.mu.Unlock()
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
srv.closed = true
|
||||||
|
|
||||||
|
srv.tryCloseDoneLocked()
|
||||||
|
|
||||||
|
// Close all active connections and listeners.
|
||||||
|
for _, cancel := range srv.listeners {
|
||||||
|
cancel()
|
||||||
|
}
|
||||||
|
for _, cancel := range srv.conns {
|
||||||
|
cancel()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
srv.mu.Unlock()
|
||||||
|
|
||||||
|
select {
|
||||||
|
case <-srv.done():
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Shutdown gracefully shuts down the server without interrupting any
|
||||||
|
// active connections. Shutdown works by first closing all open listeners
|
||||||
|
// and then waiting indefinitely for connections to close.
|
||||||
|
// If the provided context expires before the shutdown is complete,
|
||||||
|
// Shutdown returns the context's error.
|
||||||
//
|
//
|
||||||
// Patterns must be in the form of "hostname" or "scheme://hostname".
|
// When Shutdown is called, Serve and ListenAndServe immediately
|
||||||
// If no scheme is specified, a scheme of "gemini://" is implied.
|
// return an error. Make sure the program doesn't exit and waits instead for
|
||||||
// Wildcard patterns are supported (e.g. "*.example.com").
|
// Shutdown to return.
|
||||||
func (s *Server) Register(pattern string, responder Responder) {
|
//
|
||||||
if pattern == "" {
|
// Once Shutdown has been called on a server, it may not be reused;
|
||||||
panic("gemini: invalid pattern")
|
// future calls to methods such as Serve will return an error.
|
||||||
}
|
func (srv *Server) Shutdown(ctx context.Context) error {
|
||||||
if responder == nil {
|
srv.mu.Lock()
|
||||||
panic("gemini: nil responder")
|
{
|
||||||
}
|
if srv.closed {
|
||||||
if s.responders == nil {
|
srv.mu.Unlock()
|
||||||
s.responders = map[responderKey]Responder{}
|
return nil
|
||||||
s.hosts = map[string]bool{}
|
}
|
||||||
}
|
srv.closed = true
|
||||||
|
srv.shutdown = true
|
||||||
|
|
||||||
split := strings.SplitN(pattern, "://", 2)
|
srv.tryCloseDoneLocked()
|
||||||
var key responderKey
|
|
||||||
if len(split) == 2 {
|
|
||||||
key.scheme = split[0]
|
|
||||||
key.hostname = split[1]
|
|
||||||
} else {
|
|
||||||
key.scheme = "gemini"
|
|
||||||
key.hostname = split[0]
|
|
||||||
}
|
|
||||||
|
|
||||||
if _, ok := s.responders[key]; ok {
|
// Close all active listeners.
|
||||||
panic("gemini: multiple registrations for " + pattern)
|
for _, cancel := range srv.listeners {
|
||||||
|
cancel()
|
||||||
|
}
|
||||||
}
|
}
|
||||||
s.responders[key] = responder
|
srv.mu.Unlock()
|
||||||
s.hosts[key.hostname] = true
|
|
||||||
}
|
|
||||||
|
|
||||||
// RegisterFunc registers a responder function for the given pattern.
|
// Wait for active connections to finish.
|
||||||
func (s *Server) RegisterFunc(pattern string, responder func(*ResponseWriter, *Request)) {
|
select {
|
||||||
s.Register(pattern, ResponderFunc(responder))
|
case <-ctx.Done():
|
||||||
|
return ctx.Err()
|
||||||
|
case <-srv.done():
|
||||||
|
return nil
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// ListenAndServe listens for requests at the server's configured address.
|
// ListenAndServe listens for requests at the server's configured address.
|
||||||
func (s *Server) ListenAndServe() error {
|
// ListenAndServe listens on the TCP network address srv.Addr and then calls
|
||||||
addr := s.Addr
|
// Serve to handle requests on incoming connections. If the provided
|
||||||
|
// context expires, ListenAndServe closes l and returns the context's error.
|
||||||
|
//
|
||||||
|
// If srv.Addr is blank, ":1965" is used.
|
||||||
|
//
|
||||||
|
// ListenAndServe always returns a non-nil error.
|
||||||
|
// After Shutdown or Closed, the returned error is context.Canceled.
|
||||||
|
func (srv *Server) ListenAndServe(ctx context.Context) error {
|
||||||
|
if srv.isClosed() {
|
||||||
|
return context.Canceled
|
||||||
|
}
|
||||||
|
|
||||||
|
addr := srv.Addr
|
||||||
if addr == "" {
|
if addr == "" {
|
||||||
addr = ":1965"
|
addr = ":1965"
|
||||||
}
|
}
|
||||||
|
|
||||||
ln, err := net.Listen("tcp", addr)
|
l, err := net.Listen("tcp", addr)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
defer ln.Close()
|
|
||||||
|
|
||||||
return s.Serve(tls.NewListener(ln, &tls.Config{
|
l = tls.NewListener(l, &tls.Config{
|
||||||
ClientAuth: tls.RequestClientCert,
|
ClientAuth: tls.RequestClientCert,
|
||||||
MinVersion: tls.VersionTLS12,
|
MinVersion: tls.VersionTLS12,
|
||||||
GetCertificate: s.getCertificate,
|
GetCertificate: srv.getCertificate,
|
||||||
}))
|
})
|
||||||
|
return srv.Serve(ctx, l)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Serve listens for requests on the provided listener.
|
func (srv *Server) getCertificate(h *tls.ClientHelloInfo) (*tls.Certificate, error) {
|
||||||
func (s *Server) Serve(l net.Listener) error {
|
if srv.GetCertificate == nil {
|
||||||
var tempDelay time.Duration // how long to sleep on accept failure
|
return nil, errors.New("gemini: GetCertificate is nil")
|
||||||
|
}
|
||||||
|
return srv.GetCertificate(h.ServerName)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (srv *Server) trackListener(l *net.Listener, cancel context.CancelFunc) bool {
|
||||||
|
srv.mu.Lock()
|
||||||
|
defer srv.mu.Unlock()
|
||||||
|
if srv.closed {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
if srv.listeners == nil {
|
||||||
|
srv.listeners = make(map[*net.Listener]context.CancelFunc)
|
||||||
|
}
|
||||||
|
srv.listeners[l] = cancel
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
func (srv *Server) deleteListener(l *net.Listener) {
|
||||||
|
srv.mu.Lock()
|
||||||
|
defer srv.mu.Unlock()
|
||||||
|
delete(srv.listeners, l)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Serve accepts incoming connections on the Listener l, creating a new
|
||||||
|
// service goroutine for each. The service goroutines read the requests and
|
||||||
|
// then call the appropriate Handler to reply to them. If the provided
|
||||||
|
// context expires, Serve closes l and returns the context's error.
|
||||||
|
//
|
||||||
|
// Serve always closes l and returns a non-nil error.
|
||||||
|
// After Shutdown or Close, the returned error is context.Canceled.
|
||||||
|
func (srv *Server) Serve(ctx context.Context, l net.Listener) error {
|
||||||
|
defer l.Close()
|
||||||
|
|
||||||
|
lnctx, cancel := context.WithCancel(ctx)
|
||||||
|
defer cancel()
|
||||||
|
|
||||||
|
if !srv.trackListener(&l, cancel) {
|
||||||
|
return context.Canceled
|
||||||
|
}
|
||||||
|
defer srv.tryCloseDone()
|
||||||
|
defer srv.deleteListener(&l)
|
||||||
|
|
||||||
|
errch := make(chan error, 1)
|
||||||
|
go func() {
|
||||||
|
errch <- srv.serve(ctx, l)
|
||||||
|
}()
|
||||||
|
|
||||||
|
select {
|
||||||
|
case <-lnctx.Done():
|
||||||
|
return lnctx.Err()
|
||||||
|
case err := <-errch:
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (srv *Server) serve(ctx context.Context, l net.Listener) error {
|
||||||
|
var tempDelay time.Duration // how long to sleep on accept failure
|
||||||
for {
|
for {
|
||||||
rw, err := l.Accept()
|
rw, err := l.Accept()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -117,229 +275,118 @@ func (s *Server) Serve(l net.Listener) error {
|
|||||||
if max := 1 * time.Second; tempDelay > max {
|
if max := 1 * time.Second; tempDelay > max {
|
||||||
tempDelay = max
|
tempDelay = max
|
||||||
}
|
}
|
||||||
log.Printf("gemini: Accept error: %v; retrying in %v", err, tempDelay)
|
srv.logf("gemini: Accept error: %v; retrying in %v", err, tempDelay)
|
||||||
time.Sleep(tempDelay)
|
time.Sleep(tempDelay)
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
|
|
||||||
// Otherwise, return the error
|
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
tempDelay = 0
|
tempDelay = 0
|
||||||
go s.respond(rw)
|
go srv.serveConn(ctx, rw, false)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *Server) getCertificate(h *tls.ClientHelloInfo) (*tls.Certificate, error) {
|
func (srv *Server) trackConn(conn *net.Conn, cancel context.CancelFunc, external bool) bool {
|
||||||
cert, err := s.getCertificateFor(h.ServerName)
|
srv.mu.Lock()
|
||||||
if err != nil {
|
defer srv.mu.Unlock()
|
||||||
// Try wildcard
|
// Reject the connection under the following conditions:
|
||||||
wildcard := strings.SplitN(h.ServerName, ".", 2)
|
// - Shutdown or Close has been called and conn is external (from ServeConn)
|
||||||
if len(wildcard) == 2 {
|
// - Close (not Shutdown) has been called and conn is internal (from Serve)
|
||||||
cert, err = s.getCertificateFor("*." + wildcard[1])
|
if srv.closed && (external || !srv.shutdown) {
|
||||||
}
|
return false
|
||||||
}
|
}
|
||||||
return cert, err
|
if srv.conns == nil {
|
||||||
|
srv.conns = make(map[*net.Conn]context.CancelFunc)
|
||||||
|
}
|
||||||
|
srv.conns[conn] = cancel
|
||||||
|
return true
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *Server) getCertificateFor(hostname string) (*tls.Certificate, error) {
|
func (srv *Server) deleteConn(conn *net.Conn) {
|
||||||
if _, ok := s.hosts[hostname]; !ok {
|
srv.mu.Lock()
|
||||||
return nil, ErrCertificateNotFound
|
defer srv.mu.Unlock()
|
||||||
}
|
delete(srv.conns, conn)
|
||||||
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.
|
// ServeConn serves a Gemini response over the provided connection.
|
||||||
func (s *Server) respond(conn net.Conn) {
|
// It closes the connection when the response has been completed.
|
||||||
if d := s.ReadTimeout; d != 0 {
|
// If the provided context expires before the response has completed,
|
||||||
|
// ServeConn closes the connection and returns the context's error.
|
||||||
|
func (srv *Server) ServeConn(ctx context.Context, conn net.Conn) error {
|
||||||
|
return srv.serveConn(ctx, conn, true)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (srv *Server) serveConn(ctx context.Context, conn net.Conn, external bool) error {
|
||||||
|
defer conn.Close()
|
||||||
|
|
||||||
|
ctx, cancel := context.WithCancel(ctx)
|
||||||
|
defer cancel()
|
||||||
|
|
||||||
|
if !srv.trackConn(&conn, cancel, external) {
|
||||||
|
return context.Canceled
|
||||||
|
}
|
||||||
|
defer srv.tryCloseDone()
|
||||||
|
defer srv.deleteConn(&conn)
|
||||||
|
|
||||||
|
if d := srv.ReadTimeout; d != 0 {
|
||||||
conn.SetReadDeadline(time.Now().Add(d))
|
conn.SetReadDeadline(time.Now().Add(d))
|
||||||
}
|
}
|
||||||
if d := s.WriteTimeout; d != 0 {
|
if d := srv.WriteTimeout; d != 0 {
|
||||||
conn.SetWriteDeadline(time.Now().Add(d))
|
conn.SetWriteDeadline(time.Now().Add(d))
|
||||||
}
|
}
|
||||||
|
|
||||||
r := bufio.NewReader(conn)
|
errch := make(chan error, 1)
|
||||||
w := newResponseWriter(conn)
|
go func() {
|
||||||
// Read requested URL
|
errch <- srv.goServeConn(ctx, conn)
|
||||||
rawurl, err := r.ReadString('\r')
|
}()
|
||||||
|
|
||||||
|
select {
|
||||||
|
case <-ctx.Done():
|
||||||
|
return ctx.Err()
|
||||||
|
case err := <-errch:
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (srv *Server) goServeConn(ctx context.Context, conn net.Conn) error {
|
||||||
|
ctx, cancel := context.WithCancel(ctx)
|
||||||
|
done := ctx.Done()
|
||||||
|
cw := &contextWriter{
|
||||||
|
ctx: ctx,
|
||||||
|
done: done,
|
||||||
|
cancel: cancel,
|
||||||
|
wc: conn,
|
||||||
|
}
|
||||||
|
r := &contextReader{
|
||||||
|
ctx: ctx,
|
||||||
|
done: done,
|
||||||
|
cancel: cancel,
|
||||||
|
rc: conn,
|
||||||
|
}
|
||||||
|
|
||||||
|
w := newResponseWriter(cw)
|
||||||
|
|
||||||
|
req, err := ReadRequest(r)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return
|
w.WriteHeader(StatusBadRequest, "Bad request")
|
||||||
|
return w.Flush()
|
||||||
}
|
}
|
||||||
// Read terminating line feed
|
req.conn = conn
|
||||||
if b, err := r.ReadByte(); err != nil {
|
|
||||||
return
|
h := srv.Handler
|
||||||
} else if b != '\n' {
|
if h == nil {
|
||||||
w.WriteStatus(StatusBadRequest)
|
w.WriteHeader(StatusNotFound, "Not found")
|
||||||
|
return w.Flush()
|
||||||
}
|
}
|
||||||
// Trim carriage return
|
|
||||||
rawurl = rawurl[:len(rawurl)-1]
|
h.ServeGemini(ctx, w, req)
|
||||||
// Ensure URL is valid
|
return w.Flush()
|
||||||
if len(rawurl) > 1024 {
|
}
|
||||||
w.WriteStatus(StatusBadRequest)
|
|
||||||
} else if url, err := url.Parse(rawurl); err != nil || url.User != nil {
|
func (srv *Server) logf(format string, args ...interface{}) {
|
||||||
// Note that we return an error status if User is specified in the URL
|
if srv.ErrorLog != nil {
|
||||||
w.WriteStatus(StatusBadRequest)
|
srv.ErrorLog.Printf(format, args...)
|
||||||
} else {
|
} else {
|
||||||
// If no scheme is specified, assume a default scheme of gemini://
|
log.Printf(format, args...)
|
||||||
if url.Scheme == "" {
|
|
||||||
url.Scheme = "gemini"
|
|
||||||
}
|
|
||||||
|
|
||||||
// Store information about the TLS connection
|
|
||||||
connState := conn.(*tls.Conn).ConnectionState()
|
|
||||||
var cert *tls.Certificate
|
|
||||||
if len(connState.PeerCertificates) > 0 {
|
|
||||||
peerCert := connState.PeerCertificates[0]
|
|
||||||
// Store the TLS certificate
|
|
||||||
cert = &tls.Certificate{
|
|
||||||
Certificate: [][]byte{peerCert.Raw},
|
|
||||||
Leaf: peerCert,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
req := &Request{
|
|
||||||
URL: url,
|
|
||||||
RemoteAddr: conn.RemoteAddr(),
|
|
||||||
TLS: connState,
|
|
||||||
Certificate: cert,
|
|
||||||
}
|
|
||||||
resp := s.responder(req)
|
|
||||||
if resp != nil {
|
|
||||||
resp.Respond(w, req)
|
|
||||||
} else {
|
|
||||||
w.WriteStatus(StatusNotFound)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
w.b.Flush()
|
|
||||||
conn.Close()
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s *Server) responder(r *Request) Responder {
|
|
||||||
if h, ok := s.responders[responderKey{r.URL.Scheme, r.URL.Hostname()}]; ok {
|
|
||||||
return h
|
|
||||||
}
|
|
||||||
wildcard := strings.SplitN(r.URL.Hostname(), ".", 2)
|
|
||||||
if len(wildcard) == 2 {
|
|
||||||
if h, ok := s.responders[responderKey{r.URL.Scheme, "*." + wildcard[1]}]; ok {
|
|
||||||
return h
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// ResponseWriter is used by a Gemini handler to construct a Gemini response.
|
|
||||||
type ResponseWriter struct {
|
|
||||||
b *bufio.Writer
|
|
||||||
bodyAllowed bool
|
|
||||||
wroteHeader bool
|
|
||||||
mimetype string
|
|
||||||
}
|
|
||||||
|
|
||||||
func newResponseWriter(conn net.Conn) *ResponseWriter {
|
|
||||||
return &ResponseWriter{
|
|
||||||
b: bufio.NewWriter(conn),
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// WriteHeader writes the response header.
|
|
||||||
// If the header has already been written, WriteHeader does nothing.
|
|
||||||
//
|
|
||||||
// Meta contains more information related to the response status.
|
|
||||||
// For successful responses, Meta should contain the mimetype of the response.
|
|
||||||
// For failure responses, Meta should contain a short description of the failure.
|
|
||||||
// Meta should not be longer than 1024 bytes.
|
|
||||||
func (w *ResponseWriter) WriteHeader(status Status, meta string) {
|
|
||||||
if w.wroteHeader {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
w.b.WriteString(strconv.Itoa(int(status)))
|
|
||||||
w.b.WriteByte(' ')
|
|
||||||
w.b.WriteString(meta)
|
|
||||||
w.b.Write(crlf)
|
|
||||||
|
|
||||||
// Only allow body to be written on successful status codes.
|
|
||||||
if status.Class() == StatusClassSuccess {
|
|
||||||
w.bodyAllowed = true
|
|
||||||
}
|
|
||||||
w.wroteHeader = true
|
|
||||||
}
|
|
||||||
|
|
||||||
// WriteStatus writes the response header with the given status code.
|
|
||||||
//
|
|
||||||
// WriteStatus is equivalent to WriteHeader(status, status.Message())
|
|
||||||
func (w *ResponseWriter) WriteStatus(status Status) {
|
|
||||||
w.WriteHeader(status, status.Message())
|
|
||||||
}
|
|
||||||
|
|
||||||
// SetMimetype sets the mimetype that will be written for a successful response.
|
|
||||||
// If the mimetype is not set, it will default to "text/gemini".
|
|
||||||
func (w *ResponseWriter) SetMimetype(mimetype string) {
|
|
||||||
w.mimetype = mimetype
|
|
||||||
}
|
|
||||||
|
|
||||||
// Write writes the response body.
|
|
||||||
// If the response status does not allow for a response body, Write returns
|
|
||||||
// ErrBodyNotAllowed.
|
|
||||||
//
|
|
||||||
// If the response header has not yet been written, Write calls WriteHeader
|
|
||||||
// with StatusSuccess and the mimetype set in SetMimetype.
|
|
||||||
func (w *ResponseWriter) Write(b []byte) (int, error) {
|
|
||||||
if !w.wroteHeader {
|
|
||||||
mimetype := w.mimetype
|
|
||||||
if mimetype == "" {
|
|
||||||
mimetype = "text/gemini"
|
|
||||||
}
|
|
||||||
w.WriteHeader(StatusSuccess, mimetype)
|
|
||||||
}
|
|
||||||
if !w.bodyAllowed {
|
|
||||||
return 0, ErrBodyNotAllowed
|
|
||||||
}
|
|
||||||
return w.b.Write(b)
|
|
||||||
}
|
|
||||||
|
|
||||||
// A Responder responds to a Gemini request.
|
|
||||||
type Responder interface {
|
|
||||||
// Respond accepts a Request and constructs a Response.
|
|
||||||
Respond(*ResponseWriter, *Request)
|
|
||||||
}
|
|
||||||
|
|
||||||
// ResponderFunc is a wrapper around a bare function that implements Responder.
|
|
||||||
type ResponderFunc func(*ResponseWriter, *Request)
|
|
||||||
|
|
||||||
func (f ResponderFunc) Respond(w *ResponseWriter, r *Request) {
|
|
||||||
f(w, r)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Input returns the request query.
|
|
||||||
// If the query is invalid or no query is provided, ok will be false.
|
|
||||||
//
|
|
||||||
// Example:
|
|
||||||
//
|
|
||||||
// input, ok := gemini.Input(req)
|
|
||||||
// if !ok {
|
|
||||||
// w.WriteHeader(gemini.StatusInput, "Prompt")
|
|
||||||
// return
|
|
||||||
// }
|
|
||||||
// // ...
|
|
||||||
//
|
|
||||||
func Input(r *Request) (query string, ok bool) {
|
|
||||||
if r.URL.ForceQuery || r.URL.RawQuery != "" {
|
|
||||||
query, err := url.QueryUnescape(r.URL.RawQuery)
|
|
||||||
return query, err == nil
|
|
||||||
}
|
|
||||||
return "", false
|
|
||||||
}
|
|
||||||
|
|||||||
27
status.go
27
status.go
@@ -1,8 +1,9 @@
|
|||||||
package gemini
|
package gemini
|
||||||
|
|
||||||
// Status codes.
|
// Status represents a Gemini status code.
|
||||||
type Status int
|
type Status int
|
||||||
|
|
||||||
|
// Gemini status codes.
|
||||||
const (
|
const (
|
||||||
StatusInput Status = 10
|
StatusInput Status = 10
|
||||||
StatusSensitiveInput Status = 11
|
StatusSensitiveInput Status = 11
|
||||||
@@ -24,25 +25,15 @@ const (
|
|||||||
StatusCertificateNotValid Status = 62
|
StatusCertificateNotValid Status = 62
|
||||||
)
|
)
|
||||||
|
|
||||||
// Status code categories.
|
// Class returns the status class for the status code.
|
||||||
type StatusClass int
|
// 1x becomes 10, 2x becomes 20, and so on.
|
||||||
|
func (s Status) Class() Status {
|
||||||
const (
|
return (s / 10) * 10
|
||||||
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.
|
// String returns a text for the status code.
|
||||||
func (s Status) Message() string {
|
// It returns the empty string if the status code is unknown.
|
||||||
|
func (s Status) String() string {
|
||||||
switch s {
|
switch s {
|
||||||
case StatusInput:
|
case StatusInput:
|
||||||
return "Input"
|
return "Input"
|
||||||
|
|||||||
29
text.go
29
text.go
@@ -9,38 +9,39 @@ import (
|
|||||||
|
|
||||||
// Line represents a line of a Gemini text response.
|
// Line represents a line of a Gemini text response.
|
||||||
type Line interface {
|
type Line interface {
|
||||||
|
// String formats the line for use in a Gemini text response.
|
||||||
String() string
|
String() string
|
||||||
line() // private function to prevent other packages from implementing Line
|
line() // private function to prevent other packages from implementing Line
|
||||||
}
|
}
|
||||||
|
|
||||||
// A link line.
|
// LineLink is a link line.
|
||||||
type LineLink struct {
|
type LineLink struct {
|
||||||
URL string
|
URL string
|
||||||
Name string
|
Name string
|
||||||
}
|
}
|
||||||
|
|
||||||
// A preformatting toggle line.
|
// LinePreformattingToggle is a preformatting toggle line.
|
||||||
type LinePreformattingToggle string
|
type LinePreformattingToggle string
|
||||||
|
|
||||||
// A preformatted text line.
|
// LinePreformattedText is a preformatted text line.
|
||||||
type LinePreformattedText string
|
type LinePreformattedText string
|
||||||
|
|
||||||
// A first-level heading line.
|
// LineHeading1 is a first-level heading line.
|
||||||
type LineHeading1 string
|
type LineHeading1 string
|
||||||
|
|
||||||
// A second-level heading line.
|
// LineHeading2 is a second-level heading line.
|
||||||
type LineHeading2 string
|
type LineHeading2 string
|
||||||
|
|
||||||
// A third-level heading line.
|
// LineHeading3 is a third-level heading line.
|
||||||
type LineHeading3 string
|
type LineHeading3 string
|
||||||
|
|
||||||
// An unordered list item line.
|
// LineListItem is an unordered list item line.
|
||||||
type LineListItem string
|
type LineListItem string
|
||||||
|
|
||||||
// A quote line.
|
// LineQuote is a quote line.
|
||||||
type LineQuote string
|
type LineQuote string
|
||||||
|
|
||||||
// A text line.
|
// LineText is a text line.
|
||||||
type LineText string
|
type LineText string
|
||||||
|
|
||||||
func (l LineLink) String() string {
|
func (l LineLink) String() string {
|
||||||
@@ -88,17 +89,17 @@ func (l LineText) line() {}
|
|||||||
type Text []Line
|
type Text []Line
|
||||||
|
|
||||||
// ParseText parses Gemini text from the provided io.Reader.
|
// ParseText parses Gemini text from the provided io.Reader.
|
||||||
func ParseText(r io.Reader) Text {
|
func ParseText(r io.Reader) (Text, error) {
|
||||||
var t Text
|
var t Text
|
||||||
ParseLines(r, func(line Line) {
|
err := ParseLines(r, func(line Line) {
|
||||||
t = append(t, line)
|
t = append(t, line)
|
||||||
})
|
})
|
||||||
return t
|
return t, err
|
||||||
}
|
}
|
||||||
|
|
||||||
// ParseLines parses Gemini text from the provided io.Reader.
|
// ParseLines parses Gemini text from the provided io.Reader.
|
||||||
// It calls handler with each line that it parses.
|
// It calls handler with each line that it parses.
|
||||||
func ParseLines(r io.Reader, handler func(Line)) {
|
func ParseLines(r io.Reader, handler func(Line)) error {
|
||||||
const spacetab = " \t"
|
const spacetab = " \t"
|
||||||
var pre bool
|
var pre bool
|
||||||
scanner := bufio.NewScanner(r)
|
scanner := bufio.NewScanner(r)
|
||||||
@@ -149,6 +150,8 @@ func ParseLines(r io.Reader, handler func(Line)) {
|
|||||||
}
|
}
|
||||||
handler(line)
|
handler(line)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
return scanner.Err()
|
||||||
}
|
}
|
||||||
|
|
||||||
// String writes the Gemini text response to a string and returns it.
|
// String writes the Gemini text response to a string and returns it.
|
||||||
|
|||||||
204
tofu.go
204
tofu.go
@@ -1,204 +0,0 @@
|
|||||||
package gemini
|
|
||||||
|
|
||||||
import (
|
|
||||||
"bufio"
|
|
||||||
"crypto/sha512"
|
|
||||||
"crypto/x509"
|
|
||||||
"fmt"
|
|
||||||
"io"
|
|
||||||
"os"
|
|
||||||
"path/filepath"
|
|
||||||
"strconv"
|
|
||||||
"strings"
|
|
||||||
"time"
|
|
||||||
)
|
|
||||||
|
|
||||||
// Trust represents the trustworthiness of a certificate.
|
|
||||||
type Trust int
|
|
||||||
|
|
||||||
const (
|
|
||||||
TrustNone Trust = iota // The certificate is not trusted.
|
|
||||||
TrustOnce // The certificate is trusted once.
|
|
||||||
TrustAlways // The certificate is trusted always.
|
|
||||||
)
|
|
||||||
|
|
||||||
// KnownHosts represents a list of known hosts.
|
|
||||||
// The zero value for KnownHosts is an empty list ready to use.
|
|
||||||
type KnownHosts struct {
|
|
||||||
hosts map[string]certInfo
|
|
||||||
file *os.File
|
|
||||||
}
|
|
||||||
|
|
||||||
// LoadDefault loads the known hosts from the default known hosts path, which is
|
|
||||||
// $XDG_DATA_HOME/gemini/known_hosts.
|
|
||||||
// It creates the path and any of its parent directories if they do not exist.
|
|
||||||
// KnownHosts will append to the file whenever a certificate is added.
|
|
||||||
func (k *KnownHosts) LoadDefault() error {
|
|
||||||
path, err := defaultKnownHostsPath()
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
return k.Load(path)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Load loads the known hosts from the provided path.
|
|
||||||
// It creates the path and any of its parent directories if they do not exist.
|
|
||||||
// KnownHosts will append to the file whenever a certificate is added.
|
|
||||||
func (k *KnownHosts) Load(path string) error {
|
|
||||||
if dir := filepath.Dir(path); dir != "." {
|
|
||||||
err := os.MkdirAll(dir, 0755)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
}
|
|
||||||
f, err := os.OpenFile(path, os.O_CREATE|os.O_RDONLY, 0644)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
k.Parse(f)
|
|
||||||
f.Close()
|
|
||||||
// Open the file for append-only use
|
|
||||||
f, err = os.OpenFile(path, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0644)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
k.file = f
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// Add adds a certificate to the list of known hosts.
|
|
||||||
// If KnownHosts was loaded from a file, Add will append to the file.
|
|
||||||
func (k *KnownHosts) Add(hostname string, cert *x509.Certificate) {
|
|
||||||
k.add(hostname, cert, true)
|
|
||||||
}
|
|
||||||
|
|
||||||
// AddTemporary adds a certificate to the list of known hosts
|
|
||||||
// without writing it to the known hosts file.
|
|
||||||
func (k *KnownHosts) AddTemporary(hostname string, cert *x509.Certificate) {
|
|
||||||
k.add(hostname, cert, false)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (k *KnownHosts) add(hostname string, cert *x509.Certificate, write bool) {
|
|
||||||
if k.hosts == nil {
|
|
||||||
k.hosts = map[string]certInfo{}
|
|
||||||
}
|
|
||||||
info := certInfo{
|
|
||||||
Algorithm: "SHA-512",
|
|
||||||
Fingerprint: Fingerprint(cert),
|
|
||||||
Expires: cert.NotAfter.Unix(),
|
|
||||||
}
|
|
||||||
k.hosts[hostname] = info
|
|
||||||
// Append to the file
|
|
||||||
if write && k.file != nil {
|
|
||||||
appendKnownHost(k.file, hostname, info)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Lookup looks for the provided certificate in the list of known hosts.
|
|
||||||
// If the hostname is not in the list, Lookup returns ErrCertificateNotFound.
|
|
||||||
// If the fingerprint doesn't match, Lookup returns ErrCertificateNotTrusted.
|
|
||||||
// Otherwise, Lookup returns nil.
|
|
||||||
func (k *KnownHosts) Lookup(hostname string, cert *x509.Certificate) error {
|
|
||||||
now := time.Now().Unix()
|
|
||||||
fingerprint := Fingerprint(cert)
|
|
||||||
if c, ok := k.hosts[hostname]; ok {
|
|
||||||
if c.Expires <= now {
|
|
||||||
// Certificate is expired
|
|
||||||
return ErrCertificateExpired
|
|
||||||
}
|
|
||||||
if c.Fingerprint != fingerprint {
|
|
||||||
// Fingerprint does not match
|
|
||||||
return ErrCertificateNotTrusted
|
|
||||||
}
|
|
||||||
// Certificate is found
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
return ErrCertificateNotFound
|
|
||||||
}
|
|
||||||
|
|
||||||
// Parse parses the provided reader and adds the parsed known hosts to the list.
|
|
||||||
// Invalid lines are ignored.
|
|
||||||
func (k *KnownHosts) Parse(r io.Reader) {
|
|
||||||
if k.hosts == nil {
|
|
||||||
k.hosts = map[string]certInfo{}
|
|
||||||
}
|
|
||||||
scanner := bufio.NewScanner(r)
|
|
||||||
for scanner.Scan() {
|
|
||||||
text := scanner.Text()
|
|
||||||
parts := strings.Split(text, " ")
|
|
||||||
if len(parts) < 4 {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
|
|
||||||
hostname := parts[0]
|
|
||||||
algorithm := parts[1]
|
|
||||||
if algorithm != "SHA-512" {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
fingerprint := parts[2]
|
|
||||||
expires, err := strconv.ParseInt(parts[3], 10, 0)
|
|
||||||
if err != nil {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
|
|
||||||
k.hosts[hostname] = certInfo{
|
|
||||||
Algorithm: algorithm,
|
|
||||||
Fingerprint: fingerprint,
|
|
||||||
Expires: expires,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Write writes the known hosts to the provided io.Writer.
|
|
||||||
func (k *KnownHosts) Write(w io.Writer) {
|
|
||||||
for h, c := range k.hosts {
|
|
||||||
appendKnownHost(w, h, c)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
type certInfo struct {
|
|
||||||
Algorithm string // fingerprint algorithm e.g. SHA-512
|
|
||||||
Fingerprint string // fingerprint in hexadecimal, with ':' between each octet
|
|
||||||
Expires int64 // unix time of certificate notAfter date
|
|
||||||
}
|
|
||||||
|
|
||||||
func appendKnownHost(w io.Writer, hostname string, c certInfo) (int, error) {
|
|
||||||
return fmt.Fprintf(w, "%s %s %s %d\n", hostname, c.Algorithm, c.Fingerprint, c.Expires)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Fingerprint returns the SHA-512 fingerprint of the provided certificate.
|
|
||||||
func Fingerprint(cert *x509.Certificate) string {
|
|
||||||
sum512 := sha512.Sum512(cert.Raw)
|
|
||||||
var b strings.Builder
|
|
||||||
for i, f := range sum512 {
|
|
||||||
if i > 0 {
|
|
||||||
b.WriteByte(':')
|
|
||||||
}
|
|
||||||
fmt.Fprintf(&b, "%02X", f)
|
|
||||||
}
|
|
||||||
return b.String()
|
|
||||||
}
|
|
||||||
|
|
||||||
// defaultKnownHostsPath returns the default known_hosts path.
|
|
||||||
// The default path is $XDG_DATA_HOME/gemini/known_hosts
|
|
||||||
func defaultKnownHostsPath() (string, error) {
|
|
||||||
dataDir, err := userDataDir()
|
|
||||||
if err != nil {
|
|
||||||
return "", err
|
|
||||||
}
|
|
||||||
return filepath.Join(dataDir, "gemini", "known_hosts"), nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// userDataDir returns the user data directory.
|
|
||||||
func userDataDir() (string, error) {
|
|
||||||
dataDir, ok := os.LookupEnv("XDG_DATA_HOME")
|
|
||||||
if ok {
|
|
||||||
return dataDir, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
home, err := os.UserHomeDir()
|
|
||||||
if err != nil {
|
|
||||||
return "", err
|
|
||||||
}
|
|
||||||
return filepath.Join(home, ".local", "share"), nil
|
|
||||||
}
|
|
||||||
418
tofu/tofu.go
Normal file
418
tofu/tofu.go
Normal file
@@ -0,0 +1,418 @@
|
|||||||
|
// Package tofu implements trust on first use using hosts and fingerprints.
|
||||||
|
package tofu
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bufio"
|
||||||
|
"bytes"
|
||||||
|
"crypto/sha512"
|
||||||
|
"crypto/x509"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"os"
|
||||||
|
"sort"
|
||||||
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
"sync"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
// KnownHosts represents a list of known hosts.
|
||||||
|
// The zero value for KnownHosts represents an empty list ready to use.
|
||||||
|
//
|
||||||
|
// KnownHosts is safe for concurrent use by multiple goroutines.
|
||||||
|
type KnownHosts struct {
|
||||||
|
hosts map[string]Host
|
||||||
|
mu sync.RWMutex
|
||||||
|
}
|
||||||
|
|
||||||
|
// Add adds a host to the list of known hosts.
|
||||||
|
func (k *KnownHosts) Add(h Host) {
|
||||||
|
k.mu.Lock()
|
||||||
|
defer k.mu.Unlock()
|
||||||
|
if k.hosts == nil {
|
||||||
|
k.hosts = map[string]Host{}
|
||||||
|
}
|
||||||
|
|
||||||
|
k.hosts[h.Hostname] = h
|
||||||
|
}
|
||||||
|
|
||||||
|
// Lookup returns the known host entry corresponding to the given hostname.
|
||||||
|
func (k *KnownHosts) Lookup(hostname string) (Host, bool) {
|
||||||
|
k.mu.RLock()
|
||||||
|
defer k.mu.RUnlock()
|
||||||
|
c, ok := k.hosts[hostname]
|
||||||
|
return c, ok
|
||||||
|
}
|
||||||
|
|
||||||
|
// Entries returns the known host entries sorted by hostname.
|
||||||
|
func (k *KnownHosts) Entries() []Host {
|
||||||
|
keys := make([]string, 0, len(k.hosts))
|
||||||
|
for key := range k.hosts {
|
||||||
|
keys = append(keys, key)
|
||||||
|
}
|
||||||
|
sort.Strings(keys)
|
||||||
|
|
||||||
|
hosts := make([]Host, 0, len(k.hosts))
|
||||||
|
for _, key := range keys {
|
||||||
|
hosts = append(hosts, k.hosts[key])
|
||||||
|
}
|
||||||
|
return hosts
|
||||||
|
}
|
||||||
|
|
||||||
|
// WriteTo writes the list of known hosts to the provided io.Writer.
|
||||||
|
func (k *KnownHosts) WriteTo(w io.Writer) (int64, error) {
|
||||||
|
k.mu.RLock()
|
||||||
|
defer k.mu.RUnlock()
|
||||||
|
|
||||||
|
var written int
|
||||||
|
|
||||||
|
bw := bufio.NewWriter(w)
|
||||||
|
for _, h := range k.hosts {
|
||||||
|
n, err := bw.WriteString(h.String())
|
||||||
|
written += n
|
||||||
|
if err != nil {
|
||||||
|
return int64(written), err
|
||||||
|
}
|
||||||
|
|
||||||
|
bw.WriteByte('\n')
|
||||||
|
written += 1
|
||||||
|
}
|
||||||
|
|
||||||
|
return int64(written), bw.Flush()
|
||||||
|
}
|
||||||
|
|
||||||
|
// Load loads the known hosts entries from the provided path.
|
||||||
|
func (k *KnownHosts) Load(path string) error {
|
||||||
|
f, err := os.Open(path)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
defer f.Close()
|
||||||
|
|
||||||
|
return k.Parse(f)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Parse parses the provided io.Reader and adds the parsed hosts to the list.
|
||||||
|
// Invalid entries are ignored.
|
||||||
|
//
|
||||||
|
// For more control over errors encountered during parsing, use bufio.Scanner
|
||||||
|
// in combination with ParseHost. For example:
|
||||||
|
//
|
||||||
|
// var knownHosts tofu.KnownHosts
|
||||||
|
// scanner := bufio.NewScanner(r)
|
||||||
|
// for scanner.Scan() {
|
||||||
|
// host, err := tofu.ParseHost(scanner.Bytes())
|
||||||
|
// if err != nil {
|
||||||
|
// // handle error
|
||||||
|
// } else {
|
||||||
|
// knownHosts.Add(host)
|
||||||
|
// }
|
||||||
|
// }
|
||||||
|
// err := scanner.Err()
|
||||||
|
// if err != nil {
|
||||||
|
// // handle error
|
||||||
|
// }
|
||||||
|
//
|
||||||
|
func (k *KnownHosts) Parse(r io.Reader) error {
|
||||||
|
k.mu.Lock()
|
||||||
|
defer k.mu.Unlock()
|
||||||
|
|
||||||
|
if k.hosts == nil {
|
||||||
|
k.hosts = map[string]Host{}
|
||||||
|
}
|
||||||
|
|
||||||
|
scanner := bufio.NewScanner(r)
|
||||||
|
for scanner.Scan() {
|
||||||
|
text := scanner.Bytes()
|
||||||
|
if len(text) == 0 {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
h, err := ParseHost(text)
|
||||||
|
if err != nil {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
k.hosts[h.Hostname] = h
|
||||||
|
}
|
||||||
|
|
||||||
|
return scanner.Err()
|
||||||
|
}
|
||||||
|
|
||||||
|
// TOFU implements basic trust on first use.
|
||||||
|
//
|
||||||
|
// If the host is not on file, it is added to the list.
|
||||||
|
// If the host on file is expired, a new entry is added to the list.
|
||||||
|
// If the fingerprint does not match the one on file, an error is returned.
|
||||||
|
func (k *KnownHosts) TOFU(hostname string, cert *x509.Certificate) error {
|
||||||
|
host := NewHost(hostname, cert.Raw, cert.NotAfter)
|
||||||
|
|
||||||
|
knownHost, ok := k.Lookup(hostname)
|
||||||
|
if !ok || time.Now().After(knownHost.Expires) {
|
||||||
|
k.Add(host)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check fingerprint
|
||||||
|
if !bytes.Equal(knownHost.Fingerprint, host.Fingerprint) {
|
||||||
|
return fmt.Errorf("fingerprint for %q does not match", hostname)
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// HostWriter writes host entries to an io.WriteCloser.
|
||||||
|
//
|
||||||
|
// HostWriter is safe for concurrent use by multiple goroutines.
|
||||||
|
type HostWriter struct {
|
||||||
|
bw *bufio.Writer
|
||||||
|
cl io.Closer
|
||||||
|
mu sync.Mutex
|
||||||
|
}
|
||||||
|
|
||||||
|
// NewHostWriter returns a new host writer that writes to
|
||||||
|
// the provided io.WriteCloser.
|
||||||
|
func NewHostWriter(w io.WriteCloser) *HostWriter {
|
||||||
|
return &HostWriter{
|
||||||
|
bw: bufio.NewWriter(w),
|
||||||
|
cl: w,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// OpenHostsFile returns a new host writer that appends to the file at the given path.
|
||||||
|
// The file is created if it does not exist.
|
||||||
|
func OpenHostsFile(path string) (*HostWriter, error) {
|
||||||
|
f, err := os.OpenFile(path, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return NewHostWriter(f), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// WriteHost writes the host to the underlying io.Writer.
|
||||||
|
func (h *HostWriter) WriteHost(host Host) error {
|
||||||
|
h.mu.Lock()
|
||||||
|
defer h.mu.Unlock()
|
||||||
|
|
||||||
|
h.bw.WriteString(host.String())
|
||||||
|
h.bw.WriteByte('\n')
|
||||||
|
|
||||||
|
if err := h.bw.Flush(); err != nil {
|
||||||
|
return fmt.Errorf("failed to write host: %w", err)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Close closes the underlying io.Closer.
|
||||||
|
func (h *HostWriter) Close() error {
|
||||||
|
h.mu.Lock()
|
||||||
|
defer h.mu.Unlock()
|
||||||
|
return h.cl.Close()
|
||||||
|
}
|
||||||
|
|
||||||
|
// PersistentHosts represents a persistent set of known hosts.
|
||||||
|
type PersistentHosts struct {
|
||||||
|
hosts *KnownHosts
|
||||||
|
writer *HostWriter
|
||||||
|
}
|
||||||
|
|
||||||
|
// NewPersistentHosts returns a new persistent set of known hosts that stores
|
||||||
|
// known hosts in hosts and writes new hosts to writer.
|
||||||
|
func NewPersistentHosts(hosts *KnownHosts, writer *HostWriter) *PersistentHosts {
|
||||||
|
return &PersistentHosts{
|
||||||
|
hosts,
|
||||||
|
writer,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// LoadPersistentHosts loads persistent hosts from the file at the given path.
|
||||||
|
func LoadPersistentHosts(path string) (*PersistentHosts, error) {
|
||||||
|
hosts := &KnownHosts{}
|
||||||
|
if err := hosts.Load(path); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
writer, err := OpenHostsFile(path)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return &PersistentHosts{
|
||||||
|
hosts,
|
||||||
|
writer,
|
||||||
|
}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Add adds a host to the list of known hosts.
|
||||||
|
// It returns an error if the host could not be persisted.
|
||||||
|
func (p *PersistentHosts) Add(h Host) error {
|
||||||
|
err := p.writer.WriteHost(h)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("failed to persist host: %w", err)
|
||||||
|
}
|
||||||
|
p.hosts.Add(h)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Lookup returns the known host entry corresponding to the given hostname.
|
||||||
|
func (p *PersistentHosts) Lookup(hostname string) (Host, bool) {
|
||||||
|
return p.hosts.Lookup(hostname)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Entries returns the known host entries sorted by hostname.
|
||||||
|
func (p *PersistentHosts) Entries() []Host {
|
||||||
|
return p.hosts.Entries()
|
||||||
|
}
|
||||||
|
|
||||||
|
// TOFU implements trust on first use with a persistent set of known hosts.
|
||||||
|
//
|
||||||
|
// If the host is not on file, it is added to the list.
|
||||||
|
// If the host on file is expired, a new entry is added to the list.
|
||||||
|
// If the fingerprint does not match the one on file, an error is returned.
|
||||||
|
func (p *PersistentHosts) TOFU(hostname string, cert *x509.Certificate) error {
|
||||||
|
host := NewHost(hostname, cert.Raw, cert.NotAfter)
|
||||||
|
|
||||||
|
knownHost, ok := p.Lookup(hostname)
|
||||||
|
if !ok || time.Now().After(knownHost.Expires) {
|
||||||
|
return p.Add(host)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check fingerprint
|
||||||
|
if !bytes.Equal(knownHost.Fingerprint, host.Fingerprint) {
|
||||||
|
return fmt.Errorf("fingerprint for %q does not match", hostname)
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Close closes the underlying HostWriter.
|
||||||
|
func (p *PersistentHosts) Close() error {
|
||||||
|
return p.writer.Close()
|
||||||
|
}
|
||||||
|
|
||||||
|
// Host represents a host entry with a fingerprint using a certain algorithm.
|
||||||
|
type Host struct {
|
||||||
|
Hostname string // hostname
|
||||||
|
Algorithm string // fingerprint algorithm e.g. SHA-512
|
||||||
|
Fingerprint Fingerprint // fingerprint
|
||||||
|
Expires time.Time // unix time of the fingerprint expiration date
|
||||||
|
}
|
||||||
|
|
||||||
|
// NewHost returns a new host with a SHA-512 fingerprint of
|
||||||
|
// the provided raw data.
|
||||||
|
func NewHost(hostname string, raw []byte, expires time.Time) Host {
|
||||||
|
sum := sha512.Sum512(raw)
|
||||||
|
|
||||||
|
return Host{
|
||||||
|
Hostname: hostname,
|
||||||
|
Algorithm: "SHA-512",
|
||||||
|
Fingerprint: sum[:],
|
||||||
|
Expires: expires,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ParseHost parses a host from the provided text.
|
||||||
|
func ParseHost(text []byte) (Host, error) {
|
||||||
|
var h Host
|
||||||
|
err := h.UnmarshalText(text)
|
||||||
|
return h, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// String returns a string representation of the host.
|
||||||
|
func (h Host) String() string {
|
||||||
|
var b strings.Builder
|
||||||
|
b.WriteString(h.Hostname)
|
||||||
|
b.WriteByte(' ')
|
||||||
|
b.WriteString(h.Algorithm)
|
||||||
|
b.WriteByte(' ')
|
||||||
|
b.WriteString(h.Fingerprint.String())
|
||||||
|
b.WriteByte(' ')
|
||||||
|
b.WriteString(strconv.FormatInt(h.Expires.Unix(), 10))
|
||||||
|
return b.String()
|
||||||
|
}
|
||||||
|
|
||||||
|
// UnmarshalText unmarshals the host from the provided text.
|
||||||
|
func (h *Host) UnmarshalText(text []byte) error {
|
||||||
|
const format = "hostname algorithm hex-fingerprint expiry-unix-ts"
|
||||||
|
|
||||||
|
parts := bytes.Split(text, []byte(" "))
|
||||||
|
if len(parts) != 4 {
|
||||||
|
return fmt.Errorf("expected the format %q", format)
|
||||||
|
}
|
||||||
|
|
||||||
|
if len(parts[0]) == 0 {
|
||||||
|
return errors.New("empty hostname")
|
||||||
|
}
|
||||||
|
|
||||||
|
h.Hostname = string(parts[0])
|
||||||
|
|
||||||
|
algorithm := string(parts[1])
|
||||||
|
if algorithm != "SHA-512" {
|
||||||
|
return fmt.Errorf("unsupported algorithm %q", algorithm)
|
||||||
|
}
|
||||||
|
|
||||||
|
h.Algorithm = algorithm
|
||||||
|
|
||||||
|
fingerprint := make([]byte, 0, sha512.Size)
|
||||||
|
scanner := bufio.NewScanner(bytes.NewReader(parts[2]))
|
||||||
|
scanner.Split(scanFingerprint)
|
||||||
|
|
||||||
|
for scanner.Scan() {
|
||||||
|
b, err := strconv.ParseUint(scanner.Text(), 16, 8)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("failed to parse fingerprint hash: %w", err)
|
||||||
|
}
|
||||||
|
fingerprint = append(fingerprint, byte(b))
|
||||||
|
}
|
||||||
|
|
||||||
|
if len(fingerprint) != sha512.Size {
|
||||||
|
return fmt.Errorf("invalid fingerprint size %d, expected %d",
|
||||||
|
len(fingerprint), sha512.Size)
|
||||||
|
}
|
||||||
|
|
||||||
|
h.Fingerprint = fingerprint
|
||||||
|
|
||||||
|
unix, err := strconv.ParseInt(string(parts[3]), 10, 0)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("invalid unix timestamp: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
h.Expires = time.Unix(unix, 0)
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func scanFingerprint(data []byte, atEOF bool) (advance int, token []byte, err error) {
|
||||||
|
if atEOF && len(data) == 0 {
|
||||||
|
return 0, nil, nil
|
||||||
|
}
|
||||||
|
if i := bytes.IndexByte(data, ':'); i >= 0 {
|
||||||
|
// We have a full newline-terminated line.
|
||||||
|
return i + 1, data[0:i], nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// If we're at EOF, we have a final, non-terminated hex byte
|
||||||
|
if atEOF {
|
||||||
|
return len(data), data, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Request more data.
|
||||||
|
return 0, nil, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Fingerprint represents a fingerprint.
|
||||||
|
type Fingerprint []byte
|
||||||
|
|
||||||
|
// String returns a string representation of the fingerprint.
|
||||||
|
func (f Fingerprint) String() string {
|
||||||
|
var sb strings.Builder
|
||||||
|
|
||||||
|
for i, b := range f {
|
||||||
|
if i > 0 {
|
||||||
|
sb.WriteByte(':')
|
||||||
|
}
|
||||||
|
|
||||||
|
fmt.Fprintf(&sb, "%02X", b)
|
||||||
|
}
|
||||||
|
|
||||||
|
return sb.String()
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user