Skip to content

Commit 87bc256

Browse files
committed
http server: fix race condition for server->closed
1 parent da240b6 commit 87bc256

File tree

1 file changed

+7
-16
lines changed

1 file changed

+7
-16
lines changed

src/supplemental/http/http_server.c

+7-16
Original file line numberDiff line numberDiff line change
@@ -49,13 +49,13 @@ typedef struct http_sconn {
4949
nni_http_handler *handler; // set if we deferred to read body
5050
nni_http_handler *release; // set if we dispatched handler
5151
bool close;
52-
bool closed;
5352
bool finished;
5453
nni_aio *cbaio;
5554
nni_aio *rxaio;
5655
nni_aio *txaio;
5756
nni_aio *txdataio;
5857
nni_reap_node reap;
58+
nni_atomic_flag closed;
5959
} http_sconn;
6060

6161
typedef struct http_error {
@@ -310,16 +310,15 @@ http_sc_reap(void *arg)
310310
}
311311

312312
static void
313-
http_sc_close_locked(http_sconn *sc)
313+
http_sconn_close(http_sconn *sc)
314314
{
315315
nni_http_conn *conn;
316316

317-
if (sc->closed) {
317+
if (nni_atomic_flag_test_and_set(&sc->closed)) {
318318
return;
319319
}
320320
NNI_ASSERT(!sc->finished);
321321

322-
sc->closed = true;
323322
nni_aio_close(sc->rxaio);
324323
nni_aio_close(sc->txaio);
325324
nni_aio_close(sc->txdataio);
@@ -331,17 +330,6 @@ http_sc_close_locked(http_sconn *sc)
331330
nni_reap(&http_sc_reap_list, sc);
332331
}
333332

334-
static void
335-
http_sconn_close(http_sconn *sc)
336-
{
337-
nni_http_server *s;
338-
s = sc->server;
339-
340-
nni_mtx_lock(&s->mtx);
341-
http_sc_close_locked(sc);
342-
nni_mtx_unlock(&s->mtx);
343-
}
344-
345333
static void
346334
http_sconn_txdatdone(void *arg)
347335
{
@@ -987,13 +975,16 @@ nni_http_server_init(nni_http_server **serverp, const nng_url *url)
987975

988976
nni_mtx_lock(&http_servers_lk);
989977
NNI_LIST_FOREACH (&http_servers, s) {
978+
nni_mtx_lock(&s->mtx);
990979
if ((!s->closed) && (url->u_port == s->port) &&
991980
(strcmp(url->u_hostname, s->hostname) == 0)) {
992981
*serverp = s;
993982
s->refcnt++;
983+
nni_mtx_unlock(&s->mtx);
994984
nni_mtx_unlock(&http_servers_lk);
995985
return (0);
996986
}
987+
nni_mtx_unlock(&s->mtx);
997988
}
998989

999990
// We didn't find a server, try to make a new one.
@@ -1065,7 +1056,7 @@ http_server_stop(nni_http_server *s)
10651056
// Stopping the server is a hard stop -- it aborts any work
10661057
// being done by clients. (No graceful shutdown).
10671058
NNI_LIST_FOREACH (&s->conns, sc) {
1068-
http_sc_close_locked(sc);
1059+
http_sconn_close(sc);
10691060
}
10701061
}
10711062

0 commit comments

Comments
 (0)