/
fs.go
317 lines (266 loc) · 7.8 KB
/
fs.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
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
/*
* Copyright (c) 2013-2018 Amahi
*
* This file is part of Amahi.
*
* Amahi is free software released under the GNU GPL v3 license.
* See the LICENSE file accompanying this distribution.
*/
package main
import (
"crypto/tls"
"github.com/fsnotify/fsnotify"
// this is required for the side effect that it will register sha384/512 algorithms.
// should not be needed in the future https://codereview.appspot.com/87670045/
_ "crypto/sha512"
"errors"
"flag"
"fmt"
"github.com/amahi/go-metadata"
"golang.org/x/net/http2"
"hda_api_key"
"io/ioutil"
"math/rand"
"net"
"net/http"
"net/http/httputil"
"os"
"os/signal"
"runtime"
"strconv"
"strings"
"time"
)
// DANGER DANGER DANGER
// compile-time only options in case we need to disable checking the certs or https
const DisableCertChecking = false
const DisableHttps = false
const VERSION = "2.3"
var noDelete = false
var noUpload = false
// watcher for watching changes in files
var watcher *fsnotify.Watcher
// profiling info
// func init() { go func() { http.ListenAndServe(":4242", nil) }() }
func main() {
defer panicHandler()
setup()
var dbg = 1
var http2Debug = false
var apiKeyFlag = ""
var rootDir = ""
var localAddr = ""
var relayHost = PFE_HOST
var relayPort = PFE_PORT
var isDemo = false
// Parse the program inputs
if !PRODUCTION {
flag.IntVar(&dbg, "d", 1, "print debug information, 1 = nothing printed and 5 = print everything")
flag.BoolVar(&http2Debug, "h2", false, "HTTP2 debug")
flag.StringVar(&apiKeyFlag, "k", "", "session token used by pfe")
flag.StringVar(&rootDir, "r", "", "Use the directories in this directory as shares, instead of the registered HDA shares")
flag.StringVar(&localAddr, "l", "", "Use this as the local address of the HDA, or look it up")
flag.StringVar(&relayHost, "pfe", PFE_HOST, "address of the pfe")
flag.StringVar(&relayPort, "pfe-port", PFE_PORT, "port the pfe is using")
flag.BoolVar(&noDelete, "nd", false, "ignore delete requests silently")
flag.BoolVar(&noUpload, "nu", false, "ignore upload requests silently")
flag.BoolVar(&noBuffer, "nb", false, "ignore buffer logging silently")
}
flag.Parse()
if rootDir != "" {
isDemo = true
}
apiKey := ""
if PRODUCTION || (!PRODUCTION && (apiKeyFlag == "")) {
// no command line override - get it from the db
key, err := hda_api_key.HDA_API_key(MYSQL_CREDENTIALS)
if err != nil {
cleanQuit(2, "Amahi API key was not found")
}
apiKey = key
} else {
apiKey = apiKeyFlag
}
if dbg < 1 || dbg > 5 {
flag.PrintDefaults()
return
}
debugLevel(dbg)
if noDelete {
fmt.Printf("NOTICE: running without deleting content!\n")
}
if noUpload {
fmt.Printf("NOTICE: running without uploading content!\n")
}
initializeLogging(LOGFILE, splitFile, noBuffer)
metadata, err := metadata.Init(100000, METADATA_FILE, TMDB_API_KEY, TVRAGE_API_KEY, TVDB_API_KEY)
if err != nil {
fmt.Printf("Error initializing metadata library\n")
os.Remove(PID_FILE)
os.Exit(1)
}
service, err := NewMercuryFSService(rootDir, localAddr, isDemo)
if err != nil {
fmt.Printf("Error making service (%s, %s): %s\n", rootDir, localAddr, err.Error())
os.Remove(PID_FILE)
os.Exit(1)
}
// start ONE delayed, background metadata prefill of the cache
service.metadata = metadata
go service.Shares.startMetadataPrefill(metadata)
watcher, _ = fsnotify.NewWatcher()
defer watcher.Close()
go service.Shares.createThumbnailCache()
//log("Amahi Anywhere service v%s", VERSION)
logging.Info("Amahi Anywhere service v%s", VERSION)
debug(4, "using api-key %s", apiKey)
if http2Debug {
http2.VerboseLogs = true
}
runtime.GOMAXPROCS(1000)
go service.startLocalServer()
// Continually connect to the proxy and listen for requests
// Reconnect if there is an error
for {
conn, err := contactPfe(relayHost, relayPort, apiKey, service)
if err != nil {
//log("Error contacting the proxy.")
logging.Error("Error contacting the proxy.")
debug(2, "Error contacting the proxy: %s", err)
} else {
err = service.StartServing(conn)
if err != nil {
//log("Error serving requests")
logging.Error("Error serving requests")
debug(2, "Error in StartServing: %s", err)
}
}
// reconnect fairly quickly, with some randomness
sleepTime := time.Duration(2000 + rand.Intn(2000))
time.Sleep(sleepTime * time.Millisecond)
}
os.Remove(PID_FILE)
}
// connect to the proxy and send a POST request with the api-key
func contactPfe(relayHost, relayPort, apiKey string, service *MercuryFsService) (net.Conn, error) {
relayLocation := relayHost + ":" + relayPort
//log("Contacting Relay at: " + relayLocation)
logging.Info("Contacting Relay at: " + relayLocation)
addr, err := net.ResolveTCPAddr("tcp", relayLocation)
if err != nil {
debug(2, "Error with ResolveTCPAddr: %s", err)
return nil, err
}
tcpConn, err := net.DialTCP("tcp", nil, addr)
if err != nil {
debug(2, "Error with initial DialTCP: %s", err)
return nil, err
}
tcpConn.SetKeepAlive(true)
tcpConn.SetLinger(0)
service.info.relay_addr = relayLocation
service.TLSConfig = &tls.Config{ServerName: relayHost}
if DisableCertChecking {
warning := "WARNING WARNING WARNING: running without checking TLS certs!!"
logging.Warning(warning)
logging.Warning(warning)
logging.Warning(warning)
fmt.Println(warning)
fmt.Println(warning)
fmt.Println(warning)
service.TLSConfig = &tls.Config{InsecureSkipVerify: true}
}
// Send the api-key
buf := strings.NewReader(service.info.to_json())
request, err := http.NewRequest("PUT", "https://"+relayLocation+"/fs", buf)
if err != nil {
debug(2, "Error creating NewRequest:", err)
return nil, err
}
request.Header.Add("Api-Key", apiKey)
request.Header.Add("Authorization", fmt.Sprintf("Token %s", SECRET_TOKEN))
rawRequest, _ := httputil.DumpRequest(request, true)
debug(5, "%s", rawRequest)
var client *httputil.ClientConn
if DisableHttps {
warning := "WARNING WARNING: running without TLS!!"
logging.Warning(warning)
fmt.Println(warning)
conn := tcpConn
client = httputil.NewClientConn(conn, nil)
} else {
conn := tls.Client(tcpConn, service.TLSConfig)
client = httputil.NewClientConn(conn, nil)
}
response, err := client.Do(request)
if err != nil {
debug(2, "Error writing to connection with Do: %s", err)
return nil, err
}
if response.StatusCode != 200 {
msg := fmt.Sprintf("Got an error response: %s", response.Status)
//log(msg)
logging.Error("Got an error response: %s", response.Status)
return nil, errors.New(msg)
}
//log("Connected to the proxy")
logging.Info("Connected to the proxy")
netCon, _ := client.Hijack()
return netCon, nil
}
// Clean up and quit
func cleanQuit(exitCode int, message string) {
fmt.Println("FATAL:", message)
os.Exit(exitCode)
}
func panicHandler() {
if v := recover(); v != nil {
fmt.Println("PANIC:", v)
}
os.Remove(PID_FILE)
}
func setup() error {
checkPidFile()
c := make(chan os.Signal, 1)
signal.Notify(c, os.Interrupt)
go func() {
for sig := range c {
//log("Exiting with %v", sig)
logging.Info("Exiting with %v", sig)
os.Remove(PID_FILE)
os.Exit(1)
}
}()
return ioutil.WriteFile(PID_FILE, []byte(strconv.Itoa(os.Getpid())), 0666)
}
func checkPidFile() {
if !exists(PID_FILE) {
return
}
stale := false
f, err := os.Open(PID_FILE)
if err == nil {
pid := make([]byte, 25)
c, err := f.Read(pid)
if err == nil {
v, _ := strconv.Atoi(string(pid[:c]))
fmt.Printf("PID: %#v\n", v)
if !exists(fmt.Sprintf("/proc/%s/stat", string(pid[:c]))) {
// the process does not exist. pid file is stale
// note: this works on systems with /proc/
stale = true
os.Remove(PID_FILE)
}
}
}
if stale {
fmt.Printf("PID file exists, but it's stale. Continuing.\n")
} else {
fmt.Printf("PID file exists and process is running. Exiting.\n")
os.Exit(1)
}
}
func exists(path string) bool {
_, err := os.Stat(path)
return err == nil
}