Skip to content

Commit

Permalink
limit the size of the response packet to 10MB
Browse files Browse the repository at this point in the history
  • Loading branch information
mmsqe committed Feb 14, 2023
1 parent 7f3d7e6 commit 667a408
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 1 deletion.
4 changes: 3 additions & 1 deletion rpc/errors.go
Expand Up @@ -61,12 +61,14 @@ const (
errcodeDefault = -32000
errcodeNotificationsUnsupported = -32001
errcodeTimeout = -32002
errcodeResponseTooLarge = -32003
errcodePanic = -32603
errcodeMarshalError = -32603
)

const (
errMsgTimeout = "request timed out"
errMsgTimeout = "request timed out"
errMsgResponseTooLarge = "response too large"
)

type methodNotFoundError struct{ method string }
Expand Down
23 changes: 23 additions & 0 deletions rpc/handler.go
Expand Up @@ -149,6 +149,21 @@ func (b *batchCallBuffer) timeout(ctx context.Context, conn jsonWriter) {
b.doWrite(ctx, conn, true)
}

// responseTooLarge sends the responses added so far. For the remaining unanswered call
// messages, it sends a response too large error response.
func (b *batchCallBuffer) responseTooLarge(ctx context.Context, conn jsonWriter) {
b.mutex.Lock()
defer b.mutex.Unlock()

for _, msg := range b.calls {
if !msg.isNotification() {
resp := msg.errorResponse(&internalServerError{errcodeResponseTooLarge, errMsgResponseTooLarge})
b.resp = append(b.resp, resp)
}
}
b.doWrite(ctx, conn, true)
}

// doWrite actually writes the response.
// This assumes b.mutex is held.
func (b *batchCallBuffer) doWrite(ctx context.Context, conn jsonWriter, isErrorResponse bool) {
Expand Down Expand Up @@ -211,6 +226,8 @@ func (h *handler) handleBatch(msgs []*jsonrpcMessage) {
})
}

resBytes := 0
maxBytes := 10 * 1000 * 1000
for {
// No need to handle rest of calls if timed out.
if cp.ctx.Err() != nil {
Expand All @@ -222,6 +239,12 @@ func (h *handler) handleBatch(msgs []*jsonrpcMessage) {
}
resp := h.handleCallMsg(cp, msg)
callBuffer.pushResponse(resp)
if resp != nil {
if resBytes += len(resp.Result); resBytes > maxBytes {
callBuffer.responseTooLarge(cp.ctx, h.conn)
break
}
}
}
if timer != nil {
timer.Stop()
Expand Down

0 comments on commit 667a408

Please sign in to comment.