void testOverflow() { OsTimeLog log(3); UtlString results; results.append("Entries"); log.addEvent("event 1"); log.addEvent("event 2"); log.addEvent("event 3"); log.addEvent("event 4"); log.addEvent("event 5"); log.getLogString(results); size_t hasNoEventsMsg = results.index("No Events Logged"); CPPUNIT_ASSERT(hasNoEventsMsg == UTL_NOT_FOUND); size_t hasOverflowMsg = results.index("Overflow"); CPPUNIT_ASSERT(hasOverflowMsg != UTL_NOT_FOUND); size_t hasOverflowCount = results.index("2 events lost"); CPPUNIT_ASSERT(hasOverflowCount != UTL_NOT_FOUND); SHOWLOG(log); }
// If this is an expires line, then modify it by adding timeNow to the expiration time value. // Otherwise don't mess with it. void RegistrationDbTestContext::timeShiftExpiresLine(UtlString& line, long timeNow) { const char* EXPIRES_BEGIN = "<expires>"; const int EXPIRES_TAG_LENGTH = 9; const char* EXPIRES_END = "</expires>"; ssize_t pos1, pos2; // If the line has an expiration value, then time-shift it if (((pos1 = line.index(EXPIRES_BEGIN)) != UTL_NOT_FOUND) && ((pos2 = line.index(EXPIRES_END)) != UTL_NOT_FOUND)) { pos1 += EXPIRES_TAG_LENGTH; // skip past the tag, to the expires value CPPUNIT_ASSERT(pos2 > pos1); // expires value cannot be empty UtlString timeText(line(pos1, pos2 - pos1)); char* endptr = NULL; long timeNumber = strtol(timeText, &endptr, 10); CPPUNIT_ASSERT_EQUAL(*endptr, '\0'); char newTime[20]; // room for up to a 64-bit number, may have minus sign int newTimeLen = sprintf(newTime, "%ld", timeNow + timeNumber); CPPUNIT_ASSERT(newTimeLen > 0); // Replace the old expiration value with the new shifted value UtlString lineEnd(line(pos2, line.length() - pos2)); line.replace(pos1, newTimeLen, newTime); line.replace(pos1 + newTimeLen, lineEnd.length(), lineEnd); } }
void testGetDriverNameVersion() { UtlString goodname = MpAudioDriverFactory::getDriverNameVersion(MpAudioDriverFactory::AUDIO_DRIVER_PORTAUDIO); printf("Portaudio name and version is: %s\n", goodname.data()); CPPUNIT_ASSERT(goodname.index("error", 0, UtlString::ignoreCase) == UTL_NOT_FOUND); UtlString badname = MpAudioDriverFactory::getDriverNameVersion(MpAudioDriverFactory::AUDIO_DRIVER_LAST); CPPUNIT_ASSERT(badname.index("error", 0, UtlString::ignoreCase) != UTL_NOT_FOUND); }
void CallStateEventBuilder_DB::replaceSingleQuotes(const UtlString& value, UtlString& newValue) { size_t startIndex = 0; ssize_t newIndex = 0; newValue = value; newIndex = newValue.index('\'', startIndex); while ((newIndex = newValue.index('\'', startIndex)) != UTL_NOT_FOUND) { startIndex = newIndex + 2; newValue = newValue.replace(newIndex, 1, "\\'"); } }
// Static callback routine used to find and replace variable string values in // subscription content. // For example the NOTIFY message in the SIP stack contains "&version;" rather // than an actual version number [like "22"]. // The content provided by publish() provides the "context // independent" part of the content, and the SIP stack keeps knowledge // of the version number sequence for each subscription. This // callback combines these sources of information. UtlBoolean SipSubscribeServer::standardVersionCallback(SipMessage& notifyRequest, int version) { // Search and replace the version number in the Notify. UtlBoolean result = FALSE; if (notifyRequest.getBody() != NULL) { UtlString msgBytes; ssize_t msgLength; // Extract the NOTIFY body as a UtlString. notifyRequest.getBody()->getBytes(&msgBytes, &msgLength); const char* contentType = notifyRequest.getBody()->getContentType(); // Look for the placeholder for the version number, "&version;". ssize_t msgIndex = msgBytes.index(VERSION_PLACEHOLDER); if (msgIndex != UTL_NOT_FOUND) { char buffer[20]; sprintf(buffer, "%d", version); msgBytes.replace(msgIndex, sizeof (VERSION_PLACEHOLDER) - 1, buffer); HttpBody* tempBody = new HttpBody(msgBytes.data(), msgBytes.length(), contentType); // Write the new message contents (this deletes the old body) notifyRequest.setBody(tempBody); result = TRUE; } } return result; }
OsStatus CpPhoneMediaInterface::playAudio(const char* url, UtlBoolean repeat, UtlBoolean local, UtlBoolean remote) { OsStatus returnCode = OS_NOT_FOUND; UtlString urlString; if(url) urlString.append(url); int fileIndex = urlString.index("file://"); if(fileIndex == 0) urlString.remove(0, 6); if(mpFlowGraph && !urlString.isNull()) { // Start playing the audio file returnCode = mpFlowGraph->playFile(urlString.data(), repeat, remote ? MpCallFlowGraph::TONE_TO_NET : MpCallFlowGraph::TONE_TO_SPKR); } if(returnCode != OS_SUCCESS) { osPrintf("Cannot play audio file: %s\n", urlString.data()); } return(returnCode); }
UtlBoolean TaoEventDispatcher::handleMessage(OsMsg& rMsg) { UtlBoolean handled = FALSE; switch (rMsg.getMsgSubType()) { 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: { TaoObjHandle handle = ((TaoMessage &)rMsg).getTaoObjHandle(); int data = ((TaoMessage &)rMsg).getArgCnt(); mpProviderEvent->setIntData(data); data = ((TaoMessage &)rMsg).getCmd(); mpProviderEvent->setIntData2(data); UtlString argList = ((TaoMessage &)rMsg).getArgList(); // need to convert to ints and find a way to pass to the app argList.index(TAOMESSAGE_DELIMITER, 0); mpProviderEvent->setStringData(argList); mpProviderEvent->signal((int) handle); handled = TRUE; break; } case TaoMessage::UNSPECIFIED: default: //assert(FALSE); break; } return handled; }
void sipXTabbedCodecPage::OnSelect(wxCommandEvent &event) { wxArrayInt selections; UtlString s; int index; if (!mbCodecByName) { int numSels = mpCodecList->GetSelections(selections); if (numSels) { mCodecName = ""; for (int i=0; i<numSels; i++) { s = mpCodecList->GetString(selections[i]); if ((index = s.index(" ")) != UTL_NOT_FOUND) { // Only get name up to first space s = s.remove(index, s.length() - index); } mCodecName = mCodecName + s + " "; } mbCodecByName = true; mpCodecPref->Append("By name:"); mpCodecPref->SetSelection(3); mCodecPref = 3; sipXmgr::getInstance().setAudioCodecByName((const char *)mCodecName.data()); rebuildCodecList(0); } } }
bool cAlarmServer::loadAlarmStrings(const UtlString& stringsFile) { // load file in English for fallback bool loadResult = loadAlarmStringsFile(stringsFile); // load localized version if available if (!mLanguage.isNull() && mLanguage.compareTo("en")) { UtlString localStringsFile = stringsFile; ssize_t pos = localStringsFile.index(".xml"); if (pos != UTL_NOT_FOUND) { // append language to string file name UtlString langSuffix = mLanguage; langSuffix.insert(0, "_"); localStringsFile = localStringsFile.insert(pos, langSuffix); loadResult = loadAlarmStringsFile(localStringsFile); } else { OsSysLog::add(FAC_ALARM, PRI_NOTICE, "stringsFile %s is not .xml, not loading local language", stringsFile.data()); loadResult = false; } } return loadResult; }
void SipRedirectorPresenceRouting::removeNonVoicemailContacts( ContactList& contactList ) { // walk the list to find the contact entry for voicemail size_t index; Url contactUrl; bool bVoicemailContactFound = false; for( index = 0; index < contactList.entries(); index++ ) { if( contactList.get( index, contactUrl ) ) { UtlString userPart; contactUrl.getUserId( userPart ); if( userPart.index( VOICEMAIL_CONTACT_PREFIX ) == 0 ) { bVoicemailContactFound = true; break; } } } // if vm contact found, remove all and put vm contact back in. if( bVoicemailContactFound ) { contactList.removeAll( *this ); contactList.add( contactUrl, *this ); } }
RedirectPlugin::LookUpStatus SipRedirectorUserParam::lookUp( const SipMessage& message, const UtlString& requestString, const Url& requestUri, const UtlString& method, ContactList& contactList, RequestSeqNo requestSeqNo, int redirectorNo, SipRedirectorPrivateStorage*& privateStorage, ErrorDescriptor& errorDescriptor) { if (mStripAll) { if (SipRedirectServer::getInstance()->sipUserAgent()->isMyHostAlias(requestUri)) { UtlString userpart; requestUri.getUserId(userpart); ssize_t semiColonIndex; if ((semiColonIndex = userpart.index(';')) != UTL_NOT_FOUND) { UtlString strippedUser(userpart); strippedUser.remove(semiColonIndex); Url strippedUrl(requestUri); strippedUrl.setUserId(strippedUser); OsSysLog::add(FAC_SIP, PRI_INFO, "%s::lookUp stripped parameters from '%s' -> '%s'", mLogName.data(), userpart.data(), strippedUser.data()); contactList.add(strippedUrl, *this); } } else { if (OsSysLog::willLog(FAC_SIP, PRI_DEBUG)) { UtlString logUri; requestUri.getUri(logUri); OsSysLog::add(FAC_SIP, PRI_DEBUG, "%s::lookUp '%s' not in my domain - not modified", mLogName.data(), logUri.data()); } } } else { OsSysLog::add(FAC_SIP, PRI_DEBUG, "%s::lookUp disabled by configuration", mLogName.data()); } return RedirectPlugin::SUCCESS; }
// Swap the tags in a dialog handle. void ResourceListSet::swapTags(const UtlString& dialogHandle, UtlString& swappedDialogHandle) { // Find the commas in the dialogHandle. ssize_t index1 = dialogHandle.index(','); ssize_t index2 = dialogHandle.index(',', index1+1); // Copy the call-Id and the first comma. swappedDialogHandle.remove(0); swappedDialogHandle.append(dialogHandle, index1+1); // Copy the second tag. swappedDialogHandle.append(dialogHandle, index2+1, dialogHandle.length() - (index2+1)); // Copy the first comma and the first tag. swappedDialogHandle.append(dialogHandle, index1, index2-index1); }
void testEntries() { OsTimeLog log; UtlString results; results.append("Entries"); log.addEvent("event 1"); log.addEvent("event 2"); log.addEvent("event 3"); log.addEvent("event 4"); log.addEvent("event 5"); log.getLogString(results); size_t hasNoEventsMsg = results.index("No Events Logged"); CPPUNIT_ASSERT(hasNoEventsMsg == UTL_NOT_FOUND); size_t hasEventMsg = results.index("event 2"); CPPUNIT_ASSERT(hasEventMsg != UTL_NOT_FOUND); SHOWLOG(log); }
RedirectPlugin::LookUpStatus SipRedirectorJoin::lookUp( const SipMessage& message, const UtlString& requestString, const Url& requestUri, const UtlString& method, ContactList& contactList, RedirectPlugin::RequestSeqNo requestSeqNo, int redirectorNo, SipRedirectorPrivateStorage*& privateStorage, ErrorDescriptor& errorDescriptor) { UtlString userId; UtlString incomingCallId; requestUri.getUserId(userId); message.getCallIdField(&incomingCallId); if (!mCallJoinCode.isNull() && userId.length() > mCallJoinCode.length() && userId.index(mCallJoinCode.data()) == 0 && userId.compareTo(mExcludedUser1) != 0 && userId.compareTo(mExcludedUser2) != 0) { return lookUpDialog(requestString, incomingCallId, contactList, requestSeqNo, redirectorNo, privateStorage, // The suffix of the request URI after the // directed call pick-up code. userId.data() + mCallJoinCode.length(), // Only examine confirmed dialogs. stateConfirmed); } else { // We do not recognize the user, so we do nothing. return RedirectPlugin::SUCCESS; } }
// Extract the contents of an HttpBody. UtlString extract_contents(HttpBody* body) { UtlString res; res.append("Content-Type: "); res.append(body->getContentType()); res.append("\r\n\r\n"); res.append(body->getBytes()); // Replace the boundary string with "[boundary]". const char* boundary_string = body->getMultipartBoundary(); ssize_t location; while ((location = res.index(boundary_string)) != UTL_NOT_FOUND) { res.replace(location, strlen(boundary_string), "[boundary]"); } return res; }
// Dump the object's internal state. void ContactSet::dumpState() { // indented 8, 10, and 12 OsSysLog::add(FAC_RLS, PRI_INFO, "\t ContactSet %p mUri = '%s', mSubscriptionEarlyDialogHandle = '%s'", this, mUri.data(), mSubscriptionEarlyDialogHandle.data()); UtlHashMapIterator itor(mSubscriptions); UtlString* handle; while ((handle = dynamic_cast <UtlString*> (itor()))) { UtlHashMap* h = dynamic_cast <UtlHashMap*> (itor.value()); OsSysLog::add(FAC_RLS, PRI_INFO, "\t mSubscriptions{'%s'} %p", handle->data(), h); UtlHashMapIterator itor2(*h); UtlString* id; while ((id = dynamic_cast <UtlString*> (itor2()))) { UtlString* value = dynamic_cast <UtlString*> (itor2.value()); int semi = value->index(';'); if (semi == UTL_NOT_FOUND) { semi = value->length(); } const char* v = value->data(); OsSysLog::add(FAC_RLS, PRI_INFO, "\t id = '%s', Call-Id = '%.*s', URI = '%s'", id->data(), semi, v, v + semi + 1); } } UtlHashMapIterator itor3(mSubscriptionSets); while ((handle = dynamic_cast <UtlString*> (itor3()))) { SubscriptionSet* ss = dynamic_cast <SubscriptionSet*> (itor3.value()); ss->dumpState(); } }
bool UnifiedPresenceChangedMethod::execute(const HttpRequestContext& requestContext, UtlSList& params, void* userData, XmlRpcResponse& response, ExecutionStatus& status) { status = XmlRpcMethod::FAILED; if( params.entries() == 6 ) { // According to set XML-RPC i/f definition: //param[0] = XMPP Presence //param[1] = Jabber ID; //param[2] = SIP AOR; //param[3] = SIP State; //param[4] = Unified Presence; //param[5] = XMPP Status Message; UnifiedPresence* pUp = new UnifiedPresence( ((UtlString*)params.at(2))->data() ); pUp->setXmppPresence ( ((UtlString*)params.at(0))->data() ); pUp->setXmppStatusMessage( ((UtlString*)params.at(5))->data() ); pUp->setSipState ( ((UtlString*)params.at(3))->data() ); pUp->setUnifiedPresence ( ((UtlString*)params.at(4))->data() ); UtlString* pAor = new UtlString( ((UtlString*)params.at(2))->data() ); // make sure that the SIP AOR really has a domain part; if not, add it. if( pAor->index('@') == UTL_NOT_FOUND ) { pAor->append( '@' ); pAor->append( SipRedirectorPresenceRouting::getLocalDomainName() ); } UnifiedPresenceContainer::getInstance()->insert( pAor, pUp ); } UtlString responseString = "ok"; response.setResponse( &responseString ); status = XmlRpcMethod::OK; return true; }
void getMessageData(UtlString& content, UtlBoolean isOutgoing, UtlString& date, UtlString& hostname, UtlString& eventCount, int outputFileDescriptor) { UtlString remoteHost; UtlString remoteAddress; UtlString remotePort; UtlString remoteSourceAddress; UtlString message; UtlString branchId; UtlString transactionId; UtlString method; UtlString responseCode; UtlString responseText; UtlBoolean failed = FALSE; int hostIndex = content.index("----Remote Host:"); if(hostIndex > 0) { hostIndex += 16; int hostEnd = content.index("----", hostIndex); remoteHost.append(&(content.data()[hostIndex]), hostEnd - hostIndex); remoteAddress = remoteHost; remoteHost.append(":"); int portIndex = hostEnd + 11; int portEnd = content.index("----", portIndex); remotePort.append(&(content.data()[portIndex]), portEnd - portIndex); remoteHost.append(remotePort); int messageIndex = portEnd + 5; size_t messageEnd; if(isOutgoing) { messageEnd = content.index("--------------------END", messageIndex); // Record whether the send failed or not. failed = (content.index("User Agent failed to send message") != UTL_NOT_FOUND); } else { messageEnd = content.index("====================END", messageIndex); } if ( UTL_NOT_FOUND == messageEnd ) { messageEnd = content.length(); } message.append(&(content.data()[messageIndex]), messageEnd - messageIndex); SipMessage sipMsg(message); remoteSourceAddress = remoteHost; if(sipMsg.isResponse()) { sipMsg.getFirstHeaderLinePart(1, &responseCode); if (failed) { responseCode = responseCode + " FAILED"; } sipMsg.getFirstHeaderLinePart(2, &responseText); } else { // Get the method. sipMsg.getRequestMethod(&method); // If it is a re-INVITE, make that clear. if (method.compareTo("INVITE", UtlString::ignoreCase) == 0) { Url to; sipMsg.getToUrl(to); UtlString toTag; to.getFieldParameter("tag", toTag); if (!toTag.isNull()) { method = "re-INVITE"; } } // Prepend FAILED if it is a failed transmission. if (failed) { method = "FAILED " + method; } //We can derive the source entity from the via in // incoming requests if(!isOutgoing) { UtlString viaAddress; UtlString protocol; int viaPortNum; sipMsg.getLastVia(&viaAddress, &viaPortNum, &protocol); char numBuff[30]; sprintf(numBuff, "%d", viaPortNum); UtlString viaPort(numBuff); remoteHost = remoteAddress + ":" + viaPort; } } // transaction token: cseq,call-id,from-tag,to=tag int cseq; UtlString cseqMethod; sipMsg.getCSeqField(&cseq, &cseqMethod); char numBuf[20]; sprintf(numBuf, "%d", cseq); UtlString callId; sipMsg.getCallIdField(&callId); Url to; sipMsg.getToUrl(to); UtlString toTag; to.getFieldParameter("tag", toTag); Url from; sipMsg.getFromUrl(from); UtlString fromTag; from.getFieldParameter("tag", fromTag); transactionId = numBuf; transactionId.append(","); transactionId.append(callId); transactionId.append(","); transactionId.append(fromTag); transactionId.append(","); transactionId.append(toTag); // Write all the stuff out // Write out the node container start writeBranchNodeBegin(outputFileDescriptor); // Write out the branchId container start writeBranchSetBegin(outputFileDescriptor); // Write out the branchIds int viaIndex = 0; UtlString topVia; while(sipMsg.getViaFieldSubField(&topVia, viaIndex)) { SipMessage::getViaTag(topVia.data(), "branch", branchId); writeBranchId(outputFileDescriptor, branchId); viaIndex++; } // Write out the branchId container finish writeBranchSetEnd(outputFileDescriptor); // Write out the rest of the node data writeBranchNodeData(outputFileDescriptor, date, isOutgoing ? hostname : remoteHost, isOutgoing ? remoteHost : hostname, isOutgoing ? hostname : remoteSourceAddress, isOutgoing ? remoteSourceAddress : hostname, transactionId, eventCount, method, responseCode, responseText, message); // Write out the node container finish writeBranchNodeEnd(outputFileDescriptor); } }
int HttpGetCommand::execute(int argc, char* argv[]) { int commandStatus = CommandProcessor::COMMAND_FAILED; if(argc == 2) { commandStatus = CommandProcessor::COMMAND_SUCCESS; const char* url = argv[1]; const char* serverBegin = strstr(url, "http://"); if(serverBegin != url) { printf("unsupported protocol in Url: %s\n", url); commandStatus = CommandProcessor::COMMAND_BAD_SYNTAX; } else { serverBegin += 7; UtlString uri(serverBegin); int serverEndIndex = uri.index("/"); if(serverEndIndex < 0) serverEndIndex = uri.length(); if(serverEndIndex > 0) { UtlString server = uri; server.remove(serverEndIndex); int portIndex = server.index(":"); int port = PORT_NONE; if(portIndex > 0) { UtlString portString = server; server.remove(portIndex); portString.remove(0, portIndex + 1); printf("port string: %s\n", portString.data()); port = atoi(portString.data()); } uri.remove(0, serverEndIndex); if(uri.isNull()) uri = "/"; printf("HTTP get of %s from server %s port: %d\n", uri.data(), server.data(), port); if (!portIsValid(port)) { port = 80; printf("defaulting to http port 80\n"); } OsConnectionSocket getSocket(port, server.data()); HttpMessage getRequest; getRequest.setFirstHeaderLine("GET", uri.data(), HTTP_PROTOCOL_VERSION); int wroteBytes = getRequest.write(&getSocket); printf("wrote %d\n", wroteBytes); HttpMessage getResponse; getResponse.read(&getSocket); UtlString responseBytes; int responseLength; getResponse.getBytes(&responseBytes, &responseLength); printf("Got %d bytes\n", responseLength); printf("Response: ++++++++++++++++++++++++++++++++++\n%s\n", responseBytes.data()); } else { printf("invalid server in Url: %s\n", url); commandStatus = CommandProcessor::COMMAND_BAD_SYNTAX; } } } else { UtlString usage; getUsage(argv[0], &usage); printf("%s", usage.data()); commandStatus = CommandProcessor::COMMAND_BAD_SYNTAX; //commandStatus = CommandProcessor::COMMAND_FAILED; } return(commandStatus); }
AuthPlugin::AuthResult CallerAlias::authorizeAndModify(const UtlString& id, /**< The authenticated identity of the * request originator, if any (the null * string if not). * This is in the form of a SIP uri * identity value as used in the * credentials database (user@domain) * without the scheme or any parameters. */ const Url& requestUri, ///< parsed target Uri RouteState& routeState, ///< the state for this request. const UtlString& method,///< the request method AuthResult priorResult,///< results from earlier plugins. SipMessage& request, ///< see AuthPlugin regarding modifying bool bSpiralingRequest, ///< spiraling indication UtlString& reason ///< rejection reason ) { // get the call-id to use in logging UtlString callId; request.getCallIdField(&callId); if ( (priorResult != DENY) // no point in modifying a request that won't be sent ) { UtlString callerFrom; UtlString callerFromTagOffsetStr; UtlString aliasFrom; UtlString aliasFromTagOffsetStr; UtlString originalFromTag; if ( !routeState.getParameter(mInstanceName.data(), CALLER_FROM_PARAM, callerFrom) || !routeState.getParameter(mInstanceName.data(), CALLER_TAG_OFFSET_PARAM, callerFromTagOffsetStr) || !routeState.getParameter(mInstanceName.data(), ALIAS_FROM_PARAM, aliasFrom) || !routeState.getParameter(mInstanceName.data(), ALIAS_TAG_OFFSET_PARAM, aliasFromTagOffsetStr) || !routeState.originalCallerFromTagValue(mInstanceName.data(), originalFromTag) ) { if ( routeState.isMutable() && routeState.directionIsCallerToCalled(mInstanceName.data()) ) // a new dialog? { /* * Get the callers identity by getting the caller URI and: * remove all parameters * remove the scheme name */ UtlString callerIdentity; UtlString originalFromField; request.getFromField(&originalFromField); Url originalFromUrl(originalFromField); /* * Extract the from identity as a key for the caller alias table * Start with the From header field (someday we should use the Identity if present) */ Url fromUrl(originalFromUrl); fromUrl.removeParameters(); // parameters are not relevant for this Url::Scheme fromUrlScheme = fromUrl.getScheme(); switch (fromUrlScheme) { case Url::SipsUrlScheme: // sips and sip are equivalent for identity purposes, // so just set to sip fromUrl.setScheme(Url::SipUrlScheme); // and fall through to extract the identity... case Url::SipUrlScheme: // case Url::TelUrlScheme: will go here, since 'tel' and 'sip' are the same length fromUrl.getUri(callerIdentity); callerIdentity.remove(0,4 /* strlen("sip:") */); // strip off the scheme name break; default: // for all other schemes, treat identity as null Os::Logger::instance().log(FAC_SIP, PRI_WARNING, "CallerAlias[%s]::check4andApplyAlias From uses unsupported scheme '%s'" " - using null identity", mInstanceName.data(), Url::schemeName(fromUrlScheme) ); break; } /* * Determine whether the identity is one for which this proxy * is authoritative; if not, we will not use wildcard matches. */ bool identityIsLocal = mpSipRouter->isLocalDomain(fromUrl); // now we have callerIdentity set; use for looking up each contact. Os::Logger::instance().log(FAC_SIP, PRI_DEBUG, "CallerAlias[%s]::check4andApplyAlias " "\n caller '%s' %s", mInstanceName.data(), callerIdentity.data(), identityIsLocal ? "is local" : "is not local" ); /* * Examine the request URI, * checking for a caller alias set for its domain(including asssociated gateway sipxecsLineid) with callerIdentity */ UtlString sipxecsLineIdField; requestUri.getUrlParameter(SIPX_SIPXECS_LINEID_URI_PARAM, sipxecsLineIdField); Os::Logger::instance().log(FAC_SIP, PRI_DEBUG, "getUrlParameter: sipxecsLineid[%s]" " in CallerAlias", sipxecsLineIdField.data() ); UtlString targetDomain; requestUri.getHostWithPort(targetDomain); if (!(sipxecsLineIdField.isNull())) { targetDomain.append(";").append(SIPX_SIPXECS_LINEID_URI_PARAM).append("=").append(sipxecsLineIdField.data()); } Os::Logger::instance().log(FAC_SIP, PRI_DEBUG, "CallerAlias::targetDomain [%s]", targetDomain.data() ); // look up any caller alias for this identity and contact domain UtlString callerAlias; if (identityIsLocal && getCallerAlias(callerIdentity, targetDomain, callerAlias) ) { // found a caller alias, so rewrite the From information /* * The From header requires special handling * - we need to preserve the tag, if any, from the original header */ originalFromUrl.getFieldParameter("tag", originalFromTag); Url newFromUrl(callerAlias.data()); newFromUrl.removeFieldParameter("tag"); // specifying a tag is a no-no if ( !originalFromTag.isNull() ) { newFromUrl.setFieldParameter("tag", originalFromTag.data()); } UtlString newFromFieldValue; newFromUrl.toString(newFromFieldValue); // log the change we are making before stripping the tag from the field values Os::Logger::instance().log( FAC_SIP, PRI_INFO, "CallerAlias[%s]::check4andApplyAlias call %s set caller alias\n" " Original-From: %s\n" " Aliased-From: %s", mInstanceName.data(), callId.data(), originalFromField.data(), newFromFieldValue.data() ); // rewrite the caller identity with the aliased value request.setRawFromField(newFromFieldValue.data()); // Factor the tag values out of the field values stored in the RouteState // We do this because otherwise we'll end up encoding and sending two copies // of the tag; since some phones send really long tag values (no one knows why), // this can cause such large Record-Route headers that they cause interop problems. if ( ! originalFromTag.isNull() ) { // find the offset of the tag value in the callers from field ssize_t callerFromTagOffset; callerFromTagOffset = originalFromField.index(originalFromTag); callerFromTagOffsetStr.appendNumber(callerFromTagOffset); // strip the tag value from the original From value to be stored in the RouteState originalFromField.replace(callerFromTagOffset, originalFromTag.length(), ""); // find the offset of the tag value in the aliased from field ssize_t aliasFromTagOffset; aliasFromTagOffset = newFromFieldValue.index(originalFromTag); aliasFromTagOffsetStr.appendNumber(aliasFromTagOffset); // strip the tag value from the aliased From value to be stored in the RouteState newFromFieldValue.replace(aliasFromTagOffset, originalFromTag.length(), ""); } // save the original and new values so that we can fix them later routeState.setParameter(mInstanceName.data(), CALLER_FROM_PARAM,originalFromField); routeState.setParameter(mInstanceName.data(), CALLER_TAG_OFFSET_PARAM,callerFromTagOffsetStr); routeState.setParameter(mInstanceName.data(), ALIAS_FROM_PARAM,newFromFieldValue); routeState.setParameter(mInstanceName.data(), ALIAS_TAG_OFFSET_PARAM,aliasFromTagOffsetStr); } else { Os::Logger::instance().log( FAC_SIP, PRI_DEBUG, "CallerAlias[%s]::check4andApplyAlias call %s found no alias", mInstanceName.data(), callId.data() ); } } else { Os::Logger::instance().log(FAC_SIP, PRI_DEBUG, "CallerAlias[%s]::authorizeAndModify " "not mutable - no rewrite", mInstanceName.data() ); } } else // the callerFrom and aliasFrom parameters were found { /* * This request has had its From rewritten, so fix either the From * or the To depending on which direction this request is going. */ if (!request.isResponse()) // can't modify responses, so don't bother { size_t tagOffset; if (routeState.directionIsCallerToCalled(mInstanceName.data())) { // replace the from tag value in the stored aliased header tagOffset = strtol(aliasFromTagOffsetStr.data(), NULL, 10); aliasFrom.insert(tagOffset, originalFromTag); // put the aliased header into the message request.setRawFromField(aliasFrom); Os::Logger::instance().log(FAC_AUTH, PRI_DEBUG, "CallerAlias[%s]::authorizeAndModify " "call %s reset From", mInstanceName.data(), callId.data() ); } else // direction is Called to Caller { // replace the from tag value in the stored original header tagOffset = strtol(callerFromTagOffsetStr.data(), NULL, 10); callerFrom.insert(tagOffset, originalFromTag); request.setRawToField(callerFrom.data()); Os::Logger::instance().log(FAC_AUTH, PRI_DEBUG, "CallerAlias[%s]::authorizeAndModify " "call %s reset To", mInstanceName.data(), callId.data() ); } } } } return AuthPlugin::CONTINUE; }
void OsDateTimeBase::getLocalTimeString(UtlString& dateString) { char dateBuffer[200]; char ampm[] = "AM"; time_t ltime; struct tm *today; #ifndef _VXWORKS /* Set time zone from TZ environment variable. If TZ is not set, * the operating system is queried to obtain the default value * for the variable. */ tzset(); #endif /* _VXWORKS*/ /* Convert to time structure and adjust for PM if necessary. */ time( <ime ); today = localtime( <ime ); if( today->tm_hour >= 12 ) { strcpy( ampm, "PM" ); if (today->tm_hour > 12) today->tm_hour -= 12; } if( today->tm_hour == 0 ) /* Adjust if midnight hour. */ today->tm_hour = 12; char tz[4] = {" "}; #ifndef _VXWORKS UtlString timezone = tzname[0]; if (today->tm_isdst == 1) timezone = tzname[1]; int len = timezone.length(); if (len > 3) { size_t pos = timezone.index(" "); if (pos != UTL_NOT_FOUND) { tz[0] = timezone.data()[0]; tz[1] = timezone.data()[pos + 1]; if ((pos = timezone.index(" ", pos + 1)) != UTL_NOT_FOUND) { tz[2] = timezone.data()[pos + 1]; } } } else if (len > 0) { memcpy(tz, timezone.data(), 3); } #endif /* _VXWORKS */ tz[3] = 0; // Mon, 25-Sep-2002 05:51:44 EST sprintf(dateBuffer, "%s, %d-%s-%d %.2d:%.2d:%.2d %s %s", spDayStrings[today->tm_wday], today->tm_mday, spMonthStrings[today->tm_mon], (today->tm_year + 1900), today->tm_hour, today->tm_min, today->tm_sec, ampm, tz); dateString = dateBuffer; }
RedirectPlugin::LookUpStatus SipRedirectorRegDB::lookUp( const SipMessage& message, const UtlString& requestString, const Url& requestUri, const UtlString& method, ContactList& contactList, RequestSeqNo requestSeqNo, int redirectorNo, SipRedirectorPrivateStorage*& privateStorage, ErrorDescriptor& errorDescriptor) { unsigned long timeNow = OsDateTime::getSecsSinceEpoch(); // Local copy of requestUri Url requestUriCopy = requestUri; // Look for any grid parameter and remove it. UtlString gridParameter; UtlBoolean gridPresent = requestUriCopy.getUrlParameter("grid", gridParameter, 0); if (gridPresent) { requestUriCopy.removeUrlParameter("grid"); } if (Os::Logger::instance().willLog(FAC_SIP, PRI_DEBUG)) { UtlString temp; requestUriCopy.getUri(temp); Os::Logger::instance().log(FAC_SIP, PRI_DEBUG, "%s::lookUp gridPresent = %d, gridParameter = '%s', " "requestUriCopy after removing grid = '%s'", mLogName.data(), gridPresent, gridParameter.data(), temp.data()); } RegDB::Bindings registrations; // Give the ~~in~ URIs separate processing. UtlString user; requestUriCopy.getUserId(user); if (user.index(URI_IN_PREFIX) == 0) { // This is a ~~in~ URI. // Check for an '&' separator. ssize_t s = user.last('&'); if (s != UTL_NOT_FOUND) { // This is a ~~in~[user]&[instrument] URI. const char* instrumentp = user.data() + s + 1; UtlString u; u.append(user, sizeof (URI_IN_PREFIX) - 1, s - (sizeof (URI_IN_PREFIX) - 1)); requestUriCopy.setUserId(u); //regDB-> // getUnexpiredContactsUserInstrument(requestUriCopy, instrumentp, timeNow, registrations); UtlString identity; requestUriCopy.getIdentity(identity); _dataStore.regDB().getUnexpiredContactsUserInstrument(identity.str(), instrumentp, timeNow, registrations); } else { // This is a ~~in~[instrument] URI. const char* instrumentp = user.data() + sizeof (URI_IN_PREFIX) - 1; _dataStore.regDB().getUnexpiredContactsInstrument(instrumentp, timeNow, registrations); } } else { // Note that getUnexpiredContactsUser will reduce the requestUri to its // identity (user/host/port) part before searching in the // database. The requestUri identity is matched against the // "identity" column of the database, which is the identity part of // the "uri" column which is stored in registration.xml. UtlString identity; requestUriCopy.getIdentity(identity); _dataStore.regDB().getUnexpiredContactsUser(identity.str(), timeNow, registrations); } int numUnexpiredContacts = registrations.size(); Os::Logger::instance().log(FAC_SIP, PRI_DEBUG, "%s::lookUp got %d unexpired contacts", mLogName.data(), numUnexpiredContacts); // Check for a per-user call forward timer. // Don't set timer if we're not going to forward to voicemail. std::ostringstream userCfwdTimer; bool foundUserCfwdTimer = false; if (method.compareTo(SIP_INVITE_METHOD) == 0) { UtlString noRoute; requestUriCopy.getUrlParameter("sipx-noroute", noRoute); if ((!noRoute.isNull()) && (noRoute.compareTo("Voicemail") == 0)) { // This is not a call scenerio controlled by this users "forward to voicemail" timer } else { UtlString identity; requestUriCopy.getIdentity(identity); EntityRecord entity; foundUserCfwdTimer = _dataStore.entityDB().findByIdentity(identity.str(), entity); if (foundUserCfwdTimer) userCfwdTimer << entity.callForwardTime(); } } for (RegDB::Bindings::const_iterator iter = registrations.begin(); iter != registrations.end(); iter++) { // Query the Registration DB for the contact, expires and qvalue columns. Os::Logger::instance().log(FAC_SIP, PRI_DEBUG, "%s::lookUp contact = '%s', qvalue = '%s', path = '%s'", mLogName.data(), iter->getContact().c_str(), iter->getQvalue().c_str(), iter->getPath().c_str() ); Url contactUri(iter->getContact().c_str()); // If available set the per-user call forward timer. if (foundUserCfwdTimer) { contactUri.setHeaderParameter("expires", userCfwdTimer.str().c_str()); } // If the contact URI is the same as the request URI, ignore it. if (!contactUri.isUserHostPortEqual(requestUriCopy)) { // Check if the q-value from the database is valid, and if so, // add it into contactUri. if (!iter->getQvalue().empty()) { // :TODO: (XPL-3) need a RegEx copy constructor here // Check if q value is numeric and between the range 0.0 and 1.0. static RegEx qValueValid("^(0(\\.\\d{0,3})?|1(\\.0{0,3})?)$"); if (qValueValid.Search(iter->getQvalue().c_str())) { contactUri.setFieldParameter(SIP_Q_FIELD, iter->getQvalue().c_str()); } } // Re-apply any grid parameter. if (gridPresent) { contactUri.setUrlParameter("grid", gridParameter); } contactUri.setUrlParameter(SIP_SIPX_CALL_DEST_FIELD, "INT"); // Check if database contained a Path value. If so, add a Route // header parameter to the contact with the Path vector taken from // the registration data. if (!iter->getPath().empty()) { UtlString existingRouteValue; std::string pathVector = iter->getPath(); if ( contactUri.getHeaderParameter(SIP_ROUTE_FIELD, existingRouteValue)) { // there is already a Route header parameter in the contact; append it to the // Route derived from the Path vector. pathVector += SIP_MULTIFIELD_SEPARATOR; pathVector += existingRouteValue.str(); } contactUri.setHeaderParameter(SIP_ROUTE_FIELD, pathVector.c_str()); } // Add the contact. contactList.add( contactUri, *this ); } } return RedirectPlugin::SUCCESS; }
UtlBoolean SipConfigServerAgent::handleMessage(OsMsg& eventMessage) { osPrintf("---> SipConfigServerAgent: handleMessage...\r\n") ; int msgType = eventMessage.getMsgType(); int msgSubType = eventMessage.getMsgSubType(); // if this is a SIP message if(msgType == OsMsg::PHONE_APP && msgSubType == SipMessage::NET_SIP_MESSAGE) { const SipMessage* sipMessage = ((SipMessageEvent&)eventMessage).getMessage(); int messageType = ((SipMessageEvent&)eventMessage).getMessageStatus(); osPrintf("SipConfigServerAgent::messageType: %d\n", messageType); UtlString method; // This is a request which failed to get sent if(messageType == SipMessageEvent::TRANSPORT_ERROR) { sipMessage->getRequestMethod(&method); osPrintf("SipConfigServerAgent:: Processing message transport error method: %s\n", sipMessage->isResponse() ? method.data() : "response"); if(sipMessage->isResponse()) { int seqNum; sipMessage->getCSeqField(&seqNum, &method); // SUBSCIBE (enrollment) response if(method.compareTo(SIP_SUBSCRIBE_METHOD)) { // We are sad the device is not there osPrintf("SipConfigServerAgent::handleMessage enroll FAILURE: no response\n"); } } } else if(messageType == SipMessageEvent::AUTHENTICATION_RETRY) { } // If this is a response else if(sipMessage->isResponse()) { int seqNum; sipMessage->getCSeqField(&seqNum, &method); // SUBSCIBE (enrollment) response if(method.compareTo(SIP_NOTIFY_METHOD) && mfpNotifyResponseCallbackFunc) { mfpNotifyResponseCallbackFunc(*sipMessage); } } // This is a request else { sipMessage->getRequestMethod(&method); UtlString eventType; sipMessage->getEventField(eventType); eventType.toLower(); // SUBSRIBE (enrollment) request if(method.compareTo(SIP_SUBSCRIBE_METHOD) == 0 && eventType.index(SIP_EVENT_CONFIG) >= 0 && mfpEnrollmentCallbackFunc) { SipMessage response; SipMessage copyOfRequest(*sipMessage); // add a to tag to the sip message. This to tag will // be bubbled up to the Java layer. Also the same to tag will // be sent back in the response UtlString toAddr; UtlString toProto; int toPort; UtlString toTag; sipMessage->getToAddress(&toAddr, &toPort, &toProto, NULL, NULL, &toTag); if( toTag.isNull()) { int epochTime = (int)OsDateTime::getSecsSinceEpoch(); // Build a to tag char tagBuffer[100]; sprintf(tagBuffer, "%dasd", epochTime); copyOfRequest.setToFieldTag(tagBuffer); } int responseCode = mfpEnrollmentCallbackFunc(copyOfRequest); switch(responseCode) { case SIP_ACCEPTED_CODE: { response.setExpiresField(DEFAULT_EXPIRES); response.setResponseData(©OfRequest, SIP_ACCEPTED_CODE, SIP_ACCEPTED_TEXT); } break; default: response.setResponseData(©OfRequest, SIP_BAD_REQUEST_CODE, SIP_BAD_REQUEST_TEXT); break; } if(mpSipUserAgent) mpSipUserAgent->send(response); } } } return(TRUE); }