-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHttpSession.cpp
More file actions
375 lines (336 loc) · 7.59 KB
/
HttpSession.cpp
File metadata and controls
375 lines (336 loc) · 7.59 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
#include "HttpHeader.h"
#include "HttpServer.h"
#include "HttpSession.h"
#include <stdlib.h>
#include <memory.h>
#define MAX_BUF_SIZE (4096)
CHttpSession::CHttpSession()
{
m_pHttpParse = NULL;
m_strRootPath = ".";
m_remoteSock = INVALID_SOCKET;
memset(&m_remoteAddr, 0, sizeof(m_remoteAddr));
m_pServer = NULL;
m_bExit = false;
m_bPaused = false;
}
CHttpSession::~CHttpSession()
{
Stop();
}
int CHttpSession::Start(class CHttpServer* pServer, SOCKET sock, SOCKADDR_IN remoteAddr, string strRootPath)
{
m_pHttpParse = new CHttpRequestParse();
m_pServer = pServer;
m_strRootPath = strRootPath;
m_remoteSock = sock;
m_remoteAddr = remoteAddr;
pthread_create(&m_hWorkThread, NULL, WorkThread, this);
return 0;
}
int CHttpSession::Stop()
{
m_bExit = true;
m_bPaused = false;
if(m_remoteSock != INVALID_SOCKET)
{
close(m_remoteSock);
m_remoteSock = INVALID_SOCKET;
}
pthread_join(m_hWorkThread, NULL);
if(m_pHttpParse)
{
delete m_pHttpParse;
m_pHttpParse = NULL;
}
return 0;
}
int CHttpSession::Pause(){
m_bPaused = true;
return 0;
}
int CHttpSession::Resume(){
m_bPaused = false;
return 0;
}
void* CHttpSession::WorkThread(void* pParam)
{
CHttpSession* pObj = (CHttpSession*)pParam;
while(!pObj->m_bExit)
{
fd_set read_fds;
struct timeval timeout;
timeout.tv_sec = 1;
timeout.tv_usec = 0;
SOCKET sock = pObj->m_remoteSock;
FD_ZERO(&read_fds);
FD_SET(sock, &read_fds);
int maxfd = sock + 1;
int nRet = select(maxfd, &read_fds, NULL, NULL, &timeout);
if(nRet == 0)
{
continue;
}
else if(nRet > 0)
{
char buffer[MAX_BUF_SIZE] = {0};
int nLen = recv(sock, buffer, MAX_BUF_SIZE, 0);
if(nLen <= 0)
{
printf("client disconnect\n");
pObj->m_pServer->ExitClient(sock);
break;
}
int nRet = pObj->ParseBuffer(buffer, nLen);
if(nRet == 0)
{
printf("disconnect client\n");
pObj->m_pServer->ExitClient(sock);
break;
}
}
else
{
printf("disconnect client\n");
pObj->m_pServer->ExitClient(sock);
break;
}
}
return NULL;
}
int CHttpSession::Send(char* pBuffer, int nLen)
{
int nLeftLen = nLen;
char* pTmpBuffer = pBuffer;
while(nLeftLen > 0)
{
int nToSend = min(1316, nLeftLen);
fd_set write_fds;
struct timeval timeout;
FD_ZERO(&write_fds);
FD_SET(m_remoteSock, &write_fds);
timeout.tv_sec = 1;
timeout.tv_usec = 0;
int maxfd = m_remoteSock+1;
int nRet = select(maxfd, NULL, &write_fds, NULL, &timeout);
if(nRet > 0)
{
int nSent = 0;
if (FD_ISSET(m_remoteSock, &write_fds))
{
nSent = send(m_remoteSock, (char*)pTmpBuffer, (int)nToSend, 0);
if(nSent < 0)
{
return -1;
}
}
nLeftLen -= nSent;
pTmpBuffer += nSent;
}
else if(nRet < 0)
{
return -1;
}
else
{
continue;
}
}
return 0;
}
int CHttpSession::SendHttpError(int nErrorCode)
{
const char *not_found =
"HTTP/1.1 404 Not Found\r\n"
"Content-Type: text/html\r\n"
"Content-Length: 40\r\n"
"\r\n"
"<HTML><BODY>File not found</BODY></HTML>\r\n";
const char *bad_request =
"HTTP/1.1 400 Bad Request\r\n"
"Content-Type: text/html\r\n"
"Content-Length: 39\r\n"
"\r\n"
"<h1>Bad Request (Invalid Hostname)</h1>\r\n";
const char* nul_request =
"HTTP/1.1 204 OK"
"Content-Type: text/html"
"Content-Length: 0"
"\r\n";
switch(nErrorCode)
{
case 404:
Send((char*)not_found, (int)strlen(not_found));
break;
case 400:
Send((char*)bad_request, (int)strlen(bad_request));
break;
case 204:
Send((char*)nul_request, (int)strlen(nul_request));
break;
default:
Send((char*)not_found, (int)strlen(not_found));
break;
}
return 0;
}
int CHttpSession::SendHttpString(string strData)
{
int nRetCode = 200;
int nContLen = strData.length();
char resp_head[MAX_BUF_SIZE];
sprintf(resp_head,
"HTTP/1.1 %d OK\r\n"
"Accept-Ranges: bytes\r\n"
"Content-Length:%u\r\n"
"Content-Type: text/plain\r\n"
"\r\n", nRetCode, nContLen);
Send(resp_head, strlen(resp_head));
Send((char*)strData.c_str(), strData.length());
return 0;
}
int CHttpSession::ProcessFileRequest(string strFileName, int nFileStart, int nFileStop)
{
if(nFileStop != 0 && nFileStop < nFileStart){
SendHttpError(400);
return -1;
}
strFileName = m_strRootPath + "/" + strFileName;
FILE* pFile = fopen(strFileName.c_str(), "rb");
if(pFile == NULL)
{
printf("open file failed, filename = %s\n", strFileName.c_str());
SendHttpError(404);
return -1;
}
fseek(pFile, 0, SEEK_END);
int nFileSize = ftell(pFile);
if(nFileStart > nFileSize){
fclose(pFile);
SendHttpError(400);
return -1;
}
fseek(pFile, nFileStart, SEEK_SET);
if(nFileStop == 0){
nFileStop = nFileSize-1;
}
int nRetCode = 200;
string strFileExt = "";
string strContentType = "application/octet-stream";
size_t nPos = strFileName.find_last_of(".");
if(nPos != string::npos)
{
strFileExt = strFileName.substr(nPos+1, strFileName.length()-nPos);
}
string strdest;
strdest.resize(strFileExt.size());
transform(strFileExt.begin(), strFileExt.end(), strdest.begin(), ::tolower);
if(m_pHttpParse)
{
strContentType = m_pHttpParse->GetContentType(strFileExt);
}
int nContentSize = nFileStop - nFileStart + 1;
char resp_head[MAX_BUF_SIZE];
sprintf(resp_head,
"HTTP/1.1 %d OK\r\n"
"Accept-Ranges: bytes\r\n"
"Content-Length:%d\r\n"
"Content-Range: bytes %d-%d/%d\r\n"
"Content-Type: %s\r\n"
"\r\n",
nRetCode,
nContentSize,
nFileStart, nFileStop, nFileSize,
strContentType.c_str()
);
Send(resp_head, strlen(resp_head));
printf("%s", resp_head);
char buffer[4096];
int readed = 0;
int remainSize = nContentSize;
while(true && !m_bExit)
{
if(m_bPaused){
usleep(200);
continue;
}
int sendSize = min(4096, remainSize);
readed = (int)fread(buffer, 1, sendSize, pFile);
if(readed <= 0)
{
break;
}
if(Send(buffer, readed) != 0)
{
break;
}
remainSize -= readed;
}
fclose(pFile);
return 0;
}
//返回值 0:断开连接 1:保持连接
int CHttpSession::ParseBuffer(char* pBuffer, int nLen)
{
printf("%s", pBuffer);
if(m_pHttpParse == NULL)
{
SendHttpError(400);
return 0;
}
//nRet=0正常结束 <0有错误 >0http头未结束
int nRet = m_pHttpParse->Input(pBuffer, m_stRequestInfo);
if(nRet < 0)
{
SendHttpError(400);
return 0;
}
else if(nRet > 0)
{
return 1;
}
if(m_stRequestInfo.method == "GET")
{
string szURLName;
if(m_stRequestInfo.url != "/" && m_stRequestInfo.url != "")
{
szURLName = m_stRequestInfo.url.substr(1, m_stRequestInfo.url.length());
int nFileStart = 0;
int nFileStop = 0;
http_header::iterator it_range = m_stRequestInfo.http_headers.find("Range");
if(it_range != m_stRequestInfo.http_headers.end())
{
string szRangeContext = it_range->second;
size_t nPos0 = szRangeContext.find('=');
size_t nPos1 = szRangeContext.find('-');
if(nPos1 != string::npos && nPos1 != string::npos)
{
string szStart = szRangeContext.substr(nPos0+1, nPos1-nPos0-1);
string szStop = szRangeContext.substr(nPos1+1, szRangeContext.length());
nFileStart = atoi(szStart.data());
nFileStop = atoi(szStop.data());
}
}
ProcessFileRequest(szURLName, nFileStart, nFileStop);
}
}
else if(m_stRequestInfo.method == "POST")
{
SendHttpString(m_stRequestInfo.body);
}
bool bKeepAlive = false;
http_header::iterator it_connection = m_stRequestInfo.http_headers.find("Connection");
if(it_connection != m_stRequestInfo.http_headers.end())
{
if(it_connection->second == "keep-alive")
{
bKeepAlive = true;
}
}
m_stRequestInfo.body = "";
m_stRequestInfo.http_headers.clear();
m_stRequestInfo.method = "";
m_stRequestInfo.url = "";
m_stRequestInfo.version = "";
return bKeepAlive ? 1 : 0;
}