int OsDatagramSocket::write(const char* buffer, int bufferLength, const char* ipAddress, int port) { int bytesSent = 0; struct sockaddr_in toSockAddress; toSockAddress.sin_family = AF_INET; toSockAddress.sin_port = htons(port); if(ipAddress == NULL || !strcmp(ipAddress, "0.0.0.0") || strlen(ipAddress) == 0 || (toSockAddress.sin_addr.s_addr = inet_addr(ipAddress)) == OS_INVALID_INET_ADDRESS) { osPrintf("OsDatagramSocket::write invalid IP address: \"%s\"\n", ipAddress); } else { // Why isn't this abstracted into OsSocket, as is done in ::write(2)? bytesSent = sendto(socketDescriptor, #ifdef _VXWORKS (char*) #endif buffer, bufferLength, 0, (struct sockaddr*) &toSockAddress, sizeof(struct sockaddr_in)); if(bytesSent != bufferLength) { OsSysLog::add(FAC_SIP, PRI_ERR, "OsDatagramSocket::write(4) %d ipAddress = '%s', " "port = %d, bytesSent = %d, " "bufferLength = %d, errno = %d '%s'", socketDescriptor, ipAddress ? ipAddress : "[null]", port, bytesSent, bufferLength, errno, strerror(errno)); time_t rightNow; (void) time(&rightNow); mNumRecentWriteErrors++; if (MIN_REPORT_SECONDS <= (rightNow - mLastWriteErrorTime)) { mNumTotalWriteErrors += mNumRecentWriteErrors; if (0 == mNumTotalWriteErrors) { mLastWriteErrorTime = rightNow; } osPrintf("OsDataGramSocket::write:\n" " In last %ld seconds: %d errors; total %d errors;" " last errno=%d\n", (rightNow - mLastWriteErrorTime), mNumRecentWriteErrors, mNumTotalWriteErrors, OsSocketGetERRNO()); mLastWriteErrorTime = rightNow; mNumRecentWriteErrors = 0; } } } return(bytesSent); }
/** * * Method Name: ProcessReceiverReport * * * Inputs: unsigned char *puchRTCPReport - pointer to an RTCP Receiver Report * unsigned long ulReportCount - Optional Count of receiver reports * * Outputs: None * * Returns: unsigned long * * Description: Takes the RTCP Receiver Report passed and calls the * CReceiverReport object's IReceiverReport interface to parse the * Receiver packet and extract the receiver statistics contained * therein. Although no more than one receiver report is expected * under the current Pingtel call model, it is possible that * multiple receiver reports (one per PingTel source) may be sent. * In this case, a new CReceiverReport object shall be created and * queued if not already existing on the Receiver Report list. * * * Usage Notes: Notifications shall be generated to all subscribing parties to * inform them of the receipt of a new Receiver Report. The * notification shall contain the event type and a pointer to the * Receiver Report's IGetReceiverStatistics interface. * * */ unsigned long CRTCPSource::ProcessReceiverReport(unsigned char *puchRTCPReport, unsigned long ulReportCount) { bool bRTCPHeader = FALSE; unsigned long ulReceiverSSRC = 0; CReceiverReport *poReceiverReport = NULL; unsigned long ulBytesProcessed = 0; unsigned long ulReportSize = 0; // Determine the Receiver Report count if it hasn't already been provided // to us. if(ulReportCount == 0) { // Set a flag to identify the existence of an RTCP Header bRTCPHeader = TRUE; // Pull the Report Count from the header so we know how many reports // we need to process ulReportCount = GetReportCount(puchRTCPReport); if (0 == ulReportCount) { // $$$ bRTCPHeader is the culprit that makes this necessary... // It is passed to a couple of routines that should not care // whether the header is still present. The header is // processed in the call to ParseReceiverReport when the // header flag is set. That processing should be done here, // the length set to 8, then all the remaining reports should // be processed without regard to the header. But // BETTER IS THE ENEMY OF GOOD! // hzm 16Aug01 ulReportSize = GetReportLength(puchRTCPReport); osPrintf("ProcessReceiverReport: RR/RC=0, len=%lu\n", ulReportSize); } } // Let's prepare to iterate through each reception report until complete while(ulReportCount > 0) { // Extract the corresponding SSRC with the knowledge that this report // comes with a full formed RTCP header. ulReceiverSSRC = GetReceiverSSRC(bRTCPHeader, puchRTCPReport); // Has a Receiver Report object been instantiated for this participant? // Probably not, if this is the first Receiver Report received in a // session if((poReceiverReport = m_tReceiverReportList.GetEntry(RRSsrcComparitor, (void *)ulReceiverSSRC)) != NULL); // $$$ IS THE ABOVE LINE, ENDING WITH A SEMICOLON, CORRECT??? - hzm // Create The Receiver Report object else if((poReceiverReport = new CReceiverReport(ulReceiverSSRC)) == NULL) { osPrintf("**** FAILURE **** CRTCPSource::ProcessReceiverReport()" " - Unable to create Inbound Receiver Report Object\n"); return(ulReportSize); } // Initialize Receiver Report object else if(!poReceiverReport->Initialize()) { // Release the Receiver Report reference. // This should cause the object to be destroyed osPrintf("**** FAILURE **** CRTCPSource::ProcessReceiverReport()" " - Unable to Initialize Inbound Receiver Report Object\n"); ((IReceiverReport *)poReceiverReport)->Release(); return(ulReportSize); } // Place the new Receiver Report object on the collection list else if(!m_tReceiverReportList.AddEntry(poReceiverReport)) { // Release the Receiver Report reference. // This should cause the object to be destroyed osPrintf("**** FAILURE **** CRTCPSource::ProcessReceiverReport()" " - Unable to Add Inbound Receiver Report Object to Collection\n"); ((IReceiverReport *)poReceiverReport)->Release(); return(ulReportSize); } // A Receiver object exists to process this report. // Let's delegate to its parsing methods to complete this report's // processing. if((ulBytesProcessed = poReceiverReport->ParseReceiverReport(bRTCPHeader, puchRTCPReport)) == 0) { osPrintf("**** FAILURE **** CRTCPSource::ProcessReceiverReport()" " - Unable to Parse Inbound Receiver Report\n"); return(ulReportSize); } // We've made it through our first receiver report successfully and we // must adjust the flags, counts, and report pointers for the next // go-round. bRTCPHeader = FALSE; ulReportSize += ulBytesProcessed; puchRTCPReport += ulBytesProcessed; ulReportCount--; // Send Event SendRTCPEvent(RTCP_RR_RCVD, (void *)poReceiverReport); } return(ulReportSize); }
int main(int argc, char* argv[]) { int provisioningAgentPort = 8110; int watchdogRpcServerPort = 8092; ACDServer* pAcdServer; // Disable osPrintf's enableConsoleOutput(false); UtlString argString; for (int argIndex = 1; argIndex < argc; argIndex++) { osPrintf("arg[%d]: %s\n", argIndex, argv[argIndex]); argString = argv[argIndex]; NameValueTokenizer::frontBackTrim(&argString, "\t "); if (argString.compareTo("-v") == 0) { enableConsoleOutput(true); osPrintf("Version: %s (%s)\n", VERSION, PACKAGE_REVISION); return(1); } else if (argString.compareTo("-c") == 0) { // Enable osPrintf's enableConsoleOutput(true); } else if (argString.compareTo("-d") == 0) { // Switch ACDServer PRI_DEBUG to PRI_NOTICE gACD_DEBUG = PRI_NOTICE; } else if (argString.compareTo("-P") == 0) { argString = argv[++argIndex]; provisioningAgentPort = atoi(argString.data()); } else if (argString.compareTo("-W") == 0) { argString = argv[++argIndex]; watchdogRpcServerPort = atoi(argString.data()); } else { enableConsoleOutput(true); osPrintf("usage: %s [-v] [-c] [-d] [-P port] [-W wport]\nwhere:\n -v Provides the software version\n" " -c Enables console output of log and debug messages\n" " -d Changes ACDServer DEBUG logging to run at NOTICE level\n" " -P port Specifies the provisioning interface port number\n" " -W wport Specifies the Watchdog interface port number\n", argv[0]); return(1); } } // Create the ACDServer and get to work. pAcdServer = new ACDServer(provisioningAgentPort, watchdogRpcServerPort); // Loop forever until signaled to shut down while (!Os::UnixSignals::instance().isTerminateSignalReceived() && !gShutdownFlag) { OsTask::delay(2000); } // Shut down the ACDServer. delete pAcdServer; // Flush the log file Os::Logger::instance().flush(); // Say goodnight Gracie... // Use _exit to avoid the atexit() processing which will cause the // destruction of static objects...yet there are still threads out // there using those static objects. This prevents core dumps // due to those threads accessing the static objects post destruction. // // --Woof! _exit(0); /*NOTREACHED*/ return 0 ; // To appease the compiler gods }
OsStatus OsProcessWnt::setIORedirect(OsPath &rStdInputFilename, OsPath &rStdOutputFilename, OsPath &rStdErrorFilename) { OsStatus retval = OS_FAILED; UtlBoolean bOneFailed = FALSE; if (!rStdInputFilename.isNull()) { mStdInputHandle = CreateFile(rStdInputFilename.data(), GENERIC_READ, // access mode FILE_SHARE_READ, // share mode 0, // SD OPEN_EXISTING, // how to create FILE_ATTRIBUTE_NORMAL, // file attributes NULL); // handle to template file if (mStdInputHandle == INVALID_HANDLE_VALUE) { osPrintf("Could not open input file for Std Input for new process\n"); bOneFailed = TRUE; } else { mStdInputFilename = rStdInputFilename; } } if (!rStdErrorFilename.isNull()) { mStdErrorHandle = CreateFile(rStdErrorFilename.data(), GENERIC_WRITE, // access mode FILE_SHARE_READ, // share mode 0, // SD OPEN_ALWAYS, // how to create FILE_ATTRIBUTE_NORMAL, // file attributes NULL); // handle to template file if (mStdErrorHandle == INVALID_HANDLE_VALUE) { osPrintf("Could not open %s for Std Error on new process\n"); bOneFailed = TRUE; } else { mStdErrorFilename = rStdErrorFilename; } } if (!rStdOutputFilename.isNull()) { mStdOutputHandle = CreateFile(rStdOutputFilename.data(), GENERIC_WRITE, // access mode FILE_SHARE_READ, // share mode 0, // SD OPEN_ALWAYS, // how to create FILE_ATTRIBUTE_NORMAL, // file attributes NULL); // handle to template file if (mStdOutputHandle == INVALID_HANDLE_VALUE) { osPrintf("Could not open %s for Std Error on new process\n"); bOneFailed = TRUE; } else { mStdOutputFilename = rStdOutputFilename; } } if (!bOneFailed) retval = OS_SUCCESS; else { if (mStdErrorHandle != INVALID_HANDLE_VALUE) CloseHandle(mStdErrorHandle); if (mStdOutputHandle != INVALID_HANDLE_VALUE) CloseHandle(mStdOutputHandle); if (mStdInputHandle != INVALID_HANDLE_VALUE) CloseHandle(mStdInputHandle); } return retval; }
void CRTCPSource::ProcessPacket(unsigned char *puchDataBuffer, unsigned long ulBufferLength, int verbose) { unsigned char *SAVEpuchDataBuffer = puchDataBuffer; unsigned long SAVEulBufferLength = ulBufferLength; #ifdef DEBUG_RTCP_PACKETS /* [ */ if (0 < numPacketsToDump--) { verbose = 1; } if (verbose) { unsigned char *tp = puchDataBuffer; unsigned long tl = ulBufferLength; int i = 0; osPrintf("CRTCPSource::ProcessPacket(%8p, %lu)\n", puchDataBuffer, ulBufferLength); while(tl > 0) { osPrintf(" %02X", *tp++); if (0xf == (0xf & i++)) osPrintf("\n"); tl--; } if (0 != (0xf & i)) osPrintf("\n"); } #endif /* DEBUG_RTCP_PACKETS ] */ // This could be either a simple or composite report. Let's process the // buffer until there is nothing more to process. while(ulBufferLength > 0) { unsigned long ulBytesProcessed = 0; // Let's peek into the RTCP header to determine the payload type of an // RTCP report and route it to the appropriate handler. switch(GetPayloadType(puchDataBuffer)) { // Process Sender Report case etSenderReport: ulBytesProcessed = ProcessSenderReport(puchDataBuffer); #ifdef DEBUG_RTCP_PACKETS /* [ */ if (verbose) { osPrintf(" Sender Report (%lu bytes)\n", ulBytesProcessed); } #endif /* DEBUG_RTCP_PACKETS ] */ break; // Process Receiver Report case etReceiverReport: ulBytesProcessed = ProcessReceiverReport(puchDataBuffer); #ifdef DEBUG_RTCP_PACKETS /* [ */ if (verbose) { osPrintf(" Recvr Report (%lu bytes)\n", ulBytesProcessed); } #endif /* DEBUG_RTCP_PACKETS ] */ break; // Process Source Description Report case etSDESReport: ulBytesProcessed = ProcessSDESReport(puchDataBuffer); #ifdef DEBUG_RTCP_PACKETS /* [ */ if (verbose) { osPrintf(" SDES Report (%lu bytes)\n", ulBytesProcessed); } #endif /* DEBUG_RTCP_PACKETS ] */ break; // Process Bye Report case etByeReport: ulBytesProcessed = ProcessByeReport(puchDataBuffer); #ifdef DEBUG_RTCP_PACKETS /* [ */ if (verbose) { osPrintf(" Bye Report (%lu bytes)\n", ulBytesProcessed); } #endif /* DEBUG_RTCP_PACKETS ] */ break; // Process Application Report case etAppReport: ulBytesProcessed = ProcessAppReport(puchDataBuffer); #ifdef DEBUG_RTCP_PACKETS /* [ */ if (verbose) { osPrintf(" App Report (%lu bytes)\n", ulBytesProcessed); } #endif /* DEBUG_RTCP_PACKETS ] */ break; // Unrecognized Report default: { int count, i; osPrintf("** TROUBLE ** CRTCPSource::ProcessPacket()" " - Unrecognized RTCP Report Type of %d\n", GetPayloadType(puchDataBuffer)); osPrintf(" - Remaining buffer length of %lu", ulBufferLength); count = ulBufferLength > 0 ? ulBufferLength : 0; count = count < 100 ? count : 100; if (count > 0) osPrintf(" containing\n==>"); for (i=0; i<count; i++) { if (15 == (15 & i)) osPrintf(" %02X\n ", *puchDataBuffer); else osPrintf(" %02X", *puchDataBuffer); puchDataBuffer++; } osPrintf("\n"); } if (!verbose) { ProcessPacket(SAVEpuchDataBuffer, SAVEulBufferLength, 1); } return; } #ifdef DEBUG_RTCP_PACKETS /* [ */ if (verbose) { unsigned char *tp = puchDataBuffer; unsigned long tl = ulBytesProcessed; int i = 0; while(tl > 0) { osPrintf(" %02X", *tp++); if (0xf == (0xf & i++)) osPrintf("\n"); tl--; } if (0 != (0xf & i)) osPrintf("\n"); } #endif /* DEBUG_RTCP_PACKETS ] */ // Adjust length remaining and the buffer pointer so that we are // prepared to recognize and process other reports. puchDataBuffer += ulBytesProcessed; ulBufferLength -= ulBytesProcessed; } }
void debug(const char* msg ) { osPrintf("\n******************************\n"); osPrintf("%s\n", msg); osPrintf("******************************\n"); }
ProvisioningAttrList* XmlRpcSignIn::Action(ProvisioningAttrList& rRequestAttributes) { ProvisioningAttrList* pResponse; UtlString uriString; UtlString status; osPrintf("{method} = action\n{object-class} = login\n"); rRequestAttributes.dumpAttributes(); osPrintf("\n"); // Extract the action attribute from the request // operate on either sign-in or sign-out attributes if (rRequestAttributes.getAttribute(XMLRPC_SIGN_IN_TAG, uriString)) { // See if the Agent is not already signed-in Url contactUrl(uriString); mpSipPresenceMonitor->getState(contactUrl, status); if (status.compareTo(STATUS_OPEN) == 0) { // Already signed-in, return error pResponse = new ProvisioningAttrList; pResponse->setAttribute("method-name", "action"); pResponse->setAttribute("result-code", ProvisioningAgent::SUCCESS); pResponse->setAttribute("result-text", "SUCCESS: User already signed-in"); return pResponse; } // Sign-in the Agent mpSipPresenceMonitor->setStatus(contactUrl, StateChangeNotifier::PRESENT); // Build up the response. pResponse = new ProvisioningAttrList; pResponse->setAttribute("method-name", "action"); pResponse->setAttribute("result-code", ProvisioningAgent::SUCCESS); pResponse->setAttribute("result-text", "SUCCESS: sign-in"); return pResponse; } else if (rRequestAttributes.getAttribute(XMLRPC_SIGN_OUT_TAG, uriString)) { // See if the Agent is not already signed-out Url contactUrl(uriString); mpSipPresenceMonitor->getState(contactUrl, status); if (status.compareTo(STATUS_CLOSED) == 0) { // Already signed-out, return error pResponse = new ProvisioningAttrList; pResponse->setAttribute("method-name", "action"); pResponse->setAttribute("result-code", ProvisioningAgent::SUCCESS); pResponse->setAttribute("result-text", "SUCCESS: User already signed-out"); return pResponse; } // Sign-out the Agent mpSipPresenceMonitor->setStatus(contactUrl, StateChangeNotifier::AWAY); // Build up the response. pResponse = new ProvisioningAttrList; pResponse->setAttribute("method-name", "action"); pResponse->setAttribute("result-code", ProvisioningAgent::SUCCESS); pResponse->setAttribute("result-text", "SUCCESS: sign-out"); return pResponse; } else if (rRequestAttributes.getAttribute(XMLRPC_SIGN_IN_STATUS_TAG, uriString)) { // Get the Agent status Url contactUrl(uriString); mpSipPresenceMonitor->getState(contactUrl, status); // Build up the response. pResponse = new ProvisioningAttrList; pResponse->setAttribute("method-name", "action"); pResponse->setAttribute("result-code", ProvisioningAgent::SUCCESS); pResponse->setAttribute("result-text", status); return pResponse; } else { // Unrecognized or missing action-object pResponse = new ProvisioningAttrList; pResponse->setAttribute("method-name", "action"); pResponse->setAttribute("result-code", ProvisioningAgent::FAILURE); pResponse->setAttribute("result-text", "Invalid action operation"); return pResponse; } }
UtlBoolean TaoClientTask::handleMessage(OsMsg& rMsg) { /////////////////////////////////////////////////////////// // UtlBoolean handled = TRUE; // This should really initialized as FALSE. But for now // we use this to avoid assertion when the scroll wheel // spins too fast and receiveEvent fails. // // Need to be fixed later. ------ Feng 3/26/2000 // /////////////////////////////////////////////////////////// switch (rMsg.getMsgSubType()) { case TaoMessage::REQUEST_ADDRESS: case TaoMessage::REQUEST_CALL: case TaoMessage::REQUEST_CONNECTION: case TaoMessage::REQUEST_PHONECOMPONENT: case TaoMessage::REQUEST_PROVIDER: case TaoMessage::REQUEST_TERMINAL: case TaoMessage::REQUEST_TERMCONNECTION: if (sendRequest((TaoMessage&) rMsg, 0)) { handled = TRUE; } break; case TaoMessage::RESPONSE_ADDRESS: case TaoMessage::RESPONSE_CALL: case TaoMessage::RESPONSE_CONNECTION: case TaoMessage::RESPONSE_PROVIDER: case TaoMessage::RESPONSE_TERMCONNECTION: case TaoMessage::RESPONSE_TERMINAL: case TaoMessage::RESPONSE_PHONECOMPONENT: handled = receiveMsg((TaoMessage&) rMsg); if (!handled) { osPrintf("TaoClientTask::handleMessage response msg not handled msg subtype = %d\n", rMsg.getMsgSubType()); UtlString buffer; int bufferLen; ((TaoMessage&) rMsg).getBytes(&buffer, &bufferLen); osPrintf("%s\n", buffer.data()); /////////// WE DONT KNOW WHY IT WOULDN"T BE HANDLED } break; case TaoMessage::UNSPECIFIED: default: // assert(FALSE); handled = FALSE; osPrintf("\n ERROR! TaoClientTask::handleMessage - UNKNOWN MESSAGE TYPE %d\n", rMsg.getMsgSubType()); UtlString buffer; int bufferLen; ((TaoMessage&) rMsg).getBytes(&buffer, &bufferLen); osPrintf("%s\n", buffer.data()); break; } return handled; }
UtlBoolean CommandMsgProcessor::handleMessage(OsMsg& eventMessage) { int msgType = eventMessage.getMsgType(); // int msgSubType = eventMessage.getMsgSubType(); if(msgType == OsMsg::PHONE_APP) // && msgSubType == CP_SIP_MESSAGE) { osPrintf("CommandMsgProcessor::handleMessage Got a message\n"); int messageType = ((SipMessageEvent&)eventMessage).getMessageStatus(); const SipMessage* sipMsg = ((SipMessageEvent&)eventMessage).getMessage(); UtlString callId; if(sipMsg) { osPrintf("numRespondToMessages: %d isResponse: %d messageType: %d TransErro: %d\n", numRespondToMessages, sipMsg->isResponse(), messageType, SipMessageEvent::TRANSPORT_ERROR); if((numRespondToMessages == -1 || numRespondToMessages > 0) && !sipMsg->isResponse() && messageType != SipMessageEvent::TRANSPORT_ERROR) { osPrintf("valid message\n"); if(numRespondToMessages > 0) { numRespondToMessages--; } SipMessage response; if(mpResponseMessage) { response = *mpResponseMessage; } response.setResponseData(sipMsg, responseStatusCode, responseStatusText.data()); UtlString address; int port; UtlString protocol; UtlString tag; sipMsg->getToAddress(&address, &port, &protocol, NULL, NULL, &tag) ; if( tag.isNull()) { int tagNum = rand(); char tag[100]; sprintf(tag, "%d", tagNum); UtlString tagWithDot(tag); tagWithDot.append(".34756498567498567"); response.setToFieldTag(tagWithDot); } UtlString msgBytes; ssize_t msgLen; response.getBytes(&msgBytes, &msgLen); osPrintf("%s",msgBytes.data()); if(mpLastResponseMessage) { delete mpLastResponseMessage; mpLastResponseMessage = NULL; } // Keep a copy of the last response sent mpLastResponseMessage = new SipMessage(response); if(userAgent->send(response)) { osPrintf("Sent response\n"); } else { osPrintf("Send failed\n"); } } } } return(TRUE); }
/** * * Method Name: ExtractTimestamps * * * Inputs: unsigned long *paulTimestamps * - Array containing the NTP/RTP Timestamps * * Outputs: None * * Returns: unsigned long - Size of the data extracted * * Description: This method shall extract the 64 bits of NTP time information * and the 32-bits of RTP timestamp and store them both in * respective report attributes. * * Usage Notes: * */ unsigned long CSenderReport::ExtractTimestamps(unsigned long *paulTimestamps) { unsigned long aulCurrentNTPTime[2]; double dTimestamp; // Load the two long word into NTP timestamp array m_aulNTPTimestamp[0] = ntohl(*paulTimestamps); paulTimestamps++; m_aulNTPTimestamp[1] = ntohl(*paulTimestamps); paulTimestamps++; // Store the RTP timestamp associated with this report m_ulRTPTimestamp = ntohl(*paulTimestamps); // Let's perform some calculations that will be useful in // determining SR Delay #ifdef WIN32 struct _timeb stLocalTime; // Get the LocalTime expressed as seconds since 1/1/70 (UTC) _ftime(&stLocalTime); // Load Most Significant word with Wall time seconds aulCurrentNTPTime[0] = (unsigned long)stLocalTime.time + WALLTIMEOFFSET; // Load Least Significant word with Wall time microseconds dTimestamp = stLocalTime.millitm * MILLI2MICRO; dTimestamp *= (double)(FOUR_GIGABYTES/MICRO2SEC); #elif defined(__pingtel_on_posix__) struct timeval tv; gettimeofday(&tv, NULL); // Load Most Significant word with Wall time seconds m_aulNTPStartTime[0] = tv.tv_sec + WALLTIMEOFFSET; // Load Least Significant word with Wall time microseconds dTimestamp = (double) tv.tv_usec / MILLI2MICRO; dTimestamp *= (double) (FOUR_GIGABYTES / MICRO2SEC); #else struct timespec stLocalTime; // Make a call to VxWorks to get this timestamp if (clock_gettime(CLOCK_REALTIME, &stLocalTime) == ERROR) { osPrintf("**** FAILURE **** LoadTimestamps() - clock_gettime failure\n"); stLocalTime.tv_sec = 0; stLocalTime.tv_nsec = 0; } // Load Most Significant word with Wall time seconds aulCurrentNTPTime[0] = stLocalTime.tv_sec + WALLTIMEOFFSET; // Load Least Significant word with Wall time microseconds dTimestamp = (double)stLocalTime.tv_nsec / MILLI2MICRO; dTimestamp *= (double)(FOUR_GIGABYTES / MICRO2SEC); #endif // Store microsecond portion of NTP aulCurrentNTPTime[1] = (unsigned long)dTimestamp; // Calculate Current RTP Timestamp by taking the difference // between the current and starting NTP timestamps double dSecondsElapsed = (double)(aulCurrentNTPTime[0] - m_aulNTPStartTime[0]); double dUSecondsElapsed = (double)(aulCurrentNTPTime[1] - m_aulNTPStartTime[1]); // Round Seconds down if Microsecond difference is less that 0. while (dUSecondsElapsed < 0) { dSecondsElapsed--; dUSecondsElapsed += MICRO2SEC; } // Express in fractions of seconds dUSecondsElapsed /= MICRO2SEC; // Express total elapsed time in sample Units per seond m_ulRTPTimestamp = (unsigned long)(dSecondsElapsed + dUSecondsElapsed); // Use the CReceiverReport's ISetReceiverStatistics Interface to timestamp // when the last Sender Report was Received. m_piSetReceiverStatistics->SetLastRcvdSRTime(m_aulNTPTimestamp); return(sizeof(m_aulNTPTimestamp) + sizeof(m_ulRTPTimestamp)); }
// Print mutex information to the console void OsMutexLinux::OsMutexShow(void) { osPrintf("OsMutex object %p\n", (void*) this); }
/** * * Method Name: LoadTimestamps * * * Inputs: None * * Outputs: unsigned long *aulTimestamps - Long word array in which to load * the NTP and RTP timestamps * (WHAT FORMAT???) * * Returns: unsigned long - Size of the data loaded (WHAT UNITS???) * * Description: This method shall use the VxWorks Network time protocol * service to get a 64 bit representation of the current Network * time and 32 bit for RTP time. * * Usage Notes: * */ unsigned long CSenderReport::LoadTimestamps(unsigned long *aulTimestamps) { double dTimestamp; #ifdef WIN32 struct _timeb stLocalTime; // Get the LocalTime expressed as seconds since 1/1/70 (UTC) _ftime(&stLocalTime); // Load Most Significant word with Wall time seconds m_aulNTPTimestamp[0] = (unsigned long)stLocalTime.time + WALLTIMEOFFSET; // Load Least Significant word with Wall time microseconds dTimestamp = stLocalTime.millitm * MILLI2MICRO; dTimestamp *= (double)(FOUR_GIGABYTES/MICRO2SEC); #elif defined(__pingtel_on_posix__) struct timeval tv; gettimeofday(&tv, NULL); // Load Most Significant word with Wall time seconds m_aulNTPStartTime[0] = tv.tv_sec + WALLTIMEOFFSET; // Load Least Significant word with Wall time microseconds dTimestamp = (double) tv.tv_usec / MILLI2MICRO; dTimestamp *= (double) (FOUR_GIGABYTES / MICRO2SEC); #else struct timespec stLocalTime; // Make a call to VxWorks to get this timestamp if (clock_gettime(CLOCK_REALTIME, &stLocalTime) == ERROR) { osPrintf("**** FAILURE **** LoadTimestamps() - clock_gettime failure\n"); stLocalTime.tv_sec = 0; stLocalTime.tv_nsec = 0; } // Load Most Significant word with Wall time seconds m_aulNTPTimestamp[0] = stLocalTime.tv_sec + WALLTIMEOFFSET; // Load Least Significant word with Wall time microseconds dTimestamp = (double)stLocalTime.tv_nsec / MILLI2MICRO; dTimestamp *= (double)(FOUR_GIGABYTES / MICRO2SEC); #endif // Store microsecond portion of NTP m_aulNTPTimestamp[1] = (unsigned long)dTimestamp; // Assign NTP Time to Sender Report Buffer *aulTimestamps = htonl(m_aulNTPTimestamp[0]); aulTimestamps++; *aulTimestamps = htonl(m_aulNTPTimestamp[1]); aulTimestamps++; // Calculate RTP Timestamp by taking the difference between the current // and starting NTP timestamps double dSecondsElapsed = (double)(m_aulNTPTimestamp[0] - m_aulNTPStartTime[0]); double dUSecondsElapsed = (double)(m_aulNTPTimestamp[1] - m_aulNTPStartTime[1]); // Round Seconds down if Microsecond difference is less that 0. while (dUSecondsElapsed < 0) { dSecondsElapsed--; dUSecondsElapsed += MICRO2SEC; } // Express in fractions of seconds dUSecondsElapsed /= MICRO2SEC; // Express total elapsed time in sample Units per second double dElapsedUnits = (dSecondsElapsed + dUSecondsElapsed) / ((1.0) / ((double)m_ulSamplesPerSecond)); // Adjust by random offset and format in Network Byte Order m_ulRTPTimestamp = (unsigned long) (dElapsedUnits + m_ulRandomOffset); *aulTimestamps = htonl(m_ulRTPTimestamp); return(sizeof(m_aulNTPTimestamp) + sizeof(m_ulRTPTimestamp)); }
/** * * Method Name: SetRTPTimestamp * * * Inputs: unsigned long ulRandomOffset - Random Offset for RTP Timestamp * unsigned long ulSamplesPerSecond - Number of samples per second * * Outputs: None * * Returns: void * * Description: The SetRTPTimestamp method shall initialized values that are * used to determine the RTP Timestamp value to be sent out in * an SR Report. * * Usage Notes: * */ void CSenderReport::SetRTPTimestamp(unsigned long ulRandomOffset, unsigned long ulSamplesPerSecond) { // Set Timestamp Information m_ulRandomOffset = ulRandomOffset; m_ulSamplesPerSecond = ulSamplesPerSecond; // Let's check whether an initial NTP timestamp has been established. // If so, ignore. if(!m_aulNTPStartTime[0] && !m_aulNTPStartTime[1]) { double dTimestamp; #ifdef WIN32 struct _timeb stLocalTime; // Get the LocalTime expressed as seconds since 1/1/70 (UTC) _ftime(&stLocalTime); // Load Most Significant word with Wall time seconds m_aulNTPStartTime[0] = (unsigned long)stLocalTime.time + WALLTIMEOFFSET; // Load Least Significant word with Wall time microseconds dTimestamp = stLocalTime.millitm * MILLI2MICRO; dTimestamp *= (double)(FOUR_GIGABYTES/MICRO2SEC); #elif defined(__pingtel_on_posix__) struct timeval tv; gettimeofday(&tv, NULL); // Load Most Significant word with Wall time seconds m_aulNTPStartTime[0] = tv.tv_sec + WALLTIMEOFFSET; // Load Least Significant word with Wall time microseconds dTimestamp = (double) tv.tv_usec / MILLI2MICRO; dTimestamp *= (double) (FOUR_GIGABYTES / MICRO2SEC); #else struct timespec stLocalTime; // Make a call to VxWorks to get this timestamp if (clock_gettime(CLOCK_REALTIME, &stLocalTime) == ERROR) { osPrintf("**** FAILURE **** SetRTPTimestamp() - clock_gettime failure\n"); stLocalTime.tv_sec = 0; stLocalTime.tv_nsec = 0; } // Load Most Significant word with Wall time seconds m_aulNTPStartTime[0] = stLocalTime.tv_sec + WALLTIMEOFFSET; // Load Least Significant word with Wall time microseconds dTimestamp = (double)stLocalTime.tv_nsec / MILLI2MICRO; dTimestamp *= (double)(FOUR_GIGABYTES / MICRO2SEC); #endif // Store microsecond portion of NTP m_aulNTPStartTime[1] = (unsigned long)dTimestamp; } }
// Handle messages directed to this server task. UtlBoolean MpStreamPlaylistPlayer::handleMessage(OsMsg& rMsg) { switch (rMsg.getMsgType()) { case OsMsg::OS_EVENT: OsEventMsg* pMsg = (OsEventMsg*) &rMsg; intptr_t status; int index; void* indexVoid; pMsg->getUserData(indexVoid); index = (int)(intptr_t)indexVoid; if (pMsg->getEventData(status) == OS_SUCCESS) { PlayListEntry* e = (PlayListEntry*)mPlayListDb->at(index) ; #ifdef MP_STREAM_DEBUG /* [ */ osPrintf("MpStreamPlaylistPlayer::handleMessage(%p): Received Feeder event: %s \n", this, getFeederEventString(status)); OsSysLog::add(FAC_MP, PRI_DEBUG, "MpStreamPlaylistPlayer::handleMessage(%p): Received Feeder event: %s index=%d e->index=%d", this, getFeederEventString(status), index, e?e->index:-1); #endif /* MP_STREAM_DEBUG ] */ switch (status) { case FeederRealizedEvent: setEntryState(e, PlayerRealized); break; case FeederPrefetchedEvent: setEntryState(e, PlayerPrefetched); break; case FeederStoppedEvent: if (mAggregateState != PlayerPlaying) { setEntryState(e, PlayerPrefetched); } break; case FeederRenderingEvent: break; case FeederFailedEvent: setEntryState(e, PlayerFailed); break; case FeederStreamPlayingEvent: setEntryState(e, PlayerPlaying); break; case FeederStreamPausedEvent: setEntryState(e, PlayerPaused); break; case FeederStreamStoppedEvent: setEntryState(e, PlayerStopped); break; case FeederStreamDestroyedEvent: setEntryState(e, PlayerDestroyed); break; case FeederStreamAbortedEvent: setEntryState(e, PlayerStopped); break; } } break; } return TRUE; }
void testQueuePlayerSuperDrop() { char szUrl[128] ; MpStreamQueuePlayer* pQPlayer ; MpStreamPlayer* pPlayer = NULL ; int j ; osPrintf("testQueuePlayerSuperDrop.1\n") ; for (j=0; j<TESTING_ATTEMPTS; j++) { UtlString callId ; mCfg->getCallManager()->createCall(&callId) ; mCfg->getCallManager()->unholdAllTerminalConnections(callId) ; mCfg->getCallManager()->createPlayer(MpPlayer::STREAM_QUEUE_PLAYER, callId, NULL, STREAM_SOUND_LOCAL | STREAM_FORMAT_RAW, &pPlayer) ; pQPlayer = (MpStreamQueuePlayer*) pPlayer ; sprintf(szUrl, "http://%s/nums/%d.raw", BASE_URL, 1) ; Url url(szUrl) ; pQPlayer->add(url, STREAM_SOUND_LOCAL | STREAM_FORMAT_RAW) ; pQPlayer->play() ; pQPlayer->add(url, STREAM_SOUND_LOCAL | STREAM_FORMAT_RAW) ; mCfg->getCallManager()->drop(callId) ; mCfg->getCallManager()->destroyPlayer(MpPlayer::STREAM_QUEUE_PLAYER, callId, pPlayer) ; OsTask::delay(DELAY_BEWTEEN_CALLS) ; // Delay so that we don't run out of flowgraphs } osPrintf("testQueuePlayerSuperDrop.2\n") ; for (j=0; j<TESTING_ATTEMPTS; j++) { UtlString callId ; mCfg->getCallManager()->createCall(&callId) ; mCfg->getCallManager()->unholdAllTerminalConnections(callId) ; mCfg->getCallManager()->createPlayer(MpPlayer::STREAM_QUEUE_PLAYER, callId, NULL, STREAM_SOUND_LOCAL | STREAM_FORMAT_RAW, &pPlayer) ; pQPlayer = (MpStreamQueuePlayer*) pPlayer ; sprintf(szUrl, "http://%s/nums/%d.raw", BASE_URL, 1) ; Url url(szUrl) ; pQPlayer->add(url, STREAM_SOUND_LOCAL | STREAM_FORMAT_RAW) ; pQPlayer->play() ; pQPlayer->add(url, STREAM_SOUND_LOCAL | STREAM_FORMAT_RAW) ; mCfg->getCallManager()->destroyPlayer(MpPlayer::STREAM_QUEUE_PLAYER, callId, pPlayer) ; mCfg->getCallManager()->drop(callId) ; OsTask::delay(DELAY_BEWTEEN_CALLS) ; // Delay so that we don't run out of flowgraphs } osPrintf("testQueuePlayerSuperDrop.3\n") ; for (j=0; j<TESTING_ATTEMPTS; j++) { UtlString callId ; mCfg->getCallManager()->createCall(&callId) ; mCfg->getCallManager()->unholdAllTerminalConnections(callId) ; mCfg->getCallManager()->createPlayer(MpPlayer::STREAM_QUEUE_PLAYER, callId, NULL, STREAM_SOUND_LOCAL | STREAM_FORMAT_RAW, &pPlayer) ; pQPlayer = (MpStreamQueuePlayer*) pPlayer ; sprintf(szUrl, "http://%s/nums/%d.raw", BASE_URL, 1) ; Url url(szUrl) ; pQPlayer->add(url, STREAM_SOUND_LOCAL | STREAM_FORMAT_RAW) ; pQPlayer->play() ; pQPlayer->add(url, STREAM_SOUND_LOCAL | STREAM_FORMAT_RAW) ; mCfg->getCallManager()->drop(callId) ; pQPlayer->add(url, STREAM_SOUND_LOCAL | STREAM_FORMAT_RAW) ; pQPlayer->play() ; pQPlayer->add(url, STREAM_SOUND_LOCAL | STREAM_FORMAT_RAW) ; pQPlayer->play() ; mCfg->getCallManager()->drop(callId) ; mCfg->getCallManager()->destroyPlayer(MpPlayer::STREAM_QUEUE_PLAYER, callId, pPlayer) ; OsTask::delay(DELAY_BEWTEEN_CALLS) ; // Delay so that we don't run out of flowgraphs } osPrintf("testQueuePlayerSuperDrop.4\n") ; for (j=0; j<TESTING_ATTEMPTS; j++) { UtlString callId ; mCfg->getCallManager()->createCall(&callId) ; mCfg->getCallManager()->unholdAllTerminalConnections(callId) ; mCfg->getCallManager()->createPlayer(MpPlayer::STREAM_QUEUE_PLAYER, callId, NULL, STREAM_SOUND_LOCAL | STREAM_FORMAT_RAW, &pPlayer) ; pQPlayer = (MpStreamQueuePlayer*) pPlayer ; sprintf(szUrl, "http://%s/nums/%d.raw", BASE_URL, 1) ; Url url(szUrl) ; pQPlayer->add(url, STREAM_SOUND_LOCAL | STREAM_FORMAT_RAW) ; pQPlayer->play() ; pQPlayer->add(url, STREAM_SOUND_LOCAL | STREAM_FORMAT_RAW) ; mCfg->getCallManager()->drop(callId) ; pQPlayer->add(url, STREAM_SOUND_LOCAL | STREAM_FORMAT_RAW) ; pQPlayer->play() ; pQPlayer->add(url, STREAM_SOUND_LOCAL | STREAM_FORMAT_RAW) ; pQPlayer->play() ; mCfg->getCallManager()->destroyPlayer(MpPlayer::STREAM_QUEUE_PLAYER, callId, pPlayer) ; mCfg->getCallManager()->drop(callId) ; OsTask::delay(DELAY_BEWTEEN_CALLS) ; // Delay so that we don't run out of flowgraphs } }
int proxy() { int proxyTcpPort; int proxyUdpPort; int proxyTlsPort; UtlString bindIp; int maxForwards; UtlString domainName; UtlString proxyRecordRoute; UtlString routeName; UtlString authScheme; UtlString ipAddress; OsSocket::getHostIp(&ipAddress); OsPath ConfigfileName = SipXecsService::Path(SipXecsService::ConfigurationDirType, CONFIG_SETTINGS_FILE); OsConfigDb configDb; if(OS_SUCCESS != configDb.loadFromFile(ConfigfileName)) { exit(1); } // Initialize the OsSysLog... initSysLog(&configDb); std::set_terminate(catch_global); configDb.get(CONFIG_SETTING_BIND_IP, bindIp); if ((bindIp.isNull()) || !OsSocket::isIp4Address(bindIp)) { bindIp = "0.0.0.0"; } Os::Logger::instance().log(FAC_SIP, PRI_INFO, "%s: %s", CONFIG_SETTING_BIND_IP, bindIp.data()); osPrintf("%s: %s", CONFIG_SETTING_BIND_IP, bindIp.data()); UtlString hostname; configDb.get("SIPX_PROXY_HOST_NAME", hostname); if (!hostname.isNull()) { // bias the selection of SRV records so that if the name of this host is an alternative, // it wins in any selection based on random weighting. SipSrvLookup::setOwnHostname(hostname); } Os::Logger::instance().log(FAC_SIP, PRI_INFO, "SIPX_PROXY_HOST_NAME : %s", hostname.data()); proxyUdpPort = configDb.getPort("SIPX_PROXY_UDP_PORT"); if (!portIsValid(proxyUdpPort)) { proxyUdpPort = 5060; } Os::Logger::instance().log(FAC_SIP, PRI_INFO, "SIPX_PROXY_UDP_PORT : %d", proxyUdpPort); proxyTcpPort = configDb.getPort("SIPX_PROXY_TCP_PORT") ; if (!portIsValid(proxyTcpPort)) { proxyTcpPort = 5060; } Os::Logger::instance().log(FAC_SIP, PRI_INFO, "SIPX_PROXY_TCP_PORT : %d", proxyTcpPort); proxyTlsPort = configDb.getPort("SIPX_PROXY_TLS_PORT") ; if (!portIsValid(proxyTlsPort)) { proxyTlsPort = 5061; } Os::Logger::instance().log(FAC_SIP, PRI_INFO, "SIPX_PROXY_TLS_PORT : %d", proxyTlsPort); configDb.get("SIPX_PROXY_MAX_FORWARDS", maxForwards); if(maxForwards <= 0) maxForwards = SIP_DEFAULT_MAX_FORWARDS; Os::Logger::instance().log(FAC_SIP, PRI_INFO, "SIPX_PROXY_MAX_FORWARDS : %d", maxForwards); osPrintf("SIPX_PROXY_MAX_FORWARDS : %d\n", maxForwards); int branchTimeout = -1; configDb.get("SIPX_PROXY_BRANCH_TIMEOUT", branchTimeout); if(branchTimeout < 4) { branchTimeout = 24; } int defaultExpires; int defaultSerialExpires; configDb.get("SIPX_PROXY_DEFAULT_EXPIRES", defaultExpires); configDb.get("SIPX_PROXY_DEFAULT_SERIAL_EXPIRES", defaultSerialExpires); if(defaultExpires <= 0 ) { defaultExpires = DEFAULT_SIP_TRANSACTION_EXPIRES; } else if(defaultExpires > DEFAULT_SIP_TRANSACTION_EXPIRES) { Os::Logger::instance().log(FAC_SIP, PRI_WARNING, "SipXproxymain::proxy " "large default expires value: %d NOT RECOMMENDED", defaultExpires); } if(defaultSerialExpires <= 0 || defaultSerialExpires >= defaultExpires) { defaultSerialExpires = DEFAULT_SIP_SERIAL_EXPIRES; } Os::Logger::instance().log(FAC_SIP, PRI_INFO, "SIPX_PROXY_DEFAULT_EXPIRES : %d", defaultExpires); osPrintf("SIPX_PROXY_DEFAULT_EXPIRES : %d\n", defaultExpires); Os::Logger::instance().log(FAC_SIP, PRI_INFO, "SIPX_PROXY_DEFAULT_SERIAL_EXPIRES : %d", defaultSerialExpires); osPrintf("SIPX_PROXY_DEFAULT_SERIAL_EXPIRES : %d\n", defaultSerialExpires); UtlString hostAliases; configDb.get("SIPX_PROXY_HOST_ALIASES", hostAliases); if(hostAliases.isNull()) { hostAliases = ipAddress; char portBuf[20]; sprintf(portBuf, ":%d", proxyUdpPort); hostAliases.append(portBuf); if(!routeName.isNull()) { hostAliases.append(" "); hostAliases.append(routeName); char portBuf[20]; sprintf(portBuf, ":%d", proxyUdpPort); hostAliases.append(portBuf); } Os::Logger::instance().log(FAC_SIP, PRI_NOTICE, "SIPX_PROXY_HOST_ALIASES not configured" " using implied value: %s", hostAliases.data()); } Os::Logger::instance().log(FAC_SIP, PRI_INFO, "SIPX_PROXY_HOST_ALIASES : %s", hostAliases.data()); UtlString enableCallStateObserverSetting; configDb.get(CONFIG_SETTING_CALL_STATE, enableCallStateObserverSetting); bool enableCallStateLogObserver; if ( (enableCallStateObserverSetting.isNull()) || ((0 == enableCallStateObserverSetting.compareTo("disable", UtlString::ignoreCase))) ) { enableCallStateLogObserver = false; } else if (0 == enableCallStateObserverSetting.compareTo("enable", UtlString::ignoreCase)) { enableCallStateLogObserver = true; } else { enableCallStateLogObserver = false; Os::Logger::instance().log(FAC_SIP, PRI_ERR, "SipXproxymain:: invalid configuration value for " CONFIG_SETTING_CALL_STATE " '%s' - should be 'enable' or 'disable'", enableCallStateObserverSetting.data() ); } Os::Logger::instance().log(FAC_SIP, PRI_INFO, CONFIG_SETTING_CALL_STATE " : %s", enableCallStateLogObserver ? "ENABLE" : "DISABLE" ); UtlString callStateLogFileName; if (enableCallStateLogObserver) { configDb.get(CONFIG_SETTING_CALL_STATE_LOG, callStateLogFileName); if (callStateLogFileName.isNull()) { callStateLogFileName = CALL_STATE_LOG_FILE_DEFAULT; } Os::Logger::instance().log(FAC_SIP, PRI_INFO, CONFIG_SETTING_CALL_STATE_LOG " : %s", callStateLogFileName.data()); } // Check if CSE logging should go into a database UtlString enableCallStateDbObserverSetting; configDb.get(CONFIG_SETTING_CALL_STATE_DB, enableCallStateDbObserverSetting); bool enableCallStateDbObserver; if ( (enableCallStateDbObserverSetting.isNull()) || ((0 == enableCallStateDbObserverSetting.compareTo("disable", UtlString::ignoreCase))) ) { enableCallStateDbObserver = false; } else if (0 == enableCallStateDbObserverSetting.compareTo("enable", UtlString::ignoreCase)) { enableCallStateDbObserver = true; } else { enableCallStateDbObserver = false; Os::Logger::instance().log(FAC_SIP, PRI_ERR, "SipAuthProxyMain:: invalid configuration value for %s " " '%s' - should be 'enable' or 'disable'", CONFIG_SETTING_CALL_STATE_DB, enableCallStateDbObserverSetting.data() ); } Os::Logger::instance().log(FAC_SIP, PRI_INFO, "%s : %s", CONFIG_SETTING_CALL_STATE_DB, enableCallStateDbObserver ? "ENABLE" : "DISABLE" ); UtlString callStateDbHostName; UtlString callStateDbName; UtlString callStateDbUserName; UtlString callStateDbDriver; if (enableCallStateDbObserver) { configDb.get(CONFIG_SETTING_CALL_STATE_DB_HOST, callStateDbHostName); if (callStateDbHostName.isNull()) { callStateDbHostName = CALL_STATE_DATABASE_HOST; } Os::Logger::instance().log(FAC_SIP, PRI_INFO, "%s : %s", CONFIG_SETTING_CALL_STATE_DB_HOST, callStateDbHostName.data()); configDb.get(CONFIG_SETTING_CALL_STATE_DB_NAME, callStateDbName); if (callStateDbName.isNull()) { callStateDbName = CALL_STATE_DATABASE_NAME; } Os::Logger::instance().log(FAC_SIP, PRI_INFO, "%s : %s", CONFIG_SETTING_CALL_STATE_DB_NAME, callStateDbName.data()); configDb.get(CONFIG_SETTING_CALL_STATE_DB_USER, callStateDbUserName); if (callStateDbUserName.isNull()) { callStateDbUserName = CALL_STATE_DATABASE_USER; } Os::Logger::instance().log(FAC_SIP, PRI_INFO, "%s : %s", CONFIG_SETTING_CALL_STATE_DB_USER, callStateDbUserName.data()); configDb.get(CONFIG_SETTING_CALL_STATE_DB_DRIVER, callStateDbDriver); if (callStateDbDriver.isNull()) { callStateDbDriver = CALL_STATE_DATABASE_DRIVER; } Os::Logger::instance().log(FAC_SIP, PRI_INFO, "%s : %s", CONFIG_SETTING_CALL_STATE_DB_DRIVER, callStateDbDriver.data()); } // Select logging method - database takes priority over XML file if (enableCallStateLogObserver && enableCallStateDbObserver) { enableCallStateLogObserver = false; Os::Logger::instance().log(FAC_SIP, PRI_WARNING, "SipXproxymain:: both XML and database call state " "logging was enabled - turning off XML log, only use database logging"); } // Set the maximum amount of time that TCP connections can // stay around when they are not used. int staleTcpTimeout = 3600; UtlString staleTcpTimeoutStr; // Check for missing parameter or empty value configDb.get("SIPX_PROXY_STALE_TCP_TIMEOUT", staleTcpTimeoutStr); if (staleTcpTimeoutStr.isNull()) { staleTcpTimeout = 3600; } else { // get the parameter value as an integer configDb.get("SIPX_PROXY_STALE_TCP_TIMEOUT", staleTcpTimeout); } if(staleTcpTimeout <= 0) staleTcpTimeout = -1; else if(staleTcpTimeout < 180) staleTcpTimeout = 180; Os::Logger::instance().log(FAC_SIP, PRI_INFO, "SIPX_PROXY_STALE_TCP_TIMEOUT : %d", staleTcpTimeout); osPrintf("SIPX_PROXY_STALE_TCP_TIMEOUT : %d\n", staleTcpTimeout); int maxNumSrvRecords = -1; configDb.get("SIPX_PROXY_DNSSRV_MAX_DESTS", maxNumSrvRecords); Os::Logger::instance().log(FAC_SIP, PRI_INFO, "SIPX_PROXY_DNSSRV_MAX_DESTS : %d", maxNumSrvRecords); // If explicitly set to a valid number if(maxNumSrvRecords > 0) { osPrintf("SIPX_PROXY_DNSSRV_MAX_DESTS : %d\n", maxNumSrvRecords); } else { maxNumSrvRecords = 4; } int dnsSrvTimeout = -1; //seconds configDb.get("SIPX_PROXY_DNSSRV_TIMEOUT", dnsSrvTimeout); Os::Logger::instance().log(FAC_SIP, PRI_INFO, "SIPX_PROXY_DNSSRV_TIMEOUT : %d", dnsSrvTimeout); // If explicitly set to a valid number if(dnsSrvTimeout > 0) { osPrintf("SIPX_PROXY_DNSSRV_TIMEOUT : %d\n", dnsSrvTimeout); } else { dnsSrvTimeout = 4; } // This is an obnoxious special option to work around a // problem with Sonus gateways. The Sonus proxy or redirect // server gives a list of possible gateways to recurse in a // 300 response. It does not assign any Q values so the proxy // gets the impression that it should fork them all in parallel. // When this option is enabled we recurse only the one with the // highest Q value. UtlString recurseOnlyOne300String; configDb.get("SIPX_PROXY_SPECIAL_300", recurseOnlyOne300String); recurseOnlyOne300String.toLower(); UtlBoolean recurseOnlyOne300 = FALSE; if(recurseOnlyOne300String.compareTo("enable") == 0) { recurseOnlyOne300 = TRUE; Os::Logger::instance().log(FAC_SIP, PRI_INFO, "SIPX_PROXY_SPECIAL_300 : ENABLE"); osPrintf("SIPX_PROXY_SPECIAL_300 : ENABLE\n"); } OsPath fileName = SipXecsService::Path(SipXecsService::ConfigurationDirType, FORWARDING_RULES_FILENAME); ForwardRules forwardingRules; OsFile ruleFile(fileName); if(ruleFile.exists()) { if(OS_SUCCESS != forwardingRules.loadMappings(fileName)) { Os::Logger::instance().log(FAC_SIP, PRI_WARNING, "WARNING: Failed to load: %s", fileName.data()); osPrintf("WARNING: Failed to load: %s\n", fileName.data()); } } else { // forwardingrules.xml is not readable; no processing is possible. Os::Logger::instance().log(FAC_SIP, PRI_CRIT, "forwarding rules '%s' not found -- exiting", fileName.data()); exit(1); } #ifdef TEST_PRINT { // scope the test stuff SipMessage foo; const char* uri = "sip:10.1.20.3:5100"; const char* method = SIP_ACK_METHOD; const char* eventType = SIP_EVENT_CONFIG; foo.setRequestData(method, uri, //uri, "sip:[email protected]", // fromField, "\"lajdflsdk ff\"<sip:[email protected]>", // toField, "lkadsj902387", // callId, 123, // CSeq, "sip:10.1.1.123");// contactUrl // Set the event type foo.setHeaderValue(SIP_EVENT_FIELD, eventType, // event type 0); Url msgUrl(uri); UtlString routeTo; UtlString routeType; bool authRequired; OsStatus routeStatus = forwardingRules.getRoute(msgUrl, foo, routeTo, routeType, authRequired); Url msgRouteToUri(routeTo); osPrintf("Message:\n\tmethod: %s\n\turi: %s\n\tevent: %s\nRouted:\n\tstring: %s\n\turi: %s\n\ttype: %s\n", method, uri, eventType, routeTo.data(), msgRouteToUri.toString().data(), routeType.data()); if(routeStatus != OS_SUCCESS) osPrintf("forwardingRules.getRoute returned: %d\n", routeStatus); } #endif // TEST_PRINT // Start the sip stack SipUserAgent* pSipUserAgent = new SipUserAgent( proxyTcpPort, proxyUdpPort, proxyTlsPort, NULL, // public IP address (not used in proxy) NULL, // default user (not used in proxy) bindIp, NULL, // outbound proxy NULL, // directory server NULL, // registry server NULL, // auth realm NULL, // auth DB NULL, // auth user IDs NULL, // auth passwords NULL, // line mgr SIP_DEFAULT_RTT, // first resend timeout FALSE, // default to proxy transaction SIPUA_DEFAULT_SERVER_UDP_BUFFER_SIZE, // socket layer read buffer size SIPUA_DEFAULT_SERVER_OSMSG_QUEUE_SIZE, // OsServerTask message queue size FALSE, // Use Next Available Port TRUE, // Perform message checks TRUE, // Use symmetric signaling SipUserAgent::HANDLE_OPTIONS_AUTOMATICALLY); if (!pSipUserAgent->isOk()) { Os::Logger::instance().log(FAC_SIP, PRI_EMERG, "SipUserAgent reported a problem, setting shutdown flag..."); gShutdownFlag = TRUE; } pSipUserAgent->setDnsSrvTimeout(dnsSrvTimeout); pSipUserAgent->setMaxSrvRecords(maxNumSrvRecords); pSipUserAgent->setUserAgentHeaderProperty("sipXecs/sipXproxy"); pSipUserAgent->setMaxForwards(maxForwards); pSipUserAgent->setDefaultExpiresSeconds(defaultExpires); pSipUserAgent->setDefaultSerialExpiresSeconds(defaultSerialExpires); pSipUserAgent->setMaxTcpSocketIdleTime(staleTcpTimeout); pSipUserAgent->setHostAliases(hostAliases); pSipUserAgent->setRecurseOnlyOne300Contact(recurseOnlyOne300); // Do not start the SipUserAgent until its message listeners are // set up by the creation of the SipRouter below. UtlString buffer; // Create the CSE observer, either writing to file or database SipXProxyCseObserver* cseObserver = NULL; CallStateEventWriter* pEventWriter = NULL; if (enableCallStateLogObserver) { // Set up the call state event log file pEventWriter = new CallStateEventWriter_XML(callStateLogFileName.data()); } else if (enableCallStateDbObserver) { pEventWriter = new CallStateEventWriter_DB(callStateDbName.data(), callStateDbHostName.data(), callStateDbUserName, callStateDbDriver); } if (pEventWriter) { // get the identifier for this observer int protocol = OsSocket::UDP; UtlString domainName; int port; pSipUserAgent->getViaInfo(protocol, domainName, port); char portString[12]; sprintf(portString,":%d", port); domainName.append(portString); // and start the observer cseObserver = new SipXProxyCseObserver(*pSipUserAgent, domainName, pEventWriter); cseObserver->start(); } else { // Only log error if any event logging was enabled if (enableCallStateLogObserver || enableCallStateDbObserver) { Os::Logger::instance().log(FAC_SIP, PRI_ERR, "SipAuthProxyMain:: EventWriter could not be allocated" ); enableCallStateLogObserver = false; enableCallStateDbObserver = false; } } // Create a router to route stuff either // to a local server or on out to the real world SipRouter* pRouter = new SipRouter(*pSipUserAgent, forwardingRules, configDb); // Start the router running pRouter->start(); // Do not exit, let the proxy do its stuff while( !gShutdownFlag ) { OsTask::delay(1000); } // This is a server task so gracefully shutdown the // router task by deleting it. delete pRouter ; // Stop the SipUserAgent. pSipUserAgent->shutdown(); // And delete it, too. delete pSipUserAgent ; // flush and close the call state event log if (enableCallStateLogObserver || enableCallStateDbObserver) { if (cseObserver) { delete cseObserver; } if (pEventWriter) { delete pEventWriter; } } // End the singleton threads. OsTimerTask::destroyTimerTask(); OsStunAgentTask::releaseInstance(); return 0 ; }
void testQueuePlayerManyDropCallRandom() { char szUrl[128] ; MpStreamQueuePlayer* pQPlayer ; MpStreamPlayer* pPlayer = NULL ; int i ; osPrintf("testQueuePlayerManyDropCallRandom\n") ; for (int j=0; j<TESTING_ATTEMPTS; j++) { pPlayer = NULL ; UtlString callId ; mCfg->getCallManager()->createCall(&callId) ; mCfg->getCallManager()->unholdAllTerminalConnections(callId) ; mCfg->getCallManager()->createPlayer(MpPlayer::STREAM_QUEUE_PLAYER, callId, NULL, STREAM_SOUND_LOCAL | STREAM_FORMAT_RAW, &pPlayer) ; pQPlayer = (MpStreamQueuePlayer*) pPlayer ; for (i=10; i>0; i--) { sprintf(szUrl, "http://%s/nums/%d.raw", BASE_URL, i) ; Url url(szUrl) ; pQPlayer->add(url, STREAM_SOUND_LOCAL | STREAM_FORMAT_RAW) ; } pQPlayer->play() ; int delay = abs(rand() % 5000) ; OsTask::delay(delay) ; mCfg->getCallManager()->drop(callId) ; for (i=0; i<8; i++) { switch (abs(rand() % 8)) { case 0: pQPlayer->play() ; break ; case 1: pQPlayer->wait() ; break ; case 2: pQPlayer->reset() ; break ; case 3: pQPlayer->clear() ; break ; default: { // It's not clear what this sprintf() should do, since // none of these URLs seem to be valid. // (See the top of include/test/mp/MpTestConfig.h.) sprintf(szUrl, "http://%s/nums/%d.raw", BASE_URL, i) ; Url url(szUrl) ; pQPlayer->add(url, STREAM_SOUND_LOCAL | STREAM_FORMAT_RAW); } break ; } } mCfg->getCallManager()->destroyPlayer(MpPlayer::STREAM_QUEUE_PLAYER, callId, pPlayer) ; OsTask::delay(500) ; } }
/** * Description: * closes any open connections to the IMDB safely using a mutex lock */ void initSysLog(OsConfigDb* pConfig) { UtlString consoleLogging; // Enable console logging by default? UtlString fileTarget; // Path to store log file. UtlBoolean bSpecifiedDirError ; // Set if the specified log dir does not // exist Os::LoggerHelper::instance().processName = "SipXProxy"; // // Get/Apply Log Filename // if ((pConfig->get(CONFIG_SETTING_LOG_DIR, fileTarget) != OS_SUCCESS) || fileTarget.isNull() || !OsFileSystem::exists(fileTarget)) { bSpecifiedDirError = !fileTarget.isNull() ; // If the log file directory exists use that, otherwise place the log // in the current directory OsPath workingDirectory; if (OsFileSystem::exists(CONFIG_LOG_DIR)) { fileTarget = CONFIG_LOG_DIR; OsPath path(fileTarget); path.getNativePath(workingDirectory); osPrintf("%s : %s\n", CONFIG_SETTING_LOG_DIR, workingDirectory.data()) ; Os::Logger::instance().log(FAC_SIP, PRI_INFO, "%s : %s", CONFIG_SETTING_LOG_DIR, workingDirectory.data()) ; } else { OsPath path; OsFileSystem::getWorkingDirectory(path); path.getNativePath(workingDirectory); osPrintf("%s : %s\n", CONFIG_SETTING_LOG_DIR, workingDirectory.data()) ; Os::Logger::instance().log(FAC_SIP, PRI_INFO, "%s : %s", CONFIG_SETTING_LOG_DIR, workingDirectory.data()) ; } fileTarget = workingDirectory + OsPathBase::separator + SIPX_PROXY_LOG_FILE; } else { bSpecifiedDirError = false ; osPrintf("%s : %s\n", CONFIG_SETTING_LOG_DIR, fileTarget.data()) ; Os::Logger::instance().log(FAC_SIP, PRI_INFO, "%s : %s", CONFIG_SETTING_LOG_DIR, fileTarget.data()) ; fileTarget = fileTarget + OsPathBase::separator + SIPX_PROXY_LOG_FILE; } // // Get/Apply Log Level // SipXecsService::setLogPriority( CONFIG_SETTINGS_FILE, PROXY_CONFIG_PREFIX ); Os::Logger::instance().setLoggingPriorityForFacility(FAC_SIP_INCOMING_PARSED, PRI_ERR); Os::LoggerHelper::instance().initialize(fileTarget.data()); // // Get/Apply console logging // UtlBoolean bConsoleLoggingEnabled = false ; if ((pConfig->get(CONFIG_SETTING_LOG_CONSOLE, consoleLogging) == OS_SUCCESS)) { consoleLogging.toUpper(); if (consoleLogging == "ENABLE") { Os::Logger::instance().enableConsoleOutput(true); bConsoleLoggingEnabled = true ; } } osPrintf("%s : %s\n", CONFIG_SETTING_LOG_CONSOLE, bConsoleLoggingEnabled ? "ENABLE" : "DISABLE") ; Os::Logger::instance().log(FAC_SIP, PRI_INFO, "%s : %s", CONFIG_SETTING_LOG_CONSOLE, bConsoleLoggingEnabled ? "ENABLE" : "DISABLE") ; if (bSpecifiedDirError) { Os::Logger::instance().log(FAC_LOG, PRI_CRIT, "Cannot access %s directory; please check configuration.", CONFIG_SETTING_LOG_DIR); } }
TaoStatus TaoListenerManager::addEventListener(const char* terminalName, UtlBoolean callListener) { if (terminalName) { OsWriteLock lock(mListenerRWLock); if (mListenerCnt > 0) // check if listener is already added. { for (int i = 0; i < mListenerCnt; i++) { if (mpListeners[i] && mpListeners[i]->mName.compareTo(terminalName) == 0) { mpListeners[i]->mRef++; return TAO_SUCCESS; } } } //create local event listener with proper terminal name TaoEventListener* pListener = new TaoEventListener(terminalName); if (pListener) { TaoObjHandle hSocket; if (TAO_NOT_FOUND == mpAgents->findValue(terminalName, hSocket)) { OsConnectionSocket* pConnectionSocket; pConnectionSocket = new OsConnectionSocket(DEF_TAO_EVENT_PORT, terminalName); mpConnectionSockets->insert(terminalName, (TaoObjHandle)pConnectionSocket); TaoTransportAgent *pAgent = new TaoTransportAgent(pConnectionSocket, this); mpAgents->insert(terminalName, (TaoObjHandle)pAgent); return TAO_SUCCESS; } // add to listenerDb TaoListenerDb *pListenerDb = new TaoListenerDb(); pListenerDb->mName = terminalName; pListenerDb->mpListenerPtr = (int) pListener; pListenerDb->mRef = 1; if (mListenerCnt == mMaxNumListeners) { osPrintf("***** INCREASING LISTENER COUNT in TaoListenerManager!\n"); //make more of em. mMaxNumListeners += 20; mpListeners = (TaoListenerDb **)realloc(mpListeners,sizeof(TaoListenerDb *)*mMaxNumListeners); for (int loop = mListenerCnt;loop < mMaxNumListeners;loop++) mpListeners[loop] = 0 ; } mpListeners[mListenerCnt++] = pListenerDb; if (!mListenerAdded && !callListener) { mpPhoneTask->addListener(this); mListenerAdded = true; } return(TAO_SUCCESS); } } return(TAO_FAILURE); }
int main(int argc, char* argv[]) { const char* configFileName = "siptest-config"; int proxyTcpPort; int proxyUdpPort; int proxyTlsPort; OsConfigDb configDb; // siptest uses osPrintf for output, so we have to un-suppress it. enableConsoleOutput(TRUE); if(configDb.loadFromFile(configFileName) == OS_SUCCESS) { osPrintf("Found config file: %s\n", configFileName); } else { configDb.set("SIP_TEST_UDP_PORT", "3000"); configDb.set("SIP_TEST_TCP_PORT", "3000"); configDb.set("SIP_TEST_TLS_PORT", "3001"); if(configDb.storeToFile(configFileName) == OS_SUCCESS) { osPrintf("Could not write config file: %s\n", configFileName); } } proxyUdpPort = configDb.getPort("SIP_TEST_UDP_PORT") ; proxyTcpPort = configDb.getPort("SIP_TEST_TCP_PORT") ; proxyTlsPort = configDb.getPort("SIP_TEST_TLS_PORT") ; UtlBoolean commandStatus = CommandProcessor::COMMAND_SUCCESS; char buffer[1024]; char* commandLine; CommandProcessor processor; SipLineMgr* lineMgr = new SipLineMgr(); SipRefreshMgr* refreshMgr = new SipRefreshMgr(); lineMgr->startLineMgr(); lineMgr->initializeRefreshMgr( refreshMgr ); SipUserAgent* sipUA = new SipUserAgent( proxyTcpPort ,proxyUdpPort ,proxyTlsPort ,NULL // default publicAddress ,NULL // default defaultUser ,NULL // default defaultSipAddress ,NULL // default sipProxyServers ,NULL // default sipDirectoryServers ,NULL // default sipRegistryServers ,NULL // default authenicateRealm ,NULL // default authenticateDb ,NULL // default authorizeUserIds ,NULL // default authorizePasswords ,lineMgr ); sipUA->allowMethod(SIP_REGISTER_METHOD); sipUA->allowMethod(SIP_SUBSCRIBE_METHOD); sipUA->allowMethod(SIP_NOTIFY_METHOD); sipUA->start(); sipUA->startMessageLog(); osPrintf( "SIP logging Started\n" ); refreshMgr->init( sipUA ); CommandMsgProcessor* msgProc = new CommandMsgProcessor(sipUA); msgProc->start(); processor.registerCommand("help", new HelpCommand(&processor)); processor.registerCommand("?", new HelpCommand(&processor)); processor.registerCommand("history", new HistoryCommand(&processor)); processor.registerCommand("send", new SipSendCommand(sipUA)); processor.registerCommand("lsend", new SipLSendCommand()); processor.registerCommand("get", new HttpGetCommand()); processor.registerCommand("respond", new RespondCommand(msgProc)); processor.registerCommand("rt", new RespondTemplate(msgProc)); processor.registerCommand("rrespond", new ResendResponse(msgProc)); processor.registerCommand("log", new SipLogCommand(*sipUA)); processor.registerCommand("auth", new AuthCommand(lineMgr)); processor.registerCommand("sleep", new SleepCommand()); processor.registerCommand("quit", new ExitCommand()); processor.registerCommand("exit", new ExitCommand()); //Initialization UtlBoolean doPrompt = isatty(STDIN_FILENO); if ( doPrompt ) { printf("Enter command or help/? for help\n"); printf("SIPdriver: "); } for ( commandStatus = CommandProcessor::COMMAND_SUCCESS; ( commandStatus < CommandProcessor::COMMAND_FAILED_EXIT && commandStatus != CommandProcessor::COMMAND_SUCCESS_EXIT && (commandLine = fgets(buffer,1024,stdin)) ); ) { //printf("GOT command line:\"%s\"\n", commandLine); commandStatus = processor.executeCommand(commandLine); //printf("command status: %d exit status: %d\n", commandStatus, //CommandProcessor::COMMAND_SUCCESS_EXIT); if ( doPrompt ) { printf("SIPdriver: "); } } delete msgProc; delete sipUA; return CommandProcessor::COMMAND_SUCCESS_EXIT != commandStatus; }
OsStatus OsProcessWnt::launch(UtlString &rAppName, UtlString parameters[],OsPath &startupDir, OsProcessPriorityClass prioClass, UtlBoolean bExeclusive, UtlBoolean bIgnoreChildSignals) { OsStatus retval = OS_FAILED; STARTUPINFO StartupInfo; PROCESS_INFORMATION ProcessInformation; UtlString cmdLine = startupDir + OsPath::separator; cmdLine += rAppName; /* int saved_stderr = dup(2); int saved_stdout = dup(1); int saved_stdin = dup(0); */ //build one string out of the array passed in int parameterCount = 0; while (!parameters[parameterCount].isNull()) { if(parameters[parameterCount].index(" ") != UTL_NOT_FOUND) parameters[parameterCount] = "\"" + parameters[parameterCount] + "\""; cmdLine.append(" "); cmdLine.append(parameters[parameterCount]); parameterCount++; } //clear out structure memset(&StartupInfo,'\0',sizeof(STARTUPINFO)); StartupInfo.cb = sizeof(STARTUPINFO); StartupInfo.lpReserved = NULL; StartupInfo.wShowWindow = SW_MINIMIZE|SW_HIDE; StartupInfo.lpDesktop = NULL; StartupInfo.lpTitle = NULL; StartupInfo.dwFlags |= STARTF_USESTDHANDLES; //now it's time to redirect the output,input and error streams if (mStdErrorFilename.length()) StartupInfo.hStdError = mStdErrorHandle; else StartupInfo.hStdError =GetStdHandle(STD_ERROR_HANDLE); if (mStdInputFilename.length()) StartupInfo.hStdInput = mStdInputHandle; else StartupInfo.hStdInput = GetStdHandle(STD_INPUT_HANDLE); if (mStdOutputFilename.length()) StartupInfo.hStdOutput = mStdOutputHandle; else StartupInfo.hStdOutput = GetStdHandle(STD_OUTPUT_HANDLE); //now apply the env variables the user may have set ApplyEnv(); //3...2...1... LAUNCH!!!! int retcode = CreateProcess( NULL, // name of executable module (null because we want to execute all commands) // even things such as dir (char *)cmdLine.data(), // command line string NULL, NULL, //this originally was TRUE but the web browser was never coming back. FALSE, // handle inheritance flag // CREATE_NEW_CONSOLE, CREATE_NO_WINDOW | DETACHED_PROCESS, // creation flags NULL, // new environment block startupDir.data(), // startupdir &StartupInfo, &ProcessInformation ); if (retcode != 0) { //translate the incoming priority to Wnt values DWORD wntPrio = NORMAL_PRIORITY_CLASS; switch(prioClass) { case IdlePriorityClass: wntPrio = IDLE_PRIORITY_CLASS; break; case NormalPriorityClass: wntPrio = NORMAL_PRIORITY_CLASS; break; case HighPriorityClass: wntPrio = HIGH_PRIORITY_CLASS; break; case RealtimePriorityClass: wntPrio = REALTIME_PRIORITY_CLASS; break; default: osPrintf("**** Invalid process priority class specified!\n"); osPrintf("*** Defaulting to NormalPriorityClass *** \n"); break; } if (!SetPriorityClass(ProcessInformation.hProcess, wntPrio)) { osPrintf("*** Could not change the process priority on launch ***\n"); osPrintf("*** Priority will be the parents priority ! ***\n"); } if (bExeclusive) { //here is where we check if a process by the same name is already running } mPID = ProcessInformation.dwProcessId; mParentPID = getpid(); mhProcess = ProcessInformation.hProcess; mhThread = ProcessInformation.hThread; retval = OS_SUCCESS; } else { LPVOID lpMsgBuf; FormatMessage( FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, GetLastError(), MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language (LPTSTR) &lpMsgBuf, 0, NULL ); osPrintf("***** ERROR FROM LAUNCH: %s",(LPCTSTR)lpMsgBuf); // Free the buffer. LocalFree( lpMsgBuf ); } /* dup2(saved_stderr,2); dup2(saved_stdout,1); dup2(saved_stdin, 0); */ return retval; }
// Set the string's storage capacity to the designated value. size_t UtlString::capacity(size_t N) { #ifdef _VXWORKS size_t maxFreeBlockSize = 0; #endif size_t newSize = 0; char* newData = 0; if(mCapacity < N && N > 0) { if(mCapacity + UTLSTRING_MIN_INCREMENT > N) { N = mCapacity + UTLSTRING_MIN_INCREMENT; } #ifdef _VXWORKS if (N > CHECK_BLOCK_THRESHOLD) { maxFreeBlockSize = FindMaxFreeBlock(); // We are not going over the largest block size then try to // allocate otherwise we will return NULL, and the size returned // will be zero! if (N < maxFreeBlockSize) { newData = new char[N]; } } else { newData = new char[N]; } #else //for all other OS's lets assume it really returns NULL and not crashes newData = new char[N]; #endif if (newData) { if(mSize > 0 && mpData) { memcpy(newData, mpData, mSize); } else { newData[0] = '\0'; } if(mpData && mpData != mBuiltIn) { delete[] mpData; } mpData = newData; newSize = mCapacity = N; } else { osPrintf("******** ERROR******* : UtlString::capacity failed (%"PRIuMAX"). Memory not allocated!\n", N); #ifdef _VXWORKS osPrintf("******** ERROR******* : Largest block = %"PRIuMAX", requested size = %"PRIuMAX"\n",maxFreeBlockSize, N); #endif newSize = 0; } } else { newSize = mCapacity; } return(newSize); }
int MpTopologyGraph::linkTopologyResources(MpResourceTopology& resourceTopology, UtlHashBag& newResources, UtlBoolean replaceNumInName, int resourceNum) { // Link the resources int connectionIndex = 0; UtlString outputResourceName; UtlString inputResourceName; int outputResourcePortIndex; int inputResourcePortIndex; MpResource* outputResource = NULL; MpResource* inputResource = NULL; OsStatus result; UtlHashMap newConnectionIds; #ifdef TEST_PRINT osPrintf("%d new resources in the list\n", newResources.entries()); UtlHashBagIterator iterator(newResources); MpResource* containerResource = NULL; while(containerResource = (MpResource*) iterator()) { osPrintf("found list resource: \"%s\" value: \"%s\"\n", containerResource->getName().data(), containerResource->data()); } #endif while(resourceTopology.getConnection(connectionIndex, outputResourceName, outputResourcePortIndex, inputResourceName, inputResourcePortIndex) == OS_SUCCESS) { if(replaceNumInName) { resourceTopology.replaceNumInName(outputResourceName, resourceNum); resourceTopology.replaceNumInName(inputResourceName, resourceNum); } // Look in the container of new resources first as this is more // efficient and new resources are not added immediately to a running // flowgraph outputResource = (MpResource*) newResources.find(&outputResourceName); if(outputResource == NULL) { result = lookupResource(outputResourceName, outputResource); if(result != OS_SUCCESS) { int virtPortIdx = outputResourcePortIndex>=0?outputResourcePortIndex:-1; int realPortIdx; result = lookupVirtualOutput(outputResourceName, virtPortIdx, outputResource, realPortIdx); if (result == OS_SUCCESS && outputResourcePortIndex>=0) { outputResourcePortIndex = realPortIdx; } } assert(result == OS_SUCCESS); } inputResource = (MpResource*) newResources.find(&inputResourceName); if(inputResource == NULL) { result = lookupResource(inputResourceName, inputResource); if(result != OS_SUCCESS) { int virtPortIdx = inputResourcePortIndex>=0?inputResourcePortIndex:-1; int realPortIdx; result = lookupVirtualInput(inputResourceName, virtPortIdx, inputResource, realPortIdx); if (result == OS_SUCCESS && inputResourcePortIndex>=0) { inputResourcePortIndex = realPortIdx; } } assert(result == OS_SUCCESS); } assert(outputResource); assert(inputResource); if(outputResource && inputResource) { if(outputResourcePortIndex == MpResourceTopology::MP_TOPOLOGY_NEXT_AVAILABLE_PORT) { outputResourcePortIndex = outputResource->reserveFirstUnconnectedOutput(); assert(outputResourcePortIndex >= 0); } else if(outputResourcePortIndex < MpResourceTopology::MP_TOPOLOGY_NEXT_AVAILABLE_PORT) { // First see if a real port is already in the dictionary UtlInt searchKey(outputResourcePortIndex); UtlInt* foundValue = NULL; if((foundValue = (UtlInt*) newConnectionIds.findValue(&searchKey))) { // Use the mapped index outputResourcePortIndex = foundValue->getValue(); } else { // Find an available port and add it to the map int realPortNum = outputResource->reserveFirstUnconnectedOutput(); assert(realPortNum >= 0); UtlInt* portKey = new UtlInt(outputResourcePortIndex); UtlInt* portValue = new UtlInt(realPortNum); newConnectionIds.insertKeyAndValue(portKey, portValue); outputResourcePortIndex = realPortNum; } } if(inputResourcePortIndex == MpResourceTopology::MP_TOPOLOGY_NEXT_AVAILABLE_PORT) { inputResourcePortIndex = inputResource->reserveFirstUnconnectedInput(); assert(inputResourcePortIndex >= 0); } else if(inputResourcePortIndex < MpResourceTopology::MP_TOPOLOGY_NEXT_AVAILABLE_PORT) { // First see if a real port is already in the dictionary UtlInt searchKey(inputResourcePortIndex); UtlInt* foundValue = NULL; if((foundValue = (UtlInt*) newConnectionIds.findValue(&searchKey))) { // Use the mapped index inputResourcePortIndex = foundValue->getValue(); } else { // Find an available port and add it to the map int realPortNum = inputResource->reserveFirstUnconnectedInput(); assert(realPortNum >= 0); UtlInt* portKey = new UtlInt(inputResourcePortIndex); UtlInt* portValue = new UtlInt(realPortNum); newConnectionIds.insertKeyAndValue(portKey, portValue); inputResourcePortIndex = realPortNum; } } result = addLink(*outputResource, outputResourcePortIndex, *inputResource, inputResourcePortIndex); assert(result == OS_SUCCESS); } connectionIndex++; } newConnectionIds.destroyAll(); return(connectionIndex); }
static WAVEHDR* outPrePrep(int n, DWORD bufLen) { WAVEHDR* pWH; int doAlloc = (hOutHdr[n] == NULL); MpBufferMsg* msg = NULL; MpBufferMsg* pFlush = NULL; MpBufPtr ob; static int oPP = 0; static MpBufPtr prev = NULL; // prev is for future concealment use static int concealed = 0; static int flushes = 0; static int skip = 0; assert((n > -1) && (n < N_OUT_BUFFERS)); #ifdef DEBUG_WINDOZE /* [ */ if (1) { static int spkQLen[1024]; int in = oPP % 1024; int i, j; spkQLen[in] = MpMisc.pSpkQ->numMsgs(); if (in == 1023) { osPrintf("\n\n Speaker Queue lengths [%d,%d]:\n ", oPP, frameCount); for (i=0; i<1024; i+=32) { for (j=i; j<(i+32); j++) { osPrintf("%3d", spkQLen[j]); } osPrintf("\n "); } osPrintf("\n\n"); } } #endif /* DEBUG_WINDOZE ] */ oPP++; #ifdef DEBUG_WINDOZE /* [ */ if (0 && (0 == (oPP % 1000))) { osPrintf("outPrePrep(): %d playbacks, %d flushes\n", oPP, flushes); } #endif /* DEBUG_WINDOZE ] */ while (MpMisc.pSpkQ && MprToSpkr::MAX_SPKR_BUFFERS < MpMisc.pSpkQ->numMsgs()) { OsStatus res; flushes++; res = MpMisc.pSpkQ->receive((OsMsg*&) pFlush, OsTime::NO_WAIT); if (OS_SUCCESS == res) { MpBuf_delRef(pFlush->getTag()); pFlush->releaseMsg(); } else { osPrintf("DmaTask: queue was full, now empty (4)!" " (res=%d)\n", res); } if (flushes > 100) { osPrintf("outPrePrep(): %d playbacks, %d flushes\n", oPP, flushes); flushes = 0; } } if (MpMisc.pSpkQ && (skip == 0) && (MprToSpkr::MIN_SPKR_BUFFERS > MpMisc.pSpkQ->numMsgs())) { skip = MprToSpkr::SKIP_SPKR_BUFFERS; assert(MprToSpkr::MAX_SPKR_BUFFERS >= skip); #ifdef DEBUG_WINDOZE /* [ */ osPrintf("Skip(%d,%d)\n", skip, oPP); #endif /* DEBUG_WINDOZE ] */ } ob = NULL; if (0 == skip) { if (MpMisc.pSpkQ && OS_SUCCESS == MpMisc.pSpkQ->receive((OsMsg*&)msg, OsTime::NO_WAIT)) { ob = msg->getTag(); msg->releaseMsg(); } } else { if (MpMisc.pSpkQ && MpMisc.pSpkQ->numMsgs() >= skip) skip = 0; } if (NULL == ob) { ob = conceal(prev, concealed); concealed++; } else { concealed = 0; } if (doAlloc) { hOutHdr[n] = GlobalAlloc(GPTR, sizeof(WAVEHDR)); assert(NULL != hOutHdr[n]); hOutBuf[n] = GlobalAlloc(GPTR, bufLen); assert(NULL != hOutBuf[n]); } pOutHdr[n] = pWH = (WAVEHDR*) GlobalLock(hOutHdr[n]); assert(NULL != pOutHdr[n]); pWH->lpData = (char*) GlobalLock(hOutBuf[n]); pWH->dwBufferLength = bufLen; pWH->dwUser = n; pWH->dwBytesRecorded = 0; pWH->dwFlags = 0; pWH->dwLoops = 0; pWH->lpNext = 0; pWH->reserved = 0; memcpy(pWH->lpData, MpBuf_getSamples(ob), bufLen); MpBuf_delRef(prev); prev = ob; return pWH; }
/** * * Method Name: ProcessSenderReport * * * Inputs: unsigned char *puchRTCPReport - A pointer to an RTCP Sender Report * * Outputs: None * * Returns: unsigned long * * Description: Takes the RTCP Sender Report passed and calls the CSenderReport * object's ISenderReport interface to parse the Sender packet and * extract the sender statistics contained therein. This method * shall also check for the presence of receiver reports within * the packet and call the CReceiverReport object's * IReceiverReport interface to parse and extract its contents. * Although no more than one receiver report is expected under the * current Pingtel call model, it is possible that multiple * receiver reports (one per PingTel source) may be sent. In this * case, a new CReceiverReport object shall be created and queued * if not already existing on the Receiver Report list. * * * Usage Notes: Notifications shall be generated to all subscribing parties to * inform them of the receipt of a new Source Report. The * notification shall contain the event type and a pointer to the * Source Report's IGetSenderStatistics interface. * * */ unsigned long CRTCPSource::ProcessSenderReport(unsigned char *puchRTCPReport) { unsigned long ulSenderSSRC = GetSenderSSRC(TRUE, puchRTCPReport); unsigned long ulReportCount = 0; unsigned long ulBytesProcessed; // Has a Sender Report object been instantiated for this participant? // Probably not, if this is the first Sender Report received in a session if(m_poSenderReport != NULL); // Create The Sender Report Class else if((m_poSenderReport = new CSenderReport(ulSenderSSRC, m_piSetReceiverStatistics)) == NULL) { osPrintf("**** FAILURE **** CRTCPSource::ProcessSenderReport() -" " Unable to create Inbound Sender Report Object\n"); return(GetReportLength(puchRTCPReport)); } // Initialize Sender Report Class else if(!m_poSenderReport->Initialize()) { // Release the Sender Report reference. This should cause the object // to be destroyed osPrintf("**** FAILURE **** CRTCPSource::ProcessSenderReport() -" " Unable to Initialize Inbound Sender Report Object\n"); ((ISenderReport *)m_poSenderReport)->Release(); return(GetReportLength(puchRTCPReport)); } // A Sender object exists to processes this report. Let's delegate to its // parsing methods to complete this report's processing. if((ulBytesProcessed = m_poSenderReport->ParseSenderReport(puchRTCPReport)) == 0) { osPrintf("**** FAILURE **** CRTCPSource::ProcessSenderReport() -" " Unable to Parse Inbound Sender Report\n"); return(GetReportLength(puchRTCPReport)); } // Let's check whether there are Receiver reports associated with this // Sender Report. If so, delegate to the Receiver Report's processing // method. else if((ulReportCount = m_poSenderReport->GetReportCount()) > 0) { unsigned long ulRRBytesProcessed = 0; // Send Event SendRTCPEvent(RTCP_SR_RCVD, (void *)m_poSenderReport); // Adjust the buffer so that it points to the beginning of the // reception report section. puchRTCPReport += ulBytesProcessed; // Call Receiver Report processing method. if((ulRRBytesProcessed = ProcessReceiverReport(puchRTCPReport, ulReportCount)) == 0) return(GetReportLength(puchRTCPReport)); // Bump Total Byte Processed ulBytesProcessed += ulRRBytesProcessed; } return(ulBytesProcessed); }
static int openSpeakerDevices(WAVEHDR*& pWH, HWAVEOUT& hOut) { DWORD bufLen = ((N_SAMPLES * BITS_PER_SAMPLE) / 8); int i ; MMRESULT ret; MSG tMsg; BOOL bSuccess ; // set the different device ids gRingDeviceId = WAVE_MAPPER; gCallDeviceId = WAVE_MAPPER; // If either the ringer or call device is set to NONE, don't engage any audio devices if ((stricmp(DmaTask::getRingDevice(), "NONE") == 0) || (stricmp(DmaTask::getCallDevice(), "NONE") == 0)) { ResumeThread(hMicThread); return 1; } /* * Select in-call / ringer devices */ int ii; WAVEOUTCAPS devcaps; int numberOfDevicesOnSystem = waveOutGetNumDevs(); for(ii=0; ii<numberOfDevicesOnSystem; ii++) { waveOutGetDevCaps(ii,&devcaps,sizeof(WAVEOUTCAPS)); if (strcmp(devcaps.szPname, DmaTask::getRingDevice())==0) { gRingDeviceId = ii; osPrintf("SpkrThread: Selected ring device: %s\n",devcaps.szPname); } if (strcmp(devcaps.szPname, DmaTask::getCallDevice())==0) { gCallDeviceId = ii; osPrintf("SpkrThread: Selected call device: %s\n",devcaps.szPname); } } /* * Open ringer device */ if (!openAudioOut(gRingDeviceId, &audioOutH, 1, SAMPLES_PER_SEC, BITS_PER_SAMPLE)) { osPrintf("SpkrThread: Failed to open ring audio output channel\n\n"); ResumeThread(hMicThread); return 1; } do { bSuccess = GetMessage(&tMsg, NULL, 0, 0) ; } while (bSuccess && (tMsg.message != WOM_OPEN)) ; /* * Open in-call device */ if (!openAudioOut(gCallDeviceId,&audioOutCallH, 1, SAMPLES_PER_SEC, BITS_PER_SAMPLE)) { osPrintf("SpkrThread: Failed to open call audio output channel\n\n"); ResumeThread(hMicThread); return 1; } do { bSuccess = GetMessage(&tMsg, NULL, 0, 0) ; } while (bSuccess && tMsg.message != WOM_OPEN) ; // Pre load some data for (i=0; i<smSpkrQPreload; i++) { pWH = outPrePrep(i, bufLen); hOut = selectSpeakerDevice() ; if (hOut) { ret = waveOutPrepareHeader(hOut, pWH, sizeof(WAVEHDR)); if (ret != MMSYSERR_NOERROR) { showWaveError("waveOutPrepareHeader", ret, i, __LINE__); } ret = waveOutWrite(hOut, pWH, sizeof(WAVEHDR)); if (ret != MMSYSERR_NOERROR) { showWaveError("waveOutWrite", ret, i, __LINE__); } } } return 0 ; }
/** * * Method Name: ProcessSDESReport * * * Inputs: unsigned char *puchRTCPReport * - pointer to an RTCP Source Description Report * * Outputs: None * * Returns: unsigned long * * Description: Takes the RTCP SDES Report passed and calls the * CSourceDescription object's ISDESReport interface to parse the * Source Description packet and extract the identification * information contained therein. * * * Usage Notes: A call connection to a Mixer would cause all SDES Reports to * be forward as multiple SDES Reports. In this case, a new * CSourceDescription object shall be created and queued if not * already existing on the SrcDescription list. The SSRC ID will * be used to determine uniqueness among reports. * * Notifications shall be generated to all subscribing parties to * inform them of the new Source Descriptions or changes in * previously existing Source Descriptions. The notification * shall contain the event type and a pointer to the new or * modified Source Description interface (IGetSrcDescription). */ unsigned long CRTCPSource::ProcessSDESReport(unsigned char *puchRTCPReport) { bool bRTCPHeader = TRUE; unsigned long ulEventMask = 0; unsigned long ulSDESLength = 0; unsigned long ulReportCount = 0; unsigned long ulSenderSSRC = 0; unsigned long ulReportSize = GetReportLength(puchRTCPReport); CSourceDescription *poSDESReport = NULL; // Pull the Report Count from the header so we no how many reports we need // to process ulReportCount = GetReportCount(puchRTCPReport); // Let's prepare to iterate through each reception report until complete while(ulReportCount > 0) { // Extract the corresponding SSRC with the knowledge that this report // comes with a full formed RTCP header. ulSenderSSRC = GetSenderSSRC(bRTCPHeader, puchRTCPReport); // Has a SDES Report object been instantiated for this participant? // Probably not, if this is the first SDES Report received in a session if((poSDESReport = m_tSrcDescriptorList.GetEntry(SDESSsrcComparitor, (void *)ulSenderSSRC)) != NULL); // Create The SDES Report object else if((poSDESReport = new CSourceDescription(ulSenderSSRC)) == NULL) { osPrintf("**** FAILURE **** CRTCPSource::ProcessSDESReport()" " - Unable to Create Inbound SDES Report Object\n"); return(ulReportSize); } // Initialize SDES Report object else if(!poSDESReport->Initialize()) { // Release the SDES Report reference. This should cause the // object to be destroyed osPrintf("**** FAILURE **** CRTCPSource::ProcessSDESReport()" " - Unable to Initialize Inbound SDES Report Object\n"); ((ISDESReport *)poSDESReport)->Release(); return(ulReportSize); } // Place the new SDES Report object on the collection list else if(!m_tSrcDescriptorList.AddEntry(poSDESReport)) { // Release the SDES Report reference. // This should cause the object to be destroyed osPrintf("**** FAILURE **** CRTCPSource::ProcessSDESReport()" " - Unable to Add SDES Report Object to Collection\n"); ((ISDESReport *)poSDESReport)->Release(); return(ulReportSize); } else { // Set the event mask to indicate that a new SDES was received ulEventMask |= RTCP_NEW_SDES; } // A SDES object exists to processes this report. Let's delegate to // its parsing methods to complete this report's processing. if((ulSDESLength = poSDESReport->ParseSDESReport(bRTCPHeader, puchRTCPReport)) == 0) { osPrintf("**** FAILURE **** CRTCPSource::ProcessSDESReport()" " - Unable to Parse Inbound SDES Report\n"); return(ulReportSize); } // We've made it through our first SDES report successfully and we must // adjust the flags, counts, and report pointers for the next go-round. bRTCPHeader = FALSE; puchRTCPReport += ulSDESLength; ulReportCount--; // Check whether any information has changed in an existing SDES Report ulEventMask |= RTCP_SDES_UPDATE; SendRTCPEvent(ulEventMask, (void *)poSDESReport, poSDESReport->GetChanges()); ulEventMask = 0; } return(ulReportSize); }
unsigned int __stdcall SpkrThread(LPVOID Unused) { int i; DWORD bufLen = ((N_SAMPLES * BITS_PER_SAMPLE) / 8); WAVEHDR* pWH; MMRESULT ret; int played; MSG tMsg; BOOL bGotMsg ; int n; bool bDone ; static bool sLastRingerEnabled = false; OsStatus res; static bool bRunning = false ; HWAVEOUT hOut = NULL; // Verify that only 1 instance of the MicThread is running if (bRunning) { ResumeThread(hMicThread); return 1 ; } else { bRunning = true ; } ResumeThread(hMicThread); #ifdef OHISTORY /* [ */ WAVEHDR* lastWH[OHISTORY]; int lastInd[OHISTORY]; int last = 0; for (i=0;i<OHISTORY;i++) { lastWH[i] = 0; lastInd[i] = 0; } memset(histOut, 0xff, sizeof(histOut)); lastOut = 0; #endif /* OHISTORY ] */ // Initialize headers for (i=0; i<N_OUT_BUFFERS; i++) { hOutHdr[i] = hOutBuf[i] = NULL; pOutHdr[i] = NULL; } if (openSpeakerDevices(pWH, hOut)) { // NOT using a sound card // Set up a 10ms timer to call back to this routine timeSetEvent(10, 0, TimerCallbackProc, GetCurrentThreadId(), TIME_PERIODIC); } played = 0; bDone = false ; while (!bDone) { bGotMsg = GetMessage(&tMsg, NULL, 0, 0); // when switching devices, ringer to in-call we need to make // sure any outstanding buffers are flushed if (sLastRingerEnabled != DmaTask::isRingerEnabled()) { if (audioOutH) { waveOutReset(audioOutH); } if (audioOutCallH) { waveOutReset(audioOutCallH); } } if (bGotMsg) { switch (tMsg.message) { case WM_ALT_HEARTBEAT: res = MpMediaTask::signalFrameStart(); switch (res) { case OS_SUCCESS: frameCount++; break; case OS_LIMIT_REACHED: case OS_WAIT_TIMEOUT: case OS_ALREADY_SIGNALED: default: // Should bump missed frame statistic break; } break ; case WOM_DONE: pWH = (WAVEHDR *) tMsg.wParam; n = (pWH->dwUser) & USER_BUFFER_MASK; #ifdef OHISTORY /* [ */ lastWH[last] = pWH; lastInd[last] = n; last = (last + 1) % OHISTORY; if (N_OUT_BUFFERS == played) { osPrintf("after first %d buffers:", played + 1); osPrintf("\nCall Backs:"); for (i=0; i<OHISTORY; i++) { osPrintf("%c%3d", (0 == (i % 20)) ? '\n' : ' ', histOut[i]); } osPrintf("\n\nMessages:"); for (i=0; i<OHISTORY; i++) { osPrintf("%c%3d", (0 == (i % 20)) ? '\n' : ' ', lastInd[i]); } osPrintf("\n"); } #endif /* OHISTORY ] */ if (DmaTask::isOutputDeviceChanged()) { DmaTask::clearOutputDeviceChanged() ; closeSpeakerDevices() ; if (openSpeakerDevices(pWH, hOut)) { timeSetEvent(10, 0, TimerCallbackProc, GetCurrentThreadId(), TIME_PERIODIC); } continue ; } hOut = selectSpeakerDevice() ; if (hOut) { ret = waveOutUnprepareHeader(hOut, pWH, sizeof(WAVEHDR)); if (ret != MMSYSERR_NOERROR) { showWaveError("waveOutUnprepareHeader", ret, played, __LINE__); } outPostUnprep(n, false); pWH = outPrePrep(n, bufLen); ret = waveOutPrepareHeader(hOut, pWH, sizeof(WAVEHDR)); if (ret != MMSYSERR_NOERROR) { showWaveError("waveOutPrepareHeader", ret, played, __LINE__); } ret = waveOutWrite(hOut, pWH, sizeof(WAVEHDR)); if (ret != MMSYSERR_NOERROR) { showWaveError("waveOutWrite", ret, played, __LINE__); /* RL < */ if (ret == MMSYSERR_NODRIVER) { closeSpeakerDevices() ; if (openSpeakerDevices(pWH, hOut)) { timeSetEvent(10, 0, TimerCallbackProc, GetCurrentThreadId(), TIME_PERIODIC); } continue; } /* RL > */ } played++; } res = MpMediaTask::signalFrameStart(); switch (res) { case OS_SUCCESS: frameCount++; break; #ifdef DEBUG_WINDOZE /* [ */ case OS_LIMIT_REACHED: // Should bump missed frame statistic osPrintf(" Frame %d: OS_LIMIT_REACHED\n", frameCount); break; case OS_WAIT_TIMEOUT: // Should bump missed frame statistic osPrintf(" Frame %d: OS_WAIT_TIMEOUT\n", frameCount); break; case OS_ALREADY_SIGNALED: // Should bump missed frame statistic osPrintf(" Frame %d: OS_ALREADY_SIGNALED\n", frameCount); break; default: osPrintf("Frame %d, signalFrameStart() returned %d\n", frameCount, res); break; #else /* DEBUG_WINDOZE ] [ */ case OS_LIMIT_REACHED: case OS_WAIT_TIMEOUT: case OS_ALREADY_SIGNALED: default: // Should bump missed frame statistic break; #endif /* DEBUG_WINDOZE ] */ } break; case WOM_CLOSE: // Audio device was closed on us (doesn't happen as far as I // know) bDone = true ; break; default: break; } } else { // Sky is falling, kick out so that we don't spin a high priority // thread. bDone = true ; } // record our last ringer state sLastRingerEnabled = DmaTask::isRingerEnabled(); } closeSpeakerDevices() ; bRunning = false ; return 0; }
void SipUserAgentStateless::logMessage(const char* message, int messageLength) { osPrintf("%s", message); }
UtlBoolean OsDatagramSocket::reconnect() { osPrintf("WARNING: reconnect NOT implemented!\n"); return(FALSE); }