/
server.go
401 lines (315 loc) · 8.56 KB
/
server.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
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
package main
import (
"github.com/nu7hatch/gouuid"
"crypto/md5"
"crypto/sha1"
"fmt"
authlib "github.com/clawio/service-auth/lib"
"github.com/clawio/service-localfsxattr-data/lib"
pb "github.com/clawio/service-localfsxattr-data/proto/propagator"
"github.com/clawio/service-localfsxattr-data/xattr"
log "github.com/sirupsen/logrus"
"github.com/zenazn/goji/web/mutil"
"golang.org/x/net/context"
"google.golang.org/grpc"
"hash"
"hash/adler32"
"io"
"io/ioutil"
"net/http"
"os"
"path"
"strings"
"syscall"
"time"
)
const (
dirPerm = 0755
xattrKeyID = "user.id"
xattrKeyChecksum = "user.checksum"
)
type newServerParams struct {
dataDir string
tmpDir string
checksum string
prop string
sharedSecret string
}
func newServer(p *newServerParams) (*server, error) {
s := &server{}
s.p = p
return s, nil
}
type server struct {
p *newServerParams
}
func (s *server) ServeHTTPC(ctx context.Context, w http.ResponseWriter, r *http.Request) {
traceID, err := getTraceID(r)
if err != nil {
log.Error("cannot get trace ID")
http.Error(w, "", http.StatusInternalServerError)
return
}
reqLogger := log.WithField("trace", traceID)
ctx = newGRPCTraceContext(ctx, traceID)
ctx = NewLogContext(ctx, reqLogger)
reqLogger.Info("request started")
// Time request
reqStart := time.Now()
// Sniff the status and content size for logging
lw := mutil.WrapWriter(w)
defer func() {
// Compute request duration
reqDur := time.Since(reqStart)
// Log access info
reqLogger.WithFields(log.Fields{
"method": r.Method,
"type": "access",
"status_code": lw.Status(),
"duration": reqDur.Seconds(),
"size": lw.BytesWritten(),
}).Infof("%s %s %03d", r.Method, r.URL.String(), lw.Status())
reqLogger.Info("request finished")
}()
if strings.ToUpper(r.Method) == "PUT" {
reqLogger.WithField("op", "upload").Info()
s.authHandler(ctx, lw, r, s.upload)
} else if strings.ToUpper(r.Method) == "GET" {
reqLogger.WithField("op", "download").Info()
s.authHandler(ctx, lw, r, s.download)
} else {
w.WriteHeader(http.StatusNotFound)
return
}
}
func (s *server) upload(ctx context.Context, w http.ResponseWriter, r *http.Request) {
log := MustFromLogContext(ctx)
p := lib.MustFromContext(ctx)
pp := s.getPhysicalPath(p)
log.Infof("physical path is %s", pp)
tmpFn, tmpFile, err := s.tmpFile()
if err != nil {
log.Error(err)
http.Error(w, "", http.StatusInternalServerError)
return
}
log.Infof("created tmp file %s", tmpFn)
var mw io.Writer
var hasher hash.Hash
var isChecksumed bool
var computedChecksum string
switch s.p.checksum {
case "md5":
hasher = md5.New()
isChecksumed = true
mw = io.MultiWriter(tmpFile, hasher)
case "sha1":
hasher = sha1.New()
isChecksumed = true
mw = io.MultiWriter(tmpFile, hasher)
case "adler32":
hasher = adler32.New()
isChecksumed = true
mw = io.MultiWriter(tmpFile, hasher)
default:
mw = io.MultiWriter(tmpFile)
}
// TODO(labkode) Sometimes ContentLength = -1 because it is a binary
// upload with TransferEncoding: chunked.
// Instead using Copy we shoudl use a LimitedReader with a max file upload
// configuration value.
_, err = io.Copy(mw, r.Body)
if err != nil {
log.Error(err)
http.Error(w, "", http.StatusInternalServerError)
return
}
chk := s.getChecksumInfo(r)
if isChecksumed {
log.Infof("file sent with checksum %s", chk.String())
// checksums are given in hexadecimal format.
computedChecksum = fmt.Sprintf("%x", string(hasher.Sum(nil)))
if chk.Type == s.p.checksum && chk.Type != "" {
isCorrupted := computedChecksum != chk.Sum
if isCorrupted {
log.Errorf("corrupted file. expected %s and got %s",
s.p.checksum+":"+computedChecksum, chk.Sum)
http.Error(w, "", http.StatusPreconditionFailed)
return
}
}
}
log.Infof("copied r.Body into tmp file %s", tmpFn)
err = tmpFile.Close()
if err != nil {
log.Error(err)
http.Error(w, "", http.StatusInternalServerError)
return
}
log.Infof("closed tmp file %s", tmpFn)
resourceID, err := getIDFromPath(pp)
if err != nil {
log.Error(err)
http.Error(w, "", http.StatusInternalServerError)
return
}
err = xattr.SetXAttr(tmpFn, xattrKeyID, []byte(resourceID), xattr.XAttrCreate)
if err != nil {
log.Error(err)
http.Error(w, "", http.StatusInternalServerError)
return
}
log.Infof("resource id %s set for path %s in xattr %s", resourceID, pp, xattrKeyID)
if isChecksumed {
err = xattr.SetXAttr(tmpFn, xattrKeyChecksum, []byte(s.p.checksum+":"+computedChecksum), xattr.XAttrCreate)
if err != nil {
log.Error(err)
http.Error(w, "", http.StatusInternalServerError)
return
}
}
log.Infof("checksum %s set for path %s in xattr %s", computedChecksum, pp, xattrKeyChecksum)
if err = os.Rename(tmpFn, pp); err != nil {
log.Error(err)
http.Error(w, "", http.StatusInternalServerError)
return
}
log.Infof("renamed tmp file %s to %s", tmpFn, pp)
con, err := grpc.Dial(s.p.prop, grpc.WithInsecure())
if err != nil {
log.Error(err)
http.Error(w, "", http.StatusInternalServerError)
return
}
defer con.Close()
log.Infof("created connection to %s", s.p.prop)
client := pb.NewPropClient(con)
in := &pb.PutReq{}
in.Path = p
in.AccessToken = authlib.MustFromTokenContext(ctx)
_, err = client.Put(ctx, in)
if err != nil {
log.Error(err)
http.Error(w, "", http.StatusInternalServerError)
return
}
log.Infof("saved path %s into %s", p, s.p.prop)
w.WriteHeader(http.StatusCreated)
}
func (s *server) download(ctx context.Context, w http.ResponseWriter, r *http.Request) {
log := MustFromLogContext(ctx)
p := lib.MustFromContext(ctx)
pp := s.getPhysicalPath(p)
log.Infof("physical path is %s", pp)
fd, err := os.Open(pp)
if err == syscall.ENOENT {
log.Error(err.Error())
http.Error(w, "", http.StatusNotFound)
return
}
if err != nil {
log.Error(err)
http.Error(w, "", http.StatusInternalServerError)
return
}
log.Infof("opened %s", pp)
info, err := fd.Stat()
if err != nil {
log.Error(err)
http.Error(w, "", http.StatusInternalServerError)
return
}
log.Infof("stated %s got size %d", pp, info.Size())
if info.IsDir() {
log.Errorf("%s is a directory", pp)
http.Error(w, "", http.StatusBadRequest)
return
}
defer fd.Close()
_, err = io.Copy(w, fd)
if err != nil {
log.Error(err)
http.Error(w, "", http.StatusInternalServerError)
return
}
log.Infof("copied %s to res.body", pp)
}
func (s *server) authHandler(ctx context.Context, w http.ResponseWriter, r *http.Request,
next func(ctx context.Context, w http.ResponseWriter, r *http.Request)) {
log := MustFromLogContext(ctx)
idt, err := s.getIdentityFromReq(r)
if err != nil {
log.Error(err)
http.Error(w, "", http.StatusUnauthorized)
return
}
p := getPathFromReq(r) // already sanitized
if !isUnderHome(p, idt) {
// TODO use here share service
log.Warnf("%s cannot access %s", *idt, p)
http.Error(w, "", http.StatusForbidden)
return
}
if p == getHome(idt) {
http.Error(w, "", http.StatusMethodNotAllowed)
return
}
log.Infof("path is %s", p)
ctx = authlib.NewContext(ctx, idt)
ctx = lib.NewContext(ctx, p)
ctx = authlib.NewTokenContext(ctx, s.getTokenFromReq(r))
next(ctx, w, r)
}
func (s *server) tmpFile() (string, *os.File, error) {
file, err := ioutil.TempFile(s.p.tmpDir, serviceID)
if err != nil {
return "", nil, err
}
fn := path.Join(path.Clean(file.Name()))
return fn, file, nil
}
func (s *server) getPhysicalPath(p string) string {
return path.Join(s.p.dataDir, path.Clean(p))
}
func (s *server) getTokenFromReq(r *http.Request) string {
var token string
// Look for an Authorization header
if ah := r.Header.Get("Authorization"); ah != "" {
// Should be a bearer token
if len(ah) > 6 && strings.ToUpper(ah[0:6]) == "BEARER" {
token = ah[7:]
}
}
if token == "" {
// Look for "auth_token" parameter
r.ParseMultipartForm(10e6)
if tokStr := r.Form.Get("access_token"); tokStr != "" {
token = tokStr
}
}
return token
}
func (s *server) getIdentityFromReq(r *http.Request) (*authlib.Identity, error) {
return authlib.ParseToken(s.getTokenFromReq(r), s.p.sharedSecret)
}
func getIDFromPath(path string) ([]byte, error) {
id, err := xattr.GetXAttr(path, xattrKeyID)
if err != nil {
if err == syscall.ENODATA || err == syscall.ENOENT {
rawUUID, err := uuid.NewV4()
if err != nil {
return []byte(""), err
}
return []byte(rawUUID.String()), nil
}
return []byte(""), err
}
if len(id) == 0 { // xattr is empty but is set
rawUUID, err := uuid.NewV4()
if err != nil {
return []byte(""), err
}
id = []byte(rawUUID.String())
}
return id, nil
}