castor/main.go

85 lines
2.0 KiB
Go
Raw Normal View History

2020-09-12 20:30:41 +00:00
package main
import (
"bufio"
"crypto/tls"
2020-09-16 20:45:36 +00:00
"flag"
2020-09-12 20:30:41 +00:00
"mime"
"net"
"net/url"
"git.yetaga.in/alazyreader/castor/certificates"
"git.yetaga.in/alazyreader/castor/handlers"
2020-09-16 19:17:54 +00:00
"git.yetaga.in/alazyreader/castor/logger"
2020-09-12 20:30:41 +00:00
)
2020-09-16 19:17:54 +00:00
func handleConnection(log logger.Logger, conn net.Conn, h handlers.Handler) {
2020-09-12 20:30:41 +00:00
defer conn.Close()
scanner := bufio.NewScanner(conn)
if ok := scanner.Scan(); !ok {
2020-09-16 19:17:54 +00:00
log.Debug(scanner.Err())
2020-09-12 20:30:41 +00:00
}
u, err := url.Parse(scanner.Text())
if err != nil {
2020-09-16 19:17:54 +00:00
log.Debug(err)
2020-09-12 20:30:41 +00:00
}
2021-10-24 20:52:13 +00:00
w := handlers.NewResponse(conn, log)
r := handlers.NewRequest(u)
2020-09-16 19:17:54 +00:00
handlers.RecoveryHandler(log, h).Handle(w, r)
2020-09-12 20:30:41 +00:00
}
func main() {
2020-09-16 20:45:36 +00:00
hostname := flag.String("hostname", "localhost", "comma-separated list of hostnames to generate certificates for")
regenCerts := flag.Bool("regenerate-certs", false, "set to true to regenerate cert files")
serveFrom := flag.String("path", "./root/", "filepath to serve files from; defaults to ./root/")
flag.Parse()
2020-09-16 19:17:54 +00:00
log := logger.NewLogger(true)
2020-09-12 20:30:41 +00:00
mime.AddExtensionType(".gemini", "text/gemini")
mime.AddExtensionType(".gmi", "text/gemini")
2020-09-16 20:11:51 +00:00
err := certificates.TestCertificateExists("./certs/cert.pem", "./certs/key.pem")
var cer tls.Certificate
2020-09-16 20:45:36 +00:00
if err != nil || *regenCerts {
log.Info("Generating new certificate...")
2020-09-16 20:45:36 +00:00
key, cert, err := certificates.GenerateKeyPair(*hostname)
if err != nil {
log.Info("error generating certificates", err)
return
}
2020-09-16 20:11:51 +00:00
err = certificates.WriteCertsToFile("./certs/cert.pem", "./certs/key.pem", cert, key)
if err != nil {
log.Info("error saving certificates", err)
return
}
2020-09-12 20:30:41 +00:00
}
2020-09-16 20:11:51 +00:00
cer, err = tls.LoadX509KeyPair("./certs/cert.pem", "./certs/key.pem")
2020-09-12 20:30:41 +00:00
if err != nil {
log.Info("error loading certificates", err)
return
2020-09-12 20:30:41 +00:00
}
tlsc := tls.Config{
Certificates: []tls.Certificate{cer},
MinVersion: tls.VersionTLS12,
}
2020-09-12 20:30:41 +00:00
2020-09-16 20:11:51 +00:00
listener, err := tls.Listen("tcp", ":1965", &tlsc)
2020-09-12 20:30:41 +00:00
if err != nil {
log.Info(err)
return
}
for {
conn, err := listener.Accept()
if err != nil {
log.Debug(err.Error())
continue
}
2020-09-16 20:45:36 +00:00
go handleConnection(log, conn, handlers.NewFileHandler(*serveFrom))
2020-09-12 20:30:41 +00:00
}
}