-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathsession.cpp
More file actions
428 lines (364 loc) · 12.4 KB
/
Copy pathsession.cpp
File metadata and controls
428 lines (364 loc) · 12.4 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
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
//
// C++ Implementation: session
//
// Description: The handler of a Session.
//
// Author: Huy Phan <hphan@hphan-hp>, (C) 2008-2009
//
// Created: 04/15/2009
//
#include <netinet/in.h>
#include <arpa/inet.h>
#include <st.h>
#include "hoxEnums.h"
#include "hoxLog.h"
#include "hoxExcept.h"
#include "hoxDebug.h"
#include "hoxTypes.h"
#include "hoxSocketAPI.h"
#include "hoxSessionMgr.h"
#include "hoxUtil.h"
#include "hoxTable.h"
#include "hoxDbClient.h"
#include "hoxFileMgr.h"
#include <boost/tokenizer.hpp>
#include <sstream>
#include <map>
/******************************************************************
* Constants
*/
#define NEW_PLAYER_SCORE 1500 /* The initial score of new Players. */
#define SESSION_MANAGER_INTERVAL 5 /* Session manager interval (in seconds) */
#define TABLE_MANAGER_INTERVAL 1 /* Table manager interval (in seconds) */
/******************************************************************
* Extern declaration
*/
extern int my_index; /* Current process index: defined in main.cpp */
extern pid_t my_pid; /* Current process pid: defined in main.cpp */
/******************************************************************
* Implementation
*/
/**
* Send back a response to the client.
*/
void
_write_response( st_netfd_t nfd,
hoxResponse_SPtr pResponse,
hoxClientType clientType )
{
std::string sResp = pResponse->toString();
if ( clientType == hoxCLIENT_TYPE_HTTP )
{
sResp = hoxPollingSession::build_http_response( sResp );
}
else if ( clientType == hoxCLIENT_TYPE_FLASH )
{
sResp += '\0';
}
(void) hoxSocketAPI::write_data( nfd, sResp );
}
/**
* Handle the special REGISTER request.
*/
void
_handle_request_REGISTER( st_netfd_t nfd,
const hoxRequest_SPtr& pRequest,
hoxClientType clientType )
{
const char* FNAME = __FUNCTION__;
hoxResult result = hoxRC_UNKNOWN;
hoxResponse_SPtr pResponse;
std::string sContent;
hoxLog(LOG_INFO, "%s: ENTER.", FNAME);
try
{
const std::string sPlayerId = pRequest->getParam("pid");
const std::string hpassword = pRequest->getParam("password");
const std::string sEmail = pRequest->getParam("email");
if ( sPlayerId.empty() || hpassword.empty() )
{
throw hoxError(hoxRC_ERR, "Player-ID or Password is empty");
}
hoxPlayer_SPtr pPlayer( new hoxPlayer( sPlayerId ) );
/* Check if the Player's ID has been taken. */
if ( hoxRC_OK == hoxDbClient::get_player_info( pPlayer ) )
{
throw hoxError(hoxRC_NOT_FOUND, "Player-ID not available");
}
pPlayer->setScore( NEW_PLAYER_SCORE );
pPlayer->setHPassword( hpassword );
/* Put (save/create) this new Player into the Database. */
if ( hoxRC_OK != hoxDbClient::put_player_info( pPlayer, sEmail ) )
{
throw hoxError(hoxRC_ERR, "Failed to register new player into DB");
}
sContent = "Successfully registered new account: [" + sPlayerId + "]";
result = hoxRC_OK;
}
catch( hoxError error )
{
result = error.code();
sContent = error.what();
hoxLog(LOG_WARN, "%s: Error caught [%s].", FNAME, error.toString().c_str());
}
/* Return the response. */
pResponse.reset( new hoxResponse( pRequest->getType(), result ) );
pResponse->setContent( sContent + std::string("\n") );
_write_response( nfd, pResponse, clientType );
}
/**
* Read the FIRST incoming request from a given socket.
*/
hoxResult
_read_first_request( const int thread_id,
st_netfd_t nfd,
hoxClientType& clientType,
hoxRequest_SPtr& pRequest )
{
const struct in_addr* from = (struct in_addr *) st_netfd_getspecific(nfd);
hoxResult result = hoxRC_UNKNOWN;
std::string sRequest;
clientType = hoxCLIENT_TYPE_HOXCHESS; // The default client-type.
result = hoxSocketAPI::read_line( nfd, sRequest, PERSIST_READ_TIMEOUT );
if ( sRequest.empty() ) /* Check for socket-close condition. */
{
return hoxRC_CLOSED; // Empty request due to socket-close
}
else if ( result != hoxRC_OK )
{
hoxLog(LOG_INFO, "%s: (Thread %d) Failed to read request from [%s].",
__FUNCTION__, thread_id, inet_ntoa(*from) );
return result;
}
/* Check if this is a HTTP (GET/POST) request. */
hoxHttpRequest httpRequest;
if ( sRequest.find("GET") == 0 || sRequest.find("POST") == 0 )
{
httpRequest.parseURI( sRequest );
result = httpRequest.continueReadRequest( nfd );
if ( result != hoxRC_OK )
{
return result;
}
if ( httpRequest.method == "GET" )
{
hoxPollingSession::handle_http_GET( nfd, httpRequest );
return hoxRC_HANDLED;
}
else // ... POST method, the 'real' request is in the body.
{
sRequest = httpRequest.body;
hoxUtil::trimLast( sRequest, '\n' );
clientType = hoxCLIENT_TYPE_HTTP;
}
}
/* Parse the request as HOXChess-specific request. */
hoxLog(LOG_DEBUG, "%s: Request: [%s]", __FUNCTION__, sRequest.c_str());
pRequest.reset( new hoxRequest( sRequest ) );
if ( ! pRequest->isValid() )
{
hoxLog(LOG_INFO, "%s: Request [%s] is invalid.", __FUNCTION__, sRequest.c_str());
return hoxRC_NOT_VALID;
}
/* Detect and specially handle Flash-based clients. */
if ( pRequest->getType() == hoxREQUEST_LOGIN )
{
const std::string sVersion = pRequest->getParam("version");
hoxLog(LOG_INFO, "%s: LOGIN: client version = [%s].", __FUNCTION__, sVersion.c_str());
if ( sVersion.find("FLASHCHESS") == 0 ) {
clientType = hoxCLIENT_TYPE_FLASH;
} else if ( sVersion.find("hoxTest") == 0 ) {
clientType = hoxCLIENT_TYPE_TEST;
}
}
return hoxRC_OK;
}
/**
* Authenticate a normal Player.
* Retrieve the player's info from the Database and compare password.
*/
hoxPlayer_SPtr
_authenticate_player( const std::string& sPlayerId,
const std::string& hpassword )
{
hoxPlayer_SPtr pPlayer( new hoxPlayer( sPlayerId ) );
if ( hoxRC_OK != hoxDbClient::get_player_info( pPlayer ) )
{
throw hoxError(hoxRC_NOT_FOUND, "Failed to get player's info");
}
if ( pPlayer->getScore() == 0 && pPlayer->getHPassword().empty() )
{
hoxLog(LOG_INFO, "%s: Player [%s] not found in DB.", __FUNCTION__, sPlayerId.c_str());
throw hoxError(hoxRC_NOT_FOUND, "Authentication failed");
}
else if ( hpassword != pPlayer->getHPassword() )
{
hoxLog(LOG_INFO, "%s: Player [%s] entered wrong password.", __FUNCTION__, sPlayerId.c_str());
throw hoxError(hoxRC_NOT_VALID, "Wrong password");
}
return pPlayer;
}
/**
* Authenticate a Guest.
* @note: No need to do anything as we already checked for
* existing session (with the same guest-ID).
*/
hoxPlayer_SPtr
_authenticate_guest( const std::string& sPlayerId )
{
hoxPlayer_SPtr pPlayer( new hoxPlayer(sPlayerId, hoxPLAYER_TYPE_GUEST) );
pPlayer->setScore( NEW_PLAYER_SCORE );
hoxLog(LOG_INFO, "%s: Guest [%s] authenticated with score = [%d].",
__FUNCTION__, sPlayerId.c_str(), pPlayer->getScore() );
return pPlayer;
}
/**
* Authenticate a request.
*/
hoxSession_SPtr
_authenticate_request( st_netfd_t nfd,
const hoxRequest_SPtr& pRequest,
const hoxClientType clientType,
hoxResponse_SPtr& pResponse )
{
hoxSession_SPtr pSession;
hoxPlayer_SPtr pPlayer;
const hoxRequestType requestType = pRequest->getType();
const std::string sPlayerId = pRequest->getParam("pid");
const std::string sSessionId = pRequest->getParam("sid");
const std::string hpassword = pRequest->getParam("password");
const bool bIsGuest = ( sPlayerId.find("Guest#") == 0 );
try
{
pSession = hoxSessionMgr::getInstance()->findSession( sPlayerId );
if ( pSession )
{
if ( pSession->getId() == sSessionId )
{
hoxLog(LOG_DEBUG, "%s: Reuse session [%s %s].",
__FUNCTION__, sSessionId.c_str(), sPlayerId.c_str());
// FIXME: Need to update the network connection 'nfd'.
return pSession;
}
}
/* Make sure that the request is LOGIN. */
if ( requestType != hoxREQUEST_LOGIN )
{
throw hoxError(hoxRC_NOT_ALLOWED, "Not yet authenticated");
}
/* Perform authentication. */
if ( bIsGuest ) pPlayer = _authenticate_guest( sPlayerId );
else pPlayer = _authenticate_player( sPlayerId, hpassword );
/* If there is an existing Session, then close it first. */
if ( pSession )
{
if ( !bIsGuest && pSession->resumeConnection( nfd, clientType ) )
{
hoxLog(LOG_DEBUG, "%s: Resume session (after LOGIN) [%s %s].",
__FUNCTION__, sSessionId.c_str(), sPlayerId.c_str());
return pSession;
}
hoxLog(LOG_INFO, "%s: Closing existing session [%s]...", __FUNCTION__, pSession->getId().c_str());
hoxSessionMgr::getInstance()->closeAndDeleteSession( pSession );
hoxASSERT_MSG(!pSession, "Existing session should have been deleted");
}
/* Create a new session. */
pSession = hoxSessionMgr::getInstance()->createSession( clientType, nfd, pPlayer );
if ( ! pSession )
{
throw hoxError(hoxRC_ERR, "Failed to create a Session");
}
}
catch( const hoxError error )
{
pResponse.reset( new hoxResponse( requestType, error.code() ) );
pResponse->setContent( error.what() + std::string("\n") );
hoxLog(LOG_INFO, "%s: Error caught [%s].", __FUNCTION__, error.toString().c_str());
pSession.reset();
}
return pSession;
}
/**
* Handle session.
*/
void
handle_session( const int thread_id,
st_netfd_t nfd )
{
hoxClientType clientType;
hoxRequest_SPtr pRequest;
hoxResponse_SPtr pResponse;
/* Read the 1st request. */
hoxResult result = _read_first_request( thread_id, nfd, clientType, pRequest );
if ( result != hoxRC_OK )
{
return;
}
/* Handle the special REGISTER request. */
if ( pRequest->getType() == hoxREQUEST_REGISTER )
{
_handle_request_REGISTER( nfd, pRequest, clientType );
return;
}
/* (1) Authenticate the request, and ...
* (2) Create a Session for the client.
*/
hoxSession_SPtr pSession = _authenticate_request( nfd, pRequest, clientType, pResponse );
if ( ! pSession )
{
hoxLog(LOG_INFO, "%s: Failed to authenticate.", __FUNCTION__);
_write_response( nfd, pResponse, clientType );
return; // *** Done after writing error response.
}
try
{
pSession->handleFirstRequest( pRequest );
pSession->runEventLoop();
}
catch( const hoxError error )
{
hoxLog(LOG_INFO, "%s: Error caught [%s].", __FUNCTION__, error.toString().c_str());
}
/* ================================================
* Cleanup session if required.
* ================================================ */
if ( pSession )
{
if ( pSession->getState() == hoxSESSION_STATE_SHUTDOWN
|| clientType == hoxCLIENT_TYPE_TEST )
{
hoxLog(LOG_DEBUG, "%s: Delete session [%s]...", __FUNCTION__, pSession->getId().c_str());
hoxSessionMgr::getInstance()->closeAndDeleteSession( pSession );
hoxASSERT_MSG(!pSession, "Existing session should have been deleted");
}
}
}
/**
* The "session-manager" thread.
*/
void*
session_manager_thread( void* arg )
{
for (;;)
{
st_sleep( SESSION_MANAGER_INTERVAL );
hoxSessionMgr::getInstance()->manageSessions();
}
/* NOTREACHED */
return NULL;
}
/**
* The "table-manager" thread.
*/
void*
table_manager_thread( void* arg )
{
for (;;)
{
st_sleep( TABLE_MANAGER_INTERVAL );
hoxTableMgr::getInstance()->manageTables();
}
/* NOTREACHED */
return NULL;
}
/******************* END OF FILE *********************************************/