/
service.go
228 lines (191 loc) · 5.99 KB
/
service.go
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
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
// package service provides a http handler that reads the path in the request.url and returns
// an xml document that follows the OPDS 1.1 standard
// https://specs.opds.io/opds-1.1.html
package service
import (
"bytes"
"encoding/xml"
"errors"
"fmt"
"log"
"mime"
"net/http"
"net/url"
"os"
"path/filepath"
"strings"
"time"
"github.com/dubyte/dir2opds/opds"
"golang.org/x/tools/blog/atom"
)
func init() {
_ = mime.AddExtensionType(".mobi", "application/x-mobipocket-ebook")
_ = mime.AddExtensionType(".epub", "application/epub+zip")
_ = mime.AddExtensionType(".cbz", "application/x-cbz")
_ = mime.AddExtensionType(".cbr", "application/x-cbr")
_ = mime.AddExtensionType(".fb2", "text/fb2+xml")
_ = mime.AddExtensionType(".pdf", "application/pdf")
}
const (
pathTypeFile = iota
pathTypeDirOfDirs
pathTypeDirOfFiles
)
type OPDS struct {
TrustedRoot string
IsCalibreLibrary bool
}
type IsDirer interface {
IsDir() bool
}
func isFile(e IsDirer) bool {
return !e.IsDir()
}
const navigationType = "application/atom+xml;profile=opds-catalog;kind=navigation"
var TimeNow = timeNowFunc()
// Handler serve the content of a book file or
// returns an Acquisition Feed when the entries are documents or
// returns an Navegation Feed when the entries are other folders
func (s OPDS) Handler(w http.ResponseWriter, req *http.Request) error {
var err error
urlPath, err := url.PathUnescape(req.URL.Path)
if err != nil {
log.Printf("error while serving '%s': %s", req.URL.Path, err)
return err
}
fPath := filepath.Join(s.TrustedRoot, urlPath)
// verifyPath avoid the http transversal by checking the path is under DirRoot
_, err = verifyPath(fPath, s.TrustedRoot)
if err != nil {
log.Printf("fPath %q err: %s", fPath, err)
w.WriteHeader(http.StatusNotFound)
return nil
}
log.Printf("urlPath:'%s'", urlPath)
if _, err := os.Stat(fPath); err != nil {
log.Printf("fPath err: %s", err)
w.WriteHeader(http.StatusNotFound)
return err
}
log.Printf("fPath:'%s'", fPath)
// it's a file just serve the file
if getPathType(fPath) == pathTypeFile {
http.ServeFile(w, req, fPath)
return nil
}
navFeed := s.makeFeed(fPath, req)
var content []byte
// it is an acquisition feed
if getPathType(fPath) == pathTypeDirOfFiles {
acFeed := &opds.AcquisitionFeed{Feed: &navFeed, Dc: "http://purl.org/dc/terms/", Opds: "http://opds-spec.org/2010/catalog"}
content, err = xml.MarshalIndent(acFeed, " ", " ")
w.Header().Add("Content-Type", "application/atom+xml;profile=opds-catalog;kind=acquisition")
} else { // it is a navegation feed
content, err = xml.MarshalIndent(navFeed, " ", " ")
w.Header().Add("Content-Type", "application/atom+xml;profile=opds-catalog;kind=navigation")
}
if err != nil {
log.Printf("error while serving '%s': %s", fPath, err)
return err
}
content = append([]byte(xml.Header), content...)
http.ServeContent(w, req, "feed.xml", TimeNow(), bytes.NewReader(content))
return nil
}
func (s OPDS) makeFeed(fpath string, req *http.Request) atom.Feed {
feedBuilder := opds.FeedBuilder.
ID(req.URL.Path).
Title("Catalog in " + req.URL.Path).
Updated(TimeNow()).
AddLink(opds.LinkBuilder.Rel("start").Href("/").Type(navigationType).Build())
dirEntries, _ := os.ReadDir(fpath)
for _, entry := range dirEntries {
// ignoring files created by calibre
if s.IsCalibreLibrary && (strings.Contains(entry.Name(), ".opf") ||
strings.Contains(entry.Name(), "cover.") ||
strings.Contains(entry.Name(), "metadata.db") ||
strings.Contains(entry.Name(), "metadata_db_prefs_backup.json")) {
continue
}
pathType := getPathType(filepath.Join(fpath, entry.Name()))
feedBuilder = feedBuilder.
AddEntry(opds.EntryBuilder.
ID(req.URL.Path + entry.Name()).
Title(entry.Name()).
AddLink(opds.LinkBuilder.
Rel(getRel(entry.Name(), pathType)).
Title(entry.Name()).
Href(filepath.Join(req.URL.RequestURI(), url.PathEscape(entry.Name()))).
Type(getType(entry.Name(), pathType)).
Build()).
Build())
}
return feedBuilder.Build()
}
func getRel(name string, pathType int) string {
if pathType == pathTypeDirOfFiles || pathType == pathTypeDirOfDirs {
return "subsection"
}
ext := filepath.Ext(name)
if ext == ".png" || ext == ".jpg" || ext == ".jpeg" || ext == ".gif" {
return "http://opds-spec.org/image/thumbnail"
}
// mobi, epub, etc
return "http://opds-spec.org/acquisition"
}
func getType(name string, pathType int) string {
switch pathType {
case pathTypeFile:
return mime.TypeByExtension(filepath.Ext(name))
case pathTypeDirOfFiles:
return "application/atom+xml;profile=opds-catalog;kind=acquisition"
case pathTypeDirOfDirs:
return "application/atom+xml;profile=opds-catalog;kind=navigation"
default:
return mime.TypeByExtension("xml")
}
}
func getPathType(dirpath string) int {
fi, err := os.Stat(dirpath)
if err != nil {
log.Printf("getPathType os.Stat err: %s", err)
}
if isFile(fi) {
return pathTypeFile
}
dirEntries, err := os.ReadDir(dirpath)
if err != nil {
log.Printf("getPathType: readDir err: %s", err)
}
for _, entry := range dirEntries {
if isFile(entry) {
return pathTypeDirOfFiles
}
}
// Directory of directories
return pathTypeDirOfDirs
}
func timeNowFunc() func() time.Time {
t := time.Now()
return func() time.Time { return t }
}
// verify path use a trustedRoot to avoid http transversal
// from https://www.stackhawk.com/blog/golang-path-traversal-guide-examples-and-prevention/
func verifyPath(path, trustedRoot string) (string, error) {
// clean is already used upstream but leaving this
// to keep the functionality of the function as close as possible to the blog.
c := filepath.Clean(path)
// get the canonical path
r, err := filepath.EvalSymlinks(c)
if err != nil {
fmt.Println("Error " + err.Error())
return c, errors.New("unsafe or invalid path specified")
}
if !inTrustedRoot(r, trustedRoot) {
return r, errors.New("unsafe or invalid path specified")
}
return r, nil
}
func inTrustedRoot(path string, trustedRoot string) bool {
return strings.HasPrefix(path, trustedRoot)
}