-
Notifications
You must be signed in to change notification settings - Fork 0
/
webdav.go
177 lines (153 loc) · 4.33 KB
/
webdav.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
package main
import (
_ "embed"
"net/http"
"path/filepath"
"strings"
"sync"
"github.com/Jipok/webdavWithPATCH"
"github.com/anacrolix/torrent"
"github.com/rs/zerolog/log"
"golang.org/x/net/webdav"
)
//go:embed webdavjs.html
var WebdavjsHTML []byte
type handler struct {
tfs TFS
handler *webdavWithPATCH.Handler
}
type WebDAVServer struct {
addr string // Address to listen on, e.g. "0.0.0.0:8080"
smux *http.ServeMux
handlers map[string]*handler
mu sync.RWMutex
}
func NewWebDAVServer(addr string, secret string) *WebDAVServer {
WDSrv := WebDAVServer{
addr: addr,
smux: http.NewServeMux(),
}
WDSrv.handlers = make(map[string]*handler) // URL prefix -> Handler
mainHandler := &webdavWithPATCH.Handler{
Handler: webdav.Handler{
FileSystem: webdav.Dir(TorrentsDir),
LockSystem: webdav.NewMemLS(),
Prefix: secret,
},
}
WDSrv.smux.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) {
if !strings.HasPrefix(req.URL.Path, secret) {
return
}
// Basic Auth
if Username != "" {
req_username, req_password, ok := req.BasicAuth()
log.Debug().
Str("IP", req.RemoteAddr).
Str("username", req_username).
Str("password", req_password).
Bool("ok", ok).
Msg("BasicAuth Request")
if !ok {
w.Header().Set("WWW-Authenticate", `Basic realm="Restricted"`)
w.WriteHeader(http.StatusUnauthorized)
return
}
if req_username != Username || req_password != Password {
w.WriteHeader(http.StatusUnauthorized)
return
}
}
method := req.Method
log.Debug().Str("URL", req.URL.Path).Str("Method", method).Msg("Web Request")
// Serve fake file
if (method == "GET" || method == "HEAD") && req.URL.Path == filepath.Join(secret, "stats.txt") {
TorrentClient.WriteStatus(w)
return
}
// Try find torrent
WDSrv.mu.RLock()
for prefix, handler := range WDSrv.handlers {
println(req.URL.Path)
println(prefix)
if !strings.HasPrefix(req.URL.Path, prefix) {
continue
}
// In order not to strain the torrent(which seems to change priorities every
// NewReader), we send a request to TFS only if the file is not ready
//
// Since func returns TRUE if file not exists user can work via WebDav as with
// a regular file system. The only differences will be when reading unfinished files.
filename, _ := strings.CutPrefix(req.URL.Path, prefix)
if !handler.tfs.IsFileCompleted(filename) {
log.Debug().Str("url", req.URL.Path).Msg("Streaming torrent content")
handler.ServeHTTP(w, req)
WDSrv.mu.RUnlock()
return
}
log.Debug().Str("Prefix", prefix).Msg("Access to completed torrent content")
}
WDSrv.mu.RUnlock()
// Work as a WebDav or Web server for a regular file system
if method == "GET" && strings.HasSuffix(req.URL.Path, "/") {
if _, err := w.Write(WebdavjsHTML); err != nil {
log.Error().Err(err).Msg("Failed to write index.html")
}
return
}
// Fix web ui
if method == "HEAD" && strings.HasSuffix(req.URL.Path, "/") {
return
}
mainHandler.ServeHTTP(w, req)
})
return &WDSrv
}
func (s *WebDAVServer) Run() {
log.Info().Str("addr", "http://"+s.addr+WebDavPath).Msg("WebDAV server started")
if err := http.ListenAndServe(s.addr, s.smux); err != nil {
panic(err)
}
}
/////////////////////////////////////////////////////////////////////////////////
func NewWebDavHandler(trnt *torrent.Torrent, prefix string) {
prefix = filepath.Join(WebDavPath, prefix)
log.Debug().Str("Prefix", prefix).Msg("New WebDav Handler")
tfs := *NewTFS(trnt)
handler := &handler{
tfs: tfs,
handler: &webdavWithPATCH.Handler{
Handler: webdav.Handler{
FileSystem: tfs,
LockSystem: webdav.NewMemLS(),
Prefix: prefix,
},
},
}
Server.mu.Lock()
Server.handlers[prefix] = handler
Server.mu.Unlock()
}
func (h *handler) ServeHTTP(w http.ResponseWriter, req *http.Request) {
allowedMethods := map[string]bool{
"GET": true,
"OPTIONS": true,
"PROPFIND": true,
"HEAD": true,
}
if !allowedMethods[req.Method] {
w.WriteHeader(http.StatusMethodNotAllowed)
return
}
if req.Method == "GET" && strings.HasSuffix(req.URL.Path, "/") {
if _, err := w.Write(WebdavjsHTML); err != nil {
log.Error().Err(err).Msg("Failed to write index.html")
}
return
}
// Fix web ui
if req.Method == "HEAD" && strings.HasSuffix(req.URL.Path, "/") {
return
}
h.handler.ServeHTTP(w, req)
}