Skip to content

Commit 667a408

Browse files
committed
limit the size of the response packet to 10MB
1 parent 7f3d7e6 commit 667a408

File tree

2 files changed

+26
-1
lines changed

2 files changed

+26
-1
lines changed

rpc/errors.go

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -61,12 +61,14 @@ const (
6161
errcodeDefault = -32000
6262
errcodeNotificationsUnsupported = -32001
6363
errcodeTimeout = -32002
64+
errcodeResponseTooLarge = -32003
6465
errcodePanic = -32603
6566
errcodeMarshalError = -32603
6667
)
6768

6869
const (
69-
errMsgTimeout = "request timed out"
70+
errMsgTimeout = "request timed out"
71+
errMsgResponseTooLarge = "response too large"
7072
)
7173

7274
type methodNotFoundError struct{ method string }

rpc/handler.go

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -149,6 +149,21 @@ func (b *batchCallBuffer) timeout(ctx context.Context, conn jsonWriter) {
149149
b.doWrite(ctx, conn, true)
150150
}
151151

152+
// responseTooLarge sends the responses added so far. For the remaining unanswered call
153+
// messages, it sends a response too large error response.
154+
func (b *batchCallBuffer) responseTooLarge(ctx context.Context, conn jsonWriter) {
155+
b.mutex.Lock()
156+
defer b.mutex.Unlock()
157+
158+
for _, msg := range b.calls {
159+
if !msg.isNotification() {
160+
resp := msg.errorResponse(&internalServerError{errcodeResponseTooLarge, errMsgResponseTooLarge})
161+
b.resp = append(b.resp, resp)
162+
}
163+
}
164+
b.doWrite(ctx, conn, true)
165+
}
166+
152167
// doWrite actually writes the response.
153168
// This assumes b.mutex is held.
154169
func (b *batchCallBuffer) doWrite(ctx context.Context, conn jsonWriter, isErrorResponse bool) {
@@ -211,6 +226,8 @@ func (h *handler) handleBatch(msgs []*jsonrpcMessage) {
211226
})
212227
}
213228

229+
resBytes := 0
230+
maxBytes := 10 * 1000 * 1000
214231
for {
215232
// No need to handle rest of calls if timed out.
216233
if cp.ctx.Err() != nil {
@@ -222,6 +239,12 @@ func (h *handler) handleBatch(msgs []*jsonrpcMessage) {
222239
}
223240
resp := h.handleCallMsg(cp, msg)
224241
callBuffer.pushResponse(resp)
242+
if resp != nil {
243+
if resBytes += len(resp.Result); resBytes > maxBytes {
244+
callBuffer.responseTooLarge(cp.ctx, h.conn)
245+
break
246+
}
247+
}
225248
}
226249
if timer != nil {
227250
timer.Stop()

0 commit comments

Comments
 (0)