+
+var localOrRemoteSignature = regexp.MustCompile(`\+[AR][^\+]*`)
+
+// remoteResponseCacher wraps http.ResponseWriter. It buffers the
+// response data in the provided buffer, writes/touches a copy on a
+// local volume, adds a response header with a locally-signed locator,
+// and finally writes the data through.
+type remoteResponseCacher struct {
+ Locator string
+ Token string
+ Buffer []byte
+ Context context.Context
+ http.ResponseWriter
+ statusCode int
+}
+
+func (rrc *remoteResponseCacher) Write(p []byte) (int, error) {
+ if len(rrc.Buffer)+len(p) > cap(rrc.Buffer) {
+ return 0, errors.New("buffer full")
+ }
+ rrc.Buffer = append(rrc.Buffer, p...)
+ return len(p), nil
+}
+
+func (rrc *remoteResponseCacher) WriteHeader(statusCode int) {
+ rrc.statusCode = statusCode
+}
+
+func (rrc *remoteResponseCacher) Close() error {
+ if rrc.statusCode == 0 {
+ rrc.statusCode = http.StatusOK
+ } else if rrc.statusCode != http.StatusOK {
+ rrc.ResponseWriter.WriteHeader(rrc.statusCode)
+ rrc.ResponseWriter.Write(rrc.Buffer)
+ return nil
+ }
+ _, err := PutBlock(rrc.Context, rrc.Buffer, rrc.Locator[:32])
+ if rrc.Context.Err() != nil {
+ // If caller hung up, log that instead of subsequent/misleading errors.
+ http.Error(rrc.ResponseWriter, rrc.Context.Err().Error(), http.StatusGatewayTimeout)
+ return err
+ }
+ if err == RequestHashError {
+ http.Error(rrc.ResponseWriter, "checksum mismatch in remote response", http.StatusBadGateway)
+ return err
+ }
+ if err, ok := err.(*KeepError); ok {
+ http.Error(rrc.ResponseWriter, err.Error(), err.HTTPCode)
+ return err
+ }
+ if err != nil {
+ http.Error(rrc.ResponseWriter, err.Error(), http.StatusBadGateway)
+ return err
+ }
+
+ unsigned := localOrRemoteSignature.ReplaceAllLiteralString(rrc.Locator, "")
+ signed := SignLocator(unsigned, rrc.Token, time.Now().Add(theConfig.BlobSignatureTTL.Duration()))
+ if signed == unsigned {
+ err = errors.New("could not sign locator")
+ http.Error(rrc.ResponseWriter, err.Error(), http.StatusInternalServerError)
+ return err
+ }
+ rrc.Header().Set("X-Keep-Locator", signed)
+ rrc.ResponseWriter.WriteHeader(rrc.statusCode)
+ _, err = rrc.ResponseWriter.Write(rrc.Buffer)
+ return err
+}