Repository navigation
Expand file tree
/
Copy pathtactionthread.cpp
More file actions
229 lines (181 loc) · 5.83 KB
/
Copy pathtactionthread.cpp
File metadata and controls
229 lines (181 loc) · 5.83 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
/* Copyright (c) 2010-2015, AOYAMA Kazuharu
* All rights reserved.
*
* This software may be used and distributed according to the terms of
* the New BSD License, which is incorporated herein by reference.
*/
#include <QCoreApplication>
#include <QEventLoop>
#include <TActionThread>
#include <TWebApplication>
#include <THttpRequest>
#include <TSession>
#include <TApplicationServerBase>
#include <TAppSettings>
#include <atomic>
#include "thttpsocket.h"
#include "twebsocket.h"
#include "tsystemglobal.h"
#include "tsessionmanager.h"
#include "tfcore.h"
static std::atomic<int> threadCounter(0);
static int keepAliveTimeout = -1;
int TActionThread::threadCount()
{
return threadCounter.load();
}
bool TActionThread::waitForAllDone(int msec)
{
int cnt;
QTime time;
time.start();
while ((cnt = threadCount()) > 0) {
if (time.elapsed() > msec) {
break;
}
Tf::msleep(10);
qApp->processEvents();
}
return cnt == 0;
}
/*!
\class TActionThread
\brief The TActionThread class provides a thread context.
*/
TActionThread::TActionThread(int socket)
: QThread(), TActionContext(), httpSocket(nullptr)
{
++threadCounter;
TActionContext::socketDesc = socket;
if (keepAliveTimeout < 0) {
int timeout = Tf::appSettings()->value(Tf::HttpKeepAliveTimeout, "10").toInt();
keepAliveTimeout = qMax(timeout, 0);
}
}
TActionThread::~TActionThread()
{
if (httpSocket) {
httpSocket->deleteLater();
}
if (TActionContext::socketDesc > 0)
tf_close(TActionContext::socketDesc);
--threadCounter;
}
void TActionThread::run()
{
QList<THttpRequest> reqs;
QEventLoop eventLoop;
httpSocket = new THttpSocket();
if (Q_UNLIKELY(!httpSocket->setSocketDescriptor(TActionContext::socketDesc))) {
emitError(httpSocket->error());
goto socket_error;
}
TActionContext::socketDesc = 0;
for (;;) {
reqs = readRequest(httpSocket);
tSystemDebug("HTTP request count: %d", reqs.count());
if (Q_UNLIKELY(reqs.isEmpty())) {
break;
}
for (auto &req : reqs) {
// WebSocket?
QByteArray connectionHeader = req.header().rawHeader("Connection").toLower();
if (Q_UNLIKELY(connectionHeader.contains("upgrade"))) {
QByteArray upgradeHeader = req.header().rawHeader("Upgrade").toLower();
tSystemDebug("Upgrade: %s", upgradeHeader.data());
if (upgradeHeader == "websocket") {
// Switch to WebSocket
if (!handshakeForWebSocket(req.header())) {
goto socket_error;
}
}
goto socket_cleanup;
}
TActionContext::execute(req, httpSocket->socketId());
httpSocket->flush(); // Flush socket
TActionContext::release();
}
if (keepAliveTimeout == 0) {
break;
}
// Next request
while (!httpSocket->waitForReadyRead(100)) {
if (httpSocket->state() != QAbstractSocket::ConnectedState) {
if (httpSocket->error() != QAbstractSocket::RemoteHostClosedError) {
tSystemWarn("Error occurred : error:%d socket:%d", httpSocket->error(), httpSocket->socketId());
}
goto receive_end;
}
if (httpSocket->idleTime() >= keepAliveTimeout) {
tSystemDebug("KeepAlive timeout : socket:%d", httpSocket->socketId());
goto receive_end;
}
while (eventLoop.processEvents(QEventLoop::ExcludeSocketNotifiers)) {}
}
}
receive_end:
closeHttpSocket(); // disconnect
socket_cleanup:
// For cleanup
while (eventLoop.processEvents()) {}
socket_error:
httpSocket->deleteLater();
httpSocket = nullptr;
}
void TActionThread::emitError(int socketError)
{
emit error(socketError);
}
QList<THttpRequest> TActionThread::readRequest(THttpSocket *socket)
{
QList<THttpRequest> reqs;
while (!socket->canReadRequest()) {
// Check idle timeout
if (Q_UNLIKELY(keepAliveTimeout > 0 && socket->idleTime() >= keepAliveTimeout)) {
tSystemWarn("Reading a socket timed out after %d seconds. Descriptor:%d", keepAliveTimeout, (int)socket->socketDescriptor());
break;
}
if (Q_UNLIKELY(socket->socketDescriptor() <= 0)) {
tSystemWarn("Invalid descriptor (disconnected) : %d", (int)socket->socketDescriptor());
break;
}
socket->waitForReadyRead(500); // Repeats per 500 msecs
}
if (Q_UNLIKELY(!socket->canReadRequest())) {
socket->abort();
} else {
reqs = socket->read();
}
return reqs;
}
qint64 TActionThread::writeResponse(THttpResponseHeader &header, QIODevice *body)
{
if (keepAliveTimeout > 0) {
header.setRawHeader("Connection", "Keep-Alive");
}
return httpSocket->write(static_cast<THttpHeader*>(&header), body);
}
void TActionThread::closeHttpSocket()
{
httpSocket->close();
}
bool TActionThread::handshakeForWebSocket(const THttpRequestHeader &header)
{
if (!TWebSocket::searchEndpoint(header)) {
return false;
}
// Switch to WebSocket
int sd = TApplicationServerBase::duplicateSocket(httpSocket->socketDescriptor());
TWebSocket *ws = new TWebSocket(sd, httpSocket->peerAddress(), header);
connect(ws, SIGNAL(disconnected()), ws, SLOT(deleteLater()));
ws->moveToThread(Tf::app()->thread());
// WebSocket opening
TSession session;
QByteArray sessionId = header.cookie(TSession::sessionName());
if (!sessionId.isEmpty()) {
// Finds a session
session = TSessionManager::instance().findSession(sessionId);
}
ws->startWorkerForOpening(session);
return true;
}