Ejemplo n.º 1
0
OsStatus
UpdateMessageStatesCGI::handleWebRequest( UtlString* out )
{
    // Instantiate the mailbox manager
    UtlString redirectUrl, dynamicHtml ;
    MailboxManager* pMailboxManager = MailboxManager::getInstance();
    OsStatus result = pMailboxManager->getMediaserverURLForWeb( redirectUrl ) ;

    if( result == OS_SUCCESS )
    {
       // We have revised the links that invoke this CGI pathway
       // so that the messageId parameter is now just the eight-digit
       // message ID.
       UtlString messageId = m_messageIds;

       result = pMailboxManager->updateMessageStates(
          m_mailboxIdentity, m_category, messageId);

       // URL of the message WAV file
       Url url ( m_mailboxIdentity );
       UtlString userId;
       url.getUserId( userId );

       // Null HTML file.
       dynamicHtml  =   HTML_BEGIN \
          HTML_END ;
    }
    else
    {
        dynamicHtml =   HTML_BEGIN \
                        PROTOCOL_MISMATCH \
                        HTML_END ;
    }

    if (out)
        {
                out->remove(0);
                out->append(dynamicHtml.data());
        }

    OsSysLog::add(FAC_MEDIASERVER_CGI, PRI_DEBUG,
                  "UpdateMessageStatesCGI::handleWebRequest: out = '%s'",
                  out->data());
    return OS_SUCCESS;
}
Ejemplo n.º 2
0
// TODO reenable test
TEST_F(ClockSkewTest, DISABLED_checkClockSkew) {
    Logger logger("ClockSkewTest");

    // Get the location of the bounce proxy
    Url bounceurl = messagingSettings->getBounceProxyUrl().getTimeCheckUrl();
    ASSERT_TRUE(bounceurl.isValid());
    std::string urlString = bounceurl.toString();
    const char *url  = urlString.c_str();

    // Use libcurl to get the HTTP date from the bounce proxy server
    CURL *curl = curl_easy_init();
    if (!curl) {
        JOYNR_LOG_ERROR(logger, "unknown error during curl_easy_init");
        FAIL();
    }

    // The line below contains a macro that is marked invalid by the QTCreator parser
    // but compiles without problem
    curl_easy_setopt(curl, CURLOPT_URL, url);
    curl_easy_setopt(curl, CURLOPT_HEADERFUNCTION, getHTTPHeaderDate);
    curl_easy_setopt(curl, CURLOPT_TIMEOUT, 30);

    // This call will fail but only the date header is interesting
    curl_easy_perform(curl);
    curl_easy_cleanup(curl);

    // Was a date obtained?
    ASSERT_FALSE(datestr[0] == '\0') << "Could not read date from bounce proxy";

    // Parse the returned date using curl
    time_t epochsecs = curl_getdate(datestr, nullptr);

    ASSERT_FALSE(epochsecs < -1) << "Could not parse date from bounce proxy.";

    // Compare the time with the local time
    std::uint64_t now        = DispatcherUtils::nowInMilliseconds();
    std::uint64_t remoteTime = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::system_clock::from_time_t(epochsecs).time_since_epoch()).count();

    auto minMaxTime = std::minmax(now, remoteTime);
    std::uint64_t diff = minMaxTime.second - minMaxTime.first;

    JOYNR_LOG_INFO(logger, "Time difference is {}  msecs",now);
    EXPECT_TRUE(diff < 2000) << "Time difference between local and remote is over 2 seconds";

}
Ejemplo n.º 3
0
UtlString SessionContext::getDiscriminatingTagValue( const SipMessage& message, bool bFromCallerToCallee ) const
{
   UtlString discriminatingTag;
   Url tempUrl;

   if( bFromCallerToCallee )
   {
      // caller-to-callee uses To-tag to distinguish between dialogs
      message.getToUrl( tempUrl );
   }
   else
   {
      // callee-to-caller uses From-tag to distinguish between dialogs
      message.getFromUrl( tempUrl );
   }
   tempUrl.getFieldParameter( "tag", discriminatingTag );
   return discriminatingTag;
}
Ejemplo n.º 4
0
bool Command::remote_object(const Url &remote_url, Value *error, ObjectHandle *handle) {
  Object *object;
  if (remote_objects_.get(remote_url.str(), &object)) {
    handle->hold(object);
    return true;
  } else {
    return build_remote_object(remote_url, error, handle);
  }
}
Ejemplo n.º 5
0
UtlBoolean SipLine::getPreferredContactUri(Url& preferredContactUri) const
{
    UtlString host ; 

    preferredContactUri = mPreferredContactUri ;
    preferredContactUri.getHostAddress(host) ;

    return (host.length() > 0) ;
}
Ejemplo n.º 6
0
   void testGetUnexpiredContacts()
      {
         Url uri;
         ResultSet results;
         UtlHashMap record1;
         UtlHashMap record2;
         int timeNow = (int)OsDateTime::getSecsSinceEpoch();

         RegistrationDbTestContext testDbContext(TEST_DATA_DIR "/regdbdata",
                                                 TEST_WORK_DIR "/regdbdata"
                                                 );

         testDbContext.inputFile("getUnexpiredContacts.xml");

         RegistrationDB* regDb = RegistrationDB::getInstance();

         uri.setUserId("900");
         uri.setHostAddress("testdomain.example.com");


         regDb->getUnexpiredContactsUser(uri, timeNow, results);
         int numResults = results.getSize();
         CPPUNIT_ASSERT_EQUAL(2, numResults);


         if (numResults == 2)
         {
             // Get first record
             results.getIndex(0, record1);
             UtlString* value = (UtlString*)record1.findValue(&RegistrationDB::gContactKey);
             CPPUNIT_ASSERT_EQUAL(value->compareTo("sip:[email protected]"), 0);

             value = (UtlString*)record1.findValue(&RegistrationDB::gUriKey);
             CPPUNIT_ASSERT_EQUAL(value->compareTo("sip:[email protected]"), 0);

             // Get second record
             results.getIndex(1, record2);
             value = (UtlString*)record2.findValue(&RegistrationDB::gContactKey);
             CPPUNIT_ASSERT_EQUAL(value->compareTo("sip:[email protected]"), 0);

             value = (UtlString*)record2.findValue(&RegistrationDB::gUriKey);
             CPPUNIT_ASSERT_EQUAL(value->compareTo("sip:[email protected]"), 0);
         }
      }
Ejemplo n.º 7
0
void SipImpliedSubscriptions::buildSubscribeRequest( const SipMessage& registerMessage
                           ,int duration
                           ,SipMessage& subscribeRequest
                           ,UtlString&  callId
                           ,UtlString&  fromTag
                           ,UtlString&  fromUri
                           )
{
   UtlString registrationValue;
   UtlString tagNameValuePair;
   UtlString contactUri;
   int      sequenceNumber = 0;

   // Get the From URL, and change the tag
   Url fromUrl;
   registerMessage.getFromUrl( fromUrl );
   fromUrl.removeFieldParameter("tag"); // discard from tag from REGISTER
   registerMessage.getFromUri( &fromUri );
   (void) registerMessage.getContactUri(0, &contactUri);
   (void) registerMessage.getCSeqField(&sequenceNumber, &registrationValue);

   Url toUrl;
   registerMessage.getToUrl( toUrl );
   toUrl.removeFieldParameter("tag");
   
   UtlString toUri;
   registerMessage.getToUri( &toUri );

   registerMessage.getCallIdField( &callId );
   callId.prepend("implied-mwi-");

   // Build a from tag for the SUBSCRIBE
   //   - hash the call id so that it will be the same on each refresh
   UtlString callIdHash;
   NetMd5Codec::encode( callId.data(), callIdHash );
   fromUrl.setFieldParameter("tag", callIdHash.data() );
   fromTag = callIdHash; // for constructing the nonce

   subscribeRequest.setVoicemailData( fromUrl.toString() // From:
                                     ,toUrl.toString()   // To:
                                     ,toUri.data()       // request URI
                                     ,contactUri.data()  // taken from registration
                                     ,callId.data()
                                     ,++sequenceNumber
                                     ,duration
                                     );

   /*
    * Rewrite the event field to add our extension parameter to
    * ensure that the registration and subscription are synchronized.
    */
   const char* standardEventHeader = subscribeRequest.getHeaderValue(0, SIP_EVENT_FIELD);
   UtlString extendedEventHeader(standardEventHeader);
   extendedEventHeader.append(";" SIPX_IMPLIED_SUB "=");
   char durationString[12];
   sprintf(durationString, "%d", duration);
   extendedEventHeader.append(durationString);
   subscribeRequest.setHeaderValue(SIP_EVENT_FIELD, extendedEventHeader.data(), 0);
}
Ejemplo n.º 8
0
   void testLocalStrictRoute()
      {
         const char* message =
            "INVITE sip:example.com;lr SIP/2.0\r\n"
            "Route: <sip:[email protected]>\r\n"
            "Via: SIP/2.0/TCP 10.1.1.3:33855\r\n"
            "To: sip:[email protected]\r\n"
            "From: Caller <sip:[email protected]>; tag=30543f3483e1cb11ecb40866edd3295b\r\n"
            "Call-Id: f88dfabce84b6a2787ef024a7dbe8749\r\n"
            "Cseq: 1 INVITE\r\n"
            "Max-Forwards: 20\r\n"
            "Contact: [email protected]\r\n"
            "Content-Length: 0\r\n"
            "\r\n";

         SipMessage testMsg(message, strlen(message));
         Url requestUri;
         UtlSList removedRoutes;

         testMsg.normalizeProxyRoutes(UserAgent, requestUri, &removedRoutes);

         UtlString normalizedMsg;
         int msgLen;
         testMsg.getBytes(&normalizedMsg, &msgLen);

         const char* expectedMessage = // route header removed, uri swapped
            "INVITE sip:[email protected] SIP/2.0\r\n"
            "Via: SIP/2.0/TCP 10.1.1.3:33855\r\n"
            "To: sip:[email protected]\r\n"
            "From: Caller <sip:[email protected]>; tag=30543f3483e1cb11ecb40866edd3295b\r\n"
            "Call-Id: f88dfabce84b6a2787ef024a7dbe8749\r\n"
            "Cseq: 1 INVITE\r\n"
            "Max-Forwards: 20\r\n"
            "Contact: [email protected]\r\n"
            "Content-Length: 0\r\n"
            "\r\n";

         ASSERT_STR_EQUAL(expectedMessage, normalizedMsg.data());

         UtlString requestUriResult;
         requestUri.toString(requestUriResult);
         
         ASSERT_STR_EQUAL("sip:[email protected]", requestUriResult.data());
      }
// returns false if blocked, true otherwise, like on quick connect error
bool getUrl( char *path , long checkCRC = 0 , char *post = NULL ) {

	SafeBuf sb;
	sb.safePrintf ( "http://%s:%li%s"
			, iptoa(g_hostdb.m_myHost->m_ip)
			, (long)g_hostdb.m_myHost->m_httpPort
			, path
			);

	s_checkCRC = checkCRC;

	bool doPost = true;
	if ( strncmp ( path , "/search" , 7 ) == 0 )
		doPost = false;

	//Url u;
	s_url.set ( sb.getBufStart() );
	log("qa: getting %s",sb.getBufStart());
	if ( ! g_httpServer.getDoc ( s_url.getUrl() ,
				     0 , // ip
				     0 , // offset
				     -1 , // size
				     0 , // ifmodsince
				     NULL ,
				     gotReplyWrapper,
				     999999*1000, // timeout ms
				     0, // proxyip
				     0, // proxyport
				     -1, // maxtextdoclen
				     -1, // maxotherdoclen
				     NULL , // useragent
				     "HTTP/1.0" , // protocol
				     doPost , // doPost
				     NULL , // cookie
				     NULL , // additionalHeader
				     NULL , // fullRequest
				     post ) )
		return false;
	// error?
	processReply ( NULL , 0 );
	//log("qa: getUrl error: %s",mstrerror(g_errno));
	return true;
}	
Ejemplo n.º 10
0
static bool _doReverseNetTest(
   Node* node, Config& cfg, UserId userId, const char* token,
   string& serverUrl)
{
   bool rval = false;

   // start creating public server URL
   serverUrl = "https://";

   // setup post data, use blank host to indicate to the reverse netaccess
   // service that our public IP should be used in the netaccess test
   // use a 15 seconds timeout in waiting for a response
   DynamicObject out;
   out["host"] = "";
   out["port"] = cfg["port"];
   out["path"] = "/api/3.0/catalog/netaccess/test";
   out["sellerId"] = userId;
   out["token"] = token;
   out["timeout"] = 15;

   DynamicObject in;

   // post to bitmunk
   Url url;
   url.format("/api/3.0/catalog/netaccess/rtest");
   Messenger* m = node->getMessenger();
   if(m->postSecureToBitmunk(&url, &out, &in, userId))
   {
      rval = true;
      serverUrl.append(in["ip"]->getString());
      serverUrl.push_back(':');
      serverUrl.append(cfg["port"]->getString());

      // send event
      Event ev;
      ev["type"] = EVENT_NET_ACCESS_SUCCESS;
      ev["details"]["userId"] = userId;
      ev["details"]["serverUrl"] = serverUrl.c_str();
      node->getEventController()->schedule(ev);
   }

   return rval;
}
Ejemplo n.º 11
0
//////////////////////////////////////////////////////////////////////////////////////////////////////
// loadUrl
IStreamUrlRef loadUrlStream( const Url &url )
{
	try {
		IStreamUrlRef result = IStreamUrl::createRef( url.str(), "", "" );
		return result;
	}
	catch( ... ) {
		return IStreamUrlRef();
	}
}
Ejemplo n.º 12
0
Slime child_state(const StateExplorer &state, const Url &url) {
    Slime child_state;
    state.get_state(slime::SlimeInserter(child_state), false);
    if (child_state.get().type().getId() == slime::NIX::ID) {
        inject_children(state, url, child_state.setObject());
    } else {
        child_state.get().setString("url", url.get());
    }
    return child_state;
}
Ejemplo n.º 13
0
bool ContactList::get( size_t index, Url& contactUrl ) const
{
   UtlString contactAsString;
   bool success = get( index, contactAsString );
   if( success )
   {
      contactUrl.fromString( contactAsString );
   }
   return success;
}
int main(int argc, char **argv) {
	if (argc < 2) {
		print_usage(argv[0]);
		return 1;
	}

	if (strcmp(argv[1], "--h") == 0 || strcmp(argv[1], "--help") == 0 ) {
		print_usage(argv[0]);
		return 1;
	}

	// initialize library
	g_mem.init();
	hashinit();

	g_conf.init(NULL);

	g_log.m_logPrefix = false;

	const char *input = argv[1];
	size_t inputLen = strlen(input);

	Url url;
	url.set(input, inputLen);
	url.print();
	logf(LOG_TRACE, "\t");

	SiteGetter sg;
	sg.getSite(input, NULL, 0, 0, 0);
	logf(LOG_TRACE, "Site info");
	logf(LOG_TRACE, "\tsite         : %.*s", sg.getSiteLen(), sg.getSite());
	logf(LOG_TRACE, "\tsitehash32   : %" PRIx32, hash32(sg.getSite(), sg.getSiteLen(), 0));
	logf(LOG_TRACE, "\t");

	uint64_t probableDocId = Titledb::getProbableDocId(&url);
	logf(LOG_TRACE, "Document info");
	logf(LOG_TRACE, "\tprobabledocid      : %" PRIu64, probableDocId);
	logf(LOG_TRACE, "\tfirstprobabledocid : %" PRIu64, Titledb::getFirstProbableDocId(probableDocId));
	logf(LOG_TRACE, "\tlastprobabledocid  : %" PRIu64, Titledb::getLastProbableDocId(probableDocId));

	return 0;
}
Ejemplo n.º 15
0
/**
*  @brief
*    Loads a resource which type has to be evaluated internally
*/
bool Application::LoadResource(const String &sFilename, const String &sType)
{
	bool bResult = false;	// Error by default

	// Clear the scene, after calling this method the scene is empty
	ClearScene();

	// Destroy the currently used script
	DestroyScript();

	// Backup the filename of the current resource
	m_sResourceFilename = sFilename;

	// Is there anything to load in?
	if (sFilename.GetLength()) {
		{ // Make the directory of the scene to load in to the current directory

			// Ok, the next thing is tricky, and every solution will end up in being a hack due to lack of information.
			// Within materials, meshes etc. there are usually relative paths provided, no absolute (not just true for PixelLight file formats).
			// Further, those paths are usually relative to a project root resulting e.g. within a default directory layout like
			// - Root
			//   - Data
			//     - Meshes
			//     - Materials
			// For "normal" projects this is no issue because everything is usually relative to the root project directory...
			// ... but this viewer must be able to pick out e.g. a mesh out of nowhere and must still be able to locate the required
			// other resources like materials. So, in here, we can only work with heuristics... this can and will of course go from
			// time to time horribly wrong...

			// First try: Find the first "Data" occurrence with the given filename and hope that it's the project root directory

			// Get filename as clean URL
			Url cUrl = Url(sFilename);
			cUrl.Collapse();

			// Get the first part of the path, and then look for "Data"
			uint32 nPathPos = 0;
			String sPart = cUrl.GetFirstPath(nPathPos);
			while (sPart != "Data" && sPart.GetLength())
				sPart = cUrl.GetNextPath(nPathPos);
			if (sPart == "Data") {
				// Set the base directory of the application
				SetBaseDirectory(cUrl.GetRoot() + cUrl.GetPath().GetSubstring(0, nPathPos - 5));	// -5 = Remove "Data/"
			} else {
				// Second try: Cut of "/Data/Scenes/" and hope that it's the project root directory.
				// If it's not there, take the directory the given resource is in.

				// Validate path
				const String sDirectory = cUrl.CutFilename();

				// Search for "/Data/Scenes/" and get the prefix of that, in case it's not there just use directly the scene directory
				const int nIndex = sDirectory.IndexOf("/Data/Scenes/");

				// Set the base directory of the application
				SetBaseDirectory("file://" + ((nIndex >= 0) ? sDirectory.GetSubstring(0, nIndex) : sDirectory) + '/');
			}
		}
Ejemplo n.º 16
0
// Returns TRUE if the requested state is different from the current state.
bool SipPresenceMonitor::setStatus(const Url& aor, const Status value)
{
   if (OsSysLog::willLog(FAC_SIP, PRI_DEBUG))
   {
      UtlString aorString;
      aor.toString(aorString);
      OsSysLog::add(FAC_SIP, PRI_DEBUG,
                    "SipPresenceMonitor::setStatus aor = '%s', value = %d %s",
                    aorString.data(), value,
                    (value == StateChangeNotifier::PRESENT ? "PRESENT" :
                     value == StateChangeNotifier::AWAY ? "AWAY" :
                     "UNKNOWN"));
   }

   bool result = false;

   UtlString contact;
   aor.getUserId(contact);
   contact += mHostAndPort;
   // Make the contact be a proper URI by prepending "sip:".
   contact.prepend("sip:");

   // Create a presence event package and store it in the publisher
   SipPresenceEvent* sipPresenceEvent = new SipPresenceEvent(contact);

   UtlString id;
   makeId(id, contact);

   Tuple* tuple = new Tuple(id.data());

   tuple->setStatus(value == StateChangeNotifier::PRESENT ?
                    STATUS_OPEN :
                    STATUS_CLOSED);
   tuple->setContact(contact, 1.0);

   sipPresenceEvent->insertTuple(tuple);

   // Add the SipPresenceEvent object to the presence event list.
   result = addPresenceEvent(contact, sipPresenceEvent);

   return result;
}
Ejemplo n.º 17
0
UtlString SessionContext::getDiscriminatingTagValue( const SipMessage& message ) const
{
   UtlString discriminatingTag;
   Url tempUrl;

   // We do not know the directionality of the message.  In this case
   // we cannot tell if the discriminating tag will come from the From:
   // or To: header.  Return the one that does not match the dialog's
   // original From-tag.

   // Look at the To-Tag first
   message.getToUrl( tempUrl );
   tempUrl.getFieldParameter( "tag", discriminatingTag );
   if( discriminatingTag == mDialogOriginalFromTag )
   {
      message.getFromUrl( tempUrl );
      tempUrl.getFieldParameter( "tag", discriminatingTag );
   }
   return discriminatingTag;
}
Ejemplo n.º 18
0
bool ReplaceRule::shouldReplace(const Url & u)
{
	if (!m_stateDomains.empty() && !isMatchState(m_stateDomains))
	{
		return false;
	}

	std::string url=u.GetString();
	bool ret;
	if(!this->m_isMatchProtocol) 
	{
		//url=url.substr(url.length()-u.GetScheme().length());
		if (!u.GetScheme().empty())
		{
			url=url.substr(u.GetScheme().length()+3);
		}
	}
	ret=adbMatch(url.c_str(),m_reReplace.c_str());
	return ret;
}
Ejemplo n.º 19
0
SipRedirector::LookUpStatus
SipRedirectorMPT::lookUp(
   const SipMessage& message,
   const UtlString& requestString,
   const Url& requestUri,
   const UtlString& method,
   ContactList& contactList,
   RequestSeqNo requestSeqNo,
   int redirectorNo,
   SipRedirectorPrivateStorage*& privateStorage,
   ErrorDescriptor& errorDescriptor)
{
   UtlString userId;
   requestUri.getUserId(userId);
   OsSysLog::add(FAC_SIP, PRI_DEBUG, "%s::lookUp "
                 "userId = '%s'", mLogName.data(),
                 userId.data());

   // Look up the user ID in the map.
   mMapLock.acquire();
   UtlContainable* v = mMapUserToContacts.findValue(&userId);
   mMapLock.release();
   // If found, add the contacts.
   if (v)
   {
      // Extract all the contacts out of the contact string.
      const char* s;
      const char* s1;
      for (s = (dynamic_cast<UtlString*> (v))->data();
           *s != '\0';
           s = s1+1)
      {
         // Find the ending newline, if any.
         // (Beware that Tiny XML trims trailing newlines off text contents!)
         s1 = strchr(s, '\n');
         if (!s1)
         {
            s1 = s + strlen(s);
         }
         // Ignore it if it is null
         if (s1-s != 0)
         {
            // Construct a UtlString of this contact.
            UtlString c(s, s1-s);
            // Construct a Url of this contact.
            Url url(c.data(), FALSE);
            // Add the contact.
            contactList.add( url, *this );
         }
      }
   }

   return SipRedirector::SUCCESS;
}
Ejemplo n.º 20
0
void Connection::open(const Url& url, const ConnectionSettings& settings) {
    if (url.empty())
        throw Exception(QPID_MSG("Attempt to open URL with no addresses."));
    Url::const_iterator i = url.begin();
    do {
        const Address& addr = *i;
        i++;
        try {
            ConnectionSettings cs(settings);
            if (addr.protocol.size()) cs.protocol = addr.protocol;
            cs.host = addr.host;
            cs.port = addr.port;
            open(cs);
            break;
        }
        catch (const Exception& /*e*/) {
            if (i == url.end()) throw;
        }
    } while (i != url.end());
}
static void generateSummary( Summary &summary, char *htmlInput, const char *queryStr, const char *urlStr ) {
	Xml xml;
	ASSERT_TRUE(xml.set(htmlInput, strlen(htmlInput), 0, CT_HTML));

	Words words;
	ASSERT_TRUE(words.set(&xml, true));

	Bits bits;
	ASSERT_TRUE(bits.set(&words));

	Url url;
	url.set(urlStr);

	Sections sections;
	ASSERT_TRUE(sections.set(&words, &bits, &url, "", CT_HTML));

	Query query;
	ASSERT_TRUE(query.set2(queryStr, langEnglish, true));

	LinkInfo linkInfo;
	memset ( &linkInfo , 0 , sizeof(LinkInfo) );
	linkInfo.m_lisize = sizeof(LinkInfo);

	Title title;
	ASSERT_TRUE(title.setTitle(&xml, &words, 80, &query, &linkInfo, &url, NULL, 0, CT_HTML, langEnglish));

	Pos pos;
	ASSERT_TRUE(pos.set(&words));

	Bits bitsForSummary;
	ASSERT_TRUE(bitsForSummary.setForSummary(&words));

	Phrases phrases;
	ASSERT_TRUE(phrases.set(&words, &bits));

	Matches matches;
	matches.setQuery(&query);
	ASSERT_TRUE(matches.set(&words, &phrases, &sections, &bitsForSummary, &pos, &xml, &title, &url, &linkInfo));

	summary.setSummary(&xml, &words, &sections, &pos, &query, 180, 3, 3, 180, &url, &matches, title.getTitle(), title.getTitleLen());
}
Ejemplo n.º 22
0
/// Encode identity info into a URL
bool SipXauthIdentity::encodeUri(Url              & uri,
                                 const char*    pCallId,
                                 const Url      fromUrl,
                                 const OsDateTime * timestamp)
{
   // Don't proceed if the encapsulated identity is invalid
   if (!mIsValidIdentity)
   {
      Os::Logger::instance().log(FAC_SIP, PRI_CRIT,
                    "SipXauthIdentity::encodeUri[no msg]: "
                    "encapsulated SipXauthIdentity is invalid");
   }
   else
   {
      // make sure no existing identity in the URI
      uri.removeHeaderParameter(SipXauthIdentity::PAssertedIdentityHeaderName);
      // set Call-Id and from-tag for the signature calculation
      UtlString callId(pCallId);
      UtlString fromTag;
      fromUrl.getFieldParameter("tag", fromTag);

      OsDateTime now;
      OsDateTime::getCurTime(now);
      if (NULL==timestamp)
      {
         timestamp = &now;
      }

      UtlString value;
      encode(value, callId, fromTag, *timestamp);
      uri.setHeaderParameter(SipXauthIdentity::PAssertedIdentityHeaderName, value.data());

      Os::Logger::instance().log(FAC_SIP, PRI_DEBUG,
                    "SipXauthIdentity::encodeUri[o msg] "
                    "encoded URI '%s'",
                    uri.toString().data()
                    );
   }

   return mIsValidIdentity;
}
Ejemplo n.º 23
0
UtlBoolean SignedUrl::isUrlSigned( Url& signedUrl )
{
    UtlBoolean bUrlProperlySigned;
    UtlString existingUrlSignature;
    UtlString urlString;

    signedUrl.toString( urlString );
    if( signedUrl.getUrlParameter( SignatureUrlParamName, existingUrlSignature ) == FALSE )
    {
        bUrlProperlySigned = FALSE;
        OsSysLog::add(FAC_SIP, PRI_DEBUG,
                      "SignedUrl::isUrlSigned URL '%s' not signed",
                      urlString.data() );
    }
    else
    {
        UtlString userInfo;
        UtlString hostPort;
        UtlString strReferenceSignature;

        signedUrl.getUserId( userInfo );
        signedUrl.getHostWithPort( hostPort );
        computeSignature( userInfo, hostPort, strReferenceSignature );

        if( strReferenceSignature.compareTo( existingUrlSignature ) == 0 )
        {
            bUrlProperlySigned = TRUE;
            OsSysLog::add(FAC_SIP, PRI_DEBUG,
                          "SignedUrl::isUrlSigned URL '%s' is properly signed",
                          urlString.data() );
        }
        else
        {
            bUrlProperlySigned = FALSE;
            OsSysLog::add(FAC_SIP, PRI_DEBUG,
                          "SignedUrl::isUrlSigned URL '%s' does not have a valid signature. "
                          "Expected signature: '%s'", urlString.data(), strReferenceSignature.data() );
        }
    }
    return bUrlProperlySigned;
}
Ejemplo n.º 24
0
void ConfigGeneralWidget::browseCommand(QLineEdit *lineEdit, bool isProgram)
{
    QString location;
    if (isProgram)
    {
        Url url = FileDialog::getOpenUrl(this, tr("Browse program"), Url(QDir::rootPath()));
        location = url.path();
    }
    else
    {
        const QString oldLocation = lineEdit->text();
        Url url = FileDialog::getOpenUrl(this, tr("Browse file"),
                                         Url(!oldLocation.isEmpty() ? oldLocation : QDir::homePath()));
        location = url.path();
    }
    if (!location.isEmpty())
    {
        location.replace(QLatin1Char('\\'), QLatin1Char('/'));
        lineEdit->setText(location);
    }
}
Ejemplo n.º 25
0
bool
HttpClient::httpGetWithRedirects(const Url& url,
                                 const std::string& contentType,
                                 std::string& rPage,
                                 size_t maxRedirects)
{
    LOG_INFO << "GETing " << url.fullAddr() << " with max allowed redirects: "
             << maxRedirects;
    
    Url url1 = url;
    for (size_t i = 0; i < maxRedirects; ++i){
        mNumRedirected = i;
        if (!httpGet(url1.fullAddr(), contentType, rPage))
            return false;

        if (isStatusRedirect()){
            string redirectTo = getHeaderParam("location:"); 
            LOG_INFO << mStatusCode << " Redirect to: " << redirectTo;
            Url link;
            if (!link.setFromLink(url1, redirectTo)){
                LOG_WARNING << "Could not parse link: " << redirectTo;
                continue;
            }
            if (link.domain() != url1.domain()){
                LOG_INFO << "not following redirects outside domain";
                break;
            }
            if (link == url1){
                LOG_INFO << "Redirect loop - exiting";
                break;
            }
            url1 = link;
            rPage.clear();
        }
        else
            return true;
    }
    return false;
}
void DownloadStateEventReactor::postDownloadStateId(
   UserId userId, DownloadStateId dsId, const char* action)
{
   Messenger* messenger = mNode->getMessenger();

   Url url;
   url.format("%s/api/3.0/purchase/contracts/%s?nodeuser=%" PRIu64,
      messenger->getSelfUrl(true).c_str(), action, userId);

   DynamicObject out;
   out["downloadStateId"] = dsId;
   if(!messenger->post(&url, &out, NULL, userId))
   {
      // schedule exception event
      Event e2;
      e2["type"] = "bitmunk.eventreactor.EventReactor.exception";
      BM_ID_SET(e2["details"]["userId"], userId);
      e2["details"]["downloadStateId"] = dsId;
      e2["details"]["exception"] = Exception::getAsDynamicObject();
      mNode->getEventController()->schedule(e2);
   }
}
Ejemplo n.º 27
0
UtlBoolean SipDialogMgr::isLastLocalTransaction(const SipMessage& message, 
                                                const char* dialogHandle)
{
    UtlBoolean matchesTransaction = FALSE;
    UtlString handle(dialogHandle ? dialogHandle : "");
    // If the dialog handle was not set, get it from the message
    if(handle.isNull())
    {
       SipDialog::getDialogHandle(message, handle);
    }

    UtlString callId;
    UtlString fromTag;
    UtlString toTag;
    Url fromField;
    Url toField;
    message.getFromUrl(fromField);
    message.getToUrl(toField);
    message.getCallIdField(callId);
    fromField.getFieldParameter("tag", fromTag);
    toField.getFieldParameter("tag", toTag);

    lock();
    // Looking for any dialog that matches this handle
    SipDialog* dialog = findDialog(handle,
                                   TRUE, // if established, match early dialog
                                   TRUE); // if early, match established dialog

    if(dialog && 
       dialog->isTransactionLocallyInitiated(callId, fromTag, toTag) &&
       dialog->isSameLocalCseq(message))
    {
        matchesTransaction = TRUE;
    }

    unlock();
    
    return(matchesTransaction);
}
Ejemplo n.º 28
0
/// Encode dialog-independent identity into a URL
bool SipXauthIdentity::encodeUri(Url             & uri,     ///< target URI to get encoded identity
                                 const OsDateTime* timestamp///< timestamp for generated identity
               )
{
   // Don't proceed if the encapsulated identity is invalid
   if (!mIsValidIdentity)
   {
      Os::Logger::instance().log(FAC_SIP, PRI_CRIT,
                    "SipXauthIdentity::encodeUri[unbound]: "
                    "encapsulated SipXauthIdentity is invalid");
   }
   else
   {
      // make sure no existing identity in the URI
      uri.removeHeaderParameter(SipXauthIdentity::AuthIdentityHeaderName);

      OsDateTime now;
      OsDateTime::getCurTime(now);
      if (NULL==timestamp)
      {
         timestamp = &now;
      }

      UtlString value;
      UtlString callId;
      UtlString fromTag;
      encode(value, callId, fromTag, *timestamp, allowUnbound);
      uri.setHeaderParameter(SipXauthIdentity::AuthIdentityHeaderName, value.data());

      Os::Logger::instance().log(FAC_SIP, PRI_DEBUG,
                    "SipXauthIdentity::encodeUri[unbound] "
                    "encoded URI '%s'",
                    uri.toString().data()
                    );
   }

   return mIsValidIdentity;
}
Ejemplo n.º 29
0
void
AliasDB::getAliases (
    const Url& contactIdentity,
    ResultSet& rResultSet ) const
{
    UtlString contactIdentityStr;
    contactIdentity.getIdentity(contactIdentityStr);

    // This should erase the contents of the existing resultset
    rResultSet.clear();

    if ( !contactIdentityStr.isNull() && (m_pFastDB != NULL) )
    {
        // Thread Local Storage
        m_pFastDB->attach();

        // Match a all rows where the contact identity matches
        UtlString queryString = "contact like '%" + contactIdentityStr + "%'";

        dbQuery query;
        query=queryString;

        // Search to see if we have a Credential Row
        dbCursor< AliasRow > cursor;

        if ( cursor.select(query) > 0 )
        {
            do {
                UtlHashMap record;
                UtlString* identityValue =
                    new UtlString ( cursor->identity );
                UtlString* contactValue =
                    new UtlString ( cursor->contact );

                // Memory Leak fixes, make shallow copies of static keys
                UtlString* identityKey = new UtlString( gIdentityKey );
                UtlString* contactKey = new UtlString( gContactKey );

                record.insertKeyAndValue (
                    identityKey, identityValue );
                record.insertKeyAndValue (
                    contactKey, contactValue );

                rResultSet.addValue(record);
            } while ( cursor.next() );
        }
        // Commit the rows to memory - multiprocess workaround
        m_pFastDB->detach(0);
    }
}
Ejemplo n.º 30
0
void Command::receive(const Url &url, const Value &val) {
  if (!handle_reply_message(url, val) && !handle_register_message(url, val)) {
    Value res = root_->call(url, val);

    if (res.is_error()) {
      // only send reply to caller
      send(url.location(), ERROR_PATH, res);
    } else {
      // prepare reply
      Value reply(url.path());
      reply.push_back(res);
      if (url.is_meta()) {
        // only send to caller
        send(url.location(), REPLY_PATH, reply);
      } else {
        // notify all
        // FIXME: since notifications always go to '/.reply', why not transform this into
        // root_->notify_observers(url.path(), res) ?
        root_->notify_observers(REPLY_PATH, reply);
      }
    }
  }
}