Skip to content

Commit fc64b0a

Browse files
committed
Simplify extraction logic for HTTP header content length.
1 parent cdadeff commit fc64b0a

File tree

1 file changed

+16
-17
lines changed

1 file changed

+16
-17
lines changed

src/utility/ota/OTA-nano-rp2040.cpp

Lines changed: 16 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -134,34 +134,33 @@ int rp2040_connect_onOTARequest(char const * ota_url)
134134
mbed_watchdog_reset();
135135

136136
char const c = client->read();
137-
Serial.print(c);
138137

139138
http_header += c;
140139
if (http_header.endsWith("\r\n\r\n"))
141140
is_header_complete = true;
142141
}
143142
}
144143

145-
/* Extract concent length from HTTP header. */
146-
int content_length_val = 0;
147-
int const content_length_index = http_header.indexOf("Content-Length: ");
148-
if (content_length_index > 0)
144+
/* Extract concent length from HTTP header. A typical entry looks like
145+
* "Content-Length: 123456"
146+
*/
147+
char const * content_length_ptr = strstr(http_header.c_str(), "Content-Length");
148+
if (!content_length_ptr)
149149
{
150-
/* Attention: The following code is extremely ugly and needs major cleaning up. */
151-
String content_length;
152-
for (char * ptr = &(http_header[content_length_index + 16]); isDigit(*ptr); ptr++)
153-
content_length += *ptr;
154-
155-
content_length_val = atoi(content_length.c_str());
156-
DEBUG_VERBOSE("%s: Length of OTA binary according to HTTP header = %d bytes", __FUNCTION__, content_length_val);
157-
}
158-
else
159-
{
160-
DEBUG_ERROR("%s: Failure to extract content length from http header", __FUNCTION__);
161150
fclose(file);
151+
DEBUG_ERROR("%s: Failure to extract content length from http header", __FUNCTION__);
162152
return static_cast<int>(OTAError::RP2040_ErrorParseHttpHeader);
163153
}
164-
154+
/* Find start of numerical value. */
155+
char * ptr = const_cast<char *>(content_length_ptr);
156+
for (; (*ptr != '\0') && !isDigit(*ptr); ptr++) { }
157+
/* Extract numerical value. */
158+
String content_length_str;
159+
for (; isDigit(*ptr); ptr++) content_length_str += *ptr;
160+
int const content_length_val = atoi(content_length_str.c_str());
161+
DEBUG_VERBOSE("%s: Length of OTA binary according to HTTP header = %d bytes", __FUNCTION__, content_length_val);
162+
163+
/* Receive as many bytes as are indicated by the HTTP header - or die trying. */
165164
for(int bytes_received = 0;
166165
(bytes_received < content_length_val) && client->connected();)
167166
{

0 commit comments

Comments
 (0)