From: Matt Joiner <anacrolix@gmail.com>
Date: Tue, 6 Oct 2020 23:22:55 +0000 (+1100)
Subject: Fix webseed requests for non-trivial path components
X-Git-Tag: v1.17.1^0
X-Git-Url: http://www.git.stargrave.org/?a=commitdiff_plain;h=d3daaaf75a469104abf0da1542e96f47bb9701f0;p=btrtrc.git

Fix webseed requests for non-trivial path components
---

diff --git a/webseed/client.go b/webseed/client.go
index 0b98b931..19153dc7 100644
--- a/webseed/client.go
+++ b/webseed/client.go
@@ -109,7 +109,7 @@ func readRequestPartResponses(parts []requestPart) ([]byte, error) {
 	for _, part := range parts {
 		err := recvPartResult(&buf, part)
 		if err != nil {
-			return buf.Bytes(), err
+			return buf.Bytes(), fmt.Errorf("reading %q at %q: %w", part.req.URL, part.req.Header.Get("Range"), err)
 		}
 	}
 	return buf.Bytes(), nil
diff --git a/webseed/misc.go b/webseed/misc.go
index 140bc23b..466c664a 100644
--- a/webseed/misc.go
+++ b/webseed/misc.go
@@ -3,6 +3,7 @@ package webseed
 import (
 	"fmt"
 	"net/http"
+	"net/url"
 	"path"
 	"strings"
 
@@ -10,12 +11,21 @@ import (
 )
 
 // Creates a request per BEP 19.
-func NewRequest(url string, fileIndex int, info *metainfo.Info, offset, length int64) (*http.Request, error) {
+func NewRequest(url_ string, fileIndex int, info *metainfo.Info, offset, length int64) (*http.Request, error) {
 	fileInfo := info.UpvertedFiles()[fileIndex]
-	if strings.HasSuffix(url, "/") {
-		url += path.Join(append([]string{info.Name}, fileInfo.Path...)...)
+	if strings.HasSuffix(url_, "/") {
+		// BEP specifies that we append the file path. We need to escape each component of the path
+		// for things like spaces and '#'.
+		url_ += path.Join(
+			func() (ret []string) {
+				for _, comp := range append([]string{info.Name}, fileInfo.Path...) {
+					ret = append(ret, url.PathEscape(comp))
+				}
+				return
+			}()...,
+		)
 	}
-	req, err := http.NewRequest(http.MethodGet, url, nil)
+	req, err := http.NewRequest(http.MethodGet, url_, nil)
 	if err != nil {
 		return nil, err
 	}