78 lines
1.6 KiB
Go
78 lines
1.6 KiB
Go
package main
|
|
|
|
import (
|
|
"bufio"
|
|
"crypto/tls"
|
|
"mime"
|
|
"net"
|
|
"net/url"
|
|
|
|
"git.yetaga.in/alazyreader/castor/certificates"
|
|
"git.yetaga.in/alazyreader/castor/handlers"
|
|
)
|
|
|
|
func handleConnection(log Logger, conn net.Conn, h handlers.Handler) {
|
|
defer conn.Close()
|
|
scanner := bufio.NewScanner(conn)
|
|
if ok := scanner.Scan(); !ok {
|
|
log.Info(scanner.Err())
|
|
}
|
|
u, err := url.Parse(scanner.Text())
|
|
if err != nil {
|
|
log.Info(err)
|
|
}
|
|
w := handlers.NewResponse(conn)
|
|
r := handlers.NewRequest(u)
|
|
handlers.RecoveryHandler(h).Handle(w, r)
|
|
}
|
|
|
|
func main() {
|
|
log := NewLogger(true)
|
|
|
|
mime.AddExtensionType(".gemini", "text/gemini")
|
|
mime.AddExtensionType(".gmi", "text/gemini")
|
|
|
|
err := certificates.TestCertificateExists("./cert.pem", "./key.pem")
|
|
var cer tls.Certificate
|
|
if err != nil {
|
|
log.Info("Generating new certificate...")
|
|
key, cert, err := certificates.GenerateKeyPair("localhost")
|
|
if err != nil {
|
|
log.Info("error generating certificates", err)
|
|
return
|
|
}
|
|
err = certificates.WriteCertsToFile("./cert.pem", "./key.pem", cert, key)
|
|
if err != nil {
|
|
log.Info("error saving certificates", err)
|
|
return
|
|
}
|
|
}
|
|
|
|
cer, err = tls.LoadX509KeyPair("./cert.pem", "./key.pem")
|
|
if err != nil {
|
|
log.Info("error loading certificates", err)
|
|
return
|
|
}
|
|
|
|
tlsc := tls.Config{
|
|
Certificates: []tls.Certificate{cer},
|
|
MinVersion: tls.VersionTLS12,
|
|
}
|
|
|
|
listener, err := tls.Listen("tcp", "localhost:1965", &tlsc)
|
|
if err != nil {
|
|
log.Info(err)
|
|
return
|
|
}
|
|
|
|
for {
|
|
conn, err := listener.Accept()
|
|
if err != nil {
|
|
log.Debug(err.Error())
|
|
continue
|
|
}
|
|
|
|
go handleConnection(log, conn, handlers.NewFileHandler("./root/"))
|
|
}
|
|
}
|