Skip to content

Commit 70ef32d

Browse files
committed
net:http-server: fix potential race condition around HttpState::ping
1 parent 48c97f9 commit 70ef32d

File tree

2 files changed

+25
-7
lines changed

2 files changed

+25
-7
lines changed

code/components/net-http-server/include/HttpServer.h

+3
Original file line numberDiff line numberDiff line change
@@ -106,6 +106,9 @@ struct HttpState
106106

107107
// a function to call when we want to unblock the request
108108
std::function<void()> ping;
109+
110+
// a lock for ping being set
111+
std::mutex pingLock;
109112
};
110113

111114
class

code/components/net-http-server/src/Http1Server.cpp

+22-7
Original file line numberDiff line numberDiff line change
@@ -144,7 +144,7 @@ class Http1Response : public HttpResponse
144144

145145
virtual void End() override
146146
{
147-
if (m_chunked)
147+
if (m_chunked && m_clientStream.GetRef())
148148
{
149149
// assume chunked
150150
m_clientStream->Write("0\r\n\r\n");
@@ -154,13 +154,20 @@ class Http1Response : public HttpResponse
154154
{
155155
m_requestState->blocked = false;
156156

157-
if (m_requestState->ping)
157+
decltype(m_requestState->ping) ping;
158+
159+
{
160+
std::unique_lock<std::mutex> lock(m_requestState->pingLock);
161+
ping = m_requestState->ping;
162+
}
163+
164+
if (ping)
158165
{
159-
m_requestState->ping();
166+
ping();
160167
}
161168
}
162169

163-
if (m_closeConnection)
170+
if (m_closeConnection && m_clientStream.GetRef())
164171
{
165172
m_clientStream->Close();
166173
}
@@ -479,10 +486,17 @@ void HttpServerImpl::OnConnection(fwRefContainer<TcpServerStream> stream)
479486
}
480487
};
481488

482-
reqState->ping = [=]()
483489
{
484-
readCallback({});
485-
};
490+
std::unique_lock<std::mutex> lock(reqState->pingLock);
491+
492+
reqState->ping = [readCallback]()
493+
{
494+
if (readCallback)
495+
{
496+
readCallback({});
497+
}
498+
};
499+
}
486500

487501
stream->SetReadCallback(readCallback);
488502

@@ -502,6 +516,7 @@ void HttpServerImpl::OnConnection(fwRefContainer<TcpServerStream> stream)
502516
connectionData->request = nullptr;
503517
}
504518

519+
std::unique_lock<std::mutex> lock(reqState->pingLock);
505520
reqState->ping = {};
506521
});
507522
}

0 commit comments

Comments
 (0)