aboutsummaryrefslogtreecommitdiff
path: root/handler.go
blob: aaab9eb020a86ded4012330a3859f41f36045fff (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
package main

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

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

type GeminiError struct {
	Err    error
	Status int
}

func (e GeminiError) Error() string {
	return e.Err.Error()
}

type MainHandler struct {
	source string
}

func (h MainHandler) 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 MainHandler) isFile(path string) bool {
	fileInfo, err := os.Stat(path)
	if err != nil {
		return false
	}

	return fileInfo.Mode().IsRegular()
}

func (h MainHandler) 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 MainHandler) 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{ge.Status, ge.Error(), nil}
	}

	return gemini.Response{gemini.StatusTemporaryFailure, err.Error(), nil}
}

func (h MainHandler) 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{gemini.StatusSuccess, "text/gemini", file}
}