forked from nrfconnect/ncs-serial-modem
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsm_at_httpc.c
More file actions
1483 lines (1254 loc) · 39.2 KB
/
sm_at_httpc.c
File metadata and controls
1483 lines (1254 loc) · 39.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (c) 2026 Nordic Semiconductor ASA
*
* SPDX-License-Identifier: LicenseRef-Nordic-5-Clause
*/
#define _POSIX_C_SOURCE 200809L /* for strdup() */
#include <zephyr/kernel.h>
#include <zephyr/logging/log.h>
#include <zephyr/sys/util.h>
#include <zephyr/net/http/parser_url.h>
#include <nrf_socket.h>
#include <zephyr/net/socket.h>
#include <modem/at_parser.h>
#include <stdio.h>
#include <string.h>
#include "sm_util.h"
#include "sm_at_host.h"
#include "sm_at_httpc.h"
LOG_MODULE_REGISTER(sm_httpc, CONFIG_SM_LOG_LEVEL);
#define HTTP_RECV_BUF_SIZE 2048
#define HTTP_URL_MAX_LEN 512
#define HTTP_HOST_MAX_LEN 256
#define HTTP_PATH_MAX_LEN 256
#define HTTP_EXTRA_HEADERS_SIZE 512
#define HTTP_RESPONSE_TIMEOUT_MS CONFIG_SM_HTTPC_RESPONSE_TIMEOUT_MS
#define HTTP_MAX_REQUESTS NRF_MODEM_MAX_SOCKET_COUNT
/* Periodic scan, so idle timeout fires without a socket poll wakeup (silent server). */
#define HTTP_TIMEOUT_SCAN_MS MIN(1000U, (uint32_t)HTTP_RESPONSE_TIMEOUT_MS / 4U)
/* Fixed HTTP header lines */
#define HTTP_VERSION_LINE " HTTP/1.1\r\n"
#define HTTP_HDR_USER_AGENT "User-Agent: nRF91-Serial-Modem\r\n"
#define HTTP_HDR_ACCEPT "Accept: */*\r\n"
/* Forward declarations of socket functions */
extern struct sm_socket *find_socket(int fd);
extern int set_xapoll_events(struct sm_socket *sock, uint8_t events);
extern void xapoll_stop(struct sm_socket *sock);
/* HTTP request methods */
enum sm_http_method {
HTTP_GET,
HTTP_POST,
HTTP_PUT,
HTTP_DELETE,
HTTP_HEAD,
};
/* HTTP request states */
enum http_state {
HTTP_STATE_IDLE,
HTTP_STATE_SENDING_REQUEST,
HTTP_STATE_SENDING_BODY,
HTTP_STATE_RECEIVING_HEADERS,
HTTP_STATE_RECEIVING_BODY,
};
/* HTTP request structure */
struct http_request {
int fd; /* Socket file descriptor (from AT socket) */
enum http_state state; /* Current state */
enum sm_http_method method; /* HTTP method */
char *hostname; /* Hostname (dynamically allocated) */
char *path; /* URL path (dynamically allocated) */
uint16_t port; /* Port number */
int request_body_len; /* Content-Length for request body (POST/PUT) */
char *extra_headers; /* Extra HTTP headers (dynamically allocated) */
uint8_t *recv_buf; /* Receive buffer (dynamically allocated) */
int recv_buf_len; /* Bytes in receive buffer */
char *send_ptr; /* Pointer to data being sent */
int send_remaining; /* Bytes remaining to send */
char *send_buf; /* Buffer for HTTP request headers (dynamically allocated) */
int status_code; /* HTTP status code */
int content_length; /* Content-Length from header (-1 if not present) */
int total_received; /* Total bytes received */
bool headers_complete; /* Headers fully received */
bool need_rearm_pollin; /* Flag for socket layer to re-arm POLLIN */
int64_t timeout_timestamp; /* Idle timeout deadline; reset on each send/receive */
struct modem_pipe *pipe; /* AT pipe that created this request */
bool manual_mode; /* Manual mode: body not auto-received, host pulls chunks */
int bytes_sent; /* Response-body bytes sent to the host */
bool connection_close; /* Server sent "Connection: close" header */
};
static const char * const http_method_str[] = {
[HTTP_GET] = "GET",
[HTTP_POST] = "POST",
[HTTP_PUT] = "PUT",
[HTTP_DELETE] = "DELETE",
[HTTP_HEAD] = "HEAD",
};
static struct http_request *http_requests[HTTP_MAX_REQUESTS];
static struct http_request *datamode_req; /* Request waiting for body data */
/* Forward declarations */
static void http_process_request(struct http_request *req, uint8_t events);
static void http_close_request(struct http_request *req);
static void http_fail_request(struct http_request *req);
static void http_finish_request(struct http_request *req);
static int http_start_request(struct http_request *req);
static bool http_headers_complete(struct http_request *req, char *header_end,
struct sm_socket *sock, bool hup);
static void http_warn_incomplete_transfer(const struct http_request *req);
static int http_recv_read(struct http_request *req, struct sm_socket *sock);
static void http_process_recv_headers(struct http_request *req, struct sm_socket *sock,
uint8_t events);
static void http_process_recv_body(struct http_request *req, struct sm_socket *sock,
uint8_t events);
static int parse_http_status_code(const char *buf, int *status_code);
static int parse_content_length(const char *buf, const char *header_end, int *length);
static bool parse_connection_close(const char *buf, const char *header_end);
static void http_timeout_work_fn(struct k_work *work);
static K_MUTEX_DEFINE(http_mutex);
static K_WORK_DELAYABLE_DEFINE(http_timeout_dwork, http_timeout_work_fn);
static bool http_any_active_request_unlocked(void)
{
for (int i = 0; i < HTTP_MAX_REQUESTS; i++) {
if (http_requests[i] != NULL && http_requests[i]->state != HTTP_STATE_IDLE) {
return true;
}
}
return false;
}
/* Arm the scan timer when a request enters a non-idle state (safe without http_mutex). */
static void http_timeout_monitor_arm(void)
{
(void)k_work_reschedule_for_queue(&sm_work_q, &http_timeout_dwork,
K_MSEC(HTTP_TIMEOUT_SCAN_MS));
}
/*
* Sole enforcement of HTTP idle timeout (SM_HTTPC_RESPONSE_TIMEOUT_MS sliding window).
* Runs on sm_work_q; reschedules while any request remains active.
*/
static void http_timeout_work_fn(struct k_work *work)
{
ARG_UNUSED(work);
k_mutex_lock(&http_mutex, K_FOREVER);
for (int i = 0; i < HTTP_MAX_REQUESTS; i++) {
struct http_request *req = http_requests[i];
if (req == NULL || req->state == HTTP_STATE_IDLE) {
continue;
}
/* Body is being streamed via data mode; data mode manages its own
* lifecycle. Do not apply the response idle timeout here.
*/
if (req->state == HTTP_STATE_SENDING_BODY) {
continue;
}
if (k_uptime_get() > req->timeout_timestamp) {
LOG_ERR("HTTP request %d idle timeout state %d", req->fd, req->state);
http_fail_request(req);
}
}
const bool any = http_any_active_request_unlocked();
k_mutex_unlock(&http_mutex);
if (any) {
http_timeout_monitor_arm();
}
}
/* Find request by socket fd */
static struct http_request *find_request(int fd)
{
for (int i = 0; i < HTTP_MAX_REQUESTS; i++) {
if (http_requests[i] && http_requests[i]->fd == fd) {
return http_requests[i];
}
}
return NULL;
}
/* Allocate new request */
static struct http_request *alloc_request(void)
{
for (int i = 0; i < HTTP_MAX_REQUESTS; i++) {
if (!http_requests[i]) {
http_requests[i] = malloc(sizeof(struct http_request));
if (!http_requests[i]) {
return NULL;
}
memset(http_requests[i], 0, sizeof(struct http_request));
http_requests[i]->recv_buf = malloc(HTTP_RECV_BUF_SIZE);
if (!http_requests[i]->recv_buf) {
free(http_requests[i]);
http_requests[i] = NULL;
return NULL;
}
http_requests[i]->fd = -1;
http_requests[i]->state = HTTP_STATE_IDLE;
http_requests[i]->content_length = -1;
http_requests[i]->pipe = sm_at_host_get_current_pipe();
return http_requests[i];
}
}
return NULL;
}
/* Parse URL into components */
static int http_parse_url_components(const char *url, size_t url_len, struct http_request *req)
{
struct http_parser_url parser = {0};
int ret;
ret = http_parser_parse_url(url, url_len, 0, &parser);
if (ret) {
LOG_ERR("Failed to parse URL: %d", ret);
return -EINVAL;
}
/* Extract hostname */
if (parser.field_set & (1 << UF_HOST)) {
unsigned int host_len = parser.field_data[UF_HOST].len;
if (host_len >= HTTP_HOST_MAX_LEN) {
LOG_ERR("Hostname too long");
return -EINVAL;
}
req->hostname = strndup(url + parser.field_data[UF_HOST].off, host_len);
if (!req->hostname) {
return -ENOMEM;
}
} else {
LOG_ERR("No host in URL");
return -EINVAL;
}
/* Extract port if specified */
if (parser.field_set & (1 << UF_PORT)) {
req->port = parser.port;
} else {
/* Determine port based on scheme */
if (parser.field_set & (1 << UF_SCHEMA)) {
unsigned int schema_len = parser.field_data[UF_SCHEMA].len;
const char *scheme_start = url + parser.field_data[UF_SCHEMA].off;
if (schema_len == 5 && strncmp(scheme_start, "https", 5) == 0) {
req->port = 443;
} else {
req->port = 80;
}
} else {
req->port = 80;
}
}
/* Extract path (and query string if present, e.g. /foo?bar=1) */
if (parser.field_set & (1 << UF_PATH)) {
size_t path_len = parser.field_data[UF_PATH].len;
size_t query_len = 0;
if (parser.field_set & (1 << UF_QUERY)) {
/* query offset immediately follows path; include '?' separator */
query_len = 1 + parser.field_data[UF_QUERY].len;
}
size_t total_len = path_len + query_len;
if (total_len >= HTTP_PATH_MAX_LEN) {
LOG_ERR("Path+query too long");
return -EINVAL;
}
req->path = strndup(url + parser.field_data[UF_PATH].off, total_len);
if (!req->path) {
return -ENOMEM;
}
} else {
req->path = strdup("/");
if (!req->path) {
return -ENOMEM;
}
}
return 0;
}
/* Build HTTP request headers */
static int http_build_request(struct http_request *req, char *buf, size_t buf_len)
{
int len = snprintf(buf, buf_len,
"%s %s" HTTP_VERSION_LINE
"Host: %s\r\n"
HTTP_HDR_USER_AGENT
HTTP_HDR_ACCEPT,
http_method_str[req->method], req->path, req->hostname);
if (req->request_body_len > 0) {
len += snprintf(buf + len, buf_len - len, "Content-Length: %d\r\n",
req->request_body_len);
}
/* Add extra headers if provided */
if (req->extra_headers != NULL) {
len += snprintf(buf + len, buf_len - len, "%s", req->extra_headers);
}
len += snprintf(buf + len, buf_len - len, "\r\n");
return len;
}
/* Compile-time length of a string literal (excludes null terminator) */
#define STRLIT_LEN(s) (sizeof(s) - 1)
/* Calculate the buffer size needed to hold the HTTP request headers */
static size_t http_headers_size(const struct http_request *req)
{
return strlen(http_method_str[req->method]) + 1 +
strlen(req->path) + STRLIT_LEN(HTTP_VERSION_LINE) +
STRLIT_LEN("Host: ") + strlen(req->hostname) + STRLIT_LEN("\r\n") +
STRLIT_LEN(HTTP_HDR_USER_AGENT) +
STRLIT_LEN(HTTP_HDR_ACCEPT) +
(req->request_body_len > 0 ?
STRLIT_LEN("Content-Length: 2147483647\r\n") : 0) +
(req->extra_headers ? strlen(req->extra_headers) : 0) +
STRLIT_LEN("\r\n") + 1; /* final blank line + null terminator */
}
/*
* Allocate req->send_buf and fill it with the HTTP request header block.
* Returns the number of bytes written, or a negative error code.
*/
static int http_alloc_build_headers(struct http_request *req)
{
size_t send_buf_size = http_headers_size(req);
req->send_buf = malloc(send_buf_size);
if (!req->send_buf) {
LOG_ERR("Failed to allocate send buffer (%zu bytes)", send_buf_size);
return -ENOMEM;
}
return http_build_request(req, req->send_buf, send_buf_size);
}
/* Start HTTP request (non-blocking) */
static int http_start_request(struct http_request *req)
{
int ret;
struct sm_socket *sock;
LOG_INF("HTTP %d %s: %s:%d%s", req->method, http_method_str[req->method],
req->hostname, req->port, req->path);
ret = http_alloc_build_headers(req);
if (ret < 0) {
return ret;
}
req->send_ptr = req->send_buf;
req->send_remaining = ret;
req->state = HTTP_STATE_SENDING_REQUEST;
req->timeout_timestamp = k_uptime_get() + HTTP_RESPONSE_TIMEOUT_MS;
sock = find_socket(req->fd);
if (!sock) {
return -EINVAL;
}
ret = set_xapoll_events(sock, ZSOCK_POLLOUT | ZSOCK_POLLIN);
if (ret) {
LOG_ERR("Failed to set XAPOLL events: %d", ret);
return ret;
}
http_timeout_monitor_arm();
return 0;
}
/* Close and cleanup request */
static void http_close_request(struct http_request *req)
{
if (req->hostname != NULL) {
free(req->hostname);
req->hostname = NULL;
}
if (req->path != NULL) {
free(req->path);
req->path = NULL;
}
if (req->extra_headers != NULL) {
free(req->extra_headers);
req->extra_headers = NULL;
}
if (req->recv_buf != NULL) {
free(req->recv_buf);
req->recv_buf = NULL;
}
if (req->send_buf != NULL) {
free(req->send_buf);
req->send_buf = NULL;
}
if (req->fd >= 0) {
/* Stop XAPOLL events for this socket */
struct sm_socket *sock = find_socket(req->fd);
if (sock) {
xapoll_stop(sock);
}
req->fd = -1;
}
/* Clear datamode_req if it points to this request */
if (datamode_req == req) {
datamode_req = NULL;
}
/* Free this request and clear its slot */
for (int i = 0; i < HTTP_MAX_REQUESTS; i++) {
if (http_requests[i] == req) {
http_requests[i] = NULL;
break;
}
}
free(req);
}
/* Send error via XHTTPCSTAT with -1 status code */
static void http_send_error(struct http_request *req)
{
urc_send_to(req->pipe, "\r\n#XHTTPCSTAT: %d,-1,%d,%d\r\n", req->fd,
req->total_received, (int)req->connection_close);
}
/* Send status URC */
static void http_send_status(struct http_request *req)
{
urc_send_to(req->pipe, "\r\n#XHTTPCSTAT: %d,%d,%d,%d\r\n", req->fd, req->status_code,
req->total_received, (int)req->connection_close);
}
/* Send cancel status URC with bytes already delivered to host */
static void http_send_cancel_status(struct http_request *req)
{
urc_send_to(req->pipe, "\r\n#XHTTPCSTAT: %d,-1,%d,%d\r\n", req->fd,
req->bytes_sent, (int)req->connection_close);
}
/* Send error and close request */
static void http_fail_request(struct http_request *req)
{
http_send_error(req);
http_close_request(req);
}
/* Send status URC and close request (successful completion) */
static void http_finish_request(struct http_request *req)
{
http_send_status(req);
http_close_request(req);
}
/* Send headers complete URC */
static void http_send_headers_complete(struct http_request *req)
{
urc_send_to(req->pipe, "\r\n#XHTTPCHEAD: %d,%d,%d\r\n", req->fd, req->status_code,
req->content_length);
}
/* Send data URC followed by raw bytes */
static void http_send_data(struct http_request *req, const uint8_t *data, int len)
{
if (len <= 0) {
return;
}
urc_send_to(req->pipe, "\r\n#XHTTPCDATA: %d,%d,%d\r\n", req->fd, req->bytes_sent, len);
req->bytes_sent += len;
data_send(req->pipe, data, len);
}
/*
* Detect HTTP/1.1 chunked transfer EOF marker in a body data buffer.
* The final chunk is always "0\r\n\r\n" (zero-length chunk, RFC 9112 §7.1.1).
*/
static bool chunked_eof(const uint8_t *data, int len)
{
return len >= 5 && memcmp(data + len - 5, "0\r\n\r\n", 5) == 0;
}
/* Parse HTTP status code from response buffer */
static int parse_http_status_code(const char *buf, int *status_code)
{
char *status_line;
int ret;
status_line = strstr(buf, "HTTP/1.");
if (!status_line) {
return -ENOENT;
}
ret = sscanf(status_line, "HTTP/1.%*d %d", status_code);
if (ret != 1) {
LOG_WRN("Failed to parse status code");
return -EINVAL;
}
return 0;
}
/* Parse Connection: close header from response buffer */
static bool parse_connection_close(const char *buf, const char *header_end)
{
const char *p;
p = strstr(buf, "Connection: close");
if (!p) {
p = strstr(buf, "connection: close");
}
return p != NULL && p < header_end;
}
/* Parse Content-Length header from response buffer */
static int parse_content_length(const char *buf, const char *header_end, int *length)
{
char *cl_header;
char *value_start;
int ret;
cl_header = strstr(buf, "Content-Length:");
if (!cl_header) {
cl_header = strstr(buf, "content-length:");
}
if (!cl_header || cl_header >= header_end) {
return -ENOENT;
}
value_start = cl_header + STRLIT_LEN("Content-Length:"); /* Skip "Content-Length:" */
while (*value_start == ' ') {
value_start++;
}
ret = sscanf(value_start, "%d", length);
if (ret != 1) {
return -EINVAL;
}
return 0;
}
/* Called when the complete HTTP response header has been received.
* Parses status/content-length, handles piggybacked body data, and notifies the host.
* Returns true if the http request was finished (prematurely).
*/
static bool http_headers_complete(struct http_request *req, char *header_end,
struct sm_socket *sock, bool hup)
{
int ret;
int body_offset = header_end - (char *)req->recv_buf + STRLIT_LEN("\r\n\r\n");
int body_len = req->recv_buf_len - body_offset;
ret = parse_http_status_code((char *)req->recv_buf, &req->status_code);
if (ret < 0) {
LOG_WRN("HTTP %d: Failed to parse status code: %d", req->fd, ret);
}
ret = parse_content_length((char *)req->recv_buf, header_end, &req->content_length);
if (ret == 0) {
LOG_INF("HTTP %d: Content-Length=%d", req->fd, req->content_length);
} else {
LOG_DBG("HTTP %d: No Content-Length header", req->fd);
}
req->connection_close = parse_connection_close((char *)req->recv_buf, header_end);
if (req->connection_close) {
LOG_INF("HTTP %d: Server sent Connection: close", req->fd);
}
req->headers_complete = true;
req->state = HTTP_STATE_RECEIVING_BODY;
/* Adjust total_received to count only body bytes, not header bytes.
* Must be done before any early return so that #XHTTPCSTAT always
* reports body bytes (0 for HEAD/204/304, actual body for others).
*/
req->total_received -= body_offset;
http_send_headers_complete(req);
/* HEAD responses never carry a body (RFC 9110 §9.3.2). Finish now. */
if (req->method == HTTP_HEAD) {
http_finish_request(req);
return true;
}
/* 1xx, 204 No Content and 304 Not Modified have no body (RFC 9110 §6.3). */
if (req->status_code / 100 == 1 ||
req->status_code == 204 ||
req->status_code == 304) {
http_finish_request(req);
return true;
}
if (req->manual_mode) {
/*
* Keep piggybacked body bytes (if any) for the first pull.
* Stop XAPOLL so only the host drives reception via
* AT#XHTTPCDATA=<handle>.
*/
if (body_len > 0)
memmove(req->recv_buf, req->recv_buf + body_offset, body_len);
req->recv_buf_len = body_len;
LOG_DBG("HTTP %d: Headers complete (manual), status %d, piggybacked=%d",
req->fd, req->status_code, req->recv_buf_len);
xapoll_stop(sock);
/* need_rearm_pollin stays false */
return true;
}
/* Auto mode: send any piggybacked body bytes immediately */
if (body_len > 0)
http_send_data(req, req->recv_buf + body_offset, body_len);
/* Clear buffer for next recv */
req->recv_buf_len = 0;
LOG_DBG("HTTP %d: Headers complete, status %d", req->fd, req->status_code);
/*
* If POLLHUP arrived together with POLLIN, the connection is already
* closing; finish now rather than re-arming POLLIN on a socket that
* will never fire again.
*/
if (hup) {
if (req->content_length > 0 && req->bytes_sent < req->content_length)
LOG_WRN("HTTP %d: Incomplete transfer - received %d/%d bytes",
req->fd, req->bytes_sent, req->content_length);
http_finish_request(req);
return true;
}
/*
* Finish early when all body data is already in hand (piggybacked):
* either content-length is satisfied, or chunked terminator was received.
* With keep-alive connections there is no subsequent EOF to trigger the
* completion check in the RECEIVING_BODY path.
*/
if ((req->content_length >= 0 && req->bytes_sent >= req->content_length) ||
(req->content_length < 0 &&
chunked_eof(req->recv_buf + body_offset, body_len))) {
http_finish_request(req);
return true;
}
return false;
}
static void http_warn_incomplete_transfer(const struct http_request *req)
{
if (req->content_length > 0 &&
req->total_received < req->content_length &&
!req->connection_close) {
LOG_WRN("HTTP %d: Incomplete transfer - received %d/%d bytes",
req->fd, req->total_received, req->content_length);
}
}
/*
* Read from the socket into recv_buf. On success, updates recv_buf_len,
* total_received, and the idle timeout.
*
* Returns: >0 bytes read
* 0 EOF (connection closed)
* -1 EAGAIN (POLLIN re-armed)
* -errno other recv error (caller should fail the request)
*/
static int http_recv_read(struct http_request *req, struct sm_socket *sock)
{
int ret;
ret = zsock_recv(req->fd, req->recv_buf + req->recv_buf_len,
HTTP_RECV_BUF_SIZE - req->recv_buf_len - 1, MSG_DONTWAIT);
if (ret < 0) {
if (errno == EAGAIN || errno == EWOULDBLOCK) {
set_xapoll_events(sock, ZSOCK_POLLIN);
return -1;
}
if (errno == ETIMEDOUT) {
LOG_ERR("Recv timed out");
return -ETIMEDOUT;
}
LOG_ERR("Recv failed: %d", errno);
return -errno;
}
if (ret == 0) {
return 0;
}
req->recv_buf_len += ret;
req->recv_buf[req->recv_buf_len] = '\0';
req->total_received += ret;
req->timeout_timestamp = k_uptime_get() + HTTP_RESPONSE_TIMEOUT_MS;
return ret;
}
static void http_process_recv_headers(struct http_request *req, struct sm_socket *sock,
uint8_t events)
{
char *header_end = strstr((char *)req->recv_buf, "\r\n\r\n");
if (header_end) {
if (http_headers_complete(req, header_end, sock, events & ZSOCK_POLLHUP)) {
return;
}
req->need_rearm_pollin = true;
return;
}
if (req->recv_buf_len >= HTTP_RECV_BUF_SIZE - 1) {
LOG_ERR("HTTP headers too large");
http_fail_request(req);
return;
}
req->need_rearm_pollin = true;
}
static void http_process_recv_body(struct http_request *req, struct sm_socket *sock,
uint8_t events)
{
bool body_done;
if (req->manual_mode) {
/*
* POLLIN fired in body state after xapoll_stop (race).
* zsock_recv already consumed bytes from the socket buffer
* into recv_buf and incremented total_received. Keep
* recv_buf intact so the host can pull it; do NOT reset
* recv_buf_len or the data is silently lost.
*/
xapoll_stop(sock);
return;
}
body_done = chunked_eof(req->recv_buf, req->recv_buf_len);
http_send_data(req, req->recv_buf, req->recv_buf_len);
req->recv_buf_len = 0;
/* Finish if content-length satisfied, chunked EOF, or connection closing. */
if (body_done ||
(req->content_length > 0 && req->bytes_sent >= req->content_length) ||
(events & ZSOCK_POLLHUP)) {
http_finish_request(req);
return;
}
req->need_rearm_pollin = true;
}
/* Process HTTP request state machine (event-driven via XAPOLL) */
static void http_process_request(struct http_request *req, uint8_t events)
{
int ret;
struct sm_socket *sock = find_socket(req->fd);
if (!sock) {
LOG_ERR("HTTP %d: Socket not found", req->fd);
http_fail_request(req);
return;
}
LOG_DBG("HTTP %d: process_request state=%d events=0x%x time=%lld timeout=%lld", req->fd,
req->state, events, k_uptime_get(), req->timeout_timestamp);
/* POLLERR/POLLNVAL are always fatal; POLLHUP is handled per-state below. */
if (events & (ZSOCK_POLLERR | ZSOCK_POLLNVAL)) {
LOG_ERR("HTTP %d: Socket error (events=0x%x)", req->fd, events);
http_fail_request(req);
return;
}
/* POLLHUP during sending means the server closed the connection unexpectedly. */
if ((events & ZSOCK_POLLHUP) && req->state == HTTP_STATE_SENDING_REQUEST) {
LOG_ERR("HTTP %d: Connection closed during send (events=0x%x)", req->fd,
events);
http_fail_request(req);
return;
}
switch (req->state) {
case HTTP_STATE_SENDING_REQUEST:
/* Handle writable socket */
if (events & ZSOCK_POLLOUT) {
ret = zsock_send(req->fd, req->send_ptr, req->send_remaining,
MSG_DONTWAIT);
if (ret < 0) {
if (errno == EAGAIN || errno == EWOULDBLOCK) {
/* Need to wait for next POLLOUT */
set_xapoll_events(sock, ZSOCK_POLLOUT | ZSOCK_POLLIN);
return;
}
LOG_ERR("Send failed: %d", errno);
http_fail_request(req);
return;
}
req->send_ptr += ret;
req->send_remaining -= ret;
if (req->send_remaining == 0) {
/* All headers sent, now wait for response */
req->state = HTTP_STATE_RECEIVING_HEADERS;
req->recv_buf_len = 0;
set_xapoll_events(sock, ZSOCK_POLLIN);
} else {
/* More to send */
set_xapoll_events(sock, ZSOCK_POLLOUT | ZSOCK_POLLIN);
}
}
break;
case HTTP_STATE_RECEIVING_HEADERS:
/*
* POLLHUP without POLLIN: closed before any response. When POLLIN
* arrives at the same time, drain the socket buffer (e.g. Connection: close).
*/
if ((events & ZSOCK_POLLHUP) && !(events & ZSOCK_POLLIN)) {
LOG_ERR("HTTP %d: Connection closed before headers (POLLHUP)",
req->fd);
http_fail_request(req);
return;
}
if (!(events & ZSOCK_POLLIN)) {
return;
}
ret = http_recv_read(req, sock);
if (ret < 0) {
if (ret != -1) {
http_fail_request(req);
}
return;
}
if (ret == 0) {
http_fail_request(req);
return;
}
http_process_recv_headers(req, sock, events);
break;
case HTTP_STATE_RECEIVING_BODY:
/* POLLHUP alone: server closed cleanly after sending body. */
if ((events & ZSOCK_POLLHUP) && !(events & ZSOCK_POLLIN)) {
http_warn_incomplete_transfer(req);
http_finish_request(req);
return;
}
if (!(events & ZSOCK_POLLIN)) {
return;
}
ret = http_recv_read(req, sock);
if (ret < 0) {
if (ret != -1) {
http_fail_request(req);
}
return;
}
if (ret == 0) {
http_warn_incomplete_transfer(req);
http_finish_request(req);
return;
}
http_process_recv_body(req, sock, events);
break;
case HTTP_STATE_IDLE:
/* Nothing to do */
break;
default:
LOG_ERR("Invalid state: %d", req->state);
break;
}
}
/* Public function called by socket layer when poll events occur */
bool sm_at_httpc_poll_event(int fd, uint8_t events)
{
struct http_request *req = NULL;
k_mutex_lock(&http_mutex, K_FOREVER);
req = find_request(fd);
if (req) {
req->need_rearm_pollin = false;
http_process_request(req, events);
/* req may have been freed by http_process_request; re-find safely */
req = find_request(fd);
}
k_mutex_unlock(&http_mutex);
return (req && req->need_rearm_pollin);
}
/* Build HTTP request headers and send them synchronously for streaming POST/PUT */
static int http_send_request_headers(struct http_request *req)
{
int ret;
int sent;
int n;
LOG_INF("HTTP %d %s (streaming): %s:%d%s", req->method,
http_method_str[req->method], req->hostname, req->port, req->path);
ret = http_alloc_build_headers(req);
if (ret < 0) {
return ret;
}
req->timeout_timestamp = k_uptime_get() + HTTP_RESPONSE_TIMEOUT_MS;
/* Send headers synchronously (blocking) */
sent = 0;
while (sent < ret) {
n = zsock_send(req->fd, req->send_buf + sent, ret - sent, 0);
if (n < 0) {
return -errno;
}
sent += n;
req->timeout_timestamp = k_uptime_get() + HTTP_RESPONSE_TIMEOUT_MS;
}
free(req->send_buf);
req->send_buf = NULL;
/* Headers sent; body will now be streamed via data mode. */
req->state = HTTP_STATE_SENDING_BODY;
http_timeout_monitor_arm();
return 0;
}
/* Data mode callback: streams POST/PUT body directly to socket */
static int http_datamode_callback(uint8_t op, const uint8_t *data, int len, uint8_t flags)
{
int err = 0;
if (op == DATAMODE_SEND) {
if (!datamode_req) {
LOG_ERR("No request for data mode");
exit_datamode_handler(sm_at_host_get_current(), -EINVAL);
return -EINVAL;
}
/* Stream body chunk directly to the socket */
int sent = 0;
while (sent < len) {
int ret = zsock_send(datamode_req->fd, data + sent, len - sent, 0);
if (ret < 0) {
int err_code = -errno;
struct http_request *req_failed = datamode_req;
datamode_req = NULL;
LOG_ERR("Failed to stream request body: %d", err_code);
exit_datamode_handler(sm_at_host_get_current(), err_code);
http_fail_request(req_failed);
return err_code;
}
sent += ret;
}