From 87d841d81bfe2cecfed57a29d487d60ee932be54 Mon Sep 17 00:00:00 2001
From: Sergey Lyubka <valenok@gmail.com>
Date: Tue, 1 Oct 2013 18:49:44 +0100
Subject: [PATCH] Set content_len to 0 for GET requests without Content-Length
 header.

---
 build/src/mongoose.c | 11 +++++++++--
 mongoose.c           | 11 +++++++++--
 2 files changed, 18 insertions(+), 4 deletions(-)

diff --git a/build/src/mongoose.c b/build/src/mongoose.c
index fcb293617..cdc9ae18d 100644
--- a/build/src/mongoose.c
+++ b/build/src/mongoose.c
@@ -3643,9 +3643,16 @@ static int getreq(struct mg_connection *conn, char *ebuf, size_t ebuf_len) {
     snprintf(ebuf, ebuf_len, "Bad request: [%.*s]", conn->data_len, conn->buf);
   } else {
     // Request is valid. Set content_len attribute by parsing Content-Length
-    // If Content-Length is absent, instruct mg_read() to read from the socket
-    // until socket is closed.
+    // If Content-Length is absent, set content_len to 0 if request is GET,
+    // and set it to INT64_MAX otherwise. Setting to INT64_MAX instructs
+    // mg_read() to read from the socket until socket is closed.
+    // The reason for treating GET and POST/PUT differently is that libraries
+    // like jquery do not set Content-Length in GET requests, and we don't
+    // want mg_read() to hang waiting until socket is timed out.
     conn->content_len = INT64_MAX;
+    if (!mg_strcasecmp(conn->request_info.request_method, "GET")) {
+      conn->content_len = 0;
+    }
     if ((cl = get_header(&conn->request_info, "Content-Length")) != NULL) {
       conn->content_len = strtoll(cl, NULL, 10);
     }
diff --git a/mongoose.c b/mongoose.c
index 35ce41a96..02fb9f8e2 100644
--- a/mongoose.c
+++ b/mongoose.c
@@ -4954,9 +4954,16 @@ static int getreq(struct mg_connection *conn, char *ebuf, size_t ebuf_len) {
     snprintf(ebuf, ebuf_len, "Bad request: [%.*s]", conn->data_len, conn->buf);
   } else {
     // Request is valid. Set content_len attribute by parsing Content-Length
-    // By default, in the absence of Content-Length, instruct mg_read()
-    // to read from the socket until the socket is closed.
+    // If Content-Length is absent, set content_len to 0 if request is GET,
+    // and set it to INT64_MAX otherwise. Setting to INT64_MAX instructs
+    // mg_read() to read from the socket until socket is closed.
+    // The reason for treating GET and POST/PUT differently is that libraries
+    // like jquery do not set Content-Length in GET requests, and we don't
+    // want mg_read() to hang waiting until socket is timed out.
     conn->content_len = INT64_MAX;
+    if (!mg_strcasecmp(conn->request_info.request_method, "GET")) {
+      conn->content_len = 0;
+    }
     if ((cl = get_header(&conn->request_info, "Content-Length")) != NULL) {
       conn->content_len = strtoll(cl, NULL, 10);
     }
-- 
GitLab