bool TrySipInvite(EthernetHeaderStruct* ethernetHeader, IpHeaderStruct* ipHeader, UdpHeaderStruct* udpHeader, u_char* udpPayload, u_char* packetEnd) { CStdString logMsg; bool result = false; bool drop = false; CStdString sipMethod; int sipLength = ntohs(udpHeader->len) - sizeof(UdpHeaderStruct); char* sipEnd = (char*)udpPayload + sipLength; if (DLLCONFIG.m_ipFragmentsReassemble == false && sipEnd > (char*)packetEnd && ipHeader->offset() == 0) { FLOG_DEBUG(s_sipExtractionLog, "Will try to process incomplete first fragment with id:%u",ipHeader->packetId()); sipEnd = (char*)packetEnd; } if(sipLength < 3 || sipEnd > (char*)packetEnd) { drop = true; // packet too short } else if(memcmp(SIP_METHOD_INVITE, (void*)udpPayload, SIP_METHOD_INVITE_SIZE) == 0) { sipMethod = SIP_METHOD_INVITE; } else if(memcmp(SIP_METHOD_ACK, (void*)udpPayload, SIP_METHOD_ACK_SIZE) == 0) { sipMethod = SIP_METHOD_ACK; } else if((DLLCONFIG.m_sipTreat200OkAsInvite == true) && (memcmp(SIP_RESPONSE_200_OK, (void*)udpPayload, SIP_RESPONSE_200_OK_SIZE) == 0)) { sipMethod = SIP_METHOD_200_OK; LOG4CXX_DEBUG(s_sipExtractionLog, "TrySipInvite: packet matches 200 OK and SipTreat200OkAsInvite is enabled"); } else if((DLLCONFIG.m_sipDetectSessionProgress == true) && (memcmp(SIP_RESPONSE_SESSION_PROGRESS, (void*)udpPayload, SIP_RESPONSE_SESSION_PROGRESS_SIZE) == 0)) { sipMethod = SIP_RESPONSE_SESSION_PROGRESS; } else { drop = true; } if (drop == false) { result = true; SipInviteInfoRef info(new SipInviteInfo()); info->m_sipMethod = sipMethod; char* fromField = memFindAfter("From:", (char*)udpPayload, sipEnd); if(!fromField) { fromField = memFindAfter("\nf:", (char*)udpPayload, sipEnd); } char* toField = memFindAfter("To:", (char*)udpPayload, sipEnd); if(!toField) { toField = memFindAfter("\nt:", (char*)udpPayload, sipEnd); } char* callIdField = memFindAfter("Call-ID:", (char*)udpPayload, sipEnd); if(!callIdField) { callIdField = memFindAfter("\ni:", (char*)udpPayload, sipEnd); } char* replacesField = memFindAfter("Replaces:", (char*)udpPayload, sipEnd); if(!replacesField) { replacesField = memFindAfter("\nr:", (char*)udpPayload, sipEnd); } char * dialedNumber = NULL; if(!(DLLCONFIG.m_sipDialedNumberFieldName.length()==0) ) { dialedNumber = memFindAfter(DLLCONFIG.m_sipDialedNumberFieldName + ":", (char*)udpPayload,sipEnd); } char * sipRemoteParty = NULL; if(!(DLLCONFIG.m_sipRemotePartyFieldName.length()==0) ) { sipRemoteParty = memFindAfter(DLLCONFIG.m_sipRemotePartyFieldName + ":", (char*)udpPayload,sipEnd); } char* contactField = memFindAfter("Contact:", (char*)udpPayload, sipEnd); if(!contactField) { contactField = memFindAfter("\nc:", (char*)udpPayload, sipEnd); } char * audioSdpStart = (char*) udpPayload;; char * audioSdpEnd = (char*) sipEnd;; char* audioStart = memFindAfter("m=audio", (char*)udpPayload, sipEnd); char* videoStart = memFindAfter("m=video", (char*)udpPayload, sipEnd); if (audioStart < videoStart) { audioSdpEnd = videoStart; } if (audioStart > videoStart) { audioSdpStart = audioStart; } char* localExtensionField = memFindAfter(DLLCONFIG.m_sipLocalPartyFieldName, (char*)udpPayload, sipEnd); char* audioField = NULL; char* connectionAddressField = NULL; char* attribSendonly = memFindAfter("a=sendonly", (char*)audioSdpStart, audioSdpEnd); char* attribInactive = memFindAfter("a=inactive", (char*)audioSdpStart, audioSdpEnd); char* rtpmapAttribute = memFindAfter("\na=rtpmap:", (char*)audioSdpStart, audioSdpEnd); char* userAgentField = memFindAfter("\nUser-Agent:", (char*)udpPayload, sipEnd); if(DLLCONFIG.m_sipRequestUriAsLocalParty == true) { char* sipUriAttribute = memFindAfter("INVITE ", (char*)udpPayload, sipEnd); if(sipUriAttribute) { if(s_sipExtractionLog->isDebugEnabled()) { CStdString uri; GrabLine(sipUriAttribute, sipEnd, uri); LOG4CXX_DEBUG(s_sipExtractionLog, "uri: " + uri); } char* sipUriAttributeEnd = memFindEOL(sipUriAttribute, sipEnd); char* sipUser = memFindAfter("sip:", sipUriAttribute, sipUriAttributeEnd); if(sipUser) { if(DLLCONFIG.m_sipReportFullAddress) { GrabSipUserAddress(sipUser, sipUriAttributeEnd, info->m_requestUri); } else { GrabSipUriUser(sipUser, sipUriAttributeEnd, info->m_requestUri); } } else { if(DLLCONFIG.m_sipReportFullAddress) { GrabSipUserAddress(sipUriAttribute, sipUriAttributeEnd, info->m_requestUri); } else { GrabSipUriUser(sipUriAttribute, sipUriAttributeEnd, info->m_requestUri); } } if(s_sipExtractionLog->isDebugEnabled()) { LOG4CXX_DEBUG(s_sipExtractionLog, "extracted uri: " + info->m_requestUri); } } } if(fromField) { if(s_sipExtractionLog->isDebugEnabled()) { CStdString from; GrabLine(fromField, sipEnd, from); LOG4CXX_DEBUG(s_sipExtractionLog, "from: " + from); } char* fromFieldEnd = memFindEOL(fromField, sipEnd); GrabSipName(fromField, fromFieldEnd, info->m_fromName); char* sipUser = memFindAfter("sip:", fromField, fromFieldEnd); if(sipUser) { if(DLLCONFIG.m_sipReportFullAddress) { GrabSipUserAddress(sipUser, fromFieldEnd, info->m_from); } else { GrabSipUriUser(sipUser, fromFieldEnd, info->m_from); } GrabSipUriDomain(sipUser, fromFieldEnd, info->m_fromDomain); } else { if(DLLCONFIG.m_sipReportFullAddress) { GrabSipUserAddress(fromField, fromFieldEnd, info->m_from); } else { GrabSipUriUser(fromField, fromFieldEnd, info->m_from); } GrabSipUriDomain(fromField, fromFieldEnd, info->m_fromDomain); } } if(toField) { CStdString to; char* toFieldEnd = GrabLine(toField, sipEnd, to); LOG4CXX_DEBUG(s_sipExtractionLog, "to: " + to); GrabSipName(toField, toFieldEnd, info->m_toName); char* sipUser = memFindAfter("sip:", toField, toFieldEnd); if(sipUser) { if(DLLCONFIG.m_sipReportFullAddress) { GrabSipUserAddress(sipUser, toFieldEnd, info->m_to); } else { GrabSipUriUser(sipUser, toFieldEnd, info->m_to); } GrabSipUriDomain(sipUser, toFieldEnd, info->m_toDomain); } else { if(DLLCONFIG.m_sipReportFullAddress) { GrabSipUserAddress(toField, toFieldEnd, info->m_to); } else { GrabSipUriUser(toField, toFieldEnd, info->m_to); } GrabSipUriDomain(toField, toFieldEnd, info->m_toDomain); } if(DLLCONFIG.m_sipGroupPickUpPattern == info->m_to) { info->m_SipGroupPickUpPatternDetected = true; } } if(dialedNumber) { CStdString token; GrabTokenSkipLeadingWhitespaces(dialedNumber, sipEnd, token); info->m_sipDialedNumber = token; } if(sipRemoteParty) { CStdString token; char* sip = memFindAfter("sip:", sipRemoteParty, sipEnd); if(sip) { if(DLLCONFIG.m_sipReportFullAddress) { GrabSipUserAddress(sip, sipEnd, token); } else { GrabSipUriUser(sip, sipEnd, token); } } else { if(DLLCONFIG.m_sipReportFullAddress) { GrabSipUserAddress(sipRemoteParty, sipEnd, token); } else { GrabSipUriUser(sipRemoteParty, sipEnd, token); } } info->m_sipRemoteParty = token; } if(callIdField) { GrabTokenSkipLeadingWhitespaces(callIdField, sipEnd, info->m_callId); audioField = memFindAfter("m=audio ", callIdField, sipEnd); connectionAddressField = memFindAfter("c=IN IP4 ", callIdField, sipEnd); } if(replacesField) { CStdString fieldContent; GrabTokenSkipLeadingWhitespaces(replacesField, sipEnd, fieldContent); int firstsemicoma; firstsemicoma = fieldContent.Find(';'); if(firstsemicoma != -1) { info->m_replacesId = fieldContent.substr(0, firstsemicoma); } LOG4CXX_DEBUG(s_sipExtractionLog, "replaces CallId:" + info->m_replacesId); } if(localExtensionField) { CStdString localExtension; GrabTokenSkipLeadingWhitespaces(localExtensionField, sipEnd, localExtension); if(localExtension.size() > 0) { info->m_from = localExtension; } } if(userAgentField) { GrabTokenSkipLeadingWhitespaces(userAgentField, sipEnd, info->m_userAgent); } if(audioField) { GrabToken(audioField, sipEnd, info->m_fromRtpPort); } if(attribSendonly || attribInactive) { info->m_attrSendonly = true; } if(connectionAddressField) { CStdString connectionAddress; GrabToken(connectionAddressField, sipEnd, connectionAddress); struct in_addr fromIp; if(connectionAddress.size()) { if(ACE_OS::inet_aton((PCSTR)connectionAddress, &fromIp)) { info->m_fromRtpIp = fromIp; if (DLLCONFIG.m_sipDropIndirectInvite) { if((unsigned int)fromIp.s_addr != (unsigned int)ipHeader->ip_src.s_addr) { // SIP invite SDP connection address does not match with SIP packet origin drop =true; } } } } } if(contactField && sipMethod == SIP_METHOD_INVITE) { CStdString contact; char* contactFieldEnd = GrabLine(contactField, sipEnd, contact); LOG4CXX_DEBUG(s_sipExtractionLog, "contact: " + contact); GrabSipName(contactField, contactFieldEnd, info->m_contactName); char* sipUser = memFindAfter("sip:", contactField, contactFieldEnd); if(sipUser) { if(DLLCONFIG.m_sipReportFullAddress) { GrabSipUserAddress(sipUser, contactFieldEnd, info->m_contact); } else { GrabSipUriUser(sipUser, contactFieldEnd, info->m_contact); } GrabSipUriDomain(sipUser, contactFieldEnd, info->m_contactDomain); } else { if(DLLCONFIG.m_sipReportFullAddress) { GrabSipUserAddress(contactField, contactFieldEnd, info->m_contact); } else { GrabSipUriUser(contactField, contactFieldEnd, info->m_contact); } GrabSipUriDomain(contactField, contactFieldEnd, info->m_contactDomain); } } // SIP fields extraction for(std::list<CStdString>::iterator it = DLLCONFIG.m_sipExtractFields.begin(); it != DLLCONFIG.m_sipExtractFields.end(); it++) { CStdString fieldName = *it + ":"; char* szField = memFindAfter((PSTR)(PCSTR)fieldName, (char*)udpPayload, sipEnd); if(szField) { CStdString field; // XXX // The line below was replaced because I experienced // cases where we would have a leading whitespace in the // tag which has been extracted. However, since we are // dealing with SIP, RFC 3261, section 7.3.1 illustrates // that any leading whitespaces after the colon is not // in fact part of the header value. Therefore, I // created the GrabLineSkipLeadingWhitespace() function // which I use in this particular case. // // Hope this is ok. // // --Gerald // //GrabLine(szField, sipEnd, field); GrabLineSkipLeadingWhitespace(szField, sipEnd, field); info->m_extractedFields.insert(std::make_pair(*it, field)); } } if(DLLCONFIG.m_rtpReportDtmf) { if(rtpmapAttribute) { CStdString rtpPayloadType, nextToken; char *nextStep = NULL; while(rtpmapAttribute && rtpmapAttribute < sipEnd) { rtpPayloadType = ""; GrabTokenSkipLeadingWhitespaces(rtpmapAttribute, audioSdpEnd, rtpPayloadType); nextToken.Format("%s ", rtpPayloadType); nextStep = memFindAfter((char*)nextToken.c_str(), rtpmapAttribute, audioSdpEnd); /* We need our "nextStep" to contain at least the length * of the string "telephone-event", 15 characters */ if(nextStep && ((sipEnd - nextStep) >= 15)) { if(ACE_OS::strncasecmp(nextStep, "telephone-event", 15) == 0) { /* Our DTMF packets are indicated using * the payload type rtpPayloadType */ info->m_telephoneEventPayloadType = rtpPayloadType; info->m_telephoneEventPtDefined = true; break; } } rtpmapAttribute = memFindAfter("\na=rtpmap:", rtpmapAttribute, audioSdpEnd); } } } //Determine the being used codec: should be the first rtpmap if(sipMethod == SIP_METHOD_200_OK || sipMethod == SIP_RESPONSE_SESSION_PROGRESS) { rtpmapAttribute = memFindAfter("\na=rtpmap:", (char*)audioSdpStart, audioSdpEnd); if(rtpmapAttribute) { CStdString line; GrabLineSkipLeadingWhitespace(rtpmapAttribute, sipEnd, line); info->m_orekaRtpPayloadType = GetOrekaRtpPayloadTypeForSdpRtpMap(line); } } if((unsigned int)info->m_fromRtpIp.s_addr == 0) { // In case connection address could not be extracted, use SIP invite sender IP address if(DLLCONFIG.m_dahdiIntercept == true) { info->m_fromRtpIp = ipHeader->ip_dest; } else { info->m_fromRtpIp = ipHeader->ip_src; } } if(sipMethod == SIP_METHOD_200_OK) { info->m_senderIp = ipHeader->ip_dest; info->m_receiverIp = ipHeader->ip_src; } else { info->m_senderIp = ipHeader->ip_src; info->m_receiverIp = ipHeader->ip_dest; } info->m_originalSenderIp = ipHeader->ip_src; info->m_recvTime = time(NULL); memcpy(info->m_senderMac, ethernetHeader->sourceMac, sizeof(info->m_senderMac)); memcpy(info->m_receiverMac, ethernetHeader->destinationMac, sizeof(info->m_receiverMac)); if(sipMethod.Equals(SIP_METHOD_INVITE) || info->m_fromRtpPort.size()) { // Only log SIP non-INVITE messages that contain SDP (i.e. with a valid RTP port) info->ToString(logMsg); logMsg = sipMethod + ": " + logMsg; LOG4CXX_INFO(s_sipPacketLog, logMsg); } //Sip INVITE without sdp will be reported, but other methods without sdp will not be if(drop == false && sipMethod == SIP_METHOD_INVITE && info->m_from.size() && info->m_to.size() && info->m_callId.size()) { VoIpSessionsSingleton::instance()->ReportSipInvite(info); } else if(drop == false && info->m_fromRtpPort.size() && info->m_from.size() && info->m_to.size() && info->m_callId.size()) { VoIpSessionsSingleton::instance()->ReportSipInvite(info); } } return result; }
bool Skype::loadSkypeBuddies() { // std::string re = "CONNSTATUS OFFLINE"; // while (re == "CONNSTATUS OFFLINE" || re.empty()) { // sleep(1); gchar buffer[1024]; int bytes_read = read(fd_output, buffer, 1023); if (bytes_read > 0) { buffer[bytes_read] = 0; std::string b(buffer); LOG4CXX_WARN(logger, "Skype wrote this on stdout '" << b << "'"); if (b.find("Incorrect Password") != std::string::npos) { LOG4CXX_INFO(logger, "Incorrect password, logging out") m_np->handleDisconnected(m_user, pbnetwork::CONNECTION_ERROR_AUTHENTICATION_FAILED, "Incorrect password"); close(fd_output); logout(); return FALSE; } } std::string re = send_command("NAME Spectrum"); if (m_counter++ > 15) { LOG4CXX_ERROR(logger, "Logging out, because we tried to connect the Skype over DBUS 15 times without success"); m_np->handleDisconnected(m_user, pbnetwork::CONNECTION_ERROR_AUTHENTICATION_IMPOSSIBLE, "Skype is not ready. This issue have been logged and admins will check it and try to fix it soon."); close(fd_output); logout(); return FALSE; } if (re.empty() || re == "CONNSTATUS OFFLINE" || re == "ERROR 68") { return TRUE; } close(fd_output); if (send_command("PROTOCOL 7") != "PROTOCOL 7") { LOG4CXX_ERROR(logger, "PROTOCOL 7 failed, logging out"); m_np->handleDisconnected(m_user, pbnetwork::CONNECTION_ERROR_AUTHENTICATION_IMPOSSIBLE, "Skype is not ready. This issue have been logged and admins will check it and try to fix it soon."); logout(); return FALSE; } m_np->handleConnected(m_user); std::map<std::string, std::string> group_map; std::string groups = send_command("SEARCH GROUPS CUSTOM"); if (groups.find(' ') != std::string::npos) { groups = groups.substr(groups.find(' ') + 1); std::vector<std::string> grps; boost::split(grps, groups, boost::is_any_of(",")); BOOST_FOREACH(std::string grp, grps) { if (grp.empty()) continue; std::vector<std::string> data; std::string name = send_command("GET GROUP " + grp + " DISPLAYNAME"); if (name.find("ERROR") == 0) { continue; } boost::split(data, name, boost::is_any_of(" ")); name = GET_RESPONSE_DATA(name, "DISPLAYNAME"); std::string users = send_command("GET GROUP " + data[1] + " USERS"); try { users = GET_RESPONSE_DATA(users, "USERS"); } catch (std::out_of_range& oor) { continue; } boost::split(data, users, boost::is_any_of(",")); BOOST_FOREACH(std::string u, data) { if (!u.empty()) group_map[u] = grp; } } }
void IlbcToPcmFilter::AudioChunkIn(AudioChunkRef& inputAudioChunk) { int r_samples = 0, fs = 0, i = 0, pos = 0, o_samples = 0, j = 0; float ilbcf[240]; m_outputAudioChunk.reset(); if(inputAudioChunk.get() == NULL) { return; } if(inputAudioChunk->GetNumSamples() == 0) { return; } AudioChunkDetails outputDetails = *inputAudioChunk->GetDetails(); if(SupportsInputRtpPayloadType(outputDetails.m_rtpPayloadType) == false) { return; } r_samples = inputAudioChunk->GetNumSamples(); if((r_samples % 50) && (r_samples % 38)) { /* Strange iLBC frame that is not a multiple of 50 bytes * (30ms frame) and neither is it a multiple of 38 bytes * (20ms frame). We should probably log something? */ LOG4CXX_ERROR(this->s_ilbclog, "Error, received iLBC frame is not a multiple of 50 or 38!"); return; } if(!(r_samples % 50)) { i = r_samples / 50; o_samples = i * 240; fs = 50; #if 0 LOG4CXX_INFO(this->s_ilbclog, "Frame size is 50 bytes"); #endif } else { i = r_samples / 38; o_samples = i * 160; fs = 38; #if 0 LOG4CXX_INFO(this->s_ilbclog, "Frame size is 38 bytes"); #endif } m_outputAudioChunk.reset(new AudioChunk()); outputDetails.m_rtpPayloadType = -1; outputDetails.m_encoding = PcmAudio; outputDetails.m_numBytes = (o_samples * 2); short* outputBuffer = (short*)m_outputAudioChunk->CreateBuffer(outputDetails); unsigned char* inputBuffer = (unsigned char*)inputAudioChunk->m_pBuffer; for(i = 0; i < r_samples; i += fs) { if((pos+((fs == 50) ? 240 : 160)) <= o_samples) { if(fs == 50) { iLBC_decode(ilbcf, inputBuffer+i, &dec30, 1); for(j = 0; j < 240; j++) { outputBuffer[pos + j] = (short)ilbcf[j]; } pos += 240; } else { iLBC_decode(ilbcf, inputBuffer+i, &dec20, 1); for(j = 0; j < 160; j++) { outputBuffer[pos + j] = (short)ilbcf[j]; } pos += 160; } } else { /* This should ordinarily never happen. * Log something? */ CStdString logMsg; logMsg.Format("Strange, I ran out of space: pos=%d, o_samples=%d, r_samples=%d, i=%d, " "(pos+((fs == 50) ? 240 : 160))=%d", pos, o_samples, r_samples, i, (pos+((fs == 50) ? 240 : 160))); LOG4CXX_ERROR(this->s_ilbclog, logMsg); return; } } }
void Component::handleDataWritten(const Swift::SafeByteArray &data) { LOG4CXX_INFO(logger_xml, "XML OUT " << safeByteArrayToString(data)); }
void RdmaPerformanceTestServer::onDisconnected(shared_ptr<RdmaConnection> connection) { LOG4CXX_INFO(mLogger ,"DISCONNECTED"); }
static void LuaLogInfo(const std::string &str) { LOG4CXX_INFO(gScriptLogger, str); }
/** * Default Constructor */ Scheduler::Scheduler(){ time(0,0,0); LoggerPtr log(Logger::getLogger("Scheduler")); LOG4CXX_INFO(log, string("Scheduler Created")); }
void PlanOperation::setErrorMessage(const std::string& message) { LOG4CXX_INFO(logger, this << " " << planOperationName() << " sets error message: " << message); getResponseTask()->addErrorMessage(_operatorId + ": " + message); }
void MainThread() { // Avoid program exit on broken pipe ACE_OS::signal (SIGPIPE, (ACE_SignalHandler) SIG_IGN); OrkLogManager::Instance()->Initialize(); LOG4CXX_INFO(LOG.rootLog, CStdString("\n\nOrkAudio service starting\n")); ConfigManager::Instance()->Initialize(); // Initialize object factory and register existing objects ObjectFactory::GetSingleton()->Initialize(); ObjectRef objRef; objRef.reset(new PingMsg); ObjectFactory::GetSingleton()->RegisterObject(objRef); objRef.reset(new TapeMsg); ObjectFactory::GetSingleton()->RegisterObject(objRef); objRef.reset(new TapeResponse); ObjectFactory::GetSingleton()->RegisterObject(objRef); objRef.reset(new SimpleResponseMsg); ObjectFactory::GetSingleton()->RegisterObject(objRef); objRef.reset(new DeleteTapeMsg); ObjectFactory::GetSingleton()->RegisterObject(objRef); objRef.reset(new CaptureMsg); ObjectFactory::GetSingleton()->RegisterObject(objRef); objRef.reset(new TcpPingMsg); ObjectFactory::GetSingleton()->RegisterObject(objRef); objRef.reset(new ReportingSkipTapeMsg); ObjectFactory::GetSingleton()->RegisterObject(objRef); objRef.reset(new RecordMsg); ObjectFactory::GetSingleton()->RegisterObject(objRef); objRef.reset(new PauseMsg); ObjectFactory::GetSingleton()->RegisterObject(objRef); objRef.reset(new StopMsg); ObjectFactory::GetSingleton()->RegisterObject(objRef); objRef.reset(new InitMsg); ObjectFactory::GetSingleton()->RegisterObject(objRef); //objRef.reset(new CrashMsg); //ObjectFactory::GetSingleton()->RegisterObject(objRef); //objRef.reset(new TestMsg); //ObjectFactory::GetSingleton()->RegisterObject(objRef); bool capturePluginOk = false; if(CapturePluginProxy::Singleton()->Initialize()) { capturePluginOk = true; } std::list<ACE_DLL> pluginDlls; LoadPlugins(pluginDlls); // Register in-built filters FilterRef filter(new AlawToPcmFilter()); FilterRegistry::instance()->RegisterFilter(filter); filter.reset(new UlawToPcmFilter()); FilterRegistry::instance()->RegisterFilter(filter); filter.reset(new GsmToPcmFilter()); FilterRegistry::instance()->RegisterFilter(filter); filter.reset(new IlbcToPcmFilter()); FilterRegistry::instance()->RegisterFilter(filter); filter.reset(new AudioGainFilter()); FilterRegistry::instance()->RegisterFilter(filter); filter.reset(new G722ToPcmFilter()); FilterRegistry::instance()->RegisterFilter(filter); filter.reset(new SpeexDecoder() ); FilterRegistry::instance()->RegisterFilter(filter); filter.reset(new G721CodecDecoder()); FilterRegistry::instance()->RegisterFilter(filter); // Register in-built tape processors and build the processing chain OrkTrack::Initialize(CONFIG.m_trackerHostname, CONFIG.m_trackerServicename, CONFIG.m_trackerTcpPort); BatchProcessing::Initialize(); CommandProcessing::Initialize(); Reporting::Initialize(); TapeFileNaming::Initialize(); DirectionSelector::Initialize(); TapeProcessorRegistry::instance()->CreateProcessingChain(); if (!ACE_Thread_Manager::instance()->spawn(ACE_THR_FUNC(ImmediateProcessing::ThreadHandler))) { LOG4CXX_INFO(LOG.rootLog, CStdString("Failed to create immediate processing thread")); } if(CONFIG.m_storageAudioFormat != FfNative) { // storage format is not native, which means we need batch workers to compress to wanted format if (!ACE_Thread_Manager::instance()->spawn_n(CONFIG.m_numBatchThreads, ACE_THR_FUNC(BatchProcessing::ThreadHandler))) { LOG4CXX_INFO(LOG.rootLog, CStdString("Failed to create batch processing thread")); } } if (!ACE_Thread_Manager::instance()->spawn(ACE_THR_FUNC(Reporting::ThreadHandler))) { LOG4CXX_INFO(LOG.rootLog, CStdString("Failed to create reporting thread")); } if (!ACE_Thread_Manager::instance()->spawn(ACE_THR_FUNC(TapeFileNaming::ThreadHandler))) { LOG4CXX_INFO(LOG.rootLog, CStdString("Failed to create tape file naming thread")); } if (!ACE_Thread_Manager::instance()->spawn_n(CONFIG.m_numCommandThreads,ACE_THR_FUNC(CommandProcessing::ThreadHandler))) { LOG4CXX_INFO(LOG.rootLog, CStdString("Failed to create the Command Processing thread")); } if (!ACE_Thread_Manager::instance()->spawn_n(CONFIG.m_numDirectionSelectorThreads,ACE_THR_FUNC(DirectionSelector::ThreadHandler))) { LOG4CXX_INFO(LOG.rootLog, CStdString("Failed to create the DirectionSelector thread")); } // Create command line server if (!ACE_Thread_Manager::instance()->spawn(ACE_THR_FUNC(CommandLineServer::run), (void *)CONFIG.m_commandLineServerPort)) { LOG4CXX_INFO(LOG.rootLog, CStdString("Failed to create command line server")); } // Create Http server if (!ACE_Thread_Manager::instance()->spawn(ACE_THR_FUNC(HttpServer::run), (void *)CONFIG.m_httpServerPort)) { LOG4CXX_INFO(LOG.rootLog, CStdString("Failed to create Http server")); } // Create event streaming server if(!ACE_Thread_Manager::instance()->spawn(ACE_THR_FUNC(EventStreamingServer::run), (void *)CONFIG.m_eventStreamingServerPort)) { LOG4CXX_INFO(LOG.rootLog, CStdString("Failed to create event streaming server")); } if(capturePluginOk) { CapturePluginProxy::Singleton()->Run(); } SocketStreamer::Initialize(); //ACE_Thread_Manager::instance ()->wait (); while(!Daemon::Singleton()->IsStopping()) { ACE_OS::sleep(1); } CapturePluginProxy::Singleton()->Shutdown(); // Wait that all ACE threads have returned //ACE_Thread_Manager::instance ()->wait (); ACE_OS::sleep(2); //***** This is to avoid an exception when NT service exiting //***** Need to find out the real problem and fix #ifdef WIN32 SetErrorMode(SEM_FAILCRITICALERRORS | SEM_NOGPFAULTERRORBOX); SetUnhandledExceptionFilter((LPTOP_LEVEL_EXCEPTION_FILTER)ExceptionFilter); #endif //***** LOG4CXX_INFO(LOG.rootLog, CStdString("Service stopped")); OrkLogManager::Instance()->Shutdown(); }
bool TrySip200Ok(EthernetHeaderStruct* ethernetHeader, IpHeaderStruct* ipHeader, UdpHeaderStruct* udpHeader, u_char* udpPayload, u_char* packetEnd) { bool result = false; if(DLLCONFIG.m_sipTreat200OkAsInvite == true) { return false; } int sipLength = ntohs(udpHeader->len) - sizeof(UdpHeaderStruct); char* sipEnd = (char*)udpPayload + sipLength; if(sipLength < SIP_RESPONSE_200_OK_SIZE || sipEnd > (char*)packetEnd) { ; // packet too short } else if (memcmp(SIP_RESPONSE_200_OK, (void*)udpPayload, SIP_RESPONSE_200_OK_SIZE) == 0) { result = true; Sip200OkInfoRef info(new Sip200OkInfo()); char* fromField = memFindAfter("From:", (char*)udpPayload, sipEnd); if(!fromField) { fromField = memFindAfter("\nf:", (char*)udpPayload, sipEnd); } char* toField = memFindAfter("To:", (char*)udpPayload, sipEnd); if(!toField) { toField = memFindAfter("\nt:", (char*)udpPayload, sipEnd); } char* callIdField = memFindAfter("Call-ID:", (char*)udpPayload, sipEnd); if(!callIdField) { callIdField = memFindAfter("\ni:", (char*)udpPayload, sipEnd); } char* audioField = NULL; char* connectionAddressField = NULL; if(callIdField) { GrabTokenSkipLeadingWhitespaces(callIdField, sipEnd, info->m_callId); audioField = memFindAfter("m=audio ", callIdField, sipEnd); connectionAddressField = memFindAfter("c=IN IP4 ", callIdField, sipEnd); } if(audioField && connectionAddressField) { info->m_hasSdp = true; GrabToken(audioField, sipEnd, info->m_mediaPort); CStdString connectionAddress; GrabToken(connectionAddressField, sipEnd, connectionAddress); struct in_addr mediaIp; if(connectionAddress.size()) { if(ACE_OS::inet_aton((PCSTR)connectionAddress, &mediaIp)) { info->m_mediaIp = mediaIp; } } } if(fromField) { if(s_sipExtractionLog->isDebugEnabled()) { CStdString from; GrabLine(fromField, sipEnd, from); LOG4CXX_DEBUG(s_sipExtractionLog, "from: " + from); } char* fromFieldEnd = memFindEOL(fromField, sipEnd); char* sipUser = memFindAfter("sip:", fromField, fromFieldEnd); if(sipUser) { if(DLLCONFIG.m_sipReportFullAddress) { GrabSipUserAddress(sipUser, fromFieldEnd, info->m_from); } else { GrabSipUriUser(sipUser, fromFieldEnd, info->m_from); } } else { if(DLLCONFIG.m_sipReportFullAddress) { GrabSipUserAddress(fromField, fromFieldEnd, info->m_from); } else { GrabSipUriUser(fromField, fromFieldEnd, info->m_from); } } } if(toField) { CStdString to; char* toFieldEnd = GrabLine(toField, sipEnd, to); LOG4CXX_DEBUG(s_sipExtractionLog, "to: " + to); char* sipUser = memFindAfter("sip:", toField, toFieldEnd); if(sipUser) { if(DLLCONFIG.m_sipReportFullAddress) { GrabSipUserAddress(sipUser, toFieldEnd, info->m_to); } else { GrabSipUriUser(sipUser, toFieldEnd, info->m_to); } } else { if(DLLCONFIG.m_sipReportFullAddress) { GrabSipUserAddress(toField, toFieldEnd, info->m_to); } else { GrabSipUriUser(toField, toFieldEnd, info->m_to); } } } info->m_senderIp = ipHeader->ip_src; info->m_receiverIp = ipHeader->ip_dest; CStdString logMsg; info->ToString(logMsg); logMsg = "200 OK: " + logMsg; if(info->m_hasSdp) { LOG4CXX_INFO(s_sipPacketLog, logMsg); } else { LOG4CXX_DEBUG(s_sipPacketLog, logMsg); } VoIpSessionsSingleton::instance()->ReportSip200Ok(info); } return result; }
bool TrySip302MovedTemporarily(EthernetHeaderStruct* ethernetHeader, IpHeaderStruct* ipHeader, UdpHeaderStruct* udpHeader, u_char* udpPayload, u_char* packetEnd) { bool result = false; bool drop = false; if(DLLCONFIG.m_sip302MovedTemporarilySupport == false) { return false; } int sipLength = ntohs(udpHeader->len) - sizeof(UdpHeaderStruct); char* sipEnd = (char*)udpPayload + sipLength; CStdString sipMethod = "302 Moved Temporarily"; if(sipLength < SIP_RESPONSE_302_MOVED_TEMPORARILY_SIZE || sipEnd > (char*)packetEnd) { drop = true; // packet too short } else if(memcmp(SIP_RESPONSE_302_MOVED_TEMPORARILY, (void*)udpPayload, SIP_RESPONSE_302_MOVED_TEMPORARILY_SIZE) != 0) { drop = true; } if(drop == false) { result = true; Sip302MovedTemporarilyInfoRef info(new Sip302MovedTemporarilyInfo()); char* fromField = memFindAfter("From:", (char*)udpPayload, sipEnd); if(!fromField) { fromField = memFindAfter("\nf:", (char*)udpPayload, sipEnd); } char* toField = memFindAfter("To:", (char*)udpPayload, sipEnd); if(!toField) { toField = memFindAfter("\nt:", (char*)udpPayload, sipEnd); } char* callIdField = memFindAfter("Call-ID:", (char*)udpPayload, sipEnd); if(!callIdField) { callIdField = memFindAfter("\ni:", (char*)udpPayload, sipEnd); } char* contactField = memFindAfter("Contact:", (char*)udpPayload, sipEnd); if(!contactField) { contactField = memFindAfter("\nc:", (char*)udpPayload, sipEnd); } if(fromField) { if(s_sipExtractionLog->isDebugEnabled()) { CStdString from; GrabLine(fromField, sipEnd, from); LOG4CXX_DEBUG(s_sipExtractionLog, "from: " + from); } char* fromFieldEnd = memFindEOL(fromField, sipEnd); GrabSipName(fromField, fromFieldEnd, info->m_fromName); char* sipUser = memFindAfter("sip:", fromField, fromFieldEnd); if(sipUser) { if(DLLCONFIG.m_sipReportFullAddress) { GrabSipUserAddress(sipUser, fromFieldEnd, info->m_from); } else { GrabSipUriUser(sipUser, fromFieldEnd, info->m_from); } GrabSipUriDomain(sipUser, fromFieldEnd, info->m_fromDomain); } else { if(DLLCONFIG.m_sipReportFullAddress) { GrabSipUserAddress(fromField, fromFieldEnd, info->m_from); } else { GrabSipUriUser(fromField, fromFieldEnd, info->m_from); } GrabSipUriDomain(fromField, fromFieldEnd, info->m_fromDomain); } } if(toField) { CStdString to; char* toFieldEnd = GrabLine(toField, sipEnd, to); LOG4CXX_DEBUG(s_sipExtractionLog, "to: " + to); GrabSipName(toField, toFieldEnd, info->m_toName); char* sipUser = memFindAfter("sip:", toField, toFieldEnd); if(sipUser) { if(DLLCONFIG.m_sipReportFullAddress) { GrabSipUserAddress(sipUser, toFieldEnd, info->m_to); } else { GrabSipUriUser(sipUser, toFieldEnd, info->m_to); } GrabSipUriDomain(sipUser, toFieldEnd, info->m_toDomain); } else { if(DLLCONFIG.m_sipReportFullAddress) { GrabSipUserAddress(toField, toFieldEnd, info->m_to); } else { GrabSipUriUser(toField, toFieldEnd, info->m_to); } GrabSipUriDomain(toField, toFieldEnd, info->m_toDomain); } } if(contactField) { CStdString contact; char* contactFieldEnd = GrabLine(contactField, sipEnd, contact); LOG4CXX_DEBUG(s_sipExtractionLog, "contact: " + contact); GrabSipName(contactField, contactFieldEnd, info->m_contactName); char* sipUser = memFindAfter("sip:", contactField, contactFieldEnd); if(sipUser) { if(DLLCONFIG.m_sipReportFullAddress) { GrabSipUserAddress(sipUser, contactFieldEnd, info->m_contact); } else { GrabSipUriUser(sipUser, contactFieldEnd, info->m_contact); } GrabSipUriDomain(sipUser, contactFieldEnd, info->m_contactDomain); } else { if(DLLCONFIG.m_sipReportFullAddress) { GrabSipUserAddress(contactField, contactFieldEnd, info->m_contact); } else { GrabSipUriUser(contactField, contactFieldEnd, info->m_contact); } GrabSipUriDomain(contactField, contactFieldEnd, info->m_contactDomain); } } if(callIdField) { GrabTokenSkipLeadingWhitespaces(callIdField, sipEnd, info->m_callId); } info->m_senderIp = ipHeader->ip_src; info->m_receiverIp = ipHeader->ip_dest; if(!info->m_callId.size()) { drop = true; } if(!info->m_contact) { drop = true; } CStdString logMsg; info->ToString(logMsg); logMsg = sipMethod + ": " + logMsg; LOG4CXX_INFO(s_sipPacketLog, logMsg); if(drop == false) { VoIpSessionsSingleton::instance()->ReportSip302MovedTemporarily(info); } else { CStdString packetInfo; info->ToString(packetInfo); logMsg.Format("Dropped this %s: %s", sipMethod, packetInfo); LOG4CXX_INFO(s_sipPacketLog, logMsg); } } return result; }
bool TrySipBye(EthernetHeaderStruct* ethernetHeader, IpHeaderStruct* ipHeader, UdpHeaderStruct* udpHeader, u_char* udpPayload, u_char* packetEnd) { bool result = false; int sipLength = ntohs(udpHeader->len) - sizeof(UdpHeaderStruct); char* sipEnd = (char*)udpPayload + sipLength; if(sipLength < (int)sizeof(SIP_METHOD_BYE) || sipEnd > (char*)packetEnd) { return false; } if (memcmp(SIP_METHOD_BYE, (void*)udpPayload, SIP_METHOD_BYE_SIZE) == 0) { result = true; SipByeInfoRef info(new SipByeInfo()); char* fromField = memFindAfter("From:", (char*)udpPayload, sipEnd); if(!fromField) { fromField = memFindAfter("\nf:", (char*)udpPayload, sipEnd); } char* toField = memFindAfter("To:", (char*)udpPayload, sipEnd); if(!toField) { toField = memFindAfter("\nt:", (char*)udpPayload, sipEnd); } char* callIdField = memFindAfter("Call-ID:", (char*)udpPayload, sipEnd); if(!callIdField) { callIdField = memFindAfter("\ni:", (char*)udpPayload, sipEnd); } if(callIdField) { GrabTokenSkipLeadingWhitespaces(callIdField, sipEnd, info->m_callId); } if(fromField) { if(s_sipExtractionLog->isDebugEnabled()) { CStdString from; GrabLine(fromField, sipEnd, from); LOG4CXX_DEBUG(s_sipExtractionLog, "from: " + from); } char* fromFieldEnd = memFindEOL(fromField, sipEnd); GrabSipName(fromField, fromFieldEnd, info->m_fromName); char* sipUser = memFindAfter("sip:", fromField, fromFieldEnd); if(sipUser) { if(DLLCONFIG.m_sipReportFullAddress) { GrabSipUserAddress(sipUser, fromFieldEnd, info->m_from); } else { GrabSipUriUser(sipUser, fromFieldEnd, info->m_from); } GrabSipUriDomain(sipUser, fromFieldEnd, info->m_fromDomain); } else { if(DLLCONFIG.m_sipReportFullAddress) { GrabSipUserAddress(fromField, fromFieldEnd, info->m_from); } else { GrabSipUriUser(fromField, fromFieldEnd, info->m_from); } GrabSipUriDomain(fromField, fromFieldEnd, info->m_fromDomain); } } if(toField) { CStdString to; char* toFieldEnd = GrabLine(toField, sipEnd, to); LOG4CXX_DEBUG(s_sipExtractionLog, "to: " + to); GrabSipName(toField, toFieldEnd, info->m_toName); char* sipUser = memFindAfter("sip:", toField, toFieldEnd); if(sipUser) { if(DLLCONFIG.m_sipReportFullAddress) { GrabSipUserAddress(sipUser, toFieldEnd, info->m_to); } else { GrabSipUriUser(sipUser, toFieldEnd, info->m_to); } GrabSipUriDomain(sipUser, toFieldEnd, info->m_toDomain); } else { if(DLLCONFIG.m_sipReportFullAddress) { GrabSipUserAddress(toField, toFieldEnd, info->m_to); } else { GrabSipUriUser(toField, toFieldEnd, info->m_to); } GrabSipUriDomain(toField, toFieldEnd, info->m_toDomain); } } info->m_senderIp = ipHeader->ip_src; info->m_receiverIp = ipHeader->ip_dest; CStdString logMsg; info->ToString(logMsg); LOG4CXX_INFO(s_sipPacketLog, "BYE: " + logMsg); if(callIdField && DLLCONFIG.m_sipIgnoreBye == false) { VoIpSessionsSingleton::instance()->ReportSipBye(info); } } return result; }
bool TrySipRefer(EthernetHeaderStruct* ethernetHeader, IpHeaderStruct* ipHeader, UdpHeaderStruct* udpHeader, u_char* udpPayload, u_char* packetEnd) { bool result = false; int sipLength = ntohs(udpHeader->len) - sizeof(UdpHeaderStruct); char* sipEnd = (char*)udpPayload + sipLength; if(sipLength < SIP_METHOD_REFER_SIZE || sipEnd > (char*)packetEnd) { ; // packet too short } else if(memcmp(SIP_METHOD_REFER, (void*)udpPayload, SIP_METHOD_REFER_SIZE) == 0) { result = true; SipReferRef info(new SipRefer()); info->m_timestamp = time(NULL); char* referToField = memFindAfter("Refer-To:", (char*)udpPayload, sipEnd); char* referredByField = memFindAfter("Referred-By:", (char*)udpPayload, sipEnd); char* callIdField = memFindAfter("Call-ID:", (char*)udpPayload, sipEnd); if(!callIdField) { callIdField = memFindAfter("\ni:", (char*)udpPayload, sipEnd); } char* fromField = memFindAfter("From:", (char*)udpPayload, sipEnd); if(!fromField) { fromField = memFindAfter("\nf:", (char*)udpPayload, sipEnd); } char* toField = memFindAfter("To:", (char*)udpPayload, sipEnd); if(!toField) { toField = memFindAfter("\nt:", (char*)udpPayload, sipEnd); } if(callIdField) { GrabTokenSkipLeadingWhitespaces(callIdField, sipEnd, info->m_callId); } if(fromField) { if(s_sipExtractionLog->isDebugEnabled()) { CStdString from; GrabLine(fromField, sipEnd, from); LOG4CXX_DEBUG(s_sipExtractionLog, "from: " + from); } char* fromFieldEnd = memFindEOL(fromField, sipEnd); GrabSipName(fromField, fromFieldEnd, info->m_fromName); char* sipUser = memFindAfter("sip:", fromField, fromFieldEnd); if(sipUser) { GrabSipUriUser(sipUser, fromFieldEnd, info->m_from); GrabSipUriDomain(sipUser, fromFieldEnd, info->m_fromDomain); } else { GrabSipUriUser(fromField, fromFieldEnd, info->m_from); GrabSipUriDomain(fromField, fromFieldEnd, info->m_fromDomain); } } if(toField) { CStdString to; char* toFieldEnd = GrabLine(toField, sipEnd, to); LOG4CXX_DEBUG(s_sipExtractionLog, "to: " + to); GrabSipName(toField, toFieldEnd, info->m_toName); char* sipUser = memFindAfter("sip:", toField, toFieldEnd); if(sipUser) { GrabSipUriUser(sipUser, toFieldEnd, info->m_to); GrabSipUriDomain(sipUser, toFieldEnd, info->m_toDomain); } else { GrabSipUriUser(toField, toFieldEnd, info->m_to); GrabSipUriDomain(toField, toFieldEnd, info->m_toDomain); } } if(referToField) { char* referToFieldEnd = memFindEOL(referToField, sipEnd); char* sipUser = memFindAfter("sip:", referToField, referToFieldEnd); if(sipUser) { GrabSipUriUser(sipUser, referToFieldEnd, info->m_referToParty); } } if(referredByField) { char* referredByFieldEnd = memFindEOL(referredByField, sipEnd); char* sipUser = memFindAfter("sip:", referredByField, referredByFieldEnd); if(sipUser) { GrabSipUriUser(sipUser, referredByFieldEnd, info->m_referredByParty); } } if((!(info->m_to.length()==0)) && (info->m_to.CompareNoCase(info->m_referToParty) != 0) && (info->m_to.CompareNoCase(info->m_referredByParty) != 0)) { info->m_referredParty = info->m_to; } if((!(info->m_from.length()==0)) && (info->m_from.CompareNoCase(info->m_referToParty) != 0) && (info->m_from.CompareNoCase(info->m_referredByParty) != 0)) { info->m_referredParty = info->m_from; } info->m_senderIp = ipHeader->ip_src; info->m_receiverIp = ipHeader->ip_dest; CStdString logMsg; info->ToString(logMsg); logMsg = "REFER: " + logMsg; LOG4CXX_INFO(s_sipPacketLog, logMsg); VoIpSessionsSingleton::instance()->ReportSipRefer(info); } return result; }
bool TrySipNotify(EthernetHeaderStruct* ethernetHeader, IpHeaderStruct* ipHeader, UdpHeaderStruct* udpHeader, u_char* udpPayload, u_char* packetEnd) { int sipLength = ntohs(udpHeader->len) - sizeof(UdpHeaderStruct); char* sipEnd = (char*)udpPayload + sipLength; if(sipLength < (int)sizeof(SIP_METHOD_BYE) || sipEnd > (char*)packetEnd) { return false; } if (boost::starts_with((char*)udpPayload, "NOTIFY")) { SipNotifyInfoRef info(new SipNotifyInfo()); info->m_senderIp = ipHeader->ip_src; info->m_receiverIp = ipHeader->ip_dest; char* callIdField = memFindAfter("Call-ID:", (char*)udpPayload, sipEnd); if(!callIdField) { callIdField = memFindAfter("\ni:", (char*)udpPayload, sipEnd); } if(callIdField) { GrabTokenSkipLeadingWhitespaces(callIdField, sipEnd, info->m_callId); } char* dspField = memFindAfter(DLLCONFIG.m_necNotifyDispLine, (char*)udpPayload, sipEnd); if(!dspField) { dspField = memFindAfter("\nt:", (char*)udpPayload, sipEnd); } if(dspField) { char* contentLen = memFindAfter("Content-Length: 50", (char*)udpPayload, sipEnd); if (contentLen) { dspField = contentLen+50; while (*dspField != ' ') dspField--; // find the position of the lastest token before end } GrabTokenSkipLeadingWhitespaces(dspField, sipEnd, info->m_dsp); CStdString hex; for(int i=0;i<info->m_dsp.length();i++) { char byteAsHex[2]; sprintf(byteAsHex, "%.2x",*(info->m_dsp.c_str()+i)); hex += byteAsHex; } if (hex == DLLCONFIG.m_necOnHoldMarker) { info->m_onHoldMarker = true; } if (hex == DLLCONFIG.m_necOffHoldMarker) { info->m_offHoldMarker = true; } } char* pkeyField = memFindAfter("Ind-Pkey=", (char*)udpPayload, sipEnd); if (!pkeyField) { pkeyField = memFindAfter("Ind-Fkey=", (char*)udpPayload, sipEnd); } if (pkeyField) { CStdString pkeyToken; GrabTokenSkipLeadingWhitespaces(pkeyField, sipEnd, pkeyToken); sscanf(pkeyToken.c_str(),"%d",&info->m_pkey); } if (callIdField && DLLCONFIG.m_sipNotifySupport) { LOG4CXX_INFO(s_sipPacketLog, "NOTIFY: " + info->ToString()); VoIpSessionsSingleton::instance()->ReportSipNotify(info); return true; } } return false; }
/*void EventHandler::processNewPaymentverify(EventCmd &e, vector<string> &check_cmd) { if(check_cmd.size()!=6) return; uid_type uid; int server_id; string tran_id = check_cmd[4]; string product_id = check_cmd[5]; bool check = safeAtoll(check_cmd[1], uid); if(check == false) return; check = safeAtoi(check_cmd[3], server_id); if(check == false) return; if(tran_id.size()==0||tran_id.size() >32) return; NewPaymentInfo * npi = dh_->loadNewPaymentInfo(tran_id); if(npi == NULL){ //sendErrorResponse(e.fd_, CMD_NEWPAYMENTVERIFY, ERROR_PAYMENT_NOT_RECEIVED_YET); sendErrorResponseFroPayment(e.fd_, CMD_NEWPAYMENTVERIFY, ERROR_PAYMENT_NOT_RECEIVED_YET,tran_id); return; } if(uid!=npi->uid_ || product_id != npi->product_id_ || server_id != npi->server_id_){ //sendErrorResponse(e.fd_, CMD_NEWPAYMENTVERIFY, ERROR_PAYMENT_ORDER_INFO_NOT_MATCH); sendErrorResponseFroPayment(e.fd_, CMD_NEWPAYMENTVERIFY, ERROR_PAYMENT_ORDER_INFO_NOT_MATCH,tran_id); return; } PaymentConfig * pc = game_config.getPaymentConfig(product_id); if(pc == NULL){ //sendErrorResponse(e.fd_, CMD_NEWPAYMENTVERIFY, ERROR_CONFIG_ERROR); sendErrorResponseFroPayment(e.fd_, CMD_NEWPAYMENTVERIFY, ERROR_CONFIG_ERROR,tran_id); return; } if(pc->price_ != npi->order_money_){ //sendErrorResponse(e.fd_, CMD_NEWPAYMENTVERIFY, ERROR_PAYMENT_ORDER_INFO_NOT_MATCH); sendErrorResponseFroPayment(e.fd_, CMD_NEWPAYMENTVERIFY, ERROR_PAYMENT_ORDER_INFO_NOT_MATCH,tran_id); return; } if(npi->order_status_ == NEW_PAYMENT_SENDDING){ //sendErrorResponse(e.fd_, CMD_NEWPAYMENTVERIFY, ERROR_PAYMENT_WRONG_TIME); sendErrorResponseFroPayment(e.fd_, CMD_NEWPAYMENTVERIFY, ERROR_PAYMENT_WRONG_TIME,tran_id); return; } if(npi->order_status_ == NEW_PAYMENT_COMPLETE){ //sendErrorResponse(e.fd_, CMD_NEWPAYMENTVERIFY, ERROR_PAYMENT_TRADE_COMPLETE); sendErrorResponseFroPayment(e.fd_, CMD_NEWPAYMENTVERIFY, ERROR_PAYMENT_TRADE_COMPLETE,tran_id); return; } npi->order_status_ = NEW_PAYMENT_SENDDING; check = dh_->saveNewPaymentStatus(npi->tran_id_, npi->order_status_); if(check == false){ //sendErrorResponse(e.fd_, CMD_NEWPAYMENTVERIFY, ERROR_SYSTEM_CRITICAL_ERROR); sendErrorResponseFroPayment(e.fd_, CMD_NEWPAYMENTVERIFY, ERROR_SYSTEM_CRITICAL_ERROR,tran_id); return; } int local_product_id = pc->local_id_; delete npi; npi = NULL; pthread_t tid; struct NewPaymentAdd *npa; npa = (struct NewPaymentAdd *) malloc (sizeof(NewPaymentAdd)); if(npa == NULL) { //sendErrorResponse(e.fd_, CMD_NEWPAYMENTVERIFY, ERROR_SYSTEM_CRITICAL_ERROR); sendErrorResponseFroPayment(e.fd_, CMD_NEWPAYMENTVERIFY, ERROR_SYSTEM_CRITICAL_ERROR,tran_id); return; } npa->eq = this->eq_; npa->fd_ = e.fd_; npa->local_product_id = local_product_id; npa->server_id = server_id; npa->uid = uid; npa->tran_id = new string(tran_id); pthread_create(&tid,NULL,paymentAdd,(void *)npa); return; }*/ void EventHandler::processPBak(EventCmd &e, vector<string> &check_cmd) { if(check_cmd.size()!=6) return; uid_type uid; int server_id; string tran_id = check_cmd[4]; string product_id = check_cmd[5]; bool check = safeAtoll(check_cmd[1], uid); if(check == false) return; check = safeAtoi(check_cmd[3], server_id); if(check == false) return; if(tran_id.size()==0||tran_id.size() >32) return; User * user =safeGetUser(uid, CMD_PBAK,e.fd_,check_cmd[2]); if(user == NULL) return; LOG4CXX_INFO(logger_, "pbak;"<<uid); NewPaymentInfo * npi = dh_->loadNewPaymentInfoBak(tran_id); if(npi == NULL){ //sendErrorResponse(e.fd_, CMD_NEWPAYMENTVERIFY, ERROR_PAYMENT_NOT_RECEIVED_YET); sendErrorResponseFroPayment(e.fd_, CMD_PBAK, ERROR_PAYMENT_NOT_RECEIVED_YET,tran_id); return; } if(uid!=npi->uid_ || product_id != npi->product_id_ || server_id != npi->server_id_){ //sendErrorResponse(e.fd_, CMD_NEWPAYMENTVERIFY, ERROR_PAYMENT_ORDER_INFO_NOT_MATCH); sendErrorResponseFroPayment(e.fd_, CMD_PBAK, ERROR_PAYMENT_ORDER_INFO_NOT_MATCH,tran_id); return; } if(server_id != this->server_id_){ sendErrorResponseFroPayment(e.fd_, CMD_PBAK, ERROR_PAYMENT_ORDER_INFO_NOT_MATCH,tran_id); return; } PaymentConfig * pc = game_config.getPaymentConfig(product_id); if(pc == NULL){ //sendErrorResponse(e.fd_, CMD_NEWPAYMENTVERIFY, ERROR_CONFIG_ERROR); sendErrorResponseFroPayment(e.fd_, CMD_PBAK, ERROR_CONFIG_ERROR,tran_id); return; } if(pc->price_ != npi->order_money_){ //sendErrorResponse(e.fd_, CMD_NEWPAYMENTVERIFY, ERROR_PAYMENT_ORDER_INFO_NOT_MATCH); sendErrorResponseFroPayment(e.fd_, CMD_PBAK, ERROR_PAYMENT_ORDER_INFO_NOT_MATCH,tran_id); return; } if(npi->order_status_ != NEW_PAYMENT_RECEIVED){ sendErrorResponseFroPayment(e.fd_, CMD_PBAK, ERROR_PAYMENT_TRADE_COMPLETE,tran_id); return; } npi->order_status_ = NEW_PAYMENT_COMPLETE; check = dh_->saveNewPaymentStatusBak(npi->tran_id_, npi->order_status_); user->diamond_ += pc->amount_; user->pay_count_ ++; ActConfig * ac = game_config.getActConfig(ACT_1); if(ac != NULL){ act_1(user,pc->amount_); } check = dh_->saveUser(user); if(check == false){ sendErrorResponse(e.fd_, CMD_PBAK,ERROR_SYSTEM_CRITICAL_ERROR); return; } LOG4CXX_INFO(logger_, "pbaksucc;"<<uid<<";"<<user->diamond_); string res = buildPBakResponse(user, npi); nh_->sendString(e.fd_, res); if(npi!= NULL){ delete npi; npi = NULL; } return; }
void LoadPlugins(std::list<ACE_DLL>& pluginDlls) { CStdString pluginsDirectory = CONFIG.m_pluginsDirectory; #ifdef WIN32 if(pluginsDirectory.size() == 0) { // default windows plugins directory pluginsDirectory = "./plugins/"; } CStdString pluginExtension = ".dll"; #else if(pluginsDirectory.size() == 0) { // default unix plugins directory pluginsDirectory = "/usr/lib/orkaudio/plugins/"; } CStdString pluginExtension = ".so"; #endif CStdString pluginPath; ACE_DLL dll; ACE_DIR* dir = ACE_OS::opendir((PCSTR)pluginsDirectory); if (!dir) { LOG4CXX_ERROR(LOG.rootLog, CStdString("Plugins directory could not be found:" + pluginsDirectory + " check your config.xml")); } else { dirent* dirEntry = NULL; while((dirEntry = ACE_OS::readdir(dir))) { CStdString dirEntryFilename = dirEntry->d_name; int extensionPos = dirEntryFilename.Find(pluginExtension); if ( extensionPos != -1 && (dirEntryFilename.size() - extensionPos) == pluginExtension.size() ) { pluginPath = pluginsDirectory + "/" + dirEntry->d_name; dll.open((PCSTR)pluginPath); ACE_TCHAR* error = dll.error(); if(error) { LOG4CXX_ERROR(LOG.rootLog, CStdString("Failed to load plugin: ") + pluginPath); #ifndef WIN32 CStdString logMsg; logMsg.Format("DLL Error: %s", dlerror()); LOG4CXX_ERROR(LOG.rootLog, logMsg); #endif } else { LOG4CXX_INFO(LOG.rootLog, CStdString("Loaded plugin: ") + pluginPath); InitializeFunction initfunction; initfunction = (InitializeFunction)dll.symbol("OrkInitialize"); if (initfunction) { initfunction(); pluginDlls.push_back(dll); } else { LOG4CXX_ERROR(LOG.rootLog, CStdString("Failed to initialize plugin: ") + pluginPath); } } } } ACE_OS::closedir(dir); } }
TNC_Result ProcwatcherIMV::receiveMessage(TNC_BufferReference message, TNC_UInt32 length, TNC_MessageType messageType) { //把FileEntry存好 // // //this->entry = policyManager->getFileEntries(); //(this->entry).push_back(FileEntry("/bin/","12345678901234567890")); // // LOG4CXX_DEBUG(logger, "receiveMessage round " << this->getRound()); if (firstMessage) { LOG4CXX_DEBUG(logger, "Received first message, should be the x509 cert"); firstMessage = 0; if (processFirstMessage(message, length) < 0) { return TNC_RESULT_FATAL; } if (!checkClientKnown()) { LOG4CXX_INFO(logger, "Client Certificate unknown. :-("); tncs.provideRecommendation(TNC_IMV_ACTION_RECOMMENDATION_NO_ACCESS, TNC_IMV_EVALUATION_RESULT_DONT_KNOW); } else { nonceBuf = new unsigned char[50]; //验证完AIK证书后,发一个nonce过去,以防止重放攻击 LOG4CXX_TRACE(logger, "Generating nonce..."); if (RAND_bytes(nonceBuf,10) == 0) { LOG4CXX_FATAL(logger, "RAND_bytes() failed!!!"); nothingWrong = false; delete[] nonceBuf; return -1; } else { for(int i=0;i<10;i++) { printf("%02hhx",nonceBuf[i]); } translate2chars((char *)nonceBuf,20); //计算hash(n*(hash(file),用于等下收到客户端发过来的该内容时做匹配,类似attestation里的calculate函数 calculateHash(entry); this->tncs.sendMessage(nonceBuf, 20, VENDOR_ID,MESSAGE_SUBTYPE); delete[] nonceBuf; } } } else { char *temp_buf = (char *)malloc(MAX); //memcpy(temp_buf,message,20); strcpy(temp_buf,(char *)message); // print received message dirty out. WARNING: don't ape this, // message should end with non-null! Heed: Message can be evil! LOG4CXX_INFO(logger, "Received 2nd Message: " << message); /* only send one message to ProcwatcherIMC */ // /* validation finish, set recommendation & co */ // validationFinished = true; // // // for no access: //// actionRecommendation = TNC_IMV_ACTION_RECOMMENDATION_NO_ACCESS; // // for isolate: //// actionRecommendation = TNC_IMV_ACTION_RECOMMENDATION_ISOLATE; // // for access allow: // actionRecommendation = TNC_IMV_ACTION_RECOMMENDATION_ALLOW; // // // set evaluation (see TNC_IMV_EVALUATION_RESULT_...) // evaluationResult = TNC_IMV_EVALUATION_RESULT_DONT_KNOW; //验证签名!标准值来自于:已知进程hash+nonce translate2chars(temp_buf,20); std::stringstream ss; ss.write((const char *)message, length); std::vector<prop_type> properties = readAllProperties(ss); LOG4CXX_INFO(logger, "good file-hash signature :-)" ); validationFinished = true; actionRecommendation = TNC_IMV_ACTION_RECOMMENDATION_ALLOW; evaluationResult = TNC_IMV_EVALUATION_RESULT_DONT_KNOW; free(temp_buf); } // return all ok return TNC_RESULT_SUCCESS; }
void jscripter_inventory::stop(webEngine::task* tsk) { LOG4CXX_INFO(logger, _T("### ") << std::string(__FUNCTION__) << _T(" of ") << pluginInfo.interface_name); }
void RowEchelon<T>::getNullspace(MatrixT& N) const { if(R.isEmpty()) { N.clear(); return; } Assert((int)firstEntry.size() == R.m+1); int nullspace_dims=getNull(); N.resize(R.n,nullspace_dims); //first get nullspace vectors from 0 to firstEntry[0] int i,j,numVecs=0; int m=R.m,n=R.n; for(j=0;j<firstEntry[0];j++) { N.setCol(numVecs,0); N(j,numVecs)=1; numVecs++; } for(i=0;i<m;i++) { //cancel out the i'th entry for(j=firstEntry[i]+1;j<firstEntry[i+1];j++) { if(numVecs >= N.n) { LOG4CXX_INFO(KrisLibrary::logger(),"Num nullspace vectors "<<numVecs); LOG4CXX_INFO(KrisLibrary::logger(),"Found more nullspace vectors than found dims, row "<<i); LOG4CXX_INFO(KrisLibrary::logger(),MatrixPrinter(R)); } Assert(numVecs < N.n); VectorT xn; N.getColRef(numVecs,xn); xn.setZero(); xn[firstEntry[i]] = R(i,j); xn[j] = -R(i,firstEntry[i]); //cancel out all the entries prior to i int isave=i; i--; for(;i>=0;i--) { VectorT ri; R.getRowRef(i,ri); //calculate alpha int ji=firstEntry[i]; Assert(ji != n); int ji2=firstEntry[i+1]; //(i+1==m?n:firstEntry[i+1]); T alpha; if(ji2 == n) alpha = Zero; else { VectorT rji2; rji2.setRef(ri,ji2,1,R.n-ji2); VectorT xji2; xji2.setRef(xn,ji2,1,R.n-ji2); alpha = xji2.dot(rji2); } xn[ji] = -alpha/ri[ji]; } i=isave; numVecs++; } } if(numVecs != nullspace_dims) { LOG4CXX_ERROR(KrisLibrary::logger(),"Error in counting rank in row-eschelon decomposition"); LOG4CXX_INFO(KrisLibrary::logger(),"Num nullspace vectors "<<numVecs); LOG4CXX_INFO(KrisLibrary::logger(),MatrixPrinter(R)); } Assert(numVecs == nullspace_dims); /* VectorT temp; for(int i=0;i<numVecs;i++) { VectorT xi; N.getColRef(i,xi); xi.print(); R.mul(xi,temp); if(temp.maxAbsElement() > 1e-4) { LOG4CXX_INFO(KrisLibrary::logger(),"Nullspace vector "<<i<<" not in null space!"); xi.print(); LOG4CXX_INFO(KrisLibrary::logger(),"Result = "); temp.print(); KrisLibrary::loggerWait(); } } */ VectorT* N0 = new VectorT[nullspace_dims]; for(int i=0;i<nullspace_dims;i++) N.getColRef(i,N0[i]); int num=OrthonormalBasis(N0,N0,nullspace_dims); Assert(num == nullspace_dims); delete [] N0; }
int DataSvrClientGroup::init(CnfSvrClient * csc) { _csc = csc; pthread_mutex_init(&_mutex, NULL); LOG4CXX_INFO(_logger, __FUNCTION__ << ", ok!"); return 1; }
void Component::handleDataRead(const Swift::SafeByteArray &data) { std::string d = safeByteArrayToString(data); if (!boost::starts_with(d, "<auth")) { LOG4CXX_INFO(logger_xml, "XML IN " << d); } }
void BatchProcessing::ThreadHandler(void *args) { CStdString debug; CStdString logMsg; CStdString processorName("BatchProcessing"); TapeProcessorRef batchProcessing = TapeProcessorRegistry::instance()->GetNewTapeProcessor(processorName); if(batchProcessing.get() == NULL) { LOG4CXX_ERROR(LOG.batchProcessingLog, "Could not instanciate BatchProcessing"); return; } BatchProcessing* pBatchProcessing = (BatchProcessing*)(batchProcessing->Instanciate().get()); pBatchProcessing->SetQueueSize(CONFIG.m_batchProcessingQueueSize); int threadId = 0; { MutexSentinel sentinel(pBatchProcessing->m_mutex); threadId = pBatchProcessing->m_threadCount++; } CStdString threadIdString = IntToString(threadId); debug.Format("thread Th%s starting - queue size:%d", threadIdString, CONFIG.m_batchProcessingQueueSize); LOG4CXX_INFO(LOG.batchProcessingLog, debug); bool stop = false; for(;stop == false;) { AudioFileRef fileRef; AudioFileRef outFileRef; AudioTapeRef audioTapeRef; CStdString trackingId = "[no-trk]"; try { audioTapeRef = pBatchProcessing->m_audioTapeQueue.pop(); if(audioTapeRef.get() == NULL) { if(Daemon::Singleton()->IsStopping()) { stop = true; } if(Daemon::Singleton()->GetShortLived()) { Daemon::Singleton()->Stop(); } } else { fileRef = audioTapeRef->GetAudioFileRef(); trackingId = audioTapeRef->m_trackingId; // Let's work on the tape we have pulled //CStdString threadIdString = IntToString(threadId); LOG4CXX_INFO(LOG.batchProcessingLog, "[" + trackingId + "] Th" + threadIdString + " processing " + audioTapeRef->GetIdentifier() + " localside:" + CaptureEvent::LocalSideToString(audioTapeRef->m_localSide) + " audiokeepdirection:" + CaptureEvent::AudioKeepDirectionToString(audioTapeRef->m_audioKeepDirectionEnum)); if(audioTapeRef->m_audioKeepDirectionEnum == CaptureEvent::AudioKeepDirectionInvalid) { LOG4CXX_WARN(LOG.batchProcessingLog, "[" + trackingId + "] Th" + threadIdString + " invalid audiokeepdirection:" + IntToString(audioTapeRef->m_audioKeepDirectionEnum)); } //fileRef->MoveOrig(); // #### could do this only when original and output file have the same extension. Irrelevant for now as everything is captured as mcf file fileRef->Open(AudioFile::READ); AudioChunkRef chunkRef; AudioChunkRef tmpChunkRef; unsigned int frameSleepCounter; frameSleepCounter = 0; switch(CONFIG.m_storageAudioFormat) { case FfUlaw: outFileRef.reset(new LibSndFileFile(SF_FORMAT_ULAW | SF_FORMAT_WAV)); break; case FfAlaw: outFileRef.reset(new LibSndFileFile(SF_FORMAT_ALAW | SF_FORMAT_WAV)); break; case FfGsm: outFileRef.reset(new LibSndFileFile(SF_FORMAT_GSM610 | SF_FORMAT_WAV)); break; case FfPcmWav: default: outFileRef.reset(new LibSndFileFile(SF_FORMAT_PCM_16 | SF_FORMAT_WAV)); } FilterRef filter; FilterRef decoder1; FilterRef decoder2; FilterRef decoder; FilterRef audiogain; std::bitset<RTP_PAYLOAD_TYPE_MAX> seenRtpPayloadTypes; std::vector<FilterRef> decoders1; std::vector<FilterRef> decoders2; for(int pt=0; pt<RTP_PAYLOAD_TYPE_MAX; pt++) { decoder1 = FilterRegistry::instance()->GetNewFilter(pt); decoders1.push_back(decoder1); decoder2 = FilterRegistry::instance()->GetNewFilter(pt); decoders2.push_back(decoder2); } bool firstChunk = true; bool voIpSession = false; size_t numSamplesS1 = 0; size_t numSamplesS2 = 0; size_t numSamplesOut = 0; CStdString filterName("AudioGain"); audiogain = FilterRegistry::instance()->GetNewFilter(filterName); if(audiogain.get() == NULL) { debug = "Could not instanciate AudioGain filter"; throw(debug); } bool forceChannel1 = false; while(fileRef->ReadChunkMono(chunkRef)) { // ############ HACK //ACE_Time_Value yield; //yield.set(0,1); //ACE_OS::sleep(yield); // ############ HACK AudioChunkDetails details = *chunkRef->GetDetails(); int channelToSkip = 0; if(BatchProcessing::SkipChunk(audioTapeRef, chunkRef, channelToSkip) == true) { LOG4CXX_DEBUG(LOG.batchProcessingLog, "[" + trackingId + "] Th" + threadIdString + " skipping chunk of channel:" + IntToString(details.m_channel)); if(forceChannel1 == false) { if(channelToSkip == 1) { forceChannel1 = true; } } continue; } if(forceChannel1 == true) { details.m_channel = 1; chunkRef->SetDetails(&details); } decoder.reset(); if(details.m_rtpPayloadType < -1 || details.m_rtpPayloadType >= RTP_PAYLOAD_TYPE_MAX) { logMsg.Format("RTP payload type out of bound:%d", details.m_rtpPayloadType); throw(logMsg); } // Instanciate any decoder we might need during a VoIP session if(details.m_rtpPayloadType != -1) { voIpSession = true; if(details.m_channel == 2) { decoder2 = decoders2.at(details.m_rtpPayloadType); decoder = decoder2; } else { decoder1 = decoders1.at(details.m_rtpPayloadType); decoder = decoder1; } bool ptAlreadySeen = seenRtpPayloadTypes.test(details.m_rtpPayloadType); seenRtpPayloadTypes.set(details.m_rtpPayloadType); if(decoder.get() == NULL) { if(ptAlreadySeen == false) { // First time we see a particular unsupported payload type in this session, log it CStdString rtpPayloadType = IntToString(details.m_rtpPayloadType); LOG4CXX_ERROR(LOG.batchProcessingLog, "[" + trackingId + "] Th" + threadIdString + " unsupported RTP payload type:" + rtpPayloadType); } // We cannot decode this chunk due to unknown codec, go to next chunk continue; } else if(ptAlreadySeen == false) { // First time we see a particular supported payload type in this session, log it CStdString rtpPayloadType = IntToString(details.m_rtpPayloadType); LOG4CXX_INFO(LOG.batchProcessingLog, "[" + trackingId + "] Th" + threadIdString + " RTP payload type:" + rtpPayloadType); } } if(!voIpSession || (firstChunk && decoder.get())) { firstChunk = false; // At this point, we know we have a working codec, create an RTP mixer and open the output file if(voIpSession) { CStdString filterName("RtpMixer"); filter = FilterRegistry::instance()->GetNewFilter(filterName); if(filter.get() == NULL) { debug = "Could not instanciate RTP mixer"; throw(debug); } filter->SetSessionInfo(trackingId); } CStdString path = CONFIG.m_audioOutputPath + "/" + audioTapeRef->GetPath(); FileRecursiveMkdir(path, CONFIG.m_audioFilePermissions, CONFIG.m_audioFileOwner, CONFIG.m_audioFileGroup, CONFIG.m_audioOutputPath); CStdString file = path + "/" + audioTapeRef->GetIdentifier(); outFileRef->Open(file, AudioFile::WRITE, false, fileRef->GetSampleRate()); } if(voIpSession) { if(details.m_channel == 2) { decoder2->AudioChunkIn(chunkRef); decoder2->AudioChunkOut(tmpChunkRef); if(tmpChunkRef.get()) { numSamplesS2 += tmpChunkRef->GetNumSamples(); } } else { decoder1->AudioChunkIn(chunkRef); decoder1->AudioChunkOut(tmpChunkRef); if(tmpChunkRef.get()) { numSamplesS1 += tmpChunkRef->GetNumSamples(); } } audiogain->AudioChunkIn(tmpChunkRef); audiogain->AudioChunkOut(tmpChunkRef); filter->AudioChunkIn(tmpChunkRef); filter->AudioChunkOut(tmpChunkRef); } else { audiogain->AudioChunkIn(tmpChunkRef); audiogain->AudioChunkOut(tmpChunkRef); } outFileRef->WriteChunk(tmpChunkRef); if(tmpChunkRef.get()) { numSamplesOut += tmpChunkRef->GetNumSamples(); } if(CONFIG.m_batchProcessingEnhancePriority == false) { // Give up CPU between every audio buffer to make sure the actual recording always has priority //ACE_Time_Value yield; //yield.set(0,1); // 1 us //ACE_OS::sleep(yield); // Use this instead, even if it still seems this holds the whole process under Linux instead of this thread only. struct timespec ts; ts.tv_sec = 0; ts.tv_nsec = 1; ACE_OS::nanosleep (&ts, NULL); } if(CONFIG.m_transcodingSleepEveryNumFrames > 0 && CONFIG.m_transcodingSleepUs > 0) { if(frameSleepCounter >= (unsigned int)CONFIG.m_transcodingSleepEveryNumFrames) { frameSleepCounter = 0; struct timespec ts; ts.tv_sec = 0; ts.tv_nsec = CONFIG.m_transcodingSleepUs*1000; ACE_OS::nanosleep (&ts, NULL); } else { frameSleepCounter += 1; } } } if(voIpSession && !firstChunk) { // Flush the RTP mixer AudioChunkRef stopChunk(new AudioChunk()); stopChunk->GetDetails()->m_marker = MEDIA_CHUNK_EOS_MARKER; filter->AudioChunkIn(stopChunk); filter->AudioChunkOut(tmpChunkRef); while(tmpChunkRef.get()) { outFileRef->WriteChunk(tmpChunkRef); numSamplesOut += tmpChunkRef->GetNumSamples(); filter->AudioChunkOut(tmpChunkRef); } } fileRef->Close(); outFileRef->Close(); logMsg.Format("[%s] Th%s stop: num samples: s1:%u s2:%u out:%u", trackingId, threadIdString, numSamplesS1, numSamplesS2, numSamplesOut); LOG4CXX_INFO(LOG.batchProcessingLog, logMsg); CStdString audioFilePath = CONFIG.m_audioOutputPath + "/" + audioTapeRef->GetPath(); CStdString audioFileName; audioFileName = audioFilePath + "/" + audioTapeRef->GetIdentifier() + outFileRef->GetExtension(); if(CONFIG.m_audioFilePermissions) { if(FileSetPermissions(audioFileName, CONFIG.m_audioFilePermissions)) { CStdString logMsg; logMsg.Format("Error setting permissions of %s to %o: %s", audioFileName.c_str(), CONFIG.m_audioFilePermissions, strerror(errno)); LOG4CXX_ERROR(LOG.batchProcessingLog, "[" + trackingId + "] Th" + threadIdString + " " + logMsg); } } if(CONFIG.m_audioFileGroup.size() && CONFIG.m_audioFileOwner.size()) { if(FileSetOwnership(audioFileName, CONFIG.m_audioFileOwner, CONFIG.m_audioFileGroup)) { logMsg.Format("Error setting ownership and group of %s to %s:%s: %s", audioFileName.c_str(), CONFIG.m_audioFileOwner, CONFIG.m_audioFileGroup, strerror(errno)); LOG4CXX_ERROR(LOG.batchProcessingLog, "[" + trackingId + "] Th" + threadIdString + " " + logMsg); } } if(CONFIG.m_deleteNativeFile && numSamplesOut) { fileRef->Delete(); LOG4CXX_INFO(LOG.batchProcessingLog, "[" + trackingId + "] Th" + threadIdString + " deleting native: " + audioTapeRef->GetIdentifier()); } else if(CONFIG.m_deleteFailedCaptureFile) { fileRef->Delete(); LOG4CXX_INFO(LOG.batchProcessingLog, "[" + trackingId + "] Th" + threadIdString + " deleting native that could not be transcoded: " + audioTapeRef->GetIdentifier()); } // Finished processing the tape, pass on to next processor if(numSamplesOut) { pBatchProcessing->RunNextProcessor(audioTapeRef); } } } catch (CStdString& e) { LOG4CXX_ERROR(LOG.batchProcessingLog, "[" + trackingId + "] Th" + threadIdString + " " + e); if(fileRef.get()) {fileRef->Close();} if(outFileRef.get()) {outFileRef->Close();} if(CONFIG.m_deleteFailedCaptureFile && fileRef.get() != NULL) { LOG4CXX_INFO(LOG.batchProcessingLog, "[" + trackingId + "] Th" + threadIdString + " deleting native and transcoded"); if(fileRef.get()) {fileRef->Delete();} if(outFileRef.get()) {outFileRef->Delete();} } } //catch(...) //{ // LOG4CXX_ERROR(LOG.batchProcessingLog, CStdString("unknown exception")); //} } LOG4CXX_INFO(LOG.batchProcessingLog, CStdString("Exiting thread Th" + threadIdString)); }
Component::Component(Swift::EventLoop *loop, Swift::NetworkFactories *factories, Config *config, Factory *factory, Transport::UserRegistry *userRegistry) { m_component = NULL; m_userRegistry = NULL; m_server = NULL; m_reconnectCount = 0; m_config = config; m_config->onBackendConfigUpdated.connect(boost::bind(&Component::handleBackendConfigChanged, this)); m_factory = factory; m_loop = loop; m_userRegistry = userRegistry; m_rawXML = false; m_jid = Swift::JID(CONFIG_STRING(m_config, "service.jid")); m_factories = factories; m_reconnectTimer = m_factories->getTimerFactory()->createTimer(3000); m_reconnectTimer->onTick.connect(bind(&Component::start, this)); if (CONFIG_BOOL(m_config, "service.server_mode")) { LOG4CXX_INFO(logger, "Creating component in server mode on port " << CONFIG_INT(m_config, "service.port")); m_server = new Swift::Server(loop, m_factories, m_userRegistry, m_jid, CONFIG_STRING(m_config, "service.server"), CONFIG_INT(m_config, "service.port")); if (!CONFIG_STRING(m_config, "service.cert").empty()) { #ifndef _WIN32 //TODO: fix LOG4CXX_INFO(logger, "Using PKCS#12 certificate " << CONFIG_STRING(m_config, "service.cert")); LOG4CXX_INFO(logger, "SSLv23_server_method used."); TLSServerContextFactory *f = new OpenSSLServerContextFactory(); CertificateWithKey::ref certificate = boost::make_shared<PKCS12Certificate>(CONFIG_STRING(m_config, "service.cert"), createSafeByteArray(CONFIG_STRING(m_config, "service.cert_password"))); m_server->addTLSEncryption(f, certificate); #endif } else { LOG4CXX_WARN(logger, "No PKCS#12 certificate used. TLS is disabled."); } // m_server->start(); m_stanzaChannel = m_server->getStanzaChannel(); m_iqRouter = m_server->getIQRouter(); m_server->addPayloadParserFactory(new GenericPayloadParserFactory<StorageParser>("private", "jabber:iq:private")); m_server->addPayloadParserFactory(new GenericPayloadParserFactory<Swift::AttentionParser>("attention", "urn:xmpp:attention:0")); m_server->addPayloadParserFactory(new GenericPayloadParserFactory<Swift::XHTMLIMParser>("html", "http://jabber.org/protocol/xhtml-im")); m_server->addPayloadParserFactory(new GenericPayloadParserFactory<Transport::BlockParser>("block", "urn:xmpp:block:0")); m_server->addPayloadParserFactory(new GenericPayloadParserFactory<Swift::InvisibleParser>("invisible", "urn:xmpp:invisible:0")); m_server->addPayloadParserFactory(new GenericPayloadParserFactory<Swift::StatsParser>("query", "http://jabber.org/protocol/stats")); m_server->addPayloadParserFactory(new GenericPayloadParserFactory<Swift::GatewayPayloadParser>("query", "jabber:iq:gateway")); m_server->addPayloadParserFactory(new GenericPayloadParserFactory<Swift::MUCPayloadParser>("x", "http://jabber.org/protocol/muc")); m_server->addPayloadSerializer(new Swift::AttentionSerializer()); m_server->addPayloadSerializer(new Swift::XHTMLIMSerializer()); m_server->addPayloadSerializer(new Transport::BlockSerializer()); m_server->addPayloadSerializer(new Swift::InvisibleSerializer()); m_server->addPayloadSerializer(new Swift::StatsSerializer()); m_server->addPayloadSerializer(new Swift::SpectrumErrorSerializer()); m_server->addPayloadSerializer(new Swift::GatewayPayloadSerializer()); m_server->onDataRead.connect(boost::bind(&Component::handleDataRead, this, _1)); m_server->onDataWritten.connect(boost::bind(&Component::handleDataWritten, this, _1)); } else { LOG4CXX_INFO(logger, "Creating component in gateway mode"); m_component = new Swift::Component(loop, m_factories, m_jid, CONFIG_STRING(m_config, "service.password")); m_component->setSoftwareVersion("Spectrum", SPECTRUM_VERSION); m_component->onConnected.connect(bind(&Component::handleConnected, this)); m_component->onError.connect(boost::bind(&Component::handleConnectionError, this, _1)); m_component->onDataRead.connect(boost::bind(&Component::handleDataRead, this, _1)); m_component->onDataWritten.connect(boost::bind(&Component::handleDataWritten, this, _1)); m_component->addPayloadParserFactory(new GenericPayloadParserFactory<StorageParser>("private", "jabber:iq:private")); m_component->addPayloadParserFactory(new GenericPayloadParserFactory<Swift::AttentionParser>("attention", "urn:xmpp:attention:0")); m_component->addPayloadParserFactory(new GenericPayloadParserFactory<Swift::XHTMLIMParser>("html", "http://jabber.org/protocol/xhtml-im")); m_component->addPayloadParserFactory(new GenericPayloadParserFactory<Transport::BlockParser>("block", "urn:xmpp:block:0")); m_component->addPayloadParserFactory(new GenericPayloadParserFactory<Swift::InvisibleParser>("invisible", "urn:xmpp:invisible:0")); m_component->addPayloadParserFactory(new GenericPayloadParserFactory<Swift::StatsParser>("query", "http://jabber.org/protocol/stats")); m_component->addPayloadParserFactory(new GenericPayloadParserFactory<Swift::GatewayPayloadParser>("query", "jabber:iq:gateway")); m_component->addPayloadParserFactory(new GenericPayloadParserFactory<Swift::MUCPayloadParser>("x", "http://jabber.org/protocol/muc")); m_component->addPayloadSerializer(new Swift::AttentionSerializer()); m_component->addPayloadSerializer(new Swift::XHTMLIMSerializer()); m_component->addPayloadSerializer(new Transport::BlockSerializer()); m_component->addPayloadSerializer(new Swift::InvisibleSerializer()); m_component->addPayloadSerializer(new Swift::StatsSerializer()); m_component->addPayloadSerializer(new Swift::SpectrumErrorSerializer()); m_component->addPayloadSerializer(new Swift::GatewayPayloadSerializer()); m_stanzaChannel = m_component->getStanzaChannel(); m_iqRouter = m_component->getIQRouter(); } m_capsMemoryStorage = new CapsMemoryStorage(); m_capsManager = new CapsManager(m_capsMemoryStorage, m_stanzaChannel, m_iqRouter); m_entityCapsManager = new EntityCapsManager(m_capsManager, m_stanzaChannel); m_entityCapsManager->onCapsChanged.connect(boost::bind(&Component::handleCapsChanged, this, _1)); m_presenceOracle = new Transport::PresenceOracle(m_stanzaChannel); m_presenceOracle->onPresenceChange.connect(bind(&Component::handlePresence, this, _1)); // // m_registerHandler = new SpectrumRegisterHandler(m_component); // m_registerHandler->start(); }
void NetHandler::start() { m_bRunning = true; fd_set readset; FD_ZERO(&master); int listenFd = initSockets(); if (listenFd < 0) { LOG4CXX_FATAL(logger_, "socket create failed!"); exit(1); } if (listenFd > fdmax) { fdmax = listenFd; } LOG4CXX_INFO(logger_, "NetHandler started."); struct timeval timeout; for (; ; ) { if (!m_bRunning) { break; } readset = master; timeout.tv_sec = 1; timeout.tv_usec = 0; int count = select(fdmax + 1, &readset, NULL, NULL, &timeout); if (count < 0) { LOG4CXX_FATAL(logger_, "Select error!"); exit(1); } time_t now = Clock::getCurrentSystemTime(); if (!preNetEvent(now)) { LOG4CXX_ERROR(logger_, "PreNetEvent returned false, terminating..."); break; } if (count > 0) { for (int i = 0; i <= fdmax; i++) { if (FD_ISSET(i, &readset)) { if (isListenSocket(i)) { struct sockaddr_in sa; socklen_t slen = sizeof (sa); int nfd = accept(i, (struct sockaddr*) &sa, &slen); if (nfd < 0) { LOG4CXX_ERROR(logger_, "Accept error!"); } else { FD_SET(nfd, &master); if (nfd > fdmax) { fdmax = nfd; } size_t rsize = readCacheSize(i); NetCache *cache = addConnection(nfd, sa, rsize); createProtocolHandler(cache, i); } } else { NetCache *cache = getCacheFromFd(i); if (cache != NULL) { int64 uid = cache->uid; bool readSucc = cache->read(); if (readSucc) { string req; while (cache->assemble(req) && !cache->remove) { //LOG4CXX_DEBUG(logger_, "Command Received \"" << req.substr(0, 2) << "\" from uid:" << uid << " fd:" << i); if (cache->ph != NULL) { cache->ph->handle(uid, req); } else { LOG4CXX_ERROR(logger_, "Protocol handler is NULL for fd:" << i); } } } if (!readSucc || (cache->remove && !cache->waitToWrite())) { if (uid >= 0 && cache->ph != NULL) { cache->ph->leave(uid); } doCloseConnection(i); LOG4CXX_DEBUG(logger_, "Client disconnected with fd:" << i); if (isConnectSocket(i)) { int newFd = connectFailed(i); fdmax = max(fdmax, newFd); } } } else { LOG4CXX_ERROR(logger_, "Cannot find cache for fd:" << i); } } } } } } }
void AdminInterface::handleMessageReceived(Swift::Message::ref message) { if (!message->getTo().getNode().empty()) return; if (message->getFrom().toBare().toString() != CONFIG_STRING(m_component->getConfig(), "service.admin_jid")) { LOG4CXX_WARN(logger, "Message not from admin user, but from " << message->getFrom().toBare().toString()); return; } // Ignore empty messages if (message->getBody().empty()) { return; } LOG4CXX_INFO(logger, "Message from admin received"); message->setTo(message->getFrom()); message->setFrom(m_component->getJID()); if (message->getBody() == "status") { int users = m_userManager->getUserCount(); int backends = m_server->getBackendCount(); message->setBody("Running (" + boost::lexical_cast<std::string>(users) + " users connected using " + boost::lexical_cast<std::string>(backends) + " backends)"); } else if (message->getBody() == "online_users") { std::string lst; const std::map<std::string, User *> &users = m_userManager->getUsers(); if (users.size() == 0) lst = "0"; for (std::map<std::string, User *>::const_iterator it = users.begin(); it != users.end(); it ++) { lst += (*it).first + "\n"; } message->setBody(lst); } else if (message->getBody() == "online_users_count") { int users = m_userManager->getUserCount(); message->setBody(boost::lexical_cast<std::string>(users)); } else if (message->getBody() == "reload") { bool done = m_component->getConfig()->reload(); if (done) { message->setBody("Config reloaded"); } else { message->setBody("Error during config reload"); } } else if (message->getBody() == "online_users_per_backend") { std::string lst; int id = 1; const std::list <NetworkPluginServer::Backend *> &backends = m_server->getBackends(); for (std::list <NetworkPluginServer::Backend *>::const_iterator b = backends.begin(); b != backends.end(); b++) { NetworkPluginServer::Backend *backend = *b; lst += "Backend " + boost::lexical_cast<std::string>(id) + " (ID=" + backend->id + ")"; lst += backend->acceptUsers ? "" : " - not-accepting"; lst += backend->longRun ? " - long-running" : ""; lst += ":\n"; if (backend->users.size() == 0) { lst += " waiting for users\n"; } else { time_t now = time(NULL); for (std::list<User *>::const_iterator u = backend->users.begin(); u != backend->users.end(); u++) { User *user = *u; lst += " " + user->getJID().toBare().toString(); lst += " - non-active for " + boost::lexical_cast<std::string>(now - user->getLastActivity()) + " seconds"; lst += "\n"; } } id++; } message->setBody(lst); } else if (message->getBody().find("has_online_user") == 0) { User *user = m_userManager->getUser(getArg(message->getBody())); std::cout << getArg(message->getBody()) << "\n"; message->setBody(boost::lexical_cast<std::string>(user != NULL)); } else if (message->getBody() == "backends_count") { int backends = m_server->getBackendCount(); message->setBody(boost::lexical_cast<std::string>(backends)); } else if (message->getBody() == "res_memory") { double shared = 0; double rss = 0; #ifndef WIN32 process_mem_usage(shared, rss); #endif const std::list <NetworkPluginServer::Backend *> &backends = m_server->getBackends(); BOOST_FOREACH(NetworkPluginServer::Backend * backend, backends) { rss += backend->res; } message->setBody(boost::lexical_cast<std::string>(rss)); }
void NetHandler::start() { m_bRunning = true; // first let's increase the limit of open files int maxconn = 100000; struct rlimit srl; srl.rlim_cur = maxconn + 10; srl.rlim_max = maxconn + 10; if (setrlimit(RLIMIT_NOFILE, &srl) < 0) { LOG4CXX_FATAL(logger_, "Cannot set RLimit!"); exit(1); } epfd = epoll_create(maxconn); if (epfd < 0) { LOG4CXX_FATAL(logger_, "epoll_create error!"); exit(1); } // Now let's ignore broken pipes struct sigaction sa; memset(&sa, 0, sizeof (sa)); sa.sa_handler = SIG_IGN; if (sigaction(SIGPIPE, &sa, NULL) < 0) { LOG4CXX_WARN(logger_, "Error ignoring SIGPIPE!"); } if (initSockets() < 0) { exit(1); } struct epoll_event ev, evs[MAX_EVENTS]; LOG4CXX_INFO(logger_, "Nethandler started."); for (; ; ) { if (!m_bRunning) { break; } int count = epoll_wait(epfd, evs, MAX_EVENTS, 1000); if (count < 0) { LOG4CXX_FATAL(logger_, "epoll_wait error!"); } time_t now = Clock::getCurrentSystemTime(); if (!preNetEvent(now)) { LOG4CXX_ERROR(logger_, "PreNetEvent returned false, terminating..."); break; } for (int i = 0; i < count; i++) { int fd = evs[i].data.fd; if (isListenSocket(fd)) { struct sockaddr_in sa; socklen_t slen = sizeof (sa); int nfd = 0; nfd = accept(fd, (struct sockaddr*) &sa, &slen); if (nfd > 0) { ev.events = EPOLLIN | EPOLLHUP; //| EPOLLRDHUP; ev.data.fd = nfd; if (epoll_ctl(epfd, EPOLL_CTL_ADD, nfd, &ev) < 0) { LOG4CXX_ERROR(logger_, "epoll_ctl error, cannot add client!"); } else { size_t rsize = readCacheSize(fd); //size_t rsize = (fd==wsfd ? NetCache::WEBSERVER_READ_SIZE : NetCache::DEFAULT_READ_SIZE); NetCache *cache = addConnection(nfd, sa, rsize); createProtocolHandler(cache, fd); } } } else // data { NetCache *cache = getCacheFromFd(fd); if (cache != NULL) { __uint32_t events = evs[i].events; bool readError = false; if ((events & EPOLLIN) > 0) { int64 uid = cache->uid; readError = !cache->read(); if (!readError) { string req; while (cache->assemble(req) && !cache->remove) { //LOG4CXX_DEBUG(logger_, "Command Received: \"" << req.c_str() << "\" from uid:" << uid << " fd:" << fd); if (cache->ph != NULL) { cache->ph->handle(uid, req); } else { LOG4CXX_ERROR(logger_, "Protocol handler is NULL for fd:" << fd); } } } } if ((events & EPOLLOUT) > 0) { if ( isConnecting( fd )) { connectSuccess( fd ); } else if (cache->write()) { ev.events = EPOLLIN | EPOLLHUP; // | EPOLLRDHUP; ev.data.fd = fd; epoll_ctl(epfd, EPOLL_CTL_MOD, fd, &ev); } } if ((cache->remove && !cache->waitToWrite()) || readError || (events & EPOLLHUP) > 0 || //(events&EPOLLRDHUP)>0 || (events & EPOLLERR) > 0) { int64 uid = cache->uid; if (uid >= 0 && cache->ph != NULL) { cache->ph->leave(uid); } LOG4CXX_DEBUG(logger_, "Client disconnected of fd:" << fd << ", remove: " << cache->remove << ", read error: " << readError << ", hup: " << (events & EPOLLHUP) //<< //", rdhup: " << (events & EPOLLRDHUP) << ", epoll error: " << (events & EPOLLERR)); doCloseConnection(fd); if (isConnectSocket(fd)) { connectFailed(fd); } } } else { LOG4CXX_ERROR(logger_, "Cannot find cache for fd:" << fd); } } } } }
void DirectionSelector::ThreadHandler(void *args) { SetThreadName("orka:ds"); CStdString debug; CStdString logMsg; CStdString processorName("DirectionSelector"); TapeProcessorRef directionSelector = TapeProcessorRegistry::instance()->GetNewTapeProcessor(processorName); if(directionSelector.get() == NULL) { LOG4CXX_ERROR(LOG.directionSelectorLog, "Could not instanciate DirectionSelector"); return; } DirectionSelector* pDirectionSelector = (DirectionSelector*)(directionSelector->Instanciate().get()); pDirectionSelector->SetQueueSize(CONFIG.m_directionSelectorQueueSize); int threadId = 0; { MutexSentinel sentinel(pDirectionSelector->m_mutex); threadId = pDirectionSelector->m_threadCount++; } CStdString threadIdString = IntToString(threadId); debug.Format("thread Th%s starting - queue size:%d", threadIdString, CONFIG.m_directionSelectorQueueSize); LOG4CXX_INFO(LOG.directionSelectorLog, debug); pDirectionSelector->LoadAreaCodesMap(); bool stop = false; for(;stop == false;) { AudioFileRef fileRef; oreka::shared_ptr<MediaChunkFile> outFile (new MediaChunkFile()); AudioTapeRef audioTapeRef; CStdString trackingId = "[no-trk]"; int numSamplesOutv = 0; AudioChunkRef chunkRef; try { audioTapeRef = pDirectionSelector->m_audioTapeQueue.pop(); if(audioTapeRef.get() == NULL) { if(Daemon::Singleton()->IsStopping()) { stop = true; } if(Daemon::Singleton()->GetShortLived()) { Daemon::Singleton()->Stop(); } } else { //Iterating through area codes map to check which side will be retain bool found = false; int foundPos = -1; CStdString side; std::map<CStdString, CStdString>::iterator it; for(it = pDirectionSelector->m_areaCodesMap.begin(); it!= pDirectionSelector->m_areaCodesMap.end() && found == false; it++) { //For now, we dont consider local party which has nothing to do with area codes // foundPos = audioTapeRef->m_localParty.find(it->first); // if(foundPos == 0) // { // side = it->second; // found = true; // break; // } foundPos = audioTapeRef->m_remoteParty.find(it->first); if(foundPos == 0) { side = it->second; found = true; break; } } if(found == true) { AudioDirectionMarksRef defaultKeptSide(new AudioDirectionMarks()); defaultKeptSide->m_timestamp = 1; //make sure it the first event in the chain of event in term of timestamp if(audioTapeRef->m_audioDirectionMarks.size() > 0) { std::vector<AudioDirectionMarksRef>::iterator it; it = audioTapeRef->m_audioDirectionMarks.begin(); defaultKeptSide->m_nextTimestampMark = (*it)->m_timestamp; //next mark, will be the first api called, if any } defaultKeptSide->m_audioKeepDirectionEnum = (CaptureEvent::AudioKeepDirectionEnum)CaptureEvent::AudioKeepDirectionToEnum(side); audioTapeRef->m_audioDirectionMarks.insert(audioTapeRef->m_audioDirectionMarks.begin(),defaultKeptSide); } CStdString mcfExt, tmpExt, tmpFileName, origFileName, origFileNameWoExt; mcfExt = ".mcf"; tmpExt = ".tmp"; audioTapeRef->SetExtension(mcfExt); //the real extension at this point origFileName = audioTapeRef->m_audioOutputPath + "/"+ audioTapeRef->GetFilename(); origFileNameWoExt = audioTapeRef->m_audioOutputPath + "/" + audioTapeRef->GetPath() + audioTapeRef->GetIdentifier(); //copy a temporary file for processing audioTapeRef->SetExtension(tmpExt); tmpFileName = audioTapeRef->m_audioOutputPath + "/"+ audioTapeRef->GetFilename(); if(ACE_OS::rename((PCSTR)origFileName, (PCSTR)tmpFileName) != 0){ LOG4CXX_ERROR(LOG.directionSelectorLog, "Can not rename audio file for processing"); } fileRef = audioTapeRef->GetAudioFileRef(); trackingId = audioTapeRef->m_trackingId; fileRef->SetFilename(tmpFileName); //audioTapeRef->SetExtension(fullfilename) does not take affect on audiofileRef, fileRef->Open(AudioFile::READ); outFile->Open(origFileNameWoExt, AudioFile::WRITE); while(fileRef->ReadChunkMono(chunkRef)) { AudioChunkDetails details = *chunkRef->GetDetails(); std::vector<AudioDirectionMarksRef>::iterator it; for(it = audioTapeRef->m_audioDirectionMarks.begin(); it != audioTapeRef->m_audioDirectionMarks.end(); it++) { if(((*it)->m_timestamp == 0)) { continue; } if((details.m_arrivalTimestamp >= (*it)->m_timestamp) && ((details.m_arrivalTimestamp < (*it)->m_nextTimestampMark) || ((*it)->m_nextTimestampMark == 0))) //this audio chunk is in between 2 kept-direction reports marks { if(audioTapeRef->m_localSide == CaptureEvent::LocalSideSide1) { if(((*it)->m_audioKeepDirectionEnum == CaptureEvent::AudioKeepDirectionLocal) && (details.m_channel == 2)) { memset(chunkRef->m_pBuffer, 0, details.m_numBytes); //blank side 2 } else if(((*it)->m_audioKeepDirectionEnum == CaptureEvent::AudioKeepDirectionRemote) && (details.m_channel == 1)) { memset(chunkRef->m_pBuffer, 0, details.m_numBytes); //blank side 1 } } else if(audioTapeRef->m_localSide == CaptureEvent::LocalSideSide2) { if(((*it)->m_audioKeepDirectionEnum == CaptureEvent::AudioKeepDirectionLocal) && (details.m_channel == 1)) { memset(chunkRef->m_pBuffer, 0, details.m_numBytes); } else if(((*it)->m_audioKeepDirectionEnum == CaptureEvent::AudioKeepDirectionRemote) && (details.m_channel == 2)) { memset(chunkRef->m_pBuffer, 0, details.m_numBytes); } } } } outFile->WriteChunk(chunkRef); } outFile->Close(); ACE_OS::unlink((PCSTR)tmpFileName); fileRef->Close(); audioTapeRef->SetExtension(mcfExt); //return back to mcf ext fileRef->SetFilename(origFileName); // weird here, but it needs to be done, otherwise audioTapeRef will associate with tmp File pDirectionSelector->RunNextProcessor(audioTapeRef); } } catch (CStdString& e) { LOG4CXX_ERROR(LOG.directionSelectorLog, "[" + trackingId + "] Th" + threadIdString + " " + e); if(fileRef.get()) {fileRef->Close();} } } LOG4CXX_INFO(LOG.directionSelectorLog, CStdString("Exiting thread Th" + threadIdString)); }
void MyIrcSession::on_numericMessageReceived(IrcMessage *message) { QString channel; QStringList members; std::string nick; IrcNumericMessage *m = (IrcNumericMessage *) message; QStringList parameters = m->parameters(); switch (m->code()) { case 301: break; case 315: LOG4CXX_INFO(logger, "End of /who request " << TO_UTF8(parameters[1])); break; case 332: m_topicData = TO_UTF8(parameters[2]); break; case 333: nick = TO_UTF8(parameters[2]); if (nick.find("!") != std::string::npos) { nick = nick.substr(0, nick.find("!")); } if (nick.find("/") != std::string::npos) { nick = nick.substr(0, nick.find("/")); } np->handleSubject(user, TO_UTF8(parameters[1]) + suffix, m_topicData, nick); break; case 352: { channel = parameters[1]; nick = TO_UTF8(parameters[5]); IRCBuddy &buddy = getIRCBuddy(TO_UTF8(channel), nick); if (parameters[6].toUpper().startsWith("G")) { if (!buddy.isAway()) { buddy.setAway(true); np->handleParticipantChanged(user, nick, TO_UTF8(channel) + suffix, buddy.isOp(), pbnetwork::STATUS_AWAY); } } else if (buddy.isAway()) { buddy.setAway(false); np->handleParticipantChanged(user, nick, TO_UTF8(channel) + suffix, buddy.isOp(), pbnetwork::STATUS_ONLINE); } break; } case 353: channel = parameters[2]; members = parameters[3].split(" "); LOG4CXX_INFO(logger, user << ": Received members for " << TO_UTF8(channel) << suffix); for (int i = 0; i < members.size(); i++) { bool op = 0; std::string nickname = TO_UTF8(members.at(i)); op = correctNickname(nickname); IRCBuddy &buddy = getIRCBuddy(TO_UTF8(channel), nickname); buddy.setOp(op); np->handleParticipantChanged(user, nickname, TO_UTF8(channel) + suffix, buddy.isOp(), pbnetwork::STATUS_ONLINE); } break; case 366: // ask /who to get away states channel = parameters[1]; LOG4CXX_INFO(logger, user << "Asking /who for channel " << TO_UTF8(channel)); sendCommand(IrcCommand::createWho(channel)); break; case 432: np->handleDisconnected(user, pbnetwork::CONNECTION_ERROR_INVALID_USERNAME, "Erroneous Nickname"); break; case 321: m_rooms.clear(); m_names.clear(); break; case 322: m_rooms.push_back(TO_UTF8(parameters[1])); m_names.push_back(TO_UTF8(parameters[1])); break; case 323: np->handleRoomList("", m_rooms, m_names); break; default: break; } //qDebug() << "numeric message received:" << receiver() << origin << code << params; }
void DealPlatEvent::HandleUserLogin(Event* e) { if (!e->has_userlogin_req()) { return; } PlatDataHandler* pDH = eh_->getDataHandler(); const UserLogin_Req& req = e->userlogin_req(); const string& platid = req.platform_id(); if(platid.size()<=0) return; int siteid = req.siteid(); const string& name = req.name(); const string& profile_link = req.profile_link(); int gender = (req.gender() == 0) ? Gender_Girl : Gender_Boy ; vector<string> friends_platid; for (int i = 0; i < req.friends_platid_size(); i ++) { friends_platid.push_back(req.friends_platid(i)); } bool isYellowDmd = req.is_yellow_dmd(); bool isYellowDmdYear = req.is_yellow_dmd_year(); bool isHighYellowDmd = req.is_high_yellow_dmd(); int lvlYellowDmd = req.yellow_dmd_lv(); string strTaskMarketId = req.taskmarketid(); //string strChannel = req.channel(); WebCrossPromotion* pPromotion = e->mutable_userlogin_req()->mutable_promotion(); int region = req.region(); int nNewUserRegion = (int)req.defregion(); LOG4CXX_INFO(logger_, "Game request UserLogin with openid: " << platid); LoadStatus state = LOAD_INVALID; int level = 0; int nRtnRegion=0; int64 uid=0; bool bIsNewPlayer = false; bool isHighDmdYear = req.is_high_dmd_year(); DB_Plat* pDBPlat = processUserLogin(platid, siteid, name, profile_link, gender, friends_platid, isYellowDmd, isYellowDmdYear, lvlYellowDmd, state,region,nNewUserRegion,level,nRtnRegion,uid,bIsNewPlayer,isHighYellowDmd,strTaskMarketId,pPromotion,isHighDmdYear); if (pDBPlat != NULL) { //UserLogin_Rsp* rsp = e->mutable_userlogin_rsp(); //rsp->set_server(eh_->getServerIp()); //rsp->set_port(eh_->getServerPort()); //rsp->set_port1(eh_->getServerPort1()); //rsp->set_uid(user->GetUid()); //rsp->set_secret(user->secret(eh_->getReversion())); //rsp->set_webfd(webfd); //rsp->set_sid(sid); //rsp->set_region(region); //rsp->set_mainload("0");//此项已失效 //rsp->set_version(FlashVersionCfg::Instance().GetCfgVersion(eh_->GetSrvID())); //e->clear_userlogin_req(); e->set_state(UserLogin_PG_Rsp); //空间十年,所有的服只能领一次 if (req.nbackflowflag()==4) { if (pDBPlat->qqtenyearbackflowflag() > 1) { e->mutable_userlogin_req()->set_nbackflowflag(0); } /* else { pDBPlat->set_qqtenyearbackflowflag(1); }*/ //还是领过再置标志 } if(uid>0) { e->mutable_userlogin_req()->set_uid(uid); e->mutable_userlogin_req()->set_level(level); e->mutable_userlogin_req()->set_region(nRtnRegion); e->mutable_userlogin_req()->set_undealgiftcnt(pDH->GetUnDealGiftCnt(pDBPlat)); e->mutable_userlogin_req()->set_undealfrdgiftcnt(pDH->GetUnDealFrdGiftCnt(pDBPlat)); e->mutable_userlogin_req()->set_yellowdmdtime(pDBPlat->yellowdmdtime()); e->mutable_userlogin_req()->set_invitefrdcnt(pDBPlat->invitefrdcnt()); e->mutable_userlogin_req()->set_invitefriendid(pDBPlat->invitefriends().invitefriendid()); e->mutable_userlogin_req()->set_isnewplayer( bIsNewPlayer ); e->mutable_userlogin_req()->set_bluedmdtime(pDBPlat->bluedmdtime()); DB_PlatGift* pDBGiftInfo = pDBPlat->mutable_giftinfo(); e->mutable_userlogin_req()->set_daysendgiftcnt(pDBGiftInfo->daysendgiftcnt()); e->mutable_userlogin_req()->set_invitefrdcntday(pDBPlat->invitefrdcntday()); e->mutable_userlogin_req()->set_qqtaskstep(pDBPlat->mutable_taskmark()->step()); e->mutable_userlogin_req()->set_nadultflag(100); //每次登陆都设置为可登陆 如果没有验证的话会有其他消息将玩家再次踢下线 pPromotion->set_chanle( pDBPlat->channel() ); // RceInviteFriend* pinviteMsg = e->mutable_ce_rceinvitefriend(); // pinviteMsg->set_friendcount(pDBPlat->invitefrdcntday()); // pinviteMsg->set_giftgain(pDBPlat->gaininvitefrdday()); for ( int i = 0; i < pDBPlat->invitegiftrecord_size(); i++ ) { e->mutable_userlogin_req()->add_invitegiftrecord( pDBPlat->invitegiftrecord(i) ); } int gid = pDH->getGamedIdByUserId(uid); eh_->sendEventToGamed(e,gid); //SendInviteFriendMsg(pDBPlat,uid); e->set_state(Status_Plat_To_Game); e->set_cmd(EVENT_COSTGIFT_INVITE_FRD); e->set_userplat( platid ); e->set_uid( uid ); // CostGiftMsg* msg = e->mutable_costgiftmsg(); // for( int i = 0; i < pDBPlat->daygetcostgift_size(); i++ ) // { // msg->add_gotgifts( pDBPlat->daygetcostgift(i) ); // } // msg->set_invitedcnt( pDBPlat->invitefrdcntdaybylimit() ); eh_->sendEventToGamed(e,gid); if ( pDBPlat->has_callbackfrduid() ) { e->set_state(Status_Plat_To_Game); e->set_cmd(EVENT_CALLBACKFRRD_GIFT); e->set_userplat( platid ); e->set_uid( pDBPlat->callbackfrduid() ); eh_->sendEventToGamed(e,pDH->getGamedIdByUserId(pDBPlat->callbackfrduid())); SYS_LOG(uid, LT_CallBackFriendBack, 0 , 0, platid.c_str()); pDBPlat->clear_callbackfrduid(); } } } else { if (state == LOAD_WAITING) { eh_->postBackEvent(e); } } }
void msgProcessThread(void* para) { LoggerPtr rootLogger = Logger::getRootLogger(); ZxClient *pClient = 0; pClient = (ZxClient*)para; if(!pClient){ LOG4CXX_ERROR(rootLogger, "msgProcessThread param is NULL!"); return; } string hostIP = pClient->getHostIP(); CyclicQueue *pRecvQueue = pClient->getRecvMsgQueue(); pClient->incThreadNum(); pthread_t tid = syscall(SYS_gettid); LOG4CXX_INFO(rootLogger, "("<<hostIP<<")msgProcessThread tid=" << tid<<", threadNum="<<++G::m_threadNum); int ret = 0; int rc = 0; UINT recvLen = 0; UCHAR recvBuf[4096]; UINT packID = 0; Message* pMessage = 0; Status4ZxClient status; DataControl& rDataControl = pRecvQueue->getDataControl(); rDataControl.activate(); while (!G::m_bSysStop && rDataControl.isActive()) { status = pClient->getStatus(); if(pRecvQueue->isEmpty()) { if(Close == status){ break; } pthread_mutex_lock(&rDataControl.getMutex()); pthread_cond_wait(&rDataControl.getCond(), &rDataControl.getMutex()); pthread_mutex_unlock(&rDataControl.getMutex()); continue; } memset(recvBuf,0,4096); if (rDataControl.isActive()) { rc = pRecvQueue->getNextData(recvBuf,recvLen,packID); if(1 == rc){ pMessage = Message::createInstance(recvBuf,recvLen,pClient); if(pMessage){ pMessage->setPackID(packID); ret = pMessage->parseMessageBody(); if(-2 == ret){ pClient->beforeDel(); } delete pMessage; pMessage = 0; } }else if(0 == rc){ //no package get LOG4CXX_DEBUG(rootLogger, "("<<hostIP<<")No package there. Buff size="<<pRecvQueue->getSize()<<", isEmpty="<<pRecvQueue->isEmpty()); sleep(1); }else if (-1==rc){ //package len is too big,reconnect //LOG4CXX_WARN(rootLogger, "Package len is too big, clear queque!"); pRecvQueue->clear(); }else{ //unknow result LOG4CXX_ERROR(rootLogger, "("<<hostIP<<")Unknow result, rc="+G::int2String(rc)); } } }//end of while (!m_bSysStop && pDataControl) pClient->decThreadNum(); LOG4CXX_INFO(rootLogger, "("<<hostIP<<")Exit msgProcessThread, threadNum="<<--G::m_threadNum); return; }