| 1 | package bare |
| 2 | |
| 3 | import ( |
| 4 | "errors" |
| 5 | "io" |
| 6 | ) |
| 7 | |
| 8 | var ( |
| 9 | maxUnmarshalBytes uint64 = 1024 * 1024 * 32 /* 32 MiB */ |
| 10 | maxArrayLength uint64 = 1024 * 4 /* 4096 elements */ |
| 11 | maxMapSize uint64 = 1024 |
| 12 | ) |
| 13 | |
| 14 | // MaxUnmarshalBytes sets the maximum size of a message decoded by unmarshal. |
| 15 | // By default, this is set to 32 MiB. |
| 16 | func MaxUnmarshalBytes(bytes uint64) { |
| 17 | maxUnmarshalBytes = bytes |
| 18 | } |
| 19 | |
| 20 | // MaxArrayLength sets maximum number of elements in array. Defaults to 4096 elements |
| 21 | func MaxArrayLength(length uint64) { |
| 22 | maxArrayLength = length |
| 23 | } |
| 24 | |
| 25 | // MaxMapSize sets maximum size of map. Defaults to 1024 key/value pairs |
| 26 | func MaxMapSize(size uint64) { |
| 27 | maxMapSize = size |
| 28 | } |
| 29 | |
| 30 | // Use MaxUnmarshalBytes to prevent this error from occuring on messages which |
| 31 | // are large by design. |
| 32 | var ErrLimitExceeded = errors.New("Maximum message size exceeded") |
| 33 | |
| 34 | // Identical to io.LimitedReader, except it returns our custom error instead of |
| 35 | // EOF if the limit is reached. |
| 36 | type limitedReader struct { |
| 37 | R io.Reader |
| 38 | N uint64 |
| 39 | } |
| 40 | |
| 41 | func (l *limitedReader) Read(p []byte) (n int, err error) { |
| 42 | if l.N <= 0 { |
| 43 | return 0, ErrLimitExceeded |
| 44 | } |
| 45 | if uint64(len(p)) > l.N { |
| 46 | p = p[0:l.N] |
| 47 | } |
| 48 | n, err = l.R.Read(p) |
| 49 | l.N -= uint64(n) |
| 50 | return |
| 51 | } |
| 52 | |
| 53 | func newLimitedReader(r io.Reader) *limitedReader { |
| 54 | return &limitedReader{r, maxUnmarshalBytes} |
| 55 | } |