|
1 | 1 | package renderer
|
2 | 2 |
|
3 | 3 | import (
|
| 4 | + "bytes" |
4 | 5 | "errors"
|
5 |
| - "io/ioutil" |
| 6 | + "io" |
6 | 7 | "mime"
|
7 | 8 | "strings"
|
| 9 | + "time" |
8 | 10 |
|
9 | 11 | "github.com/makeworld-the-better-one/amfora/structs"
|
10 | 12 | "github.com/makeworld-the-better-one/go-gemini"
|
| 13 | + "github.com/spf13/viper" |
11 | 14 | "golang.org/x/text/encoding/ianaindex"
|
12 | 15 | )
|
13 | 16 |
|
| 17 | +var ErrTooLarge = errors.New("page content would be too large") |
| 18 | +var ErrTimedOut = errors.New("page download timed out") |
| 19 | + |
14 | 20 | // isUTF8 returns true for charsets that are compatible with UTF-8 and don't need to be decoded.
|
15 | 21 | func isUTF8(charset string) bool {
|
16 | 22 | utfCharsets := []string{"", "utf-8", "us-ascii"}
|
@@ -53,11 +59,27 @@ func MakePage(url string, res *gemini.Response, width, leftMargin int) (*structs
|
53 | 59 | return nil, errors.New("not valid content for a Page")
|
54 | 60 | }
|
55 | 61 |
|
56 |
| - rawText, err := ioutil.ReadAll(res.Body) // TODO: Don't use all memory on large pages |
57 |
| - if err != nil { |
| 62 | + buf := new(bytes.Buffer) |
| 63 | + go func() { |
| 64 | + time.Sleep(time.Duration(viper.GetInt("a-general.page_max_time")) * time.Second) |
| 65 | + res.Body.Close() |
| 66 | + }() |
| 67 | + |
| 68 | + _, err := io.CopyN(buf, res.Body, viper.GetInt64("a-general.page_max_size")) // 2 MiB max |
| 69 | + res.Body.Close() |
| 70 | + rawText := buf.Bytes() |
| 71 | + if err == nil { |
| 72 | + // Content was larger than 2 MiB |
| 73 | + return nil, ErrTooLarge |
| 74 | + } else if err != io.EOF { |
| 75 | + if strings.HasSuffix(err.Error(), "use of closed network connection") { |
| 76 | + // Timed out |
| 77 | + return nil, ErrTimedOut |
| 78 | + } |
| 79 | + // Some other error |
58 | 80 | return nil, err
|
59 | 81 | }
|
60 |
| - res.Body.Close() |
| 82 | + // Otherwise, the error is EOF, which is what we want. |
61 | 83 |
|
62 | 84 | mediatype, params, _ := mime.ParseMediaType(res.Meta)
|
63 | 85 |
|
|
0 commit comments