FedP2P/webseed/request.go

70 lines
1.8 KiB
Go
Raw Normal View History

2020-06-01 16:25:45 +08:00
package webseed
import (
"fmt"
"net/http"
"net/url"
2020-06-01 16:25:45 +08:00
"path"
"strings"
"github.com/anacrolix/torrent/metainfo"
)
type PathEscaper func(pathComps []string) string
2022-02-23 15:03:38 +08:00
// Escapes path name components suitable for appending to a webseed URL. This works for converting
// S3 object keys to URLs too.
//
2022-04-26 08:46:01 +08:00
// Contrary to the name, this actually does a QueryEscape, rather than a PathEscape. This works
// better with most S3 providers.
2022-02-23 15:03:38 +08:00
func EscapePath(pathComps []string) string {
2022-04-26 08:46:01 +08:00
return defaultPathEscaper(pathComps)
}
2022-04-26 08:46:01 +08:00
func defaultPathEscaper(pathComps []string) string {
var ret []string
for _, comp := range pathComps {
esc := url.PathEscape(comp)
// S3 incorrectly escapes + in paths to spaces, so we add an extra encoding for that. This
// seems to be handled correctly regardless of whether an endpoint uses query or path
// escaping.
esc = strings.ReplaceAll(esc, "+", "%2B")
ret = append(ret, esc)
}
return path.Join(ret...)
2020-12-21 09:24:24 +08:00
}
func trailingPath(
infoName string,
fileComps []string,
pathEscaper PathEscaper,
) string {
2022-04-26 08:46:01 +08:00
if pathEscaper == nil {
pathEscaper = defaultPathEscaper
}
return pathEscaper(append([]string{infoName}, fileComps...))
2022-02-23 15:03:38 +08:00
}
2020-06-01 16:25:45 +08:00
// Creates a request per BEP 19.
func newRequest(
url_ string, fileIndex int,
info *metainfo.Info,
offset, length int64,
pathEscaper PathEscaper,
) (*http.Request, error) {
2020-06-01 16:25:45 +08:00
fileInfo := info.UpvertedFiles()[fileIndex]
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 '#'.
2022-04-26 08:46:01 +08:00
url_ += trailingPath(info.Name, fileInfo.Path, pathEscaper)
2020-06-01 16:25:45 +08:00
}
req, err := http.NewRequest(http.MethodGet, url_, nil)
2020-06-01 16:25:45 +08:00
if err != nil {
return nil, err
}
if offset != 0 || length != fileInfo.Length {
req.Header.Set("Range", fmt.Sprintf("bytes=%d-%d", offset, offset+length-1))
}
return req, nil
}