handle one accepted connection: parse request line, dispatch GET or PUT
| 182 | |
| 183 | // handle one accepted connection: parse request line, dispatch GET or PUT |
| 184 | static void HandleClient(SOCKET client) { |
| 185 | // Read headers until \r\n\r\n; cap at 64KB. |
| 186 | static constexpr int MAX_HEADER_SIZE = 65536; |
| 187 | std::vector<char> bufVec(MAX_HEADER_SIZE + 1); |
| 188 | char* buf = bufVec.data(); |
| 189 | int total = 0; |
| 190 | int headerEnd = -1; |
| 191 | |
| 192 | while (total < MAX_HEADER_SIZE) { |
| 193 | int n = recv(client, buf + total, MAX_HEADER_SIZE - total, 0); |
| 194 | if (n <= 0) break; |
| 195 | total += n; |
| 196 | buf[total] = '\0'; |
| 197 | |
| 198 | char* found = strstr(buf, "\r\n\r\n"); |
| 199 | if (found) { |
| 200 | headerEnd = (int)(found - buf) + 4; |
| 201 | break; |
| 202 | } |
| 203 | } |
| 204 | |
| 205 | if (headerEnd < 0) { |
| 206 | closesocket(client); |
| 207 | return; |
| 208 | } |
| 209 | |
| 210 | // parse request line: "METHOD /path HTTP/1.1\r\n" |
| 211 | char method[16] = {}; |
| 212 | char path[2048] = {}; |
| 213 | if (sscanf(buf, "%15s %2047s", method, path) != 2) { |
| 214 | closesocket(client); |
| 215 | return; |
| 216 | } |
| 217 | |
| 218 | // parse Content-Length from headers (case-insensitive) |
| 219 | int64_t contentLength = -1; |
| 220 | // Only search within header portion (before \r\n\r\n) |
| 221 | const char* cl = stristr(buf, "\r\nContent-Length:"); |
| 222 | if (!cl || cl - buf > headerEnd) cl = nullptr; |
| 223 | if (!cl) { |
| 224 | cl = stristr(buf, "\nContent-Length:"); |
| 225 | if (cl && cl - buf > headerEnd) cl = nullptr; |
| 226 | } |
| 227 | if (cl) { |
| 228 | char* endptr = nullptr; |
| 229 | contentLength = _strtoi64(cl + (cl[0] == '\r' ? 17 : 16), &endptr, 10); |
| 230 | if (endptr == cl + (cl[0] == '\r' ? 17 : 16)) contentLength = -1; |
| 231 | if (contentLength < 0) contentLength = 0; |
| 232 | } |
| 233 | |
| 234 | int bodyReceived = total - headerEnd; |
| 235 | |
| 236 | if (_stricmp(method, "PUT") == 0) { |
| 237 | // Steam omits Content-Length for 0-byte files (LOCK, empty .log, etc.). |
| 238 | // Treat missing header as 0 bytes rather than rejecting. |
| 239 | if (contentLength < 0) |
| 240 | contentLength = 0; |
| 241 |
no test coverage detected