Ejemplo n.º 1
0
   void testChar2Utl()
      {
         UtlString encoded;

         char msg[2048];

         for (unsigned int test = 0; test < (sizeof(tests)/sizeof(TestData)); test++)
         {
            encoded.remove(0);
            NetBase64Codec::encode(tests[test].inputSize,
                                   tests[test].inputData,
                                   encoded
                                   );
            
            sprintf(msg,
                    "\n  test case %d encoding"
                    "\n     expected size %d data '%s'"
                    "\n     actual   size %d data '%s'",
                    test,
                    strlen(tests[test].output), tests[test].output,
                    encoded.length(), encoded.data()
                    );
            CPPUNIT_ASSERT_MESSAGE(msg,
                                   (   (encoded.length() == strlen(tests[test].output))
                                    && (encoded.compareTo(tests[test].output) == 0)
                                    ));
         }
      }
Ejemplo n.º 2
0
OsStatus sipXmediaFactoryImpl::buildCodecFactory(SdpCodecList* pFactory, 
                                                 const UtlString& sAudioPreferences,
                                                 const UtlString& sVideoPreferences,
                                                 int videoFormat,
                                                 int* iRejected)
{
   OsStatus rc = OS_FAILED;

   *iRejected = 0;

   if (pFactory)
   {
      pFactory->clearCodecs();

      // If preferred codecs supplied - add them, else add all supported
      // codecs.
      if (sAudioPreferences.length() > 0)
      {
         *iRejected = pFactory->addCodecs(sAudioPreferences);
         OsSysLog::add(FAC_MP, PRI_DEBUG, 
                       "sipXmediaFactoryImpl::buildCodecFactory: "
                       "supported codecs = %s with NumReject %d",
                       sAudioPreferences.data(), *iRejected);
         rc = OS_SUCCESS;
      }
      else
      {
         // Build up the supported codecs
         MpCodecFactory *pCodecFactory = MpCodecFactory::getMpCodecFactory();
         pCodecFactory->addCodecsToList(*pFactory);

         *iRejected = 0;
         rc = OS_SUCCESS;
      }

#ifdef VIDEO // [
      // If preferred codecs supplied - add them, else add all supported
      // codecs.
      if (sVideoPreferences.length() > 0)
      {
         *iRejected = pFactory->addCodecs(sVideoPreferences);
         OsSysLog::add(FAC_MP, PRI_DEBUG, 
                       "sipXmediaFactoryImpl::buildCodecFactory: "
                       "supported codecs = %s with NumReject %d",
                       sVideoPreferences.data(), *iRejected);
         rc = OS_SUCCESS;
      }
      else
      {
         // Build up the supported codecs
         SdpCodec::SdpCodecTypes videoCodecs[] = {};
         const int numVideoCodecs = sizeof(videoCodecs)/sizeof(SdpCodec::SdpCodecTypes);

         *iRejected = pFactory->addCodecs(numVideoCodecs, videoCodecs);
         rc = OS_SUCCESS;
      }
#endif // VIDEO ]
   }
   return rc;
}
Ejemplo n.º 3
0
// Gets a db subset of name value pairs which have the given hashSubKey as
// a prefix for the key
OsStatus OsConfigDb::getSubHash(const UtlString& rHashSubKey,
                                OsConfigDb& rSubDb) const
{
   UtlSortedListIterator itor(const_cast<UtlSortedList&>(mDb));

   DbEntry* entry;
   // Skip the initial entries in the list that do not match.
   while ((entry = static_cast <DbEntry*> (itor())))
   {
      if (strncmp(entry->key.data(), rHashSubKey.data(),
                  rHashSubKey.length()) >= 0)
      {
         break;
      }
   }

   // Process the entries in the list that do match.
   for (; entry &&
           strncmp(entry->key.data(), rHashSubKey.data(),
                   rHashSubKey.length()) == 0;
        entry = static_cast <DbEntry*> (itor()))
   {
      // Construct and add the entry to the subhash.
      // Make temporary UtlString, because that's what insertEntry demands
      // as an argument.
      UtlString key(&entry->key.data()[rHashSubKey.length()]);
      rSubDb.insertEntry(key, entry->value);
   }

   return OS_SUCCESS;
}
Ejemplo n.º 4
0
void doListOperations()
{
   UtlSList testList;

   // fill the list
   appendCountItems(testList, NUM_PERFORMANCE_STRINGS);
   
   // take the first half off the front
   if (!testList.isEmpty())
   {
      getCountItems(testList, NUM_PERFORMANCE_STRINGS / 2);
   }

   // take the rest off the end by reference
   if (!testList.isEmpty())
   {
      UtlContainable* lastItem = testList.last();
      delete dynamic_cast<UtlString*>(testList.removeReference(lastItem));
   }

   // fill the list
   appendCountItems(testList, NUM_PERFORMANCE_STRINGS);

   // search the list for each item by value
   UtlString target;
   int targetIndex;
   for (targetIndex = 0; targetIndex < NUM_PERFORMANCE_STRINGS; targetIndex += 1)
   {
      target = string[targetIndex];
      UtlString* found = dynamic_cast<UtlString*>(testList.find(&target));
      if (found)
      {
         externalForSideEffects = found->length();
      }
   }
   
   // get the object in the middle of the list by index, and remove it by value
   while(!testList.isEmpty())
   {
      int numberLeft = testList.entries();
      UtlString* middle = dynamic_cast<UtlString*>(testList.at((numberLeft / 2)));
      delete dynamic_cast<UtlString*>(testList.remove(middle));
   }

   // fill the list
   appendCountItems(testList, NUM_PERFORMANCE_STRINGS);

   // iterate over each item in the list
   UtlSListIterator iterate(testList);
   UtlString* item;
   while ((item = dynamic_cast<UtlString*>(iterate())))
   {
      externalForSideEffects = item->length();
      delete item;
   }
}
Ejemplo n.º 5
0
UtlBoolean SipNonceDb::isNonceValid(const UtlString& nonce,
                                    const UtlString& callId,
                                    const UtlString& fromTag,
                                    const UtlString& realm,
                                    const long expiredTime)
{
   UtlBoolean valid = FALSE;

   if (nonce.length() == (MD5_SIZE + HEX_TIMESTAMP_LENGTH))
   {
      UtlString timestamp = nonce(MD5_SIZE, HEX_TIMESTAMP_LENGTH);
      UtlString rcvdSignature = nonce(0,MD5_SIZE);
      UtlString msgSignature(nonceSignature(callId, fromTag, realm, timestamp.data()));
      if (0 == rcvdSignature.compareTo(msgSignature))
      {
         // check for expiration
         char* end;
         long nonceCreated = strtol(timestamp.data(), &end, 16 /* hex */);
         long now = OsDateTime::getSecsSinceEpoch();

         if ( nonceCreated+expiredTime >= now )
         {
            valid = TRUE;
         }
         else
         {
            OsSysLog::add(FAC_SIP,PRI_INFO,
                          "SipNonceDB::isNonceValid expired nonce '%s': created %ld+%ld < %ld",
                          nonce.data(), nonceCreated, expiredTime, now
                          );
         }
      }
      else
      {
         OsSysLog::add(FAC_SIP,PRI_ERR,
                       "SipNonceDB::isNonceValid nonce signature check failed '%s'",
                       nonce.data()
                       );
         OsSysLog::add(FAC_SIP,PRI_DEBUG,
                       "SipNonceDB::isNonceValid rcvd signature '%s' calculated signature '%s'",
                       rcvdSignature.data(), msgSignature.data()
                       );
      }
   }
   else
   {
      OsSysLog::add(FAC_SIP,PRI_ERR,
                    "SipNonceDb::isNonceValid invalid nonce format '%s'"
                    " length %zu expected %d",
                    nonce.data(), nonce.length(), MD5_SIZE+HEX_TIMESTAMP_LENGTH);
   }

   return(valid);
}
Ejemplo n.º 6
0
void Url::gen_value_escape(UtlString& unEscapedText)
{
   // Check if there are any characters in unEscapedText that need to be
   // escaped in a field parameter value.
   if (strspn(unEscapedText.data(),
              // Alphanumerics
              "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
              "abcdefghijklmnopqrstuvwxyz"
              "0123456789"
              // Characters allowed in tokens
              "-.!%*_+`'~"
              // Additional characters allowed by the syntax of "host"
              "[]:") != unEscapedText.length())
   {
      // Temporary string to construct the escaped value in.
      UtlString escapedText;
      // Pre-size it to the size of the un-escaped test, plus 2 for
      // the starting and ending double-quotes.
      escapedText.capacity((size_t) unEscapedText.length() + 2);
      const char* unescapedTextPtr = unEscapedText.data();

      // Start with double-quote.
      escapedText.append("\"");

      // Process each character of the un-escaped value.
      while(*unescapedTextPtr)
      {
         char unEscapedChar = *unescapedTextPtr;
         if (unEscapedChar == '"' || unEscapedChar == '\\')
         {
            // Construct a little 2-character string and append it.
            char escapedChar[2];
            escapedChar[0] = '\\';
            escapedChar[1] = *unescapedTextPtr;
            escapedText.append(&unEscapedChar, 2);
        }
        else
        {
           // Append the character directly.
           escapedText.append(&unEscapedChar, 1);
        }
         // Consider the next character.
         unescapedTextPtr++;
      }

      // End with double-quote.
      escapedText.append("\"");

      // Write the escaped string into the argumemt.
      unEscapedText = escapedText;
   }
}
Ejemplo n.º 7
0
   void testUtl2Utl()
      {
         UtlString encoded;
         UtlString decoded;

         char msg[2048];

         for (unsigned int test = 0; test < (sizeof(tests)/sizeof(TestData)); test++)
         {
            UtlString input(tests[test].inputData, tests[test].inputSize);
            
            encoded.remove(0);
            NetBase64Codec::encode(input, encoded);
            
            sprintf(msg,
                    "\n  test case %d encoding"
                    "\n     expected size %d data '%s'"
                    "\n     actual   size %d data '%s'",
                    test,
                    strlen(tests[test].output), tests[test].output,
                    encoded.length(), encoded.data()
                    );
            CPPUNIT_ASSERT_MESSAGE(msg,
                                   (   (encoded.length() == strlen(tests[test].output))
                                    && (encoded.compareTo(tests[test].output) == 0)
                                    ));

            decoded.remove(0);
            bool decodedOk;
            decodedOk = NetBase64Codec::decode(encoded, decoded);

            sprintf(msg,
                    "\n  test case %d decoding %s"
                    "\n     expected size %d data '%s'"
                    "\n     actual   size %d data '%s'",
                    test, decodedOk ? "ok" : "failed",
                    tests[test].inputSize, tests[test].inputData,
                    decoded.length(), decoded.data()
                    );
            CPPUNIT_ASSERT_MESSAGE(msg,
                                   (   decodedOk
                                    && (decoded.length() == tests[test].inputSize)
                                    && (memcmp(tests[test].inputData,
                                               decoded.data(),
                                               tests[test].inputSize
                                               )
                                        == 0)
                                    ));
         }
      }
