Skip to content

Commit 2ab4ae5

Browse files
authored
fix(torr): enhance image URL validation in AddTorrentDB and improve CheckImgUrl function (#641)
- update `AddTorrentDB` to only set the poster if the URL is non-empty and valid - refactor `CheckImgUrl` to use a context with a timeout for HTTP requests Signed-off-by: Pavel Pikta <devops@pavelpikta.com>
1 parent 1b86566 commit 2ab4ae5

File tree

2 files changed

+26
-5
lines changed

2 files changed

+26
-5
lines changed

server/torr/dbwrapper.go

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,8 @@ func AddTorrentDB(torr *Torrent) {
3232
} else {
3333
t.Data = torr.Data
3434
}
35-
if utils.CheckImgUrl(torr.Poster) {
35+
36+
if torr.Poster != "" && utils.CheckImgUrl(torr.Poster) {
3637
t.Poster = torr.Poster
3738
}
3839
t.Size = torr.Size
Lines changed: 24 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,15 @@
11
package utils
22

33
import (
4+
"context"
45
"image"
56
_ "image/gif"
67
_ "image/jpeg"
78
_ "image/png"
9+
"io"
810
"net/http"
911
"strings"
12+
"time"
1013

1114
"golang.org/x/image/webp"
1215

@@ -17,20 +20,37 @@ func CheckImgUrl(link string) bool {
1720
if link == "" {
1821
return false
1922
}
20-
resp, err := http.Get(link)
23+
24+
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
25+
defer cancel()
26+
27+
req, err := http.NewRequestWithContext(ctx, "GET", link, nil)
28+
if err != nil {
29+
log.TLogln("Error create request for image:", err)
30+
return false
31+
}
32+
33+
client := &http.Client{
34+
Timeout: 5 * time.Second,
35+
}
36+
37+
resp, err := client.Do(req)
2138
if err != nil {
2239
log.TLogln("Error check image:", err)
2340
return false
2441
}
2542
defer resp.Body.Close()
43+
44+
limitedReader := io.LimitReader(resp.Body, 512*1024)
45+
2646
if strings.HasSuffix(link, ".webp") {
27-
_, err = webp.Decode(resp.Body)
47+
_, err = webp.Decode(limitedReader)
2848
} else {
29-
_, _, err = image.Decode(resp.Body)
49+
_, _, err = image.Decode(limitedReader)
3050
}
3151
if err != nil {
3252
log.TLogln("Error decode image:", err)
3353
return false
3454
}
35-
return err == nil
55+
return true
3656
}

0 commit comments

Comments
 (0)