aboutsummaryrefslogtreecommitdiff
path: root/handler.go
blob: 1f5fbeab4a984622afe7570ecb5b278b31507230 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
package main

import (
	"fmt"
	"log"
	"net/url"
	"os"
	"path/filepath"
	"strings"

	gemini "git.sr.ht/~yotam/go-gemini"
)

// GeminiError wrap the standard Go error with a Gemini status code
type GeminiError struct {
	Err    error
	Status int
}

// Error return the string of the inner error to fulfill the error interface
func (e GeminiError) Error() string {
	return e.Err.Error()
}

// Handler is the main handler of the server
type Handler struct {
	source string
}

func (h Handler) urlAbsPath(rawURL string) (string, error) {
	u, err := url.Parse(rawURL)
	if err != nil {
		return "", GeminiError{err, gemini.StatusBadRequest}
	}

	itemPath, err := filepath.Abs(filepath.Join(h.source, u.Path))
	if err != nil {
		return "", GeminiError{err, gemini.StatusTemporaryFailure}
	}

	if !strings.HasPrefix(itemPath, h.source) {
		return "", GeminiError{fmt.Errorf("Permission Denied"), gemini.StatusBadRequest}
	}

	return itemPath, nil
}

func (h Handler) isFile(path string) bool {
	fileInfo, err := os.Stat(path)
	if err != nil {
		return false
	}

	return fileInfo.Mode().IsRegular()
}

func (h Handler) getFilePath(rawURL string) (string, error) {
	itemPath, err := h.urlAbsPath(rawURL)
	if err != nil {
		return "", err
	}

	if h.isFile(itemPath) {
		return itemPath, nil
	}

	indexPath := filepath.Join(itemPath, "index.gemi")
	if h.isFile(indexPath) {
		return indexPath, nil
	}

	return "", GeminiError{fmt.Errorf("File Not Found"), gemini.StatusNotFound}
}

func (h Handler) errorResponse(err error) gemini.Response {
	if err == nil {
		panic("nil error is not a valid parameter")
	}

	if ge, ok := err.(GeminiError); ok {
		return gemini.Response{Status: ge.Status, Meta: ge.Error(), Body: nil}
	}

	return gemini.Response{Status: gemini.StatusTemporaryFailure, Meta: err.Error(), Body: nil}
}

// Handle implement the gemini.Handler interface by serving files from a given source directory
func (h Handler) Handle(r gemini.Request) gemini.Response {
	itemPath, err := h.getFilePath(r.URL)
	if err != nil {
		return h.errorResponse(err)
	}

	log.Println("Serving file from", itemPath)

	file, err := os.Open(itemPath)
	if err != nil {
		return h.errorResponse(err)
	}

	return gemini.Response{Status: gemini.StatusSuccess, Meta: "text/gemini", Body: file}
}