Ejemplo n.º 8
0
OsStatus
StatusServerCGI::execute(UtlString* out)
{
    // forward the request to the mailbox manager
#ifdef WIN32
//  DebugBreak();
#endif
    UtlString notifyBodyText;
    OsStatus result =
       MailboxManager::getInstance()->getMWINotifyText ( m_mailboxIdentity, NULL, notifyBodyText );
    // send an OK back to the Status Server
    if (out)
    {
        // clear the response
        out->remove(0);

        // set the http headers
        char contentLengthHeader[40];
        sprintf( contentLengthHeader, "Content-Length: %zu\r\n", notifyBodyText.length() );
        out->append( (UtlString)contentLengthHeader );
        out->append( "Content-Type: application/simple-message-summary\r\n" );


        // Separate the headers from the body content (very important otherwise no body sent!)
        out->append( "\r\n" );
        out->append( notifyBodyText.data() );
    }
    return result;
}
Ejemplo n.º 9
0
// 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);
   }
}
Ejemplo n.º 10
0
OsStatus LogNotifier::handleAlarm(
      const OsTime alarmTime,
      const UtlString& callingHost,
      const cAlarmData* alarmData,
      const UtlString& alarmMsg)
{
   OsStatus retval = OS_SUCCESS;
   OsSysLog::add(alarmData->getComponent().data(), 0, FAC_ALARM, alarmData->getSeverity(),
         "%s: %s", alarmData->getCode().data(), alarmMsg.data());

   OsDateTime logTime(alarmTime);
   UtlString   strTime ;
   logTime.getIsoTimeStringZus(strTime);

   char tempMsg[500 + alarmMsg.length()];
   snprintf(tempMsg, sizeof(tempMsg), "\"%s\":%zd:%s:%s:%s:%s::%s:\"%s\"",
             strTime.data(),
             ++mEventCount,
             OsSysLog::sFacilityNames[FAC_ALARM],
             OsSysLog::priorityName(alarmData->getSeverity()),
             callingHost.data(),
             alarmData->getComponent().data(),
             alarmData->getCode().data(),
             escape(alarmMsg).data());
   tempMsg[sizeof(tempMsg)-2]='"';
   tempMsg[sizeof(tempMsg)-1]=0;

   char* szPtr = strdup(tempMsg);
   OsSysLogMsg msg(OsSysLogMsg::LOG, szPtr);
   mpOsSysLogTask->postMessage(msg);

   return retval;
}
Ejemplo n.º 11
0
UtlBoolean SipRedirectorGateway::prefixIsValid(UtlString& p)
{
   int len, digits;
   char last;

   return
      (len = mPrefix.length(),
       // Initial 'len' chars must be the prefix.
       strncmp(p.data(), mPrefix.data(), len) == 0 &&
       (digits = strspn(p.data() + len, "0123456789"),
        // Remaining chars must be digits.
        p.length() == len + digits &&
        (last = p.length(len - 1),
         // Last digit must be 1-9.
         last >= 1)));
}
Ejemplo n.º 12
0
OsStatus
UpdateMessageStatesCGI::handleOpenVXIRequest( UtlString* out )
{
    // Instantiate the mailbox manager
    MailboxManager* pMailboxManager = MailboxManager::getInstance();
        OsStatus result = pMailboxManager->updateMessageStates(m_mailboxIdentity, m_category, m_messageIds);

        UtlString dynamicVxml = getVXMLHeader();

        if( result == OS_SUCCESS )
        {
                dynamicVxml += VXML_SUCCESS_SNIPPET;
        }
        else
        {
                dynamicVxml += VXML_FAILURE_SNIPPET;
        }

        dynamicVxml += VXML_END;

        // Write out the dynamic VXML script to be processed by OpenVXI
        if (out)
        {
        out->remove(0);
        UtlString responseHeaders;
        MailboxManager::getResponseHeaders(dynamicVxml.length(), responseHeaders);

        out->append(responseHeaders.data());
        out->append(dynamicVxml.data());
        }

        return OS_SUCCESS;
}
Ejemplo n.º 13
0
// Optimization to avoid strlen call as well as the only
// safe way to work with binary or opaque data
size_t UtlString::index(const UtlString& searchString, size_t start) const
{
    size_t foundPosition = UTLSTRING_NOT_FOUND;
    // mpData may be null, so use data() which returns an
    // static empty string if mpData is null
    const char* dataPtr = data();
    size_t searchStrSize = searchString.length();
    size_t startIndex = start;

    if(searchStrSize <= mSize)
    {
        for (size_t pos = startIndex;
             pos <= (mSize - searchStrSize)
             && foundPosition == UTLSTRING_NOT_FOUND;
             pos++)
        {
            if (memcmp(dataPtr + pos, searchString.data(), searchStrSize) == 0)
            {
                foundPosition = pos;
            }
        }
    }

    return foundPosition;
}
Ejemplo n.º 14
0
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);
        }
    }
}
Ejemplo n.º 15
0
void SipSubscribeServer::setContact(SipMessage* message)
{
    // Pull out the From userId and make sure that is used
    // in the contact -- otherwise, re-subscribes may request
    // a different resource (e.g. ~~park~id instead of the
    // the park orbit).
    UtlString fromUserId ;
    Url from ;
    if (message->isResponse())
    {
        message->getToUrl(from) ;
    }
    else
    {
        message->getFromUrl(from) ;
    }

    from.getUserId(fromUserId) ;
    if (fromUserId.length())
    {
        UtlString defaultContact;
        mpDefaultUserAgent->getContactUri(&defaultContact);
        Url defaultContactUrl(defaultContact) ;
        defaultContactUrl.setUserId(fromUserId);
        message->setContactField(defaultContactUrl.toString()) ;
    }
}
Ejemplo n.º 16
0
// 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;
}
Ejemplo n.º 17
0
NatMaintainer::NatMaintainer( SipRouter* sipRouter ) :
   mRefreshRoundNumber( 0 ),
   mpRegistrationDB( RegistrationDB::getInstance() ),
   mpSubscriptionDB( SubscriptionDB::getInstance() ),
   mTimerMutex( OsMutex::Q_FIFO ),
   mpSipRouter( sipRouter ),
   mpEndpointsKeptAliveList(
      new KeepAliveEndpointDescriptor[ NUMBER_OF_UDP_PORTS ] ),
   mpKeepAliveMessage( 0 ),
   mExternalKeepAliveListMutex( OsMutex::Q_FIFO )
{
   mTimerMutex.acquire();

   // Build SIP Options message that will be used to keep remote NATed NAT & firewall pinholes open.
   UtlString optionsMessageString =
       "OPTIONS sip:[email protected] SIP/2.0\r\n"
       "To: sip:[email protected]\r\n"
       "From: \"SipXecs Keepalive\"<sip:[email protected]>;tag=30543f3483e1cb11ecb40866edd3295b-reniatniamtan\r\n"
       "Call-ID: f88dfabce84b6a2787ef024a7dbe8749-reniatniamtan\r\n"
       "Cseq: 1 OPTIONS\r\n"
       "Via: SIP/2.0/UDP willgetpatched:5060;branch=z9hG4bK-234fc22f2nnthda-reniatniamtan\r\n"
       "Max-Forwards: 20\r\n"
       "Accept: application/sdp\r\n"
       "Contact: [email protected]\r\n"
       "Content-Length: 0\r\n"
       "\r\n";  
   
   mpKeepAliveMessage = new SipMessage( optionsMessageString, optionsMessageString.length() );

}
Ejemplo n.º 18
0
OsStatus ForwardRules::getRouteTo(UtlString& RouteToString,
                                 bool& authRequired,
                                  TiXmlNode* nodeWithRouteToChild)
{
   
   OsStatus currentStatus = OS_FAILED;
   nodeWithRouteToChild->ToElement();
   TiXmlNode* routeToNode = NULL;
   TiXmlNode* routeToText = NULL;


   //get the user text value from it
   routeToNode = nodeWithRouteToChild->FirstChild(XML_TAG_ROUTETO);
   if(routeToNode)
   {
      if(routeToNode && routeToNode->Type() != TiXmlNode::ELEMENT)
      {
         return currentStatus;
      }

      TiXmlElement* routeToElement = routeToNode->ToElement();

      const char* authRequiredPtr = 
         routeToElement->Attribute(XML_ATT_AUTHREQUIRED);

      //set the authRequired attribute
      authRequired=getYN(authRequiredPtr, false) ; //defaults to false

      RouteToString.remove(0);
      routeToText = routeToElement->FirstChild();
      if(routeToText && routeToText->Type() == TiXmlNode::TEXT)
      {
         TiXmlText* routeTo = routeToText->ToText();
         if (routeTo)
         {
            RouteToString.append(routeTo->Value());
         }
      }
      // TinyXML compresses white space, so an all white space element becomes
      // zero length, but just in case, let's strip it ourselves.
      RouteToString.strip(UtlString::both);
      if (RouteToString.length() > 0)
      {
         // The route is not empty.  Declare success
         currentStatus = OS_SUCCESS;
      }
      else if (authRequired)
      {
         // The Route can be empty, as long as authRequired is set.
         // This means just route to the authProxy.
         currentStatus = OS_SUCCESS;
      }
      else
      {
         // Empty or missing route, and no authRequired...that's not allowed.
         currentStatus = OS_FAILED;
      }
   }
   return currentStatus;
}
Ejemplo n.º 19
0
UtlBoolean EmailSendTask::handleMessage( OsMsg& rMsg )
{
   UtlBoolean handled = FALSE;
   AsynchEmailMsg* pEmailMsg = dynamic_cast <AsynchEmailMsg*> ( &rMsg );

   MailMessage msg       = pEmailMsg->getMessage();

   switch ( rMsg.getMsgType() )
   {
   case OsMsg::OS_EVENT:
   {
      UtlString response = msg.Send();
      if (!response.isNull())
      {
         if (response.length() > 0)
         {
            OsSysLog::add(FAC_ALARM, PRI_ERR, "EmailSendTask: "
                  " Error sending e-mail: response %s", response.data());
         }
      }
      handled = TRUE;
      break;
   }

   default:
      OsSysLog::add(FAC_ALARM, PRI_CRIT,
                    "EmailSendTask::handleMessage: '%s' unhandled message type %d.%d",
                    mName.data(), rMsg.getMsgType(), rMsg.getMsgSubType());
      break;
   }

   return handled;
}
Ejemplo n.º 20
0
// Insert the key/value pair into the config database.
// If the database already contains an entry for this key, then replace it
// with the new key/value pair.
void OsConfigDb::set(const UtlString& rKey, const UtlString& rNewValue)
{
   OsWriteLock lock(mRWMutex);

   if (rKey.length() > 0) {
      insertEntry(rKey, rNewValue);
   }
}
Ejemplo n.º 21
0
UtlBoolean SipLine::getPreferredContactUri(Url& preferredContactUri) const
{
    UtlString host ; 

    preferredContactUri = mPreferredContactUri ;
    preferredContactUri.getHostAddress(host) ;

    return (host.length() > 0) ;
}
Ejemplo n.º 22
0
void RegistrationDbTestContext::ConvertRelativeExpirations(
   OsFile* templateFile, ///< input
   OsFile* workingFile   ///< output
                                                           )
{
   // the files are already open
   UtlString line;
   long timeNow = OsDateTime::getSecsSinceEpoch();
   while (templateFile->readLine(line) == OS_SUCCESS)
   {
      timeShiftExpiresLine(line, timeNow);
      line.append("\n");
      size_t bytesWritten = 0;
      CPPUNIT_ASSERT_EQUAL(OS_SUCCESS, workingFile->write(line.data(), line.length(), bytesWritten));
      CPPUNIT_ASSERT_EQUAL(line.length(), bytesWritten);
   }
   // the files will be closed by the wrapper
}
Ejemplo n.º 23
0
/// Translate a file pattern into a regular expression
bool DirectoryResource::pattern2RegEx(const UtlString& pattern, UtlString& patternExpression)
{
   patternExpression.remove(0);

   RegEx regularExpressionSpecial(RegularExpressionSpecial);
   
   ssize_t patternPosition = 0;
   ssize_t nextSpecialPosition;

   while ( regularExpressionSpecial.SearchAt(pattern, patternPosition) )
   {
      nextSpecialPosition = regularExpressionSpecial.MatchStart(0);
      char nextSpecial = pattern(nextSpecialPosition);
      
      if ( nextSpecialPosition == patternPosition )
      {
         if ( nextSpecial == '*' )
         {
            patternExpression.append( (patternPosition == 0)
                                     ? InitialWildcardRegexp
                                     : InsideWildcardRegexp );
            patternPosition++;
         }
         else
         {
            // all other characters that are significant in a regexp are escaped
            patternExpression.append("\\");
            patternExpression.append(nextSpecial);
            patternPosition++;
         }
      }
      else
      {
         ssize_t fixedPartLength = nextSpecialPosition - patternPosition;
         patternExpression.append(pattern, patternPosition, fixedPartLength);
         patternPosition += fixedPartLength;
         /*
          * We have not incremented past the special, so we will match it again on
          * the next iteration; this avoids having to duplicate the checks for
          * whether it is '*' or some other regular expression character here
          */
      }
   }

   // append any fixed part that follows the last wildcard
   if ((size_t)patternPosition < pattern.length())
   {
      patternExpression.append( pattern, patternPosition, UTLSTRING_TO_END );
   }

   Os::Logger::instance().log(FAC_SUPERVISOR, PRI_DEBUG,
                 "DirectoryResource::patternRegEx( '%s' ) -> '%s'",
                 pattern.data(), patternExpression.data()
                 );
   
   return ! patternExpression.isNull();
}
Ejemplo n.º 24
0
// Remove all the key/value pairs starting with the designated prefix
OsStatus OsConfigDb::removeByPrefix(const UtlString& rPrefix) 
{
   OsWriteLock lock(mRWMutex);
   DbEntry* pEntry ;

   UtlSortedListIterator itor(mDb) ;
   while ((pEntry = (DbEntry*) itor()))
   {
       if (pEntry->key.length() >= rPrefix.length())
       {
           UtlString keyPrefix = pEntry->key ;
           keyPrefix.remove(rPrefix.length()) ;
           if (keyPrefix.compareTo(rPrefix, UtlString::ignoreCase) == 0)
           {
               remove(pEntry->key) ;
           }
       }      
   }
   
   return OS_SUCCESS ;
}
DirectoryResource*
DirectoryResourceManager::findFilename(const char* fullName ///< full path to a file
                                       )
{
   OsPath fullFileName(fullName);
   UtlString dirName  = fullFileName.getDirName();
   UtlString fileName;

   fileName.append(fullName, dirName.length(), UtlString::UTLSTRING_TO_END);
   dirName.strip(UtlString::trailing, OsPath::separator[0]);

   DirectoryResource* found = NULL;
   
   Os::Logger::instance().log(FAC_SUPERVISOR, PRI_DEBUG,
                 "DirectoryResourceManager::findFilename: path '%s' file '%s'",
                 dirName.data(), fileName.data());

   {
      OsLock tableMutex(mDirectoryResourceTableLock);
      UtlSListIterator directories(mDirectoryResourceTable);
      DirectoryResource* dir;
   
      while (!found
             && (dir = dynamic_cast<DirectoryResource*>(directories.findNext(&dirName))))
      {
         if ( dir->matches(fileName) )
         {
            found = dir;
         }
      }
   }

   if (found)
   {
      UtlString matched;
      found->appendDescription(matched);
      Os::Logger::instance().log(FAC_SUPERVISOR, PRI_DEBUG,
                    "DirectoryResourceManager::findFilename: '%s' matches %s",
                    fullName, matched.data());
   }
   else
   {
      Os::Logger::instance().log(FAC_SUPERVISOR, PRI_WARNING,
                    "DirectoryResourceManager::findFilename: no match found for '%s'",
                    fullName);
   }
   
   return found;
}
Ejemplo n.º 26
0
// Constructor
OsTaskBase::OsTaskBase(const UtlString& name,
                       void* pArg,
                       const int priority,
                       const int options,
                       const int stackSize)
