void Server::accept(SessionPtr session, const error_code& error) { if (mRunning) { if (!error) { session->start(); printf("Connection established\n"); } listen(); } }
bool AsioServerTransport::reflect( const SessionPtr &sessionPtr1, const SessionPtr &sessionPtr2) { AsioSessionState & sessionState1 = dynamic_cast<AsioSessionState &>(sessionPtr1->getSessionState()); AsioSessionStatePtr sessionStatePtr1 = sessionState1.sharedFromThis(); AsioSessionState & sessionState2 = dynamic_cast<AsioSessionState &>(sessionPtr2->getSessionState()); AsioSessionStatePtr sessionStatePtr2 = sessionState2.sharedFromThis(); sessionStatePtr1->mReflecteeWeakPtr = sessionStatePtr2; sessionStatePtr2->mReflecteeWeakPtr = sessionStatePtr1; sessionStatePtr1->mReflecting = true; sessionStatePtr2->mReflecting = true; return true; }
void SessionManager::createSessionCallback(int result, const SessionPtr& session, const SessionCallback& callback) { if (!result) { applyGlobalSessionTimeout(session); onStart(session); notifyStart(session); sessions.insert(std::pair<std::string, SessionPtr>(session->getId(), session)); callback(session); } else { callback(SessionPtr()); } }
bool AsioServerTransport::reflect( const SessionPtr &sessionPtr1, const SessionPtr &sessionPtr2) { RCF2_TRACE(""); AsioSessionState & sessionState1 = dynamic_cast<AsioSessionState &>(sessionPtr1->getProactor()); AsioSessionStatePtr sessionStatePtr1 = sessionState1.shared_from_this(); AsioSessionState & sessionState2 = dynamic_cast<AsioSessionState &>(sessionPtr2->getProactor()); AsioSessionStatePtr sessionStatePtr2 = sessionState2.shared_from_this(); sessionStatePtr1->mReflecteeWeakPtr = sessionStatePtr2; sessionStatePtr2->mReflecteeWeakPtr = sessionStatePtr1; sessionStatePtr1->mReflecting = true; sessionStatePtr2->mReflecting = true; return true; }
bool ClientPool::bind(Ice::Long connection, const JidPtr& j, const string& ticket, bool flush) { MCE_DEBUG("ClientPool::bind --> connectionId:" << connection << " jid:" << jidToString(j)); int isBind = 0; Ice::Long oldConId = 0; bool res = true; { IceUtil::Mutex::Lock lock(_mutex); map<Ice::Long,ClientBufferPtr>::iterator it = _clients.find(j->index); if (it == _clients.end()) { ClientBufferPtr c = new ClientBuffer(); c->bind(j,connection); _clients[j->index] = c; c->timestamp(time(NULL)); isBind = 1; } else { //if(flush && it->second->isFlush()) { // isBind = 2; //} oldConId = it->second->activeConnection(); bool res = it->second->bind(j,connection); if(res == false) { return false; } it->second->timestamp(time(NULL)); if(oldConId != connection && oldConId) { IdleConnManager::instance().cometConnSwitch(); }else{ oldConId = 0; } } } if(isBind > 0){ try { MCE_INFO("ClientPool::bind --> invoke WTalkProxy bind " << isBind << ", " << jidToString(j) << ", ac_conn " << connection); res = WTalkProxyAdapter::instance().bind(boost::lexical_cast<string>(j->index), ticket, j); } catch(Ice::Exception& e) { MCE_WARN("ClientPool::bind --> invoke WTalkProxy bind err" << isBind << ", " << jidToString(j) << ", ac_conn " << connection << ", " << e); } } if(oldConId > 0){ SessionPtr s = Server::instance().getSession(oldConId); SessionPtr newSession = Server::instance().getSession(connection); if (s) { s->needUnbind(false); MCE_DEBUG("ClientPool::bind --> jid " << jidToString(j) << " change from " << s->jid()->userId << "_" << oldConId << " to " << newSession->jid()->userId << "_" << connection); s->responseClose(211,"code:211, comet old connection close"); } } return res; }
void SessionManager::removeSession(const SessionPtr& session) { if( !session ) return; SessionHash* hash = session->getHash(); assert(hash); auto it = sessions.Find(*hash); if (it == sessions.End()) return; sessions.Erase(it); onSessionRemoved(session); }
json SessionApi::serializeSession(const SessionPtr& aSession) noexcept { return{ { "id", aSession->getId() }, { "secure", aSession->isSecure() }, { "last_activity", aSession->getLastActivity() }, { "ip", aSession->getIp() }, { "user", { { "id", aSession->getUser()->getToken() }, { "username", aSession->getUser()->getUserName() }, } } }; }
void SessionListener::processPresence(const SessionPtr& session, const xml_document_ptr& doc) { string to = doc->child("presence").attribute("to").value(); if (to.empty()) { session->presence(doc->xml()); } else { MCE_DEBUG("presence to muc, " << to); IdType type = idType(to); if (type == ROOMID || type == ROOMJID) { MCE_DEBUG("presence to muc, " << to); //MucPresenceAdapter::instance().message(session->jid(), doc->xml()); MucPresenceMsgHandlerAdapter::instance().message(session->jid(), doc->xml()); } else if (type == JID) { session->presence(doc->xml()); } else { MCE_INFO("DefultAction::execute --> invalid id"); } } if (session->state() == SessionStateLogin) { LoginProcedureStat::instance().incPresence(); string type = doc->child("presence").attribute("type").value(); if (type != "subscribe" && type != "subscribed" && type != "unsubscribed") { string ver = ""; string subver = ""; string ext = ""; string secver = ""; string show = ""; xml_node cNode = doc->child("presence").child("c"); if (cNode) { ver = cNode.attribute("ver").value(); ext = cNode.attribute("ext").value(); subver = cNode.attribute("subver").value(); secver = cNode.attribute("secver").value(); } xml_node showNode = doc->child("presence").child("show"); if (showNode) { show = showNode.first_child().value(); } try { PresenceMsgHandlerAdapter::instance().presenceWithSecver(session->jid(),show,ver,subver,ext,secver); } catch(Ice::Exception& e) { MCE_WARN("PresenceAction::handle --> talklogic presence err :"<<e); } doc->child("presence").remove_child("status"); session->state(SessionStateChat); } } }
ClientTransportAutoPtr AsioServerTransport::createClientTransport( SessionPtr sessionPtr) { AsioSessionState & sessionState = dynamic_cast<AsioSessionState &>(sessionPtr->getSessionState()); AsioSessionStatePtr sessionStatePtr = sessionState.sharedFromThis(); ClientTransportAutoPtr clientTransportPtr = sessionStatePtr->implCreateClientTransport(); ConnectionOrientedClientTransport & coClientTransport = static_cast<ConnectionOrientedClientTransport &>( *clientTransportPtr); coClientTransport.setRcfSession(sessionState.mSessionPtr); sessionState.mSocketOpsMutexPtr.reset( new Mutex() ); coClientTransport.setSocketOpsMutex(sessionState.mSocketOpsMutexPtr); return clientTransportPtr; }
void MessageHandler::OnError(SessionPtr session, int errorType, int errorCode, const std::string& errorMsg) { std::stringstream ss; switch (errorType) { case -1: ss << "Network - Listening Error (" << session->GetId() << ") : " << errorMsg; LogManager::Warning(ss.str()); break; case 0: ss << "Network - Connection Error (" << session->GetId() << ") : " << errorMsg; LogManager::Warning(ss.str()); break; case 1: ss << "Network - Receiving Error (" << session->GetId() << ") : " << errorMsg; LogManager::Warning(ss.str()); break; case 2: ss << "Network - Sending Error (" << session->GetId() << ") : " << errorMsg; LogManager::Warning(ss.str()); break; default: ss << "Network Error (" << session->GetId() << ") : " << errorMsg; LogManager::Warning(ss.str()); break; } /* if(errorCode == 2 // boost::asio::error::eof || errorCode == 995 // boost::asio::error::operation_aborted || errorCode == 10009 // boost::asio::error::bad_descriptor || errorCode == 10054 // boost::asio::error::connection_reset ) session->Close(); */ session->Close(); }
void UdpServerTransport::cycle( int timeoutMs, const volatile bool &) //stopFlag { // poll the UDP socket for messages, and read a message if one is available fd_set fdSet; FD_ZERO(&fdSet); FD_SET( static_cast<SOCKET>(mFd), &fdSet); timeval timeout; timeout.tv_sec = timeoutMs/1000; timeout.tv_usec = 1000*(timeoutMs%1000); int ret = Platform::OS::BsdSockets::select( mFd+1, &fdSet, NULL, NULL, timeoutMs < 0 ? NULL : &timeout); int err = Platform::OS::BsdSockets::GetLastError(); if (ret == 1) { SessionStatePtr sessionStatePtr = getCurrentUdpSessionStatePtr(); if (sessionStatePtr.get() == NULL) { sessionStatePtr = SessionStatePtr(new SessionState(*this)); SessionPtr sessionPtr = getSessionManager().createSession(); sessionPtr->setSessionState(*sessionStatePtr); sessionStatePtr->mSessionPtr = sessionPtr; setCurrentUdpSessionStatePtr(sessionStatePtr); } { // read a message ReallocBufferPtr &readVecPtr = sessionStatePtr->mReadVecPtr; if (readVecPtr.get() == NULL || !readVecPtr.unique()) { readVecPtr.reset( new ReallocBuffer()); } ReallocBuffer &buffer = *readVecPtr; SockAddrStorage from; int fromlen = sizeof(from); memset(&from, 0, sizeof(from)); buffer.resize(4); int len = Platform::OS::BsdSockets::recvfrom( mFd, &buffer[0], 4, MSG_PEEK, (sockaddr *) &from, &fromlen); err = Platform::OS::BsdSockets::GetLastError(); sessionStatePtr->mRemoteAddress = IpAddress( (sockaddr&) from, fromlen, mIpAddress.getType()); if (!isIpAllowed(sessionStatePtr->mRemoteAddress)) { RCF_LOG_2()(sessionStatePtr->mRemoteAddress.getIp()) << "Client IP does not match server's IP access rules. Closing connection."; discardPacket(mFd); } else if ( len == 4 || (len == -1 && err == Platform::OS::BsdSockets::ERR_EMSGSIZE)) { unsigned int dataLength = 0; memcpy(&dataLength, &buffer[0], 4); networkToMachineOrder(&dataLength, 4, 1); if ( 0 < dataLength && dataLength <= static_cast<unsigned int>(getMaxMessageLength())) { buffer.resize(4+dataLength); memset(&from, 0, sizeof(from)); fromlen = sizeof(from); len = Platform::OS::BsdSockets::recvfrom( mFd, &buffer[0], 4+dataLength, 0, (sockaddr *) &from, &fromlen); if (static_cast<unsigned int>(len) == 4+dataLength) { getSessionManager().onReadCompleted(sessionStatePtr->mSessionPtr); } } else { ByteBuffer byteBuffer; encodeServerError(getSessionManager(), byteBuffer, RcfError_ServerMessageLength); byteBuffer.expandIntoLeftMargin(4); * (boost::uint32_t *) ( byteBuffer.getPtr() ) = static_cast<boost::uint32_t>(byteBuffer.getLength()-4); RCF::machineToNetworkOrder(byteBuffer.getPtr(), 4, 1); char *buffer = byteBuffer.getPtr(); std::size_t bufferLen = byteBuffer.getLength(); sockaddr * pRemoteAddr = NULL; Platform::OS::BsdSockets::socklen_t remoteAddrSize = 0; sessionStatePtr->mRemoteAddress.getSockAddr(pRemoteAddr, remoteAddrSize); int len = sendto( mFd, buffer, static_cast<int>(bufferLen), 0, pRemoteAddr, remoteAddrSize); RCF_UNUSED_VARIABLE(len); discardPacket(mFd); } } else { discardPacket(mFd); } } } else if (ret == 0) { //RCF_LOG_4()(mFd)(mPort)(timeoutMs) << "UdpServerTransport - no messages received within polling interval."; } else if (ret == -1) { Exception e( _RcfError_Socket(), err, RcfSubsystem_Os, "udp server select() failed "); RCF_THROW(e)(mFd)(mIpAddress.string())(err); } }
bool HttpParser::feed(const SessionPtr& session, string& data) { MCE_DEBUG("HttpParser::feed --> data:"<<data); //_tmp += data; if (_head.length() + data.length() + _postData.length() + _tmp.length() > 1024*20) { return false; } bool f = true; _tmp += data; //data = ""; while (f) { size_t p = string::npos; if (_head.empty()) { p = _tmp.find("\r\n\r\n"); } else { _postData += _tmp; _tmp = ""; // MCE_DEBUG("HttpParser::feed --> post_data:"<<_postData // << " length:"<<_postData.length()); if (_postData.length() >= _contentLength && _contentLength >=0) { if (_props["method"] == "post") { if (_contentLength == 0) { _props["body"] = ""; } else { _props["body"] = _postData.substr(0, _contentLength-1); } RequestPtr r = new Request(); if (!r->init(_props)) { return false; } session->recvRequest(r); session->response(r); _head = ""; _postData = ""; _tmp = ""; _props.clear(); _contentLength = 0; // session->shutdown(); return true; } } return true; } if (p != string::npos) { _head = _tmp.substr(0, p); _tmp = _tmp.substr(p+4); vector<string> splitVec; split(splitVec, _head, is_any_of("\r\n"), token_compress_on); vector<string> tmpVec; split(tmpVec, splitVec.at(0), is_space(), token_compress_on); if (tmpVec.size() < 3) { return false; } _props["method"] = to_lower_copy(tmpVec.at(0)); _props["path"] = tmpVec.at(1); size_t pos; const size_t offset = strlen("HTTP/"); if ((pos = tmpVec.at(2).find('.', offset)) != string::npos) { _props["version_high"] = tmpVec.at(2).substr(offset, pos - offset); _props["version_low"] = tmpVec.at(2).substr(pos + 1); } else { _props["version_high"] = tmpVec.at(2).substr(offset); _props["version_low"] = "0"; } for (vector<string>::iterator it = splitVec.begin()+1; it != splitVec.end(); ++it) { pos = it->find(':'); if (pos == string::npos) { //throw std::exception(); return false; } string name = trim_copy(it->substr(0, pos)); name = to_lower_copy(name); string value = trim_copy(it->substr(pos + 1)); _props[name] = value; if (name == "content-length") { try { _contentLength = boost::lexical_cast<int>(value); } catch(std::exception& e) { MCE_WARN("HttpParser::feed --> parse content length err:"<< e.what()); } } } if (_props["method"] == "get") { RequestPtr r = new Request(); if (!r->init(_props)) { return false; } _head = ""; _postData = ""; _tmp = ""; _props.clear(); _contentLength = 0; // RequestHandler::instance().handle(session,r); session->recvRequest(r); session->response(r); return true; } else if (_props["method"] == "post") { continue; } else { return false; } } else { return true; } } return true; }
void JsonRequestMessageHandler::OnConnect(SessionPtr session) { MessageHandler::OnConnect(session); if(session) session->SetOrderlyHandling(1, false); // no orderly msg ... }
void JsonRequestMessageHandler::OnConnect(SessionPtr session) { MessageHandler::OnConnect(session); session->SetOrderlyHandling(1, true); // orderly incoming msg ... }
TEST( NodeDaoTest, CRUD ) { mld::SparkseeManager sparkseeManager(mld::kRESOURCES_DIR + L"mysparksee.cfg"); sparkseeManager.createDatabase(mld::kRESOURCES_DIR + L"MLDTest.sparksee", L"MLDTest"); SessionPtr sess = sparkseeManager.newSession(); Graph* g = sess->GetGraph(); // Create Db scheme sparkseeManager.createBaseScheme(g); std::unique_ptr<NodeDao> dao( new NodeDao(g) ); mld::Node a(dao->invalidNode()), b(dao->invalidNode()); EXPECT_EQ(a, b); // mld::Node a2(0, AttrMap()); // EXPECT_EQ(a, a2); // EXPECT_DOUBLE_EQ(kNODE_DEF_VALUE, a2.weight()); mld::Node n1 = dao->addNode(); EXPECT_EQ(NODE_DEF_VALUE, n1.weight()); n1.setWeight(15); n1.setLabel(L"test"); // Update node content EXPECT_TRUE(dao->updateNode(n1)); // Get mld::Node n1_update(dao->getNode(n1.id())); EXPECT_EQ(n1.id(), n1_update.id()); EXPECT_EQ(15, n1_update.weight()); EXPECT_EQ(L"test", n1_update.label()); EXPECT_EQ(n1, n1_update); // Add user property not persist in db n1.data()[L"prop"].SetBooleanVoid(true); // Not equal in memory EXPECT_NE(n1_update, n1); EXPECT_TRUE(dao->updateNode(n1)); mld::Node n1_bis(dao->getNode(n1.id())); // Update the db, drop user prop when read back from db EXPECT_EQ(n1_bis, n1_update); // GET invalid node mld::Node u = dao->getNode(Objects::InvalidOID); EXPECT_EQ(Objects::InvalidOID, u.id()); // Invalid get node, exception is catched if MLD_SAFE flag is defined #ifdef MLD_SAFE mld::Node t = dao->getNode(15434); EXPECT_EQ(Objects::InvalidOID, t.id()); // Invalid remove node, exception is catched if MLD_SAFE flag is defined dao->removeNode(123123); #endif // Remove n1 node dao->removeNode(n1.id()); #ifdef MLD_SAFE u = dao->getNode(n1.id()); EXPECT_EQ(Objects::InvalidOID, u.id()); #endif dao->addNode(); dao->addNode(); // Get from Objets ObjectsPtr all(g->Select(dao->nodeType())); EXPECT_EQ(2, all->Count()); std::vector<mld::Node> allVec = dao->getNode(all); EXPECT_EQ(size_t(2), allVec.size()); // Add arbitrary prop in nodes Value v; v.SetDouble(42.0); EXPECT_TRUE(sparkseeManager.addAttrToNode(g, L"test", Double, Basic, v)); // To update model dao.reset( new NodeDao(g) ); auto n2( dao->addNode() ); EXPECT_DOUBLE_EQ(42.0, n2.data().at(L"test").GetDouble()); all.reset(); dao.reset(); sess.reset(); }
void ConnectionStat::responseClose(const SessionPtr& session, int status_code, const string& msg ) { session->shutdown(); }
void ConnectionStat::deliver(const SessionPtr& session, int status_code, int cache_time, bool is_gzip, bool keep_alive, const string& extra_header, const string& body, bool bin_data, const string& content_type, const string& nogzipmsg) { //MCE_DEBUG("ConnectionStat::deliver --> " << jidToString(session->jid()) << " body:" << body); ostringstream res; if (status_code != 200) { if (status_code == 403) { res << "HTTP/1.1 403 Forbidden\r\n"; } else if(status_code == 408){ res << "HTTP/1.1 408 Request Timeout\r\n"; } else if(status_code == 211){ res << "HTTP/1.1 211 Comet Switch\r\n"; }else { res << "HTTP/1.1 404 Not Found\r\n"; } } else { res << "HTTP/1.1 200 OK\r\n"; } if (is_gzip && !body.empty() && (!bin_data) && (!Server::instance().isWap())) { res << "Content-Encoding: gzip\r\n"; } res << "Server: XNHttpServer1.0\r\n" << "Content-Type: "<<content_type <<"\r\n" << "Content-Length: "<< body.length()<<"\r\n" << extra_header; if (keep_alive) { res << "Connection: keep-alive\r\n" << "Keep-Alive: 300\r\n"; } else { res << "Connection: close\r\n"; } if (cache_time > 0 && status_code == 200) { res << "Cache-Control: max-age="<< cache_time << "\r\n"; res << "Expires: "<< gmtTime(time(NULL)+cache_time)<< "\r\n"; } else if (cache_time == -1) { res << "Cache-Control: max-age="<<60*60*24*10<<"\r\n"; res << "Expires: "<< gmtTime(time(NULL)+60*60*24*10)<< "\r\n"; } else if (cache_time == 0) { res << "Cache-Control: no-cache"<< "\r\n" << "Expires: Thu, 01 Jan 1970 00:00:00 GMT"<< "\r\n"; } res << "\r\n"; // MCE_DEBUG("ConnectionStat -->deliver :"<< res.str() << " ISWAP:"<<IS_WAP); res.write(body.c_str(), body.length()); bool ok = false; ok = session->deliver(res.str()); if (!keep_alive) { session->shutdown(); } string msg = nogzipmsg; xml_document doc; if (doc.load(msg.c_str())) { xml_node n = doc.child("msglist").child("message"); for (; n; n = n.next_sibling("message")) { string s = n.child("body").first_child().value(); if( s.find("ugc_content") != string::npos){ MCE_INFO("ConnectionStat::deliver -->deliver ugc_content ok = " << ok); } } }else{ MCE_WARN("CometResponseStat::deliver -->deliver ugc_content document.load error"); } }
void CometResponseStat::responseClose(const SessionPtr& session,int status_code, const string& msg) { MCE_DEBUG("CometResponseStat::responseClose --> connection:" <<session->connectionId()); deliver(session, status_code, 0, false, false, "",msg); // changeStat(session, &ConnectingStat::instance()); }
void ConnectionStat::changeStat(const SessionPtr& session, ConnectionStat* stat) { session->connectionStat(stat); }
void SessionListener::processPresence(const SessionPtr& session, const xml_document_ptr& doc){ xml_node hiNode = doc->child("hi"); string userid = hiNode.child("userid").child_value(); string ticket = hiNode.child("ticket").child_value(); string token = hiNode.child("session").child_value(); MCE_INFO("LoginAction::execute -> userid: " << userid << ", ticket: " << ticket << ", token: " << token); JidPtr jid = new Jid(); try { jid->userId = boost::lexical_cast<int>(userid); } catch (std::exception& e) { MCE_WARN("LoginAction::execute -> invalid userid: " << userid << ", " << e.what()); session->shutdown(); return; } catch (...) { MCE_WARN("LoginAction::execute -> invalid userid: " << userid); session->shutdown(); return; } jid->endpoint = ServiceI::instance().getName(); session->jid(jid); bool success = false; try { success = session->bind(token, ticket);//WTalkProxyAdapter::instance().bind(token, ticket, jid); } catch (Ice::Exception& e) { MCE_WARN("LoginAction::execute -> failure binding, jid: " << jidToString(jid) << ", " << e); session->shutdown(); return; } if (success) { //_session->jid(jid); session->token(token); session->verify(true); //Server::instance().join(_session, jid); string msg = "<?xml version=\"1.0\" encoding=\"utf-8\"?><hi cmd=\"login_res\"><res>0</res></hi>"; msg.push_back('\0'); if (session->deliver(msg)) { MCE_INFO("LoginAction::execute -> success -> userid:"<<userid <<" ticket:"<<ticket); } else { //Server::instance().leave(_session); session->shutdown(); } } else { MCE_WARN("LoginAction::execute -> failure binding, userid:" << userid); string msg = "<?xml version=\"1.0\" encoding=\"utf-8\"?><hi cmd='login_res'><res>1</res></hi>"; msg.push_back('\0'); session->deliver(msg); session->shutdown(); } }
//----------------------------------------------------------------- void CometRecvStat::response(const RequestPtr& request, const SessionPtr& session) { //MCE_DEBUG("CometRecvStat::response --> connection:" // <<session->connectionId()); string strHostId = request->cookie("id"); int hostid = 0; string ticket = request->cookie("t"); string sessionid = request->cookie("wpsid"); string header; if(!strHostId.empty()){ try{ hostid = boost::lexical_cast<int>(strHostId); }catch(...){ MCE_WARN("CometRecvStat::response --> cast err, " << strHostId); } } /*if (kl != "") { size_t p = kl.find("_"); if (p != string::npos) { try { if(p+1 < kl.length()) { hostid = boost::lexical_cast<int>(kl.substr(p+1)); } } catch(std::exception& e) { MCE_WARN("CometResponseStat::response --> hostid not a int err:"<<e.what()); } } }*/ if (hostid<=0 || ticket == "") { deliver(session, 403, 0, false, false, "", "ERROR[403]: please login first"); changeStat(session, &ConnectingStat::instance()); return; } Ice::Long msgId = 0; try { msgId = boost::lexical_cast<Ice::Long>(request->getProperty("mid")); } catch(std::exception& e) { MCE_WARN("CometRecvStat::response --> cast mid err:"<<e.what()); } bool success = false; //if (!session->verify()) { try { bool needSetCookie = false; string domain = "wpi.renren.com"; if(request->host().find("kaixin") != string::npos){ domain = "wpi.kaixin.com"; } if(sessionid == "") { ostringstream os; os << "Set-Cookie: wpsid=" << session->connectionId() <<"; domain=."<<domain<<"; path=/\r\n"; header = os.str(); //用户刷新过程中,同一个sessionid可能连接到不同的接入端,导致用户状态不准,所以sessionid+serverid保证唯一 session->jid(hostid,session->connectionId()+Server::instance().getServerIndex()); needSetCookie = true; MCE_DEBUG("CometRecvStat::response --> sid absent, set cookie " << jidToString(session->jid())); } else { //////////// //added by yuanfei //new user, set a new session id Ice::Long sid = boost::lexical_cast<Ice::Long>(sessionid); sid += Server::instance().getServerIndex(); JidPtr jid = ClientPoolManager::instance().getClientPool(sid).getJid(sid); if(jid && jid->userId!=hostid) { ostringstream os; os << "Set-Cookie: wpsid=" << session->connectionId() <<"; domain=." << domain <<"; path=/\r\n"; header = os.str(); session->jid(hostid,session->connectionId()+Server::instance().getServerIndex()); needSetCookie = true; MCE_DEBUG("CometRecvStat::response --> sid present, userid incorrect, set cookie " << jidToString(session->jid())); } else { session->jid(hostid,sid); } } session->needUnbind(true); //MCE_INFO("ClientPool::bind --> " << jidToString(session->jid()) << ", ac_conn " << session->connectionId()); success = session->bind(ticket,true,false); if (success) { session->verify(true); session->isGzip(request->encoding()); //for new connection if(needSetCookie) { //MCE_DEBUG(); deliver(session, 200, 0, false, true, header,"<msglist><message type='system'><body>login successfully</body></message></msglist>"); changeStat(session,&ConnectingStat::instance()); return; } }else{ MCE_DEBUG("CometRecvStat::response --> verify failed, " << jidToString(session->jid())); deliver(session, 403, 0, false, false, "", "ERROR[403]: verify is false"); changeStat(session, &ConnectingStat::instance()); return; } } catch(Ice::Exception& e) { MCE_WARN("CometRecvStat::response -> failure binding, userid: " << hostid << ", " << e); deliver(session, 403, 0, false, false, "","ERROR[403]: userid bind err"); changeStat(session,&ConnectingStat::instance()); return; } //}else{ // success = session->bind(ticket, msgId==0, false); //} map<string,string> props = request->getProperties(); if (props.find("ins") != props.end()) { MCE_DEBUG("CometRecvStat::response --> do instant return " << jidToString(session->jid())); deliver( session, 200, 0, false, true, "", "<msglist><message type='system'><body>init ajax loop</body></message></msglist>"); changeStat(session, &ConnectingStat::instance()); return; } changeStat(session, &CometResponseStat::instance()); session->deliverNotify(msgId); }
void SessionManager::remove(const SessionPtr& session) { if (session) { sessions.erase(session->getId()); sessionDAO->remove(session, SessionDAO::SessionCallback()); } }
void SessionManager::onStop(const SessionPtr& session) { ptime stopTs = session->getStopTimestamp(); session->setLastAccessTime(stopTs); session->setLogin(false); }
void WapCometResponseStat::responseClose(const SessionPtr& session,int status_code,const string& msg) { MCE_DEBUG("WapCometResponseStat::responseClose --> connection:" <<session->connectionId()); deliver(session, status_code, 0, false, false, "",msg); }
//--------- void WapCometRecvStat::response(const RequestPtr& request, const SessionPtr& session) { MCE_DEBUG("WapCometRecvStat::response --> connection:" <<session->connectionId()); string sid = request->getProperty("sid"); string uid = request->getProperty("uid"); string pw = request->getProperty("pw"); MCE_INFO("@@WapCometRecvStat::response --> " << uid << " " << sid << " " << pw); if (uid.empty() || (sid.empty() && pw.empty())) { MCE_INFO("WapCometRecvStat::response --> parameters error"); deliver(session, 403, 0, false, false, "", "Authentication Error"); // changeStat(session, &ConnectingStat::instance()); return; } if (sid.empty()) { session->jid(boost::lexical_cast<int>(uid),session->connectionId() + Server::instance().getServerIndex()); } else { session->jid(boost::lexical_cast<int>(uid),boost::lexical_cast<Ice::Long>(sid) + Server::instance().getServerIndex()); } Ice::Long msgId = 0; try { msgId = boost::lexical_cast<Ice::Long>(request->getProperty("mid")); } catch(std::exception& e) { MCE_WARN("WapCometRecvStat::response --> cast mid err:"<<e.what()); } //一个比较特殊的处理,mid为-1时,用户立即下线 //考虑再增加一种请求类型 if(msgId == -1){ MCE_INFO("WapCometRecvStat::response --> offline now, " << jidToString(session->jid())); ClientPoolManager::instance().getClientPool(session->jid()->index).unbind(session->jid()->index, session->connectionId(), true); ConnectionStat::deliver(session, 200, 0, false, false, "", "offline now"); return; } // session->needUnbind(true); bool success = false; if(!pw.empty()){ success = session->bind(pw,msgId == 0,true); }else{ success = session->bind(sid,msgId == 0,true); } if(!success) { MCE_INFO("WapCometRecvStat::response --> bind error"); deliver(session, 403, 0, false, false, "", "Authentication Error or Session Expired"); changeStat(session, &ConnectingStat::instance()); return; } session->isGzip(request->encoding()); if(sid.empty()) { deliver(session, 200, 0, false, true, "",boost::lexical_cast<string>(session->connectionId())); changeStat(session,&ConnectingStat::instance()); return; } //MCE_DEBUG("WapCometRecvStat::response --> line:"<<__LINE__); changeStat(session, &WapCometResponseStat::instance()); //MCE_DEBUG("WapCometRecvStat::response --> line:"<<__LINE__); session->deliverNotify(msgId); //MCE_DEBUG("CometRecvStat::response --> line:"<<__LINE__); }
void IOThread::DoIocpJob() { DWORD dwTransferred = 0; LPOVERLAPPED overlapped = nullptr; ULONG_PTR completionKey = 0; int ret = GetQueuedCompletionStatus(mCompletionPort, &dwTransferred, (PULONG_PTR)&completionKey, &overlapped, GQCS_TIMEOUT); /// general I/O processing OverlappedIOContext* context = reinterpret_cast<OverlappedIOContext*>(overlapped); SessionPtr remote = context ? context->mSessionObject : nullptr; if (ret == 0 || dwTransferred == 0) { /// check time out first if ( context == nullptr && GetLastError() == WAIT_TIMEOUT) return; if (context->mIoType == IO_RECV || context->mIoType == IO_SEND) { CRASH_ASSERT(nullptr != remote); /// In most cases in here: ERROR_NETNAME_DELETED(64) remote->Disconnect(DR_COMPLETION_ERROR); DeleteIoContext(context); return; } } CRASH_ASSERT(nullptr != remote); bool completionOk = false; switch (context->mIoType) { case IO_RECV_ZERO: completionOk = remote->PostRecv(); break; case IO_SEND: remote->SendCompletion(dwTransferred); if (context->mWsaBuf.len != dwTransferred) GConsoleLog->PrintOut(true, "Partial SendCompletion requested [%d], sent [%d]\n", context->mWsaBuf.len, dwTransferred); else completionOk = true; break; case IO_RECV: remote->RecvCompletion(dwTransferred); completionOk = remote->PreRecv(); break; default: GConsoleLog->PrintOut(true, "Unknown I/O Type: %d\n", context->mIoType); CRASH_ASSERT(false); break; } if (!completionOk) { /// connection closing remote->Disconnect(DR_IO_REQUEST_ERROR); } DeleteIoContext(context); }
void SessionManager::applyGlobalSessionTimeout(const SessionPtr& session) { session->setTimeout(getGlobalSessionTimeout()); }
int CallInAuthenticateUser::getUserSession() { SessionPtr currentSession; bool reconnectAllowed; if (!APP_CONTEXT.getPropertyManager()->getPropertyBool("session.reconnect", reconnectAllowed)) { reconnectAllowed = true; } if (reconnectAllowed) { currentSession = APP_CONTEXT.getSessionStore()->getFirstDisconnectedSessionUserName(mUserName, mDomainName); if (currentSession) { WLog_Print(logger_CallInAuthenticateUser, WLOG_DEBUG, "found disconnected session - sessionId=%lu, state=%lu", currentSession->getSessionId(), currentSession->getConnectState()); } } if ((!currentSession) || (currentSession->getConnectState() != WTSDisconnected)) { // create new Session for this request currentSession = APP_CONTEXT.getSessionStore()->createSession(); WLog_Print(logger_CallInAuthenticateUser, WLOG_DEBUG, "creating new session - sessionId=%lu", currentSession->getSessionId()); currentSession->setUserName(mUserName); currentSession->setDomain(mDomainName); if (!currentSession->generateUserToken()) { WLog_Print(logger_CallInAuthenticateUser, WLOG_ERROR, "generateUserToken failed for user %s with domain %s", mUserName.c_str(), mDomainName.c_str()); mResult = 1;// will report error with answer return 1; } if (!currentSession->generateEnvBlockAndModify()) { WLog_Print(logger_CallInAuthenticateUser, WLOG_ERROR, "generateEnvBlockAndModify failed for user %s with domain %s", mUserName.c_str(), mDomainName.c_str()); mResult = 1;// will report error with answer return 1; } std::string moduleConfigName; if (!APP_CONTEXT.getPropertyManager()->getPropertyString("module", moduleConfigName)) { moduleConfigName = "X11"; } currentSession->setModuleConfigName(moduleConfigName); } else { WLog_Print(logger_CallInAuthenticateUser, WLOG_DEBUG, "connecting to disconnected session - sessionId=%lu", currentSession->getSessionId()); currentSession->setConnectState(WTSConnectQuery); } UINT32 connectionId = APP_CONTEXT.getConnectionStore()->getConnectionIdForSessionId(mSessionId); APP_CONTEXT.getConnectionStore()->getOrCreateConnection(connectionId)->setAbout2SwitchSessionId(currentSession->getSessionId()); if (currentSession->getConnectState() == WTSDown) { std::string pipeName; if (!currentSession->startModule(pipeName)) { WLog_Print(logger_CallInAuthenticateUser, WLOG_ERROR, "ModuleConfig %s does not start properly for user %s in domain %s", currentSession->getModuleConfigName().c_str(), mUserName.c_str(), mDomainName.c_str()); mResult = 1;// will report error with answer return 1; } } WLog_Print(logger_CallInAuthenticateUser, WLOG_DEBUG, "switching from session %lu to session %lu", mSessionId, currentSession->getSessionId()); TaskSwitchToPtr switchToTask = TaskSwitchToPtr(new TaskSwitchTo()); switchToTask->setConnectionId(connectionId); switchToTask->setServiceEndpoint(currentSession->getPipeName()); switchToTask->setOldSessionId(mSessionId); switchToTask->setNewSessionId(currentSession->getSessionId()); APP_CONTEXT.addTask(switchToTask); return 0; }
Session::SessionState SessionManager::validate(SessionPtr session) { assert(session); Session::SessionState state = session->validate(); return state; }
//----------------------------------------------------------------- void ConnectingStat::recvRequest(const RequestPtr& request, const SessionPtr& session) { //MCE_INFO("Request URL:"<<request->path() << " conn:" // <<session->connectionId()); ostringstream os; os << "ConnectingStat::recvRequest --> url:" << request->path() << " connectionId:" << session->connectionId() << " type:"; map<string,ActionConfig>::iterator it = _config.find(request->path()); if (it != _config.end()) { os << it->second.type; // MCE_DEBUG("ConnectingStat::recvRequest --> line:"<<__LINE__); if (it->second.type == "comet_get") { changeStat(session, &CometRecvStat::instance()); } else if (it->second.type == "wap_comet_get") { //changeStat(session, &WapCometRecvStat::instance()); } else if (it->second.type == "comet_broadcast") { changeStat(session, &BroadcastResponseStat::instance()); } else if (it->second.type == "wap_comet_broadcast") { //changeStat(session, &WapBroadcastResponseStat::instance()); } else { changeStat(session, &DefaultResponseStat::instance()); } } else { MCE_WARN("ERROR[404]: unknowen url:" << request->path() << " " << request->referer()); deliver(session, 404, 0, false, false, "", "ERROR[404]:unknowen url"); } MCE_DEBUG(os.str()); }