Skip to content

Commit

Permalink
fix : make sure the PHP request body buffer is full before giving it …
Browse files Browse the repository at this point in the history
…back (#187)

* test: large requests with Caddy

* fix: ensure that the request body buffer is full

* refactor: microoptim
  • Loading branch information
dunglas authored Aug 16, 2023
1 parent 0d2104a commit e0f2323
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 4 deletions.
32 changes: 32 additions & 0 deletions caddy/caddy_test.go
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
package caddy_test

import (
"bytes"
"fmt"
"net/http"
"strings"
"sync"
"testing"

Expand Down Expand Up @@ -41,3 +43,33 @@ func TestPHP(t *testing.T) {
}
wg.Wait()
}

func TestLargeRequest(t *testing.T) {
tester := caddytest.NewTester(t)
tester.InitServer(`
{
skip_install_trust
admin localhost:2999
http_port 9080
https_port 9443
frankenphp
}
localhost:9080 {
route {
php {
root ../testdata
}
}
}
`, "caddyfile")

tester.AssertPostResponseBody(
"http://localhost:9080/large-request.php",
[]string{},
bytes.NewBufferString(strings.Repeat("f", 1_048_576)),
http.StatusOK,
"Request body size: 1048576 (unknown)",
)
}
14 changes: 10 additions & 4 deletions frankenphp.go
Original file line number Diff line number Diff line change
Expand Up @@ -580,11 +580,17 @@ func go_sapi_flush(rh C.uintptr_t) bool {
}

//export go_read_post
func go_read_post(rh C.uintptr_t, cBuf *C.char, countBytes C.size_t) C.size_t {
func go_read_post(rh C.uintptr_t, cBuf *C.char, countBytes C.size_t) (readBytes C.size_t) {
r := cgo.Handle(rh).Value().(*http.Request)

p := make([]byte, int(countBytes))
readBytes, err := r.Body.Read(p)
p := make([]byte, countBytes)
var err error
for readBytes < countBytes && err == nil {
var n int
n, err = r.Body.Read(p[readBytes:])
readBytes += C.size_t(n)
}

if err != nil && err != io.EOF {
// invalid Read on closed Body may happen because of https://github.com/golang/go/issues/15527
fc, _ := FromContext(r.Context())
Expand All @@ -595,7 +601,7 @@ func go_read_post(rh C.uintptr_t, cBuf *C.char, countBytes C.size_t) C.size_t {
C.memcpy(unsafe.Pointer(cBuf), unsafe.Pointer(&p[0]), C.size_t(readBytes))
}

return C.size_t(readBytes)
return
}

//export go_read_cookies
Expand Down

0 comments on commit e0f2323

Please sign in to comment.