Skip to content

Commit ec28ced

Browse files
authored
fix: return 413 when the request body exceeds the configured limit (#2785)
`go_read_post` discarded read errors, so PHP saw a truncated `php://input` when Caddy's `request_body max_size` (or any `http.MaxBytesReader`) was exceeded. The request is now rejected with 413 if the error is a `*http.MaxBytesError` and response headers have not been sent yet. This works in classic and worker mode. Fixes #2781
1 parent de3de81 commit ec28ced

10 files changed

Lines changed: 348 additions & 52 deletions

‎context.go‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,8 @@ type frankenPHPContext struct {
3535
scriptFilename string
3636
requestURI string
3737

38+
// Whether the final response headers were already sent
39+
headersWritten bool
3840
// Whether the request is already closed by us
3941
isDone bool
4042
// The client's connection state as of the moment isDone was set. Captured

‎docs/config.md‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -366,6 +366,20 @@ CADDY_GLOBAL_OPTIONS="servers {
366366

367367
You can find more information about this setting in the [Caddy documentation](https://caddyserver.com/docs/caddyfile/options#enable-full-duplex).
368368

369+
### Request body size limit
370+
371+
To limit the size of request bodies, use the [`request_body`](https://caddyserver.com/docs/caddyfile/directives/request_body) directive:
372+
373+
```caddyfile
374+
request_body {
375+
max_size 10MB
376+
}
377+
```
378+
379+
Requests with a larger body get a `413 Request Entity Too Large` response.
380+
If PHP reads the body before the script starts (`POST` requests with a `Content-Type`, such as forms and file uploads), the script doesn't run.
381+
If the script reads the body itself, through `php://input` or `request_parse_body()`, the read throws a `FrankenPHP\RequestBodyTooLargeException` once the limit is reached, so a truncated body is never mistaken for a complete one.
382+
369383
## Enable the debug mode
370384

371385
When using the Docker image, set the `CADDY_GLOBAL_OPTIONS` environment variable to `debug` to enable the debug mode:

‎frankenphp.c‎

Lines changed: 27 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -980,7 +980,9 @@ PHP_FUNCTION(frankenphp_handle_request) {
980980
fci.params = result.r1;
981981
fci.param_count = result.r1 == NULL ? 0 : 1;
982982

983-
if (zend_call_function(&fci, &fcc) == SUCCESS && Z_TYPE(retval) != IS_UNDEF) {
983+
/* a body over the limit was rejected while parsing the request */
984+
if (EXPECTED(!go_is_context_done(thread_index)) &&
985+
zend_call_function(&fci, &fcc) == SUCCESS && Z_TYPE(retval) != IS_UNDEF) {
984986
callback_ret = &retval;
985987

986988
/* pass NULL instead of the NULL zval as return value */
@@ -1193,8 +1195,12 @@ static const zend_function_entry frankenphp_test_hook_functions[] = {
11931195
arginfo_frankenphp_test_persist_roundtrip) PHP_FE_END};
11941196
#endif
11951197

1198+
static zend_class_entry *frankenphp_ce_request_body_too_large_exception;
1199+
11961200
PHP_MINIT_FUNCTION(frankenphp) {
11971201
register_frankenphp_symbols(module_number);
1202+
frankenphp_ce_request_body_too_large_exception =
1203+
register_class_FrankenPHP_RequestBodyTooLargeException(zend_ce_exception);
11981204
#ifndef PHP_WIN32
11991205
/* MINIT runs once per ZTS thread — guard the atfork registration */
12001206
static pthread_once_t atfork_once = PTHREAD_ONCE_INIT;
@@ -1419,7 +1425,22 @@ static void frankenphp_sapi_flush(void *server_context) {
14191425
}
14201426

14211427
static size_t frankenphp_read_post(char *buffer, size_t count_bytes) {
1422-
return go_read_post(frankenphp_thread_index(), buffer, count_bytes);
1428+
struct go_read_post_return result =
1429+
go_read_post(frankenphp_thread_index(), buffer, count_bytes);
1430+
1431+
/* php://input can't report read errors, throw so user code doesn't take
1432+
* the truncated body for a complete one. Worker request startup and
1433+
* shutdown run in frankenphp_handle_request()'s frame, not in user code. */
1434+
zend_execute_data *ex = EG(current_execute_data);
1435+
if (result.r1 && ex != NULL &&
1436+
!(ex->func != NULL && ex->func->type == ZEND_INTERNAL_FUNCTION &&
1437+
ex->func->internal_function.handler ==
1438+
ZEND_FN(frankenphp_handle_request))) {
1439+
zend_throw_exception(frankenphp_ce_request_body_too_large_exception,
1440+
"Request body too large", 0);
1441+
}
1442+
1443+
return result.r0;
14231444
}
14241445

14251446
static char *frankenphp_read_cookies(void) {
@@ -1790,8 +1811,10 @@ static void *php_thread(void *arg) {
17901811
file_handle.primary_script = 1;
17911812
EG(exit_status) = 0;
17921813

1793-
/* Execute the PHP script, potential bailout to zend_catch */
1794-
if (EXPECTED(open_primary_script(&file_handle))) {
1814+
/* Execute the PHP script, potential bailout to zend_catch. A body over
1815+
* the limit was rejected while parsing the request. */
1816+
if (EXPECTED(!go_is_context_done(thread_index)) &&
1817+
EXPECTED(open_primary_script(&file_handle))) {
17951818
php_execute_script(&file_handle);
17961819
}
17971820
#ifndef PHP_WIN32

‎frankenphp.go‎

Lines changed: 13 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -54,6 +54,7 @@ var (
5454
ErrInvalidScriptPath = ErrRejected{"invalid script path", http.StatusNotFound}
5555
ErrInvalidContentLengthHeader = ErrRejected{"invalid Content-Length header", http.StatusBadRequest}
5656
ErrMaxWaitTimeExceeded = ErrRejected{"maximum request handling time exceeded", http.StatusServiceUnavailable}
57+
ErrRequestBodyTooLarge = ErrRejected{"request body too large", http.StatusRequestEntityTooLarge}
5758

5859
contextKey = contextKeyStruct{}
5960
serverHeader = []string{"FrankenPHP"}
@@ -683,6 +684,7 @@ func go_write_headers(threadIndex C.uintptr_t, status C.int, headers *C.zend_lli
683684
}
684685

685686
fc.responseWriter.WriteHeader(goStatus)
687+
fc.headersWritten = goStatus >= 200
686688

687689
if goStatus < 200 {
688690
// Clear headers, it's not automatically done by ResponseWriter.WriteHeader() for 1xx responses
@@ -735,12 +737,12 @@ func go_sapi_flush(threadIndex C.uintptr_t) bool {
735737
}
736738

737739
//export go_read_post
738-
func go_read_post(threadIndex C.uintptr_t, cBuf *C.char, countBytes C.size_t) (readBytes C.size_t) {
740+
func go_read_post(threadIndex C.uintptr_t, cBuf *C.char, countBytes C.size_t) (readBytes C.size_t, tooLarge C.bool) {
739741
fc := phpThreads[threadIndex].handler.frankenPHPContext()
740742

741743
// net/http forbids reading the body after the handler returns; body wrappers may touch the dead stream
742744
if fc.responseWriter == nil || fc.isDone {
743-
return 0
745+
return 0, false
744746
}
745747

746748
var rc *http.ResponseController
@@ -769,6 +771,15 @@ func go_read_post(threadIndex C.uintptr_t, cBuf *C.char, countBytes C.size_t) (r
769771
_ = rc.SetReadDeadline(time.Time{})
770772
}
771773

774+
// PHP can't see read errors: fail the request rather than expose a truncated body
775+
if _, ok := errors.AsType[*http.MaxBytesError](err); ok {
776+
if !fc.headersWritten {
777+
fc.reject(ErrRequestBodyTooLarge)
778+
}
779+
780+
tooLarge = true
781+
}
782+
772783
return
773784
}
774785

‎frankenphp.stub.php‎

Lines changed: 49 additions & 39 deletions
Original file line numberDiff line numberDiff line change
@@ -1,56 +1,66 @@
11
<?php
22

3-
/** @generate-class-entries */
3+
/**
4+
* @generate-class-entries
5+
* @generate-legacy-arginfo 80200
6+
*/
47

5-
/** @var int */
6-
const FRANKENPHP_LOG_LEVEL_DEBUG = -4;
8+
namespace {
9+
/** @var int */
10+
const FRANKENPHP_LOG_LEVEL_DEBUG = -4;
711

8-
/** @var int */
9-
const FRANKENPHP_LOG_LEVEL_INFO = 0;
12+
/** @var int */
13+
const FRANKENPHP_LOG_LEVEL_INFO = 0;
1014

11-
/** @var int */
12-
const FRANKENPHP_LOG_LEVEL_WARN = 4;
15+
/** @var int */
16+
const FRANKENPHP_LOG_LEVEL_WARN = 4;
1317

14-
/** @var int */
15-
const FRANKENPHP_LOG_LEVEL_ERROR = 8;
18+
/** @var int */
19+
const FRANKENPHP_LOG_LEVEL_ERROR = 8;
1620

17-
function frankenphp_handle_request(callable $callback): bool {}
21+
function frankenphp_handle_request(callable $callback): bool {}
1822

19-
function headers_send(int $status = 200): int {}
23+
function headers_send(int $status = 200): int {}
2024

21-
function frankenphp_finish_request(): bool {}
25+
function frankenphp_finish_request(): bool {}
2226

23-
/**
24-
* @alias frankenphp_finish_request
25-
*/
26-
function fastcgi_finish_request(): bool {}
27+
/**
28+
* @alias frankenphp_finish_request
29+
*/
30+
function fastcgi_finish_request(): bool {}
2731

28-
function frankenphp_request_headers(): array {}
32+
function frankenphp_request_headers(): array {}
2933

30-
/**
31-
* @alias frankenphp_request_headers
32-
*/
33-
function apache_request_headers(): array {}
34+
/**
35+
* @alias frankenphp_request_headers
36+
*/
37+
function apache_request_headers(): array {}
3438

35-
/**
36-
* @alias frankenphp_request_headers
37-
*/
38-
function getallheaders(): array {}
39+
/**
40+
* @alias frankenphp_request_headers
41+
*/
42+
function getallheaders(): array {}
3943

40-
function frankenphp_response_headers(): array|bool {}
44+
function frankenphp_response_headers(): array|bool {}
4145

42-
/**
43-
* @alias frankenphp_response_headers
44-
*/
45-
function apache_response_headers(): array|bool {}
46+
/**
47+
* @alias frankenphp_response_headers
48+
*/
49+
function apache_response_headers(): array|bool {}
4650

47-
/**
48-
* @param string|string[] $topics The first topic is the canonical one, the others are alternate topics
49-
*/
50-
function mercure_publish(string|array $topics, string $data = '', bool $private = false, ?string $id = null, ?string $type = null, ?int $retry = null): string {}
51+
/**
52+
* @param string|string[] $topics The first topic is the canonical one, the others are alternate topics
53+
*/
54+
function mercure_publish(string|array $topics, string $data = '', bool $private = false, ?string $id = null, ?string $type = null, ?int $retry = null): string {}
5155

52-
/**
53-
* @param int $level The importance or severity of a log event. The higher the level, the more important or severe the event. For more details, see: https://pkg.go.dev/log/slog#Level
54-
* array<string, any> $context Values of the array will be converted to the corresponding Go type (if supported by FrankenPHP) and added to the context of the structured logs using https://pkg.go.dev/log/slog#Attr
55-
*/
56-
function frankenphp_log(string $message, int $level = 0, array $context = []): void {}
56+
/**
57+
* @param int $level The importance or severity of a log event. The higher the level, the more important or severe the event. For more details, see: https://pkg.go.dev/log/slog#Level
58+
* array<string, any> $context Values of the array will be converted to the corresponding Go type (if supported by FrankenPHP) and added to the context of the structured logs using https://pkg.go.dev/log/slog#Attr
59+
*/
60+
function frankenphp_log(string $message, int $level = 0, array $context = []): void {}
61+
}
62+
63+
namespace FrankenPHP {
64+
/** Thrown when reading a request body larger than the configured limit */
65+
class RequestBodyTooLargeException extends \Exception {}
66+
}

‎frankenphp_arginfo.h‎

Lines changed: 35 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
/* This is a generated file, edit the .stub.php file instead.
2-
* Stub hash: 85fabd314ab885307e0032b9f7635fa13cc0c4b5 */
2+
* Stub hash: 57299a756b23c7443d6b09f759106ddf0ec8df20 */
33

44
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_frankenphp_handle_request, 0, 1, _IS_BOOL, 0)
55
ZEND_ARG_TYPE_INFO(0, callback, IS_CALLABLE, 0)
@@ -41,7 +41,6 @@ ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_frankenphp_log, 0, 1, IS_VOID, 0
4141
ZEND_ARG_TYPE_INFO_WITH_DEFAULT_VALUE(0, context, IS_ARRAY, 0, "[]")
4242
ZEND_END_ARG_INFO()
4343

44-
4544
ZEND_FUNCTION(frankenphp_handle_request);
4645
ZEND_FUNCTION(headers_send);
4746
ZEND_FUNCTION(frankenphp_finish_request);
@@ -50,17 +49,32 @@ ZEND_FUNCTION(frankenphp_response_headers);
5049
ZEND_FUNCTION(mercure_publish);
5150
ZEND_FUNCTION(frankenphp_log);
5251

53-
5452
static const zend_function_entry ext_functions[] = {
5553
ZEND_FE(frankenphp_handle_request, arginfo_frankenphp_handle_request)
5654
ZEND_FE(headers_send, arginfo_headers_send)
5755
ZEND_FE(frankenphp_finish_request, arginfo_frankenphp_finish_request)
58-
ZEND_FALIAS(fastcgi_finish_request, frankenphp_finish_request, arginfo_fastcgi_finish_request)
56+
#if (PHP_VERSION_ID >= 80400)
57+
ZEND_RAW_FENTRY("fastcgi_finish_request", zif_frankenphp_finish_request, arginfo_fastcgi_finish_request, 0, NULL, NULL)
58+
#else
59+
ZEND_RAW_FENTRY("fastcgi_finish_request", zif_frankenphp_finish_request, arginfo_fastcgi_finish_request, 0)
60+
#endif
5961
ZEND_FE(frankenphp_request_headers, arginfo_frankenphp_request_headers)
60-
ZEND_FALIAS(apache_request_headers, frankenphp_request_headers, arginfo_apache_request_headers)
61-
ZEND_FALIAS(getallheaders, frankenphp_request_headers, arginfo_getallheaders)
62+
#if (PHP_VERSION_ID >= 80400)
63+
ZEND_RAW_FENTRY("apache_request_headers", zif_frankenphp_request_headers, arginfo_apache_request_headers, 0, NULL, NULL)
64+
#else
65+
ZEND_RAW_FENTRY("apache_request_headers", zif_frankenphp_request_headers, arginfo_apache_request_headers, 0)
66+
#endif
67+
#if (PHP_VERSION_ID >= 80400)
68+
ZEND_RAW_FENTRY("getallheaders", zif_frankenphp_request_headers, arginfo_getallheaders, 0, NULL, NULL)
69+
#else
70+
ZEND_RAW_FENTRY("getallheaders", zif_frankenphp_request_headers, arginfo_getallheaders, 0)
71+
#endif
6272
ZEND_FE(frankenphp_response_headers, arginfo_frankenphp_response_headers)
63-
ZEND_FALIAS(apache_response_headers, frankenphp_response_headers, arginfo_apache_response_headers)
73+
#if (PHP_VERSION_ID >= 80400)
74+
ZEND_RAW_FENTRY("apache_response_headers", zif_frankenphp_response_headers, arginfo_apache_response_headers, 0, NULL, NULL)
75+
#else
76+
ZEND_RAW_FENTRY("apache_response_headers", zif_frankenphp_response_headers, arginfo_apache_response_headers, 0)
77+
#endif
6478
ZEND_FE(mercure_publish, arginfo_mercure_publish)
6579
ZEND_FE(frankenphp_log, arginfo_frankenphp_log)
6680
ZEND_FE_END
@@ -73,3 +87,17 @@ static void register_frankenphp_symbols(int module_number)
7387
REGISTER_LONG_CONSTANT("FRANKENPHP_LOG_LEVEL_WARN", 4, CONST_PERSISTENT);
7488
REGISTER_LONG_CONSTANT("FRANKENPHP_LOG_LEVEL_ERROR", 8, CONST_PERSISTENT);
7589
}
90+
91+
static zend_class_entry *register_class_FrankenPHP_RequestBodyTooLargeException(zend_class_entry *class_entry_Exception)
92+
{
93+
zend_class_entry ce, *class_entry;
94+
95+
INIT_NS_CLASS_ENTRY(ce, "FrankenPHP", "RequestBodyTooLargeException", NULL);
96+
#if (PHP_VERSION_ID >= 80400)
97+
class_entry = zend_register_internal_class_with_flags(&ce, class_entry_Exception, 0);
98+
#else
99+
class_entry = zend_register_internal_class_ex(&ce, class_entry_Exception);
100+
#endif
101+
102+
return class_entry;
103+
}

0 commit comments

Comments
 (0)