package desync import ( "bytes" "crypto/subtle" "fmt" "io" "net/http" "os" "path" "strings" "github.com/pkg/errors" ) // HTTPHandler is the server-side handler for a HTTP chunk store. type HTTPHandler struct { HTTPHandlerBase s Store SkipVerifyWrite bool // Storage-side of the converters in this case is towards the client converters Converters // Chunk file extension, derived from the converters at construction extension string } // NewHTTPHandler initializes and returns a new HTTP handler for a chunks server. func NewHTTPHandler(s Store, writable, skipVerifyWrite bool, converters Converters, auth string) http.Handler { return HTTPHandler{HTTPHandlerBase{"chunk", writable, auth}, s, skipVerifyWrite, converters, converters.storageExtension()} } func (h HTTPHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { if h.authorization != "" && subtle.ConstantTimeCompare([]byte(r.Header.Get("Authorization")), []byte(h.authorization)) != 1 { http.Error(w, "Unauthorized", http.StatusUnauthorized) return } id, err := h.idFromPath(r.URL.Path) if err != nil { http.Error(w, err.Error(), http.StatusBadRequest) return } switch r.Method { case "GET": h.get(id, w) case "HEAD": h.head(id, w) case "PUT": h.put(id, w, r) default: w.WriteHeader(http.StatusMethodNotAllowed) _, _ = w.Write([]byte("only GET, PUT and HEAD are supported")) } } func (h HTTPHandler) get(id ChunkID, w http.ResponseWriter) { var b []byte chunk, err := h.s.GetChunk(id) if err == nil { b, err = chunk.Storage(h.converters) } h.HTTPHandlerBase.get(id.String(), b, err, w) } func (h HTTPHandler) head(id ChunkID, w http.ResponseWriter) { hasChunk, err := h.s.HasChunk(id) if err != nil { fmt.Fprintf(os.Stderr, "failed to check chunk %s: %s\n", id, err) http.Error(w, "internal server error", http.StatusInternalServerError) return } if hasChunk { w.WriteHeader(http.StatusOK) return } w.WriteHeader(http.StatusNotFound) } func (h HTTPHandler) put(id ChunkID, w http.ResponseWriter, r *http.Request) { err := h.HTTPHandlerBase.validateWritable(h.s.String(), w, r) if err != nil { return } // The upstream store needs to support writing as well s, ok := h.s.(WriteStore) if !ok { fmt.Fprintf(os.Stderr, "upstream chunk store '%s' does not support writing\n", h.s) http.Error(w, "upstream chunk store does not support writing", http.StatusBadRequest) return } // Read the raw chunk data into memory b := new(bytes.Buffer) if _, err := io.Copy(b, r.Body); err != nil { fmt.Fprintf(os.Stderr, "failed to read chunk %s from client: %s\n", id, err) http.Error(w, "failed to read request body", http.StatusInternalServerError) return } // Turn it into a chunk, and validate the ID unless verification is disabled chunk, err := NewChunkFromStorage(id, b.Bytes(), h.converters, h.SkipVerifyWrite) if err != nil { http.Error(w, err.Error(), http.StatusBadRequest) return } // Store it upstream if err := s.StoreChunk(chunk); err != nil { fmt.Fprintf(os.Stderr, "failed to store chunk %s: %s\n", id, err) http.Error(w, "internal server error", http.StatusInternalServerError) return } w.WriteHeader(http.StatusOK) } func (h HTTPHandler) idFromPath(p string) (ChunkID, error) { ext := h.extension if !strings.HasSuffix(p, ext) { return ChunkID{}, errors.New("invalid chunk extension, verify compression and encryption settings") } sID := strings.TrimSuffix(path.Base(p), ext) // Chunk IDs are hex-encoded and never contain a '.'. Any extension left // after trimming means the client requested a chunk in a format this // server doesn't serve. The suffix check above can't catch that when // the server's own extension is empty (uncompressed, unencrypted). if strings.Contains(sID, ".") { return ChunkID{}, fmt.Errorf("requested chunk with an unexpected file extension, this server expects '%s', verify compression and encryption settings", ext) } if len(sID) < 4 { return ChunkID{}, fmt.Errorf("expected format '//%s", ext) } // Make sure the prefix does match the first characters of the ID. if p != path.Join("/", sID[0:4], sID+ext) { return ChunkID{}, fmt.Errorf("expected format '//%s", ext) } return ChunkIDFromString(sID) }