:  mDataGuard(OsMutex::Q_PRIORITY + OsMutex::INVERSION_SAFE),
   mState(UNINITIALIZED),
   mpArg(pArg),
   mUserData(0)
{
        // If name contains %d insert the task count/index
    assert(name.length() < 240);
    char nameBuffer[256];
    sprintf(nameBuffer, name.data(), taskCount++);
    mName.append(nameBuffer);

   if (mName != "")
      OsUtil::insertKeyValue(TASK_PREFIX, mName, (intptr_t) this);
}
Ejemplo n.º 27
0
// Return the index of the designated substring starting at the
// designated position or UTLSTRING_NOT_FOUND  if not found.
// Optimization to avoid strlen call as well as the only
// safe way to work with binary or opaque data
size_t UtlString::index(const UtlString& searchString, size_t start, CompareCase type) const
{
    size_t foundPosition = UTLSTRING_NOT_FOUND;
    size_t searchStrSize = searchString.length();
    size_t startIndex = start;

    if (type == matchCase)
    {

        foundPosition = index(searchString, start);
    }
    else
    {
        // mpData may be null, so use data() which returns an
        // static empty string if mpData is null
        const char* dataPtr = data();

        if(searchStrSize <= mSize)
        {
            for (size_t pos = startIndex;
                 pos <= (mSize - searchStrSize)
                 && foundPosition == UTLSTRING_NOT_FOUND;
                 pos++)
            {
#ifdef WIN32
                if (strnicmp(dataPtr + pos,
                             searchString.data(),
                             searchStrSize) == 0)
#else
                if(strncasecmp(dataPtr + pos,
                               searchString.data(),
                               searchStrSize) == 0)
#endif
                {
                    foundPosition = pos;
                }
            }
        }
    }

    return foundPosition;
}
Ejemplo n.º 28
0
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;
   }
}
Ejemplo n.º 29
0
OsStatus
MessageIDGenerator::recoverMessageID ( UtlString& rMessageName ) const
{
    OsSysLog::add(FAC_MEDIASERVER_CGI, PRI_DEBUG,
                  "MessageIDGenerator::recoverMessageID called");
    OsStatus result = OS_SUCCESS;

    // Create a filename in the data directory
    OsFile messageIDFile ( m_dataFileName );

    result = messageIDFile.open( OsFile::CREATE );
    OsSysLog::add(FAC_MEDIASERVER_CGI, PRI_DEBUG,
                  "MessageIDGenerator::recoverMessageID: attempt to open file '%s' returns %d",
                  m_dataFileName.data(), result);

    if (result == OS_SUCCESS)
    {
        // Recurse directories (@JC TODO)
        // Choose 1 as the sequence number to return.
        rMessageName = "00000001";
        // Save 2 as the next sequence number.
        UtlString nextSequenceNum = "00000002";
        size_t bytesWritten;
        result = messageIDFile.write( nextSequenceNum , nextSequenceNum.length(), bytesWritten );
        OsSysLog::add(FAC_MEDIASERVER_CGI, PRI_DEBUG,
                      "MessageIDGenerator::recoverMessageID: write to ID file returns %d",
                      result);
        messageIDFile.close();
    }
    else
    {
        OsSysLog::add(FAC_MEDIASERVER_CGI, PRI_CRIT,
                      "MessageIDGenerator::recoverMessageID: Attempt to recover the message ID file '%s' failed",
                      m_dataFileName.data());
    }

    OsSysLog::add(FAC_MEDIASERVER_CGI, PRI_DEBUG,
                  "MessageIDGenerator::recoverMessageID returns %d, rMessageName = '%s'",
                  result, rMessageName.data());
    return result;
}
Ejemplo n.º 30
0
// 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();
   }
}