bool SocketSession::check(){ time_t now = time(NULL); //检查不活跃期超时(activity) if(now - getLastActivity() > getWait()){ LOG_DEBUG("SocketSession::check => del a session : sid = " << getSessionId() << " userId = " << getUserId()); LOG_TRACE_ACTION(" sockSessionTimeOut"<<" | "<<getUserId()<<" | "<<getSessionId()<<" | "<<getCAppId()<<" | "<<"000000"); internalClose(); return 1; } return 0; }
std::string PongEvent::toJsonString() const { std::ostringstream oss; oss << "{name: \"" << Name << "\", params: {" << "sid: " << getSessionId() << "}}"; return oss.str(); }
SocketSession::SocketSession(string sessionId) :Session(sessionId) { lastActivity_ = std::time(NULL); LOG_DEBUG("SocketSession::SocketSession => Create SocketSession: sid : " << getSessionId() ); }
HttpSession HttpSessionStore::getSession(HttpRequest& request, HttpResponse& response, bool allowCreate) { QByteArray sessionId=getSessionId(request,response); mutex.lock(); if (!sessionId.isEmpty()) { HttpSession session=sessions.value(sessionId); if (!session.isNull()) { mutex.unlock(); session.setLastAccess(); return session; } } // Need to create a new session if (allowCreate) { QByteArray cookieName=settings->value("cookieName","sessionid").toByteArray(); QByteArray cookiePath=settings->value("cookiePath","/").toByteArray(); QByteArray cookieComment=settings->value("cookieComment").toByteArray(); QByteArray cookieDomain=settings->value("cookieDomain").toByteArray(); HttpSession session(true); qDebug("HttpSessionStore: create new session with ID %s",session.getId().data()); sessions.insert(session.getId(),session); response.setCookie(HttpCookie(cookieName,session.getId(),expirationTime/1000,cookiePath,cookieComment,cookieDomain)); mutex.unlock(); return session; } // Return a null session mutex.unlock(); return HttpSession(); }
void AddSendData2List(dataSendReq_t *dataSendReq) { sendData_t sendData; commandAttr_t *cmdAttr = getCommandAttrDefine(dataSendReq->commandId); if(NULL == cmdAttr || cmdAttr->sendOrRecv != SEND_COMMAND) { return; } sendData.commandAttr = cmdAttr; sendData.sessionId = getSessionId(); sendData.time = time(NULL); sendData.retryTimes = 0; sendData.dataLength = dataSendReq->dataLength; memcpy(sendData.data, dataSendReq->data, dataSendReq->dataLength); if(cmdAttr->needResponse == NEED_RES) { addData2needResSendList(&sendData); } else { addData2noResSendList(&sendData); } printf("eleNum of g_needResSendList = %d\r\n", g_needResSendList.eleNum); printf("eleNum of g_noResSendList = %d\r\n", g_noResSendList.eleNum); }
template<class T> void AsyncEndpoint<T>::deliver_impl(NMEAmsg_ptr msg){ bool wasEmpty = true; bool nowFull = false; { boost::mutex::scoped_lock lock(message_queueMutex); wasEmpty = message_queue.empty(); while(message_queue.size()>=message_queue_size){ message_queue.pop_front(); nowFull=true; } message_queue.push_back(msg); } if(wasEmpty){ boost::system::error_code ec(0,boost::system::system_category()); handle_write(ec); } if(!nowFull){ wasFull=false; } else if(nowFull && !wasFull){ wasFull=true; std::ostringstream oss; oss << "The message queue for "<<getSessionId()<<" was too small, old messages were lost!"; log(oss.str()); } }
void SSRC::subscribe(SubscribeRequest *const sr, const string& sId) { string sessionId = (sId.length() > 0) ? sId : getSessionId(); sr->setSessionId(sessionId); _xmlCommunication->genericRequest(sr); }
std::string GpioInfoRequestEvent::toJsonString() const { std::ostringstream oss; oss << "{\"name\": \"" << Name << "\", \"params\": {" << "\"sid\": " << getSessionId() << "}}"; return oss.str(); }
void SSRC::publish(PublishRequest *const pr, const string& sId) { string sessionId = (sId.length() > 0) ? sId : getSessionId(); pr->setSessionId(sessionId); _xmlCommunication->genericRequest(pr); }
/** * Decrypt a received message. */ const char* OtrConnection::decryptMessage(const char* from, const char* to, const char* cryptedMessage) { int ignore_message = 0; char *newMessage = NULL; ignore_message = otrl_message_receiving( userstate, &ui_ops, this, to, "prpl-jabber", from, cryptedMessage, &newMessage, NULL, NULL, NULL); if (ignore_message == 1) { // internal protocol message. show user what kind of message was received. QString msg; OtrlMessageType type = otrl_proto_message_type(cryptedMessage); if (type == OTRL_MSGTYPE_NOTOTR) msg = "no OTR Message"; else if (type == OTRL_MSGTYPE_TAGGEDPLAINTEXT) msg= "OTR TaggedPlaintexMessage"; else if (type == OTRL_MSGTYPE_QUERY) msg= "OTR QueryMessage"; else if (type == OTRL_MSGTYPE_DH_COMMIT) msg= "OTR DH-Commit Message"; else if (type == OTRL_MSGTYPE_DH_KEY) msg= "OTR DH-Key Message"; else if (type == OTRL_MSGTYPE_REVEALSIG) msg= "OTR Reveal Signature Message"; else if (type == OTRL_MSGTYPE_SIGNATURE) msg= "OTR Signature Message"; else if (type == OTRL_MSGTYPE_V1_KEYEXCH) msg= "OTR Version 1 Key Exchange Message"; else if (type == OTRL_MSGTYPE_DATA) msg ="OTR Data Message"; else if (type == OTRL_MSGTYPE_ERROR) msg ="OTR Error Message"; else if (type == OTRL_MSGTYPE_UNKNOWN) msg= "OTR Unknown Message"; else msg= "Unknown Message Type"; msg.insert(0, "Received "); QString state = "[" + getMessageStateString(to, from) + "]"; msg.append(" " + state); OtrlMessageState* stateId; stateId = getMessageState(to, from); if (stateId != NULL && *stateId == OTRL_MSGSTATE_ENCRYPTED) { msg.append("\nsessionId: " + getSessionId(to, from)); } char* retMsg = (char*) malloc( msg.length() + 1 ); strcpy(retMsg, msg.toStdString().c_str()); return retMsg; } else if (ignore_message == 0) { if (newMessage != NULL) { // replace message return newMessage; } else { // no otr message char* retMsg = (char*) malloc(strlen(cryptedMessage)+1); strcpy(retMsg, cryptedMessage); return retMsg; } } return NULL; }
void Packet_v1::Print_v1(std::string const & componentName, Manager const * manager) const { Print_base(); std::cout << "[COMPONENTID: " << componentName << " {" << PROTOV1_COMPONENTID_SIZE << "}]" << "[REQUESTID: "; COLOR_REVERSE_START; std::cout << manager->getRegisteredRequestName(getComponentId(), getRequestId()); std::cout << " {" << PROTOV1_REQUESTID_SIZE << "}]" << "[SESSIONID: " << getSessionId() << " {" << PROTOV1_SESSIONID_SIZE << "}]" << std::endl; }
void Session::start() { SessionId=getSessionId(); m_socket.async_send(boost::asio::buffer(&SessionId,4), bind(&Session::handle_write, shared_from_this(), boost::asio::placeholders::error, placeholders::bytes_transferred)); m_socket.async_receive(boost::asio::buffer(msgfactory_.GetMessageBuf(),msgfactory_.GetMessageBufLen()), boost::bind(&Session::handle_readHeader,shared_from_this(), boost::asio::placeholders::error,placeholders::bytes_transferred)); }
//according to the request this fuction composes //checks if the request is valid and construct //a response string to reply the client void getResponse(rtspd_t* rtspd, char response[]){ int status = BAD_REQUEST; printf("getting ----------- response\n"); if(strcmp(rtspd->request, "SETUP") == 0){ printf("send setup response\n"); rtspd->sessionid = getSessionId(); status = getVideo(); printf("video file ok: %d\n", status); //initMovie(rtspd->videoName, rtspd->client_fd); rtspd->data = send_frame_data_new(rtspd->videoName, rtspd->client_fd); composeResponse(rtspd, status, response); //setup complete change state to ready strcpy(rtspd->current_state, "READY"); }else if(strcmp(rtspd->request, "PLAY") == 0&& strcmp(rtspd->current_state,"READY")==0){ status = OK; composeResponse(rtspd, status, response); streamVideo(rtspd->data); strcpy(rtspd->current_state, "PLAYING"); }else if(strcmp(rtspd->request, "PLAY")==0 && strcmp(rtspd->current_state, "PLAYING")==0){ status = OK; printf("start playing, %s, %d\n\n", rtspd->videoName,rtspd->client_fd); composeResponse(rtspd, status, response); streamVideo(rtspd->data); strcpy(rtspd->current_state, "PLAYING"); }else if(strcmp(rtspd->request, "PAUSE")==0 && strcmp(rtspd->current_state, "PLAYING")==0){ status = OK; printf("pause video \n"); pauseVideo(rtspd->data); composeResponse(rtspd, status, response); strcpy(rtspd->current_state, "READY"); }else if(strcmp(rtspd->request, "TEARDOWN")==0 &&(strcmp(rtspd->current_state, "PLAYING")==0 || strcmp(rtspd->current_state, "READY")==0)){ status = OK; printf("TEARDOWN video \n"); deleteTimer(rtspd->data); composeResponse(rtspd, status, response); strcpy(rtspd->current_state, "INIT"); }else{ status = NOT_VALID; composeResponse(rtspd, status, response); } }
void SSRC::endSession(const string& sId) { EndSessionRequest *esreq = Requests::createEndSessionReq(); string sessionId = (sId.length() > 0) ? sId : getSessionId(); esreq->setSessionId(sessionId); try { _xmlCommunication->genericRequest(esreq); } catch (...) { delete esreq; throw; } delete esreq; }
void SSRC::renewSession(const string& sId) { RenewSessionRequest *rnsreq = Requests::createRenewSessionReq(); string sessionId = (sId.length() > 0) ? sId : getSessionId(); rnsreq->setSessionId(sessionId); try { _xmlCommunication->genericRequest(rnsreq); } catch (...) { delete rnsreq; throw; } delete rnsreq; }
bool SessionCatalogMigrationSource::_fetchNextNewWriteOplog(OperationContext* opCtx) { repl::OpTime nextOpTimeToFetch; EntryAtOpTimeType entryAtOpTimeType; { stdx::lock_guard<stdx::mutex> lk(_newOplogMutex); if (_newWriteOpTimeList.empty()) { _lastFetchedNewWriteOplog.reset(); return false; } std::tie(nextOpTimeToFetch, entryAtOpTimeType) = _newWriteOpTimeList.front(); } DBDirectClient client(opCtx); const auto& newWriteOplogDoc = client.findOne(NamespaceString::kRsOplogNamespace.ns(), nextOpTimeToFetch.asQuery(), nullptr, QueryOption_OplogReplay); uassert(40620, str::stream() << "Unable to fetch oplog entry with opTime: " << nextOpTimeToFetch.toBSON(), !newWriteOplogDoc.isEmpty()); auto newWriteOplogEntry = uassertStatusOK(repl::OplogEntry::parse(newWriteOplogDoc)); // If this oplog entry corresponds to transaction prepare/commit, replace it with a sentinel // entry. if (entryAtOpTimeType == EntryAtOpTimeType::kTransaction) { newWriteOplogEntry = makeSentinelOplogEntry(*newWriteOplogEntry.getSessionId(), *newWriteOplogEntry.getTxnNumber(), opCtx->getServiceContext()->getFastClockSource()->now()); } { stdx::lock_guard<stdx::mutex> lk(_newOplogMutex); _lastFetchedNewWriteOplog = newWriteOplogEntry; _newWriteOpTimeList.pop_front(); } return true; }
ReceivedFileIM & ReceivedFileIM::operator =( const ReceivedFileIM & rhs ) { *((NormalIMBase *)this) = (NormalIMBase)rhs; m_TransferType = rhs.getTransferType(); m_ConnectMode = rhs.getConnectMode(); m_SessionId = getSessionId(); m_WanIp = rhs.getWanIp(); m_WanPort = rhs.getWanPort(); //m_MajorPort = rhs.getMajorPort(); //m_LanIp = rhs.getLanIp(); //m_LanPort = rhs.getLanPort(); memcpy(m_AgentServerKey, rhs.getAgentServerKey(), 16); m_FileName = rhs.getFileName(); m_FileSize = rhs.getFileSize(); return *this; }
void GlobSessionPacket::serialize( Archive& ar ) { SessionPacket::serialize( ar ); unsigned int count; if (ar.isLoading()) { // load packet count ar << COMPACT_INT(count); m_pPackets.resize( count, NULL ); // load packets for (size_t i=0; i<m_pPackets.size(); ++i) { UT_uint8 classId; ar << classId; SessionPacket* newPacket = static_cast<SessionPacket*>( Packet::createPacket( (PClassType)classId ) ); UT_ASSERT(newPacket); // should this be safer? newPacket->setParent( this ); ar << *newPacket; m_pPackets[i] = newPacket; // for efficiency reasons, childs of a glob don't serialize their session // and document id's; therefor we set them now manually newPacket->setSessionId(getSessionId()); newPacket->setDocUUID(getDocUUID()); } } else { // save packet count count = m_pPackets.size(); ar << COMPACT_INT(count); // save packets for (size_t i=0; i<m_pPackets.size(); ++i) { // get and check packet SessionPacket* sp = m_pPackets[i]; UT_ASSERT(sp); // this really may NEVER fail or addPacket malfunctioned! UT_uint8 classId = sp->getClassType(); ar << classId << *sp; } } }
cmd_data_t* CTDMHttpRequest::composeProtoPacketForDCMDownload() { int dataLen = GetDataSize( &m_req ); int headerLen = 3 * sizeof(int) + sizeof(pkg_type_t) + sizeof(protocol_type_t); int memLen = headerLen + dataLen; cmd_data_t* cmd = (cmd_data_t*) malloc( memLen ); memset( cmd, 0, memLen ); cmd->s_id = getSessionId(); cmd->pkg_type = CMD_TDM_DCM_CONTENT_GET; cmd->pkg_len = dataLen + sizeof(protocol_type_t); cmd->pkg_data.type = PROTOCOL_HTTP; http_data_t* pd = (http_data_t*) ((char*) cmd + headerLen); memcpy( pd->urlhash, m_req.urlhash, 20 ); char* buffer = (char*) cmd + headerLen + 20; char* p = buffer; strcpy( p, m_req.client_ip ); p += strlen(p) + 1; strcpy( p, m_req.server_ip ); p += strlen(p) + 1; strcpy( p, m_req.sitename ); p += strlen(p) + 1; strcpy( p, m_req.req_url ); p += strlen(p) + 1; strcpy( p, m_req.req_agent ); p += strlen(p) + 1; strcpy( p, m_req.req_refer ); p += strlen(p) + 1; strcpy( p, m_req.req_cookie ); return cmd; }
SearchResult * SSRC::search(SearchRequest *const sr, const string& sId) { string sessionId = (sId.length() > 0) ? sId : getSessionId(); sr->setSessionId(sessionId); Result *res = NULL; SearchResult *sres = NULL; try { res = _xmlCommunication->genericRequest(sr); sres = dynamic_cast<SearchResult *>(res); if (!sres) throw RequestHandlerError("No SearchResult" " in response to SearchRequest"); } catch (...) { throw; } return sres; }
void SSRC::purgePublisher(const string& pId, const string& sId) { // take either the given or the actual publisherId for this // request. string pubId = (pId.length() > 0) ? pId : getPublisherId(); string sessionId = (sId.length() > 0) ? sId : getSessionId(); PurgePublisherRequest *ppr = Requests::createPurgePublisherReq(pubId); ppr->setSessionId(sessionId); try { _xmlCommunication->genericRequest(ppr); } catch (...) { delete ppr; throw; } delete ppr; }
void AbiCollab::startRecording( SessionRecorderInterface* pRecorder ) { UT_return_if_fail(pRecorder); const UT_GenericVector<ChangeAdjust *>* pExpAdjusts = m_Export.getAdjusts(); UT_return_if_fail(pExpAdjusts); // FIXME: fill this properly UT_sint32 iAuthorId = -1; UT_ASSERT_HARMLESS(UT_NOT_IMPLEMENTED); // create initial document packet to recorder // so the recorder knows the initial state // serialize entire document into string JoinSessionRequestResponseEvent jsre(getSessionId(), iAuthorId); if (AbiCollabSessionManager::serializeDocument(m_pDoc, jsre.m_sZABW, false /* no base64 */) == UT_OK) { // set more document properties if (!isLocallyControlled()) { UT_ASSERT_HARMLESS(pExpAdjusts->getItemCount() > 0); jsre.m_iRev = (pExpAdjusts->getItemCount() > 0 ? pExpAdjusts->getNthItem(pExpAdjusts->getItemCount()-1)->getLocalRev() : 0); } else jsre.m_iRev = m_pDoc->getCRNumber(); jsre.m_sDocumentId = m_pDoc->getDocUUIDString(); if (m_pDoc->getFilename()) jsre.m_sDocumentName = UT_go_basename_from_uri(m_pDoc->getFilename()); // store pointer m_pRecorder = pRecorder; m_pRecorder->storeOutgoing( &jsre ); } else { UT_ASSERT(UT_SHOULD_NOT_HAPPEN); } }
ReceivedFileExIpIM & ReceivedFileExIpIM::operator =( const ReceivedFileExIpIM & rhs ) { *((NormalIMBase *)this) = (NormalIMBase)rhs; m_TransferType = rhs.getTransferType(); m_ConnectMode = rhs.getConnectMode(); m_SessionId = getSessionId(); m_WanIp1 = rhs.getWanIp1(); m_WanPort1 = rhs.getWanPort1(); m_WanIp2 = rhs.getWanIp2(); m_WanPort2 = rhs.getWanPort2(); m_WanIp3 = rhs.getWanIp3(); m_WanPort3 = rhs.getWanPort3(); m_LanIp1 = rhs.getLanIp1(); m_LanPort1 = rhs.getLanPort1(); m_LanIp2 = rhs.getLanIp2(); m_LanPort2 = rhs.getLanPort2(); m_LanIp3 = rhs.getLanIp3(); m_LanPort3 = rhs.getLanPort3(); return *this; }
OperationContextSession::OperationContextSession(OperationContext* opCtx) : _opCtx(opCtx) { if (!opCtx->getLogicalSessionId()) { return; } auto& checkedOutSession = operationSessionDecoration(opCtx); if (!checkedOutSession) { auto sessionTransactionTable = SessionCatalog::get(opCtx); checkedOutSession.emplace(sessionTransactionTable->checkOutSession(opCtx)); } const auto session = checkedOutSession->scopedSession.get(); invariant(opCtx->getLogicalSessionId() == session->getSessionId()); checkedOutSession->checkOutNestingLevel++; if (checkedOutSession->checkOutNestingLevel > 1) { return; } if (opCtx->getTxnNumber()) { checkedOutSession->scopedSession->begin(opCtx, opCtx->getTxnNumber().get()); } }
cmd_data_t* CTDMThunderRequest::composeProtoPacketForDCMDownload() { int dataLen = sizeof( thunder_data_t ); int headerLen = 3 * sizeof(int) + sizeof(pkg_type_t) + sizeof(protocol_type_t); int memLen = headerLen + dataLen; cmd_data_t* cmd = (cmd_data_t*) malloc( memLen ); memset( cmd, 0, memLen ); cmd->s_id = getSessionId(); cmd->pkg_type = CMD_TDM_DCM_CONTENT_GET; cmd->pkg_len = dataLen + sizeof(protocol_type_t); cmd->pkg_data.type = PROTOCOL_THUNDER; thunder_data_t* data = &cmd->pkg_data.thunder_data; memcpy( data->m_strInfohash, m_req.m_strInfohash, 20 ); data->m_nReqType = m_req.m_nReqType; strncpy( data->m_strCid, m_req.m_strCid, 40 ); strncpy( data->m_strPeerId, m_req.m_strPeerId, 16 ); data->m_nFilesize = m_req.m_nFilesize; return cmd; }
SocketSession::~SocketSession(){ LOG_DEBUG("SocketSession::~SocketSession => Destroy session : sid = " << getSessionId() << " , uid = " << getUserId()); }
void CMSWindowsRelauncher::mainLoop(void*) { shutdownExistingProcesses(); SendSas sendSasFunc = NULL; HINSTANCE sasLib = LoadLibrary("sas.dll"); if (sasLib) { LOG((CLOG_DEBUG "found sas.dll")); sendSasFunc = (SendSas)GetProcAddress(sasLib, "SendSAS"); } DWORD sessionId = -1; bool launched = false; SECURITY_ATTRIBUTES saAttr; saAttr.nLength = sizeof(SECURITY_ATTRIBUTES); saAttr.bInheritHandle = TRUE; saAttr.lpSecurityDescriptor = NULL; if (!CreatePipe(&m_stdOutRead, &m_stdOutWrite, &saAttr, 0)) { throw XArch(new XArchEvalWindows()); } PROCESS_INFORMATION pi; ZeroMemory(&pi, sizeof(PROCESS_INFORMATION)); int failures = 0; while (m_running) { HANDLE sendSasEvent = 0; if (sasLib && sendSasFunc) { // can't we just create one event? seems weird creating a new // event every second... sendSasEvent = CreateEvent(NULL, FALSE, FALSE, "Global\\SendSAS"); } DWORD newSessionId = getSessionId(); bool running = false; if (launched) { DWORD exitCode; GetExitCodeProcess(pi.hProcess, &exitCode); running = (exitCode == STILL_ACTIVE); if (!running) { failures++; LOG((CLOG_INFO "detected application not running, pid=%d, failures=%d", pi.dwProcessId, failures)); // increasing backoff period, maximum of 10 seconds. int timeout = (failures * 2) < 10 ? (failures * 2) : 10; LOG((CLOG_DEBUG "waiting, backoff period is %d seconds", timeout)); ARCH->sleep(timeout); // double check, in case process started after we waited. GetExitCodeProcess(pi.hProcess, &exitCode); running = (exitCode == STILL_ACTIVE); } else { // reset failures when running. failures = 0; } } // only enter here when id changes, and the session isn't -1, which // may mean that there is no active session. bool sessionChanged = ((newSessionId != sessionId) && (newSessionId != -1)); // relaunch if it was running but has stopped unexpectedly. bool stoppedRunning = (launched && !running); if (stoppedRunning || sessionChanged || m_commandChanged) { m_commandChanged = false; if (launched) { LOG((CLOG_DEBUG "closing existing process to make way for new one")); shutdownProcess(pi.hProcess, pi.dwProcessId, 20); launched = false; } // ok, this is now the active session (forget the old one if any) sessionId = newSessionId; SECURITY_ATTRIBUTES sa; ZeroMemory(&sa, sizeof(SECURITY_ATTRIBUTES)); // get the token for the user in active session, which is the // one receiving input from mouse and keyboard. HANDLE userToken = getCurrentUserToken(sessionId, &sa); if (userToken != 0) { LOG((CLOG_DEBUG "got user token to launch new process")); std::string cmd = command(); if (cmd == "") { // this appears on first launch when the user hasn't configured // anything yet, so don't show it as a warning, only show it as // debug to devs to let them know why nothing happened. LOG((CLOG_DEBUG "nothing to launch, no command specified.")); continue; } // in case reusing process info struct ZeroMemory(&pi, sizeof(PROCESS_INFORMATION)); STARTUPINFO si; ZeroMemory(&si, sizeof(STARTUPINFO)); si.cb = sizeof(STARTUPINFO); si.lpDesktop = "winsta0\\default"; si.hStdError = m_stdOutWrite; si.hStdOutput = m_stdOutWrite; si.dwFlags |= STARTF_USESTDHANDLES; LPVOID environment; BOOL blockRet = CreateEnvironmentBlock(&environment, userToken, FALSE); if (!blockRet) { LOG((CLOG_ERR "could not create environment block (error: %i)", GetLastError())); continue; } else { DWORD creationFlags = NORMAL_PRIORITY_CLASS | CREATE_NO_WINDOW | CREATE_UNICODE_ENVIRONMENT; // re-launch in current active user session LOG((CLOG_INFO "starting new process")); BOOL createRet = CreateProcessAsUser( userToken, NULL, LPSTR(cmd.c_str()), &sa, NULL, TRUE, creationFlags, environment, NULL, &si, &pi); DestroyEnvironmentBlock(environment); CloseHandle(userToken); if (!createRet) { LOG((CLOG_ERR "could not launch (error: %i)", GetLastError())); continue; } else { LOG((CLOG_DEBUG "launched in session %i (cmd: %s)", sessionId, cmd.c_str())); launched = true; } } } } if (sendSasEvent) { // use SendSAS event to wait for next session. if (WaitForSingleObject(sendSasEvent, 1000) == WAIT_OBJECT_0 && sendSasFunc) { LOG((CLOG_DEBUG "calling SendSAS")); sendSasFunc(FALSE); } CloseHandle(sendSasEvent); } else { // check for session change every second. ARCH->sleep(1); } } if (launched) { LOG((CLOG_DEBUG "terminated running process on exit")); shutdownProcess(pi.hProcess, pi.dwProcessId, 20); } LOG((CLOG_DEBUG "relauncher main thread finished")); }
bool EMULATOR_SESSION_CLASS::serialise(FILE *file_ptr) // DESCRIPTION : Serialise the script session to file. // PRECONDITIONS : // POSTCONDITIONS : // EXCEPTIONS : // NOTES : //<<=========================================================================== { // write the file contents fprintf(file_ptr, "SESSION\n\n"); fprintf(file_ptr, "SESSION-TYPE emulator\n"); fprintf(file_ptr, "SESSION-FILE-VERSION %d\n", CURRENT_SESSION_FILE_VERSION); fprintf(file_ptr, "\n# Product Test Session Properties\n"); fprintf(file_ptr, "SESSION-TITLE \"%s\"\n", getSessionTitle()); fprintf(file_ptr, "SESSION-ID %03d\n", getSessionId()); fprintf(file_ptr, "MANUFACTURER \"%s\"\n", getManufacturer()); fprintf(file_ptr, "MODEL-NAME \"%s\"\n", getModelName()); fprintf(file_ptr, "SOFTWARE-VERSIONS \"%s\"\n", getSoftwareVersions()); fprintf(file_ptr, "APPLICATION-ENTITY-NAME \"%s\"\n", getApplicationEntityName()); fprintf(file_ptr, "APPLICATION-ENTITY-VERSION \"%s\"\n", getApplicationEntityVersion()); fprintf(file_ptr, "TESTED-BY \"%s\"\n", getTestedBy()); fprintf(file_ptr, "DATE \"%s\"\n", getDate()); fprintf(file_ptr, "\n# SUT ACSE Properties\n"); fprintf(file_ptr, "SUT-ROLE "); switch(getSutRole()) { case UP_ACCEPTOR_REQUESTOR: fprintf(file_ptr, "acceptorAndRequestor\n"); break; case UP_ACCEPTOR: fprintf(file_ptr, "acceptor\n"); break; case UP_REQUESTOR: fprintf(file_ptr, "requestor\n"); break; default: break; } fprintf(file_ptr, "SUT-AE-TITLE \"%s\"\n", getSutAeTitle()); fprintf(file_ptr, "SUT-MAXIMUM-LENGTH-RECEIVED %d\n", getSutMaximumLengthReceived()); fprintf(file_ptr, "SUT-IMPLEMENTATION-CLASS-UID \"%s\"\n", getSutImplementationClassUid()); fprintf(file_ptr, "SUT-IMPLEMENTATION-VERSION-NAME "); if (getSutImplementationVersionName()) fprintf(file_ptr, "\"%s\"\n", getSutImplementationVersionName()); else fprintf(file_ptr, "\"\"\n"); fprintf(file_ptr, "\n# DVT ACSE Properties\n"); fprintf(file_ptr, "DVT-AE-TITLE \"%s\"\n", getDvtAeTitle()); fprintf(file_ptr, "DVT-MAXIMUM-LENGTH-RECEIVED %d\n", getDvtMaximumLengthReceived()); fprintf(file_ptr, "DVT-IMPLEMENTATION-CLASS-UID \"%s\"\n", getDvtImplementationClassUid()); fprintf(file_ptr, "DVT-IMPLEMENTATION-VERSION-NAME "); if (getDvtImplementationVersionName()) fprintf(file_ptr, "\"%s\"\n", getDvtImplementationVersionName()); else fprintf(file_ptr, "\"\"\n"); fprintf(file_ptr, "\n# Socket Properties\n"); fprintf(file_ptr, "SUT-HOSTNAME \"%s\"\n", getSutHostname()); fprintf(file_ptr, "SUT-PORT %d\n", getSutPort()); fprintf(file_ptr, "DVT-PORT %d\n", getDvtPort()); fprintf(file_ptr, "DVT-SOCKET-TIMEOUT %d\n", getDvtSocketTimeout()); fprintf(file_ptr, "USE-SECURE-SOCKETS %s\n", (getUseSecureSockets()) ? "true" : "false"); fprintf(file_ptr, "TLS-VERSION \"%s\"\n", getTlsVersion()); fprintf(file_ptr, "CHECK-REMOTE-CERTIFICATE %s\n", (getCheckRemoteCertificate()) ? "true" : "false"); fprintf(file_ptr, "CIPHER-LIST \"%s\"\n", getCipherList()); fprintf(file_ptr, "CACHE-TLS-SESSIONS %s\n", (getCacheTlsSessions()) ? "true" : "false"); fprintf(file_ptr, "TLS-CACHE-TIMEOUT %d\n", getTlsCacheTimeout()); fprintf(file_ptr, "CREDENTIALS-FILENAME \"%s\"\n", getCredentialsFilename().c_str()); fprintf(file_ptr, "CERTIFICATE-FILENAME \"%s\"\n", getCertificateFilename().c_str()); fprintf(file_ptr, "\n# Test Session Properties\n"); fprintf(file_ptr, "LOG-ERROR %s\n", (isLogLevel(LOG_ERROR)) ? "true" : "false"); fprintf(file_ptr, "LOG-WARNING %s\n", (isLogLevel(LOG_WARNING)) ? "true" : "false"); fprintf(file_ptr, "LOG-INFO %s\n", (isLogLevel(LOG_INFO)) ? "true" : "false"); fprintf(file_ptr, "LOG-RELATION %s\n", (isLogLevel(LOG_IMAGE_RELATION)) ? "true" : "false"); fprintf(file_ptr, "LOG-DEBUG %s\n", (isLogLevel(LOG_DEBUG)) ? "true" : "false"); fprintf(file_ptr, "LOG-DULP-STATE %s\n", (isLogLevel(LOG_DULP_FSM)) ? "true" : "false"); fprintf(file_ptr, "LOG-SCP-THREAD %s\n", (getLogScpThread()) ? "true" : "false"); fprintf(file_ptr, "PDU-DUMP %s\n", (isLogLevel(LOG_PDU_BYTES)) ? "true" : "false"); fprintf(file_ptr, "STORAGE-MODE "); switch(getStorageMode()) { case SM_AS_MEDIA: fprintf(file_ptr, "as-media\n"); break; case SM_AS_DATASET: fprintf(file_ptr, "as-dataset\n"); break; case SM_NO_STORAGE: default: fprintf(file_ptr, "no-storage\n"); break; } fprintf(file_ptr, "STRICT-VALIDATION %s\n", (getStrictValidation()) ? "true" : "false"); fprintf(file_ptr, "DETAILED-VALIDATION-RESULTS %s\n", (getDetailedValidationResults()) ? "true" : "false"); fprintf(file_ptr, "SUMMARY-VALIDATION-RESULTS %s\n", (getSummaryValidationResults()) ? "true" : "false"); fprintf(file_ptr, "INCLUDE-TYPE-3-NOTPRESENT-INRESULTS %s\n", (getIncludeType3NotPresentInResults()) ? "true" : "false"); fprintf(file_ptr, "AUTO-TYPE-2-ATTRIBUTES %s\n", (getAutoType2Attributes()) ? "true" : "false"); fprintf(file_ptr, "DEFINE-SQ-LENGTH %s\n", (getDefineSqLength()) ? "true" : "false"); fprintf(file_ptr, "ADD-GROUP-LENGTH %s\n", (getAddGroupLength()) ? "true" : "false"); fprintf(file_ptr, "\n# Supported Transfer Syntaxes\n"); for (int i = 0; i < noSupportedTransferSyntaxes(); i++) { fprintf(file_ptr, "SUPPORTED-TRANSFER-SYNTAX \"%s\"\n", getSupportedTransferSyntax(i)); } fprintf(file_ptr, "\n# Definitions\n"); for (UINT i = 0; i < noDefinitionDirectories(); i++) { fprintf(file_ptr, "DEFINITION-DIRECTORY \"%s\"\n", getDefinitionDirectory(i).c_str()); } for (unsigned int j = 0; j < noDefinitionFiles(); j++) { DEFINITION_FILE_CLASS *definitionFile_ptr = getDefinitionFile(j); fprintf(file_ptr, "DEFINITION \"%s\"\n", definitionFile_ptr->getFilename()); } fprintf(file_ptr, "\n# Results\n"); fprintf(file_ptr, "RESULTS-ROOT \"%s\"\n", getResultsRoot()); fprintf(file_ptr, "APPEND-TO-RESULTS-FILE %s\n", (getAppendToResultsFile()) ? "true" : "false"); fprintf(file_ptr, "\n# Data Directory\n"); fprintf(file_ptr, "DATA-DIRECTORY \"%s\"\n", getDataDirectory()); fprintf(file_ptr, "\n# DICOMScript Description Directory\n"); fprintf(file_ptr, "DESCRIPTION-DIRECTORY \"%s\"\n", getDescriptionDirectory().c_str()); fprintf(file_ptr, "\nENDSESSION\n"); // return success return true; }
VariableSpace* SessionLocalStorage::localVariableSpace() { return localVariableSpace(getSessionId()); }
void CMSWindowsRelauncher::mainLoop(void*) { SendSas sendSasFunc = NULL; HINSTANCE sasLib = LoadLibrary("sas.dll"); if (sasLib) { LOG((CLOG_DEBUG "found sas.dll")); sendSasFunc = (SendSas)GetProcAddress(sasLib, "SendSAS"); } DWORD sessionId = -1; bool launched = false; SECURITY_ATTRIBUTES saAttr; saAttr.nLength = sizeof(SECURITY_ATTRIBUTES); saAttr.bInheritHandle = TRUE; saAttr.lpSecurityDescriptor = NULL; if (!CreatePipe(&m_stdOutRead, &m_stdOutWrite, &saAttr, 0)) { throw XArch(new XArchEvalWindows()); } PROCESS_INFORMATION pi; ZeroMemory(&pi, sizeof(PROCESS_INFORMATION)); while (m_running) { HANDLE sendSasEvent = 0; if (sasLib && sendSasFunc) { // can't we just create one event? seems weird creating a new // event every second... sendSasEvent = CreateEvent(NULL, FALSE, FALSE, "Global\\SendSAS"); } DWORD newSessionId = getSessionId(); // only enter here when id changes, and the session isn't -1, which // may mean that there is no active session. if (((newSessionId != sessionId) && (newSessionId != -1)) || m_commandChanged) { m_commandChanged = false; if (launched) { LOG((CLOG_DEBUG "closing existing process to make way for new one")); shutdownProcess(pi, 10); launched = false; } // ok, this is now the active session (forget the old one if any) sessionId = newSessionId; SECURITY_ATTRIBUTES sa; ZeroMemory(&sa, sizeof(SECURITY_ATTRIBUTES)); // get the token for the user in active session, which is the // one receiving input from mouse and keyboard. HANDLE userToken = getCurrentUserToken(sessionId, &sa); if (userToken != 0) { LOG((CLOG_DEBUG "got user token to launch new process")); std::string cmd = command(); if (cmd == "") { LOG((CLOG_WARN "nothing to launch, no command specified.")); continue; } // in case reusing process info struct ZeroMemory(&pi, sizeof(PROCESS_INFORMATION)); STARTUPINFO si; ZeroMemory(&si, sizeof(STARTUPINFO)); si.cb = sizeof(STARTUPINFO); si.lpDesktop = "winsta0\\default"; si.hStdError = m_stdOutWrite; si.hStdOutput = m_stdOutWrite; si.dwFlags |= STARTF_USESTDHANDLES; LPVOID environment; BOOL blockRet = CreateEnvironmentBlock(&environment, userToken, FALSE); if (!blockRet) { LOG((CLOG_ERR "could not create environment block (error: %i)", GetLastError())); continue; } else { DWORD creationFlags = NORMAL_PRIORITY_CLASS | CREATE_NO_WINDOW | CREATE_UNICODE_ENVIRONMENT; // re-launch in current active user session BOOL createRet = CreateProcessAsUser( userToken, NULL, LPSTR(cmd.c_str()), &sa, NULL, TRUE, creationFlags, environment, NULL, &si, &pi); DestroyEnvironmentBlock(environment); CloseHandle(userToken); if (!createRet) { LOG((CLOG_ERR "could not launch (error: %i)", GetLastError())); continue; } else { LOG((CLOG_DEBUG "launched in session %i (cmd: %s)", sessionId, cmd.c_str())); launched = true; } } } } if (sendSasEvent) { // use SendSAS event to wait for next session. if (WaitForSingleObject(sendSasEvent, 1000) == WAIT_OBJECT_0 && sendSasFunc) { LOG((CLOG_DEBUG "calling SendSAS")); sendSasFunc(FALSE); } CloseHandle(sendSasEvent); } else { // check for session change every second. ARCH->sleep(1); } } if (launched) { LOG((CLOG_DEBUG "terminated running process on exit")); shutdownProcess(pi, 10); } }