int main() { printf("Content-type: text/html\n"); startSession(); printf("\n"); if (getSession("num") == NULL) { setSession("num", "0"); setSession("num2", "0"); } if (getSession("num") == NULL) { printf("...\n"); } else { int n = atoi(getSession("num")); n++; printf("%d\n", n); char buffer[20]; sprintf(buffer, "%d", n); setSession("num", buffer); n = atoi(getSession("num2")); n+=2; printf("<br>%d\n", n); sprintf(buffer, "%d", n); setSession("num2", buffer); } return 0; }
MessageHandler::MessageHandler(QObject* parent) : QObject(parent) { d.session = 0; d.defaultReceiver = 0; d.currentReceiver = 0; setSession(qobject_cast<Session*>(parent)); }
void MetaDboBase::remove() { checkNotOrphaned(); if(isDeleted()) { // is already removed or being removed in this transaction } else if(isPersisted()) { state_ |= NeedsDelete; session_->needsFlush(this); } else if(session_) { // was added to a Session but not yet flushed Session *session = session_; setSession(0); session->discardChanges(this); state_ &= ~NeedsSave; } else { // is not yet added to the Session } }
Export::Export(Session* _session, QWidget* _parent) : QWidget(_parent), ui_(new Ui::Export) { ui_->setupUi(this); connect(ui_->btnExport,SIGNAL(clicked()),this,SLOT(exportToFile())); setSession(_session); }
SessionChildItem::SessionChildItem(SessionItem* parent) : AbstractSessionItem(parent), m_parent(parent), m_usermodel(0) { setSession(parent->session()); m_usermodel = new UserModel(session()); connect(this, SIGNAL(titleChanged(QString)), SIGNAL(channelChanged())); connect(this, SIGNAL(titleChanged(QString)), m_usermodel, SLOT(setChannel(QString))); }
void FileStore::reset() throw ( IOException ) { m_cache.reset(); open( true ); setSession(); }
HyperBusReciever::HyperBusReciever(const QString &address, quint32 port, QObject *parent) : HMsgTransporter(address,port,parent) { p = new HyperBusRecieverPrivate; p->highway = new HighWay(this); p->last_map_id = 0; p->last_pid = 0; setSession(HyperBusReciever::Normal); }
void HyperBusReciever::setSession(SessionType type) { switch( static_cast<int>(type) ) { case HyperBusReciever::Normal: setSession(HPidTools::userOf(QCoreApplication::applicationPid()) + "@127.0.0.1"); break; case HyperBusReciever::Global: setSession("global"); break; case HyperBusReciever::Local: setSession("local"); break; case HyperBusReciever::Share: setSession("share"); break; } }
void Session::onSocketConnected(const WebSocketPtr& aSocket) noexcept { auto oldSocket = getServer()->getSocket(id); if (oldSocket) { oldSocket->debugMessage("Replace session socket"); // This must be called before the new socket is associated with this session fire(SessionListener::SocketConnected(), oldSocket); oldSocket->setSession(nullptr); oldSocket->close(websocketpp::close::status::policy_violation, "Another socket was connected to this session"); } fire(SessionListener::SocketConnected(), aSocket); }
void FileStore::open( bool deleteFile ) { if ( m_msgFile ) fclose( m_msgFile ); if ( m_headerFile ) fclose( m_headerFile ); if ( m_seqNumsFile ) fclose( m_seqNumsFile ); if ( m_sessionFile ) fclose( m_sessionFile ); m_msgFile = 0; m_headerFile = 0; m_seqNumsFile = 0; m_sessionFile = 0; if ( deleteFile ) { file_unlink( m_msgFileName.c_str() ); file_unlink( m_headerFileName.c_str() ); file_unlink( m_seqNumsFileName.c_str() ); file_unlink( m_sessionFileName.c_str() ); } populateCache(); m_msgFile = file_fopen( m_msgFileName.c_str(), "r+" ); if ( !m_msgFile ) m_msgFile = file_fopen( m_msgFileName.c_str(), "w+" ); if ( !m_msgFile ) throw ConfigError( "Could not open body file: " + m_msgFileName ); m_headerFile = file_fopen( m_headerFileName.c_str(), "r+" ); if ( !m_headerFile ) m_headerFile = file_fopen( m_headerFileName.c_str(), "w+" ); if ( !m_headerFile ) throw ConfigError( "Could not open header file: " + m_headerFileName ); m_seqNumsFile = file_fopen( m_seqNumsFileName.c_str(), "r+" ); if ( !m_seqNumsFile ) m_seqNumsFile = file_fopen( m_seqNumsFileName.c_str(), "w+" ); if ( !m_seqNumsFile ) throw ConfigError( "Could not open seqnums file: " + m_seqNumsFileName ); bool setCreationTime = false; m_sessionFile = file_fopen( m_sessionFileName.c_str(), "r" ); if ( !m_sessionFile ) setCreationTime = true; else fclose( m_sessionFile ); m_sessionFile = file_fopen( m_sessionFileName.c_str(), "r+" ); if ( !m_sessionFile ) m_sessionFile = file_fopen( m_sessionFileName.c_str(), "w+" ); if ( !m_sessionFile ) throw ConfigError( "Could not open session file" ); if ( setCreationTime ) setSession(); setNextSenderMsgSeqNum( getNextSenderMsgSeqNum() ); setNextTargetMsgSeqNum( getNextTargetMsgSeqNum() ); }
void Application::executeRequest(boost::function<void (HttpRequest*&, HttpResponse*&, void*)> convertData, void* data, boost::function<void (HttpRequest*, HttpResponse*)> requestFinish) { //Create request HttpRequest* request = NULL; HttpResponse* response = NULL; HttpSession* session = NULL; convertData(request, response, data); if(request==NULL||response==NULL) { requestFinish(request, response); return; } setContextToRequest(request); if(mSessionManager) { session = mSessionManager->startSession(*request, *response); if(session) { setSession(request, session); } } IUrlHandler* urlHandler = getBeanFactory()->getBean<IUrlHandler>("urlHandler"); if(!urlHandler) { if(mSessionManager && session) { mSessionManager->endSession(session, *request, *response); } std::cout << "No URL Handler found set error page: 500" << std::endl; requestFinish(request, response); return; } if(!urlHandler->dispatchUrl(*request, *response)) { if(mSessionManager && session) { mSessionManager->endSession(session, *request, *response); } std::cout << "URL handle error set error page: 500" << std::endl; requestFinish(request, response); return; } if(mSessionManager && session) { mSessionManager->endSession(session, *request, *response); } response->flush(); requestFinish(request, response); }
bool SFTPChannel::handleOpening() { mHandle = libssh2_sftp_init(mSession->sessionHandle()); if (mHandle == NULL) { int rc = libssh2_session_last_errno(mSession->sessionHandle()); if (rc == LIBSSH2_ERROR_EAGAIN) return true; else { if (rc == LIBSSH2_ERROR_CHANNEL_FAILURE) // Reassign this channel elsewhere setSession(NULL); else criticalError(tr("Failed to open a channel %1: %2").arg((unsigned long)mHandle, 0, 16).arg(rc)); return false; } } setStatus(Open); return true; }
SessionItem::SessionItem(Session* session) : AbstractSessionItem(session), m_closing(false) { setTitle(session->host()); setSubtitle(session->nickName()); connect(session, SIGNAL(hostChanged(QString)), this, SLOT(setTitle(QString))); connect(session, SIGNAL(nickNameChanged(QString)), this, SLOT(setSubtitle(QString))); connect(session, SIGNAL(socketError(QAbstractSocket::SocketError)), this, SLOT(updateState())); connect(session, SIGNAL(connectedChanged(bool)), this, SLOT(updateState())); connect(session, SIGNAL(activeChanged(bool)), this, SLOT(updateState())); setSession(session); m_handler.setSession(session); m_handler.setDefaultReceiver(this); m_handler.setCurrentReceiver(this); connect(&m_handler, SIGNAL(receiverToBeAdded(QString)), SLOT(addChild(QString))); connect(&m_handler, SIGNAL(receiverToBeRenamed(QString,QString)), SLOT(renameChild(QString,QString))); connect(&m_handler, SIGNAL(receiverToBeRemoved(QString)), SLOT(removeChild(QString))); updateCurrent(this); updateState(); }
void ThreadedSocketConnection::processStream() { std::string msg; while( readMessage(msg) ) { if ( !m_pSession ) { if ( !setSession( msg ) ) { disconnect(); continue; } } try { m_pSession->next( msg, UtcTimeStamp() ); } catch( InvalidMessage& ) { if( !m_pSession->isLoggedOn() ) { disconnect(); return; } } } }
bool ShellChannel::handleOpening() { int rc; if (mInternalStatus == _OpenSession) { mHandle = libssh2_channel_open_session(mSession->sessionHandle()); if (mHandle == NULL) { int rc = libssh2_session_last_errno(mSession->sessionHandle()); if (rc == LIBSSH2_ERROR_EAGAIN) return true; else { if (rc == LIBSSH2_ERROR_CHANNEL_FAILURE) // This channel needs to be given away; this connection can't handle it. // TODO: Detect if this channel request has been handed off too often and kill it if so. setSession(NULL); else criticalError(tr("Failed to open a channel %1: %2").arg((unsigned long)mHandle, 0, 16).arg(rc)); return false; } } setInternalStatus(_RequestPty); } if (mInternalStatus == _RequestPty) { // Due to a bug in OpenSSH (popular server-side implementation of SSH), we must simulate blocking for PTY request. while ((rc = libssh2_channel_request_pty(mHandle, mPtyType)) == LIBSSH2_ERROR_EAGAIN) {}; if (rc < 0) { criticalError(tr("Failed to request an appropriate pty %1: %2").arg((unsigned long)mHandle, 0, 16).arg(rc)); return false; } setInternalStatus(_StartShell); } if (mInternalStatus == _StartShell) { if (mMachineReadable) rc = libssh2_channel_exec(mHandle, "sh"); else rc = libssh2_channel_shell(mHandle); if (rc < 0) { if (rc == -1) rc = libssh2_session_last_errno(mSession->sessionHandle()); if (rc == LIBSSH2_ERROR_EAGAIN) return true; criticalError(tr("Failed to open a shell %1: %2").arg((unsigned long)mHandle, 0, 16).arg(rc)); return false; } if (mMachineReadable) setInternalStatus(_SendInit); else shellReady(); } if (mInternalStatus == _SendInit) { SendResponse r = sendData(MACHINE_READABLE_INIT); if (r == SendAgain) return true; if (r != SendSucceed) criticalError("Failed to send shell initializer"); setInternalStatus(_WaitForInitReply); } if (mInternalStatus == _WaitForInitReply) { ReadReply reply = readUntilPrompt(); if (reply.readAgain) return true; if (reply.data.isNull()) return false; shellReady(); } return true; }
void IMAP::react( Event e ) { d->bytesArrived += readBuffer()->size(); switch ( e ) { case Read: parse(); if ( d->bytesArrived > 32768 && state() == NotAuthenticated ) { log( ">32k received before login" ); enqueue( "* BYE overlong login sequence\r\n" ); Connection::setState( Closing ); if ( d->reader ) { Scope s( d->reader->log() ); d->reader->read(); } } break; case Timeout: if ( state() != Logout ) { log( "Idle timeout" ); enqueue( "* BYE Tempus fugit\r\n" ); } Connection::setState( Closing ); if ( d->reader ) { Scope s( d->reader->log() ); d->reader->read(); } setSession( 0 ); break; case Connect: break; case Error: case Close: if ( session() ) { log( "Unexpected close by client" ); setSession( 0 ); } if ( !d->commands.isEmpty() ) { List<Command>::Iterator i( d->commands ); while ( i ) { Command * c = i; ++i; if ( c->state() == Command::Unparsed || c->state() == Command::Blocked || c->state() == Command::Executing ) c->error( Command::No, "Unexpected close by client" ); } } break; case Shutdown: enqueue( "* BYE server shutdown\r\n" ); if ( session() && d->commands.isEmpty() ) setSession( 0 ); break; } runCommands(); d->bytesArrived -= readBuffer()->size(); if ( timeout() == 0 || ( e == Read && state() != NotAuthenticated ) ) { switch ( state() ) { case NotAuthenticated: setTimeoutAfter( 120 ); break; case Authenticated: case Selected: if ( idle() ) setTimeoutAfter( 3600 ); // one hour while IDLE else setTimeoutAfter( 1860 ); // a half-hour without break; case Logout: break; } } }
void CallSetuptState::processRequest(const std::string &data, User &context) { std::cout << context.getUid() << " in CallSetuptState " << data.substr(0, 10) << std::endl; if (data.compare(0, 3, "cnr") == 0) { // client wants to dial a peer string encrypted = data.substr(4); //take data part auto elements = StringHelper::split(encrypted, ','); string dest_uid(elements->at(0)); string my_pub_key(elements->at(1)); std::replace(my_pub_key.begin(), my_pub_key.end(), ':', '\n'); context.setMypubKey(my_pub_key); try { if (context.getUid() == dest_uid) { throw Poco::InvalidAccessException("You cannot call yourself "); } auto receiver = LoggedUsersMap::getInstance().findUser(dest_uid); //throws out_of_range exception if (receiver != nullptr && receiver->getCurrentState()==&LoginState::getInstance()) { //this is not necessary. But checking it won't kill you shared_ptr <CallAggregator> session(new CallAggregator()); context.setSession(session); receiver->setSession(context.Session()); // receiver will register itself as a observer on 'kcs' event int bytes = receiver->writeToClientBlocking(CERT_REQUEST, 5000); if (bytes < 0) { throw IOException("write failed"); } receiver->setCurrent_state(CallSetuptState::getInstance()); context.Session()->registerAsCaller(context.shared_from_this()); cout << "registered as a caller" << endl; std::thread async_thread(std::function<void()>([&context]() -> void { //local variable should be copied auto caller = context.shared_from_this();//we can use 'context' reference but need to keep User object until thread ends string sessionKey = context.Session()->getSessionKey(); try { cout << "waiting for receiver TID :" << std::this_thread::get_id() << endl; bool timeoutReached = context.Session()->wait_for_receiver(10);//seconds //encrpt and send skey if (!timeoutReached && caller.use_count() > 1) { //if time out not reached and this is not the only reference caller->_behaviours->getCallInitializerBehaviour().sendSessionKey(sessionKey, *caller, false); //throws exceptions caller->setCurrent_state(CallingState::getInstance()); } else { throw Poco::NotFoundException("Receiver end failed"); } } catch (const Poco::Exception &e) { cerr << e.message() << endl; caller->writeToClient(REMOTE_USER_NOT_AVAILABLE); context.writeToClient(DISCONNECT);// DISCONNECT does not work if (caller->Session().get()) { caller->Session()->unregisterObserver(caller); caller->Session() = nullptr; cout << "session cleared" << endl; } caller->setCurrent_state(LoginState::getInstance()); } catch (exception &e) { cerr << "In async thread " << e.what() << endl; } })); /*std::this_thread::sleep_until(std::chrono::system_clock::now() + std::chrono::nanoseconds(1000));//wait till lambda func till copy args*/ async_thread.detach(); // now thread object can be deleted without affecting the running thread } else{ cout << "user " << dest_uid << " not available" << endl; //this_thread::__sleep_for(std::chrono::seconds(3),std::chrono::nanoseconds(0)); context.writeToClient(REMOTE_USER_NOT_AVAILABLE); context.setCurrent_state(LoginState::getInstance()); } } catch (const std::out_of_range &e) { // from find(uid) cout << "user " << dest_uid << " not available" << endl; //this_thread::__sleep_for(std::chrono::seconds(3),std::chrono::nanoseconds(0)); context.writeToClient(REMOTE_USER_NOT_AVAILABLE); context.setCurrent_state(LoginState::getInstance()); } catch (const Poco::InvalidAccessException &e) { //if caller==callie context.writeToClient(REMOTE_USER_NOT_AVAILABLE, 0); cerr << e.message() << endl; context.setCurrent_state(LoginState::getInstance()); } catch (const IOException &e) { //when writing to a closed Socket context.writeToClient(REMOTE_USER_NOT_AVAILABLE, 0); cerr << e.message() << endl; context.setCurrent_state(LoginState::getInstance()); } catch (const Poco::NullPointerException &e) { //when trying to write after SocketConnection is deleted; context.writeToClient(REMOTE_USER_NOT_AVAILABLE, 0); cerr << e.message() << endl; context.setCurrent_state(LoginState::getInstance()); } // my_pub_key.replace(':','',); }//this part has to be extracted to a seperte state. // unless receiver can process call request prior receiving cert request else if (data.compare(0, 3, "kcs") == 0) { //certificate response to server's request string my_pub_key = data.substr(4); //take data part std::replace(my_pub_key.begin(), my_pub_key.end(), ':', '\n'); context.setMypubKey(my_pub_key); if (context.Session().get()) {// session could have been ended by caller context.Session()->registerAsReceiver(context.shared_from_this()); string sKey(context.Session()->getSessionKey()); context.Session()->notify_caller(); //Notify waiting caller try { context._behaviours->getCallInitializerBehaviour().sendSessionKey(sKey, context, true); context.setCurrent_state(RingingState::getInstance()); } catch (const Poco::Exception &e) { context.writeToClient(DISCONNECT); context.setCurrent_state(LoginState::getInstance()); } } else { context.setCurrent_state(LoginState::getInstance()); } } else if (data.compare(0, 3, "rej") == 0) {//while caller is waiting itself can cancel the call if (context.Session().get()) { context.Session()->interrupt_caller(); } } }
SessionChildItem::SessionChildItem(SessionItem* parent) : AbstractSessionItem(parent), m_parent(parent) { setSession(parent->session()); connect(this, SIGNAL(titleChanged()), SLOT(updateIcon())); }
Logger::Logger(TradingSession * session_, ILoggerStartEvent * onStart_) { setSession(session_); onStartEvent = onStart_; }