Debian Codegraph @

httphandler.go

raw
1 package desync
2
3 import (
4 "bytes"
5 "crypto/subtle"
6 "fmt"
7 "io"
8 "net/http"
9 "os"
10 "path"
11 "strings"
12
13 "github.com/pkg/errors"
14 )
15
16 // HTTPHandler is the server-side handler for a HTTP chunk store.
17 type HTTPHandler struct {
18 HTTPHandlerBase
19 s Store
20 SkipVerifyWrite bool
21
22 // Storage-side of the converters in this case is towards the client
23 converters Converters
24
25 // Chunk file extension, derived from the converters at construction
26 extension string
27 }
28
29 // NewHTTPHandler initializes and returns a new HTTP handler for a chunks server.
30 func NewHTTPHandler(s Store, writable, skipVerifyWrite bool, converters Converters, auth string) http.Handler {
31 return HTTPHandler{HTTPHandlerBase{"chunk", writable, auth}, s, skipVerifyWrite, converters, converters.storageExtension()}
32 }
33
34 func (h HTTPHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
35 if h.authorization != "" && subtle.ConstantTimeCompare([]byte(r.Header.Get("Authorization")), []byte(h.authorization)) != 1 {
36 http.Error(w, "Unauthorized", http.StatusUnauthorized)
37 return
38 }
39 id, err := h.idFromPath(r.URL.Path)
40 if err != nil {
41 http.Error(w, err.Error(), http.StatusBadRequest)
42 return
43 }
44 switch r.Method {
45 case "GET":
46 h.get(id, w)
47 case "HEAD":
48 h.head(id, w)
49 case "PUT":
50 h.put(id, w, r)
51 default:
52 w.WriteHeader(http.StatusMethodNotAllowed)
53 _, _ = w.Write([]byte("only GET, PUT and HEAD are supported"))
54 }
55 }
56
57 func (h HTTPHandler) get(id ChunkID, w http.ResponseWriter) {
58 var b []byte
59 chunk, err := h.s.GetChunk(id)
60 if err == nil {
61 b, err = chunk.Storage(h.converters)
62 }
63 h.HTTPHandlerBase.get(id.String(), b, err, w)
64 }
65
66 func (h HTTPHandler) head(id ChunkID, w http.ResponseWriter) {
67 hasChunk, err := h.s.HasChunk(id)
68 if err != nil {
69 fmt.Fprintf(os.Stderr, "failed to check chunk %s: %s\n", id, err)
70 http.Error(w, "internal server error", http.StatusInternalServerError)
71 return
72 }
73 if hasChunk {
74 w.WriteHeader(http.StatusOK)
75 return
76 }
77 w.WriteHeader(http.StatusNotFound)
78 }
79
80 func (h HTTPHandler) put(id ChunkID, w http.ResponseWriter, r *http.Request) {
81 err := h.HTTPHandlerBase.validateWritable(h.s.String(), w, r)
82 if err != nil {
83 return
84 }
85
86 // The upstream store needs to support writing as well
87 s, ok := h.s.(WriteStore)
88 if !ok {
89 fmt.Fprintf(os.Stderr, "upstream chunk store '%s' does not support writing\n", h.s)
90 http.Error(w, "upstream chunk store does not support writing", http.StatusBadRequest)
91 return
92 }
93
94 // Read the raw chunk data into memory
95 b := new(bytes.Buffer)
96 if _, err := io.Copy(b, r.Body); err != nil {
97 fmt.Fprintf(os.Stderr, "failed to read chunk %s from client: %s\n", id, err)
98 http.Error(w, "failed to read request body", http.StatusInternalServerError)
99 return
100 }
101
102 // Turn it into a chunk, and validate the ID unless verification is disabled
103 chunk, err := NewChunkFromStorage(id, b.Bytes(), h.converters, h.SkipVerifyWrite)
104 if err != nil {
105 http.Error(w, err.Error(), http.StatusBadRequest)
106 return
107 }
108
109 // Store it upstream
110 if err := s.StoreChunk(chunk); err != nil {
111 fmt.Fprintf(os.Stderr, "failed to store chunk %s: %s\n", id, err)
112 http.Error(w, "internal server error", http.StatusInternalServerError)
113 return
114 }
115 w.WriteHeader(http.StatusOK)
116 }
117
118 func (h HTTPHandler) idFromPath(p string) (ChunkID, error) {
119 ext := h.extension
120 if !strings.HasSuffix(p, ext) {
121 return ChunkID{}, errors.New("invalid chunk extension, verify compression and encryption settings")
122 }
123 sID := strings.TrimSuffix(path.Base(p), ext)
124 // Chunk IDs are hex-encoded and never contain a '.'. Any extension left
125 // after trimming means the client requested a chunk in a format this
126 // server doesn't serve. The suffix check above can't catch that when
127 // the server's own extension is empty (uncompressed, unencrypted).
128 if strings.Contains(sID, ".") {
129 return ChunkID{}, fmt.Errorf("requested chunk with an unexpected file extension, this server expects '<chunkid>%s', verify compression and encryption settings", ext)
130 }
131 if len(sID) < 4 {
132 return ChunkID{}, fmt.Errorf("expected format '/<prefix>/<chunkid>%s", ext)
133 }
134
135 // Make sure the prefix does match the first characters of the ID.
136 if p != path.Join("/", sID[0:4], sID+ext) {
137 return ChunkID{}, fmt.Errorf("expected format '/<prefix>/<chunkid>%s", ext)
138 }
139 return ChunkIDFromString(sID)
140 }