all repos — flounder @ 7dff255849f753cf7b0d73de584f3bb6cb6f1645

A small site builder for the Gemini protocol

gemini.go (view raw)

  1package main
  2
  3import (
  4	"bytes"
  5	"crypto/tls"
  6	"crypto/x509" // todo move into cert file
  7	"encoding/pem"
  8	"strings"
  9	// "fmt"
 10	"git.sr.ht/~adnano/gmi"
 11	"io/ioutil"
 12	"log"
 13	"os"
 14	"path"
 15	"text/template"
 16	"time"
 17)
 18
 19func gmiIndex(w *gmi.ResponseWriter, r *gmi.Request) {
 20	t, err := template.ParseFiles("templates/index.gmi")
 21	if err != nil {
 22		log.Fatal(err)
 23	}
 24	files, _ := getIndexFiles()
 25	users, _ := getUsers()
 26	data := struct {
 27		Domain string
 28		Files  []*File
 29		Users  []string
 30	}{
 31		Domain: "flounder.online",
 32		Files:  files,
 33		Users:  users,
 34	}
 35	t.Execute(w, data)
 36}
 37
 38func gmiPage(w *gmi.ResponseWriter, r *gmi.Request) {
 39	userName := strings.Split(r.URL.Host, ".")[0]
 40	fileName := path.Join(c.FilesDirectory, userName, r.URL.Path)
 41	data, err := ioutil.ReadFile(fileName)
 42	if err != nil {
 43		// return 404 equivalent
 44		log.Fatal(err)
 45	}
 46	// TODO handle error
 47	w.Write(data)
 48}
 49
 50func runGeminiServer() {
 51	log.Println("Starting gemini server")
 52	var server gmi.Server
 53
 54	if err := server.CertificateStore.Load("./tmpcerts"); err != nil {
 55		log.Fatal(err)
 56	}
 57	server.GetCertificate = func(hostname string, store *gmi.CertificateStore) *tls.Certificate {
 58		cert, err := store.Lookup(hostname)
 59		if err != nil {
 60			switch err {
 61			case gmi.ErrCertificateExpired:
 62				// Generate a new certificate if the current one is expired.
 63				log.Print("Old certificate expired, creating new one")
 64				fallthrough
 65			case gmi.ErrCertificateUnknown:
 66				// Generate a certificate if one does not exist.
 67				cert, err := gmi.NewCertificate(hostname, time.Minute)
 68				if err != nil {
 69					// Failed to generate new certificate, abort
 70					return nil
 71				}
 72				// Store and return the new certificate
 73				err = writeCertificate("./tmpcerts/"+hostname, cert)
 74				if err != nil {
 75					return nil
 76				}
 77				store.Add(hostname, cert)
 78				return &cert
 79			}
 80		}
 81		return cert
 82	}
 83
 84	// replace with wildcard cert
 85	server.HandleFunc(c.RootDomain, gmiIndex)
 86	server.HandleFunc("*."+c.RootDomain, gmiPage)
 87
 88	server.ListenAndServe()
 89}
 90
 91// writeCertificate writes the provided certificate and private key
 92// to path.crt and path.key respectively.
 93func writeCertificate(path string, cert tls.Certificate) error {
 94	crt, err := marshalX509Certificate(cert.Leaf.Raw)
 95	if err != nil {
 96		return err
 97	}
 98	key, err := marshalPrivateKey(cert.PrivateKey)
 99	if err != nil {
100		return err
101	}
102
103	// Write the certificate
104	crtPath := path + ".crt"
105	crtOut, err := os.OpenFile(crtPath, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0600)
106	if err != nil {
107		return err
108	}
109	if _, err := crtOut.Write(crt); err != nil {
110		return err
111	}
112
113	// Write the private key
114	keyPath := path + ".key"
115	keyOut, err := os.OpenFile(keyPath, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0600)
116	if err != nil {
117		return err
118	}
119	if _, err := keyOut.Write(key); err != nil {
120		return err
121	}
122	return nil
123}
124
125// marshalX509Certificate returns a PEM-encoded version of the given raw certificate.
126func marshalX509Certificate(cert []byte) ([]byte, error) {
127	var b bytes.Buffer
128	if err := pem.Encode(&b, &pem.Block{Type: "CERTIFICATE", Bytes: cert}); err != nil {
129		return nil, err
130	}
131	return b.Bytes(), nil
132}
133
134// marshalPrivateKey returns PEM encoded versions of the given certificate and private key.
135func marshalPrivateKey(priv interface{}) ([]byte, error) {
136	var b bytes.Buffer
137	privBytes, err := x509.MarshalPKCS8PrivateKey(priv)
138	if err != nil {
139		return nil, err
140	}
141	if err := pem.Encode(&b, &pem.Block{Type: "PRIVATE KEY", Bytes: privBytes}); err != nil {
142		return nil, err
143	}
144	return b.Bytes(), nil
145}