| 2034 | } |
| 2035 | |
| 2036 | void cbm_http_server_run(cbm_http_server_t *srv) { |
| 2037 | if (!srv) |
| 2038 | return; |
| 2039 | int expected = HTTP_RUN_SCHEDULED; |
| 2040 | if (!atomic_compare_exchange_strong_explicit(&srv->run_state, &expected, HTTP_RUN_RUNNING, |
| 2041 | memory_order_acq_rel, memory_order_acquire)) |
| 2042 | return; |
| 2043 | if (!srv->listener_ok) { |
| 2044 | atomic_store_explicit(&srv->run_state, HTTP_RUN_COMPLETED, memory_order_release); |
| 2045 | return; |
| 2046 | } |
| 2047 | |
| 2048 | while (!atomic_load(&srv->stop_flag)) { |
| 2049 | cbm_http_conn_t *conn = cbm_httpd_accept(srv->listener, 200); |
| 2050 | if (!conn) |
| 2051 | continue; /* timeout — re-check stop flag */ |
| 2052 | |
| 2053 | uint64_t request_start_ms = cbm_now_ms(); |
| 2054 | cbm_http_req_t req; |
| 2055 | int rc = cbm_httpd_read_request(conn, &req); |
| 2056 | if (rc == 0) { |
| 2057 | if (atomic_load(&srv->stop_flag)) { |
| 2058 | cbm_http_req_free(&req); |
| 2059 | cbm_httpd_conn_close(conn); |
| 2060 | break; |
| 2061 | } |
| 2062 | dispatch_request(srv, conn, &req); |
| 2063 | cbm_log_http_request("graph_ui", req.method, req.path, cbm_http_conn_status(conn), |
| 2064 | (int64_t)(cbm_now_ms() - request_start_ms), req.body_len, |
| 2065 | cbm_http_conn_response_bytes(conn)); |
| 2066 | cbm_http_req_free(&req); |
| 2067 | } else if (rc > 0) { |
| 2068 | /* Parse/transport error with a known HTTP status (400/408/411/413/431). |
| 2069 | * No CORS reflection here — the request was never parsed. */ |
| 2070 | cbm_http_replyf(conn, rc, "", "bad request"); |
| 2071 | cbm_log_http_request("graph_ui", "", "", cbm_http_conn_status(conn), |
| 2072 | (int64_t)(cbm_now_ms() - request_start_ms), 0, |
| 2073 | cbm_http_conn_response_bytes(conn)); |
| 2074 | } |
| 2075 | cbm_httpd_conn_close(conn); |
| 2076 | } |
| 2077 | atomic_store_explicit(&srv->run_state, HTTP_RUN_COMPLETED, memory_order_release); |
| 2078 | } |
| 2079 | |
| 2080 | cbm_httpd_activity_t cbm_http_server_activity_for_test(cbm_http_server_t *srv) { |
| 2081 | return srv ? cbm_httpd_activity_for_test(srv->listener) : CBM_HTTPD_ACTIVITY_IDLE; |