Ejemplo n.º 1
0
nsresult
nsDOMWorkerScriptLoader::RunInternal()
{
  NS_ASSERTION(NS_IsMainThread(), "Wrong thread!");

  if (mForWorker) {
    NS_ASSERTION(mScriptCount == 1, "Bad state!");
  }

  nsRefPtr<nsDOMWorker> parentWorker = mWorker->GetParent();

  // Figure out which principal to use.
  nsIPrincipal* principal = mWorker->GetPrincipal();
  if (!principal) {
    if (!parentWorker) {
      NS_ERROR("Must have a principal if this is not a subworker!");
    }
    principal = parentWorker->GetPrincipal();
  }
  NS_ASSERTION(principal, "This should never be null here!");

  // Figure out our base URI.
  nsCOMPtr<nsIURI> baseURI;
  if (mForWorker) {
    if (parentWorker) {
      baseURI = parentWorker->GetBaseURI();
      NS_ASSERTION(baseURI, "Should have been set already!");
    }
    else {
      // May be null.
      baseURI = mWorker->GetBaseURI();

      // Don't leave a temporary URI hanging around.
      mWorker->ClearBaseURI();
    }
    NS_ASSERTION(!mWorker->GetBaseURI(), "Should not be set here!");
  }
  else {
    baseURI = mWorker->GetBaseURI();
    NS_ASSERTION(baseURI, "Should have been set already!");
  }

  nsCOMPtr<nsIDocument> parentDoc = mWorker->Pool()->ParentDocument();

  // All of these can potentially be null, but that should be ok. We'll either
  // succeed without them or fail below.
  nsCOMPtr<nsILoadGroup> loadGroup;
  if (parentDoc) {
    loadGroup = parentDoc->GetDocumentLoadGroup();
  }

  nsCOMPtr<nsIIOService> ios(do_GetIOService());

  nsIScriptSecurityManager* secMan = nsContentUtils::GetSecurityManager();
  NS_ASSERTION(secMan, "This should never be null!");

  for (PRUint32 index = 0; index < mScriptCount; index++) {
    ScriptLoadInfo& loadInfo = mLoadInfos[index];
    nsresult& rv = loadInfo.result;

    nsCOMPtr<nsIURI>& uri = loadInfo.finalURI;
    rv = nsContentUtils::NewURIWithDocumentCharset(getter_AddRefs(uri),
                                                   loadInfo.url, parentDoc,
                                                   baseURI);
    if (NS_FAILED(rv)) {
      return rv;
    }

    // If we're part of a document then check the content load policy.
    if (parentDoc) {
      PRInt16 shouldLoad = nsIContentPolicy::ACCEPT;
      rv = NS_CheckContentLoadPolicy(nsIContentPolicy::TYPE_SCRIPT, uri,
                                     principal, parentDoc,
                                     NS_LITERAL_CSTRING("text/javascript"),
                                     nsnull, &shouldLoad,
                                     nsContentUtils::GetContentPolicy(),
                                     secMan);
      if (NS_FAILED(rv) || NS_CP_REJECTED(shouldLoad)) {
        if (NS_FAILED(rv) || shouldLoad != nsIContentPolicy::REJECT_TYPE) {
          return (rv = NS_ERROR_CONTENT_BLOCKED);
        }
        return (rv = NS_ERROR_CONTENT_BLOCKED_SHOW_ALT);
      }
    }

    // If this script loader is being used to make a new worker then we need to
    // do a same-origin check. Otherwise we need to clear the load with the
    // security manager.
    rv = mForWorker ?
         principal->CheckMayLoad(uri, PR_FALSE):
         secMan->CheckLoadURIWithPrincipal(principal, uri, 0);
    NS_ENSURE_SUCCESS(rv, rv);

    // We need to know which index we're on in OnStreamComplete so we know where
    // to put the result.
    nsCOMPtr<nsISupportsPRUint32> indexSupports =
      do_CreateInstance(NS_SUPPORTS_PRUINT32_CONTRACTID, &rv);
    NS_ENSURE_SUCCESS(rv, rv);

    rv = indexSupports->SetData(index);
    NS_ENSURE_SUCCESS(rv, rv);

    // We don't care about progress so just use the simple stream loader for
    // OnStreamComplete notification only.
    nsCOMPtr<nsIStreamLoader> loader;
    rv = NS_NewStreamLoader(getter_AddRefs(loader), this);
    NS_ENSURE_SUCCESS(rv, rv);

    // Get Content Security Policy from parent document to pass into channel
    nsCOMPtr<nsIContentSecurityPolicy> csp;
    rv = principal->GetCsp(getter_AddRefs(csp));
    NS_ENSURE_SUCCESS(rv, rv);

    nsCOMPtr<nsIChannelPolicy> channelPolicy;
    if (csp) {
      channelPolicy = do_CreateInstance("@mozilla.org/nschannelpolicy;1", &rv);
      NS_ENSURE_SUCCESS(rv, rv);

      rv = channelPolicy->SetContentSecurityPolicy(csp);
      NS_ENSURE_SUCCESS(rv, rv);

      rv = channelPolicy->SetLoadType(nsIContentPolicy::TYPE_SCRIPT);
      NS_ENSURE_SUCCESS(rv, rv);
    }

    rv = NS_NewChannel(getter_AddRefs(loadInfo.channel),
                       uri, ios, loadGroup, nsnull,
                       nsIRequest::LOAD_NORMAL | nsIChannel::LOAD_CLASSIFY_URI,
                       channelPolicy);
    NS_ENSURE_SUCCESS(rv, rv);

    rv = loadInfo.channel->AsyncOpen(loader, indexSupports);
    if (NS_FAILED(rv)) {
      // Null this out so we don't try to cancel it later.
      loadInfo.channel = nsnull;
      return rv;
    }
  }

  return NS_OK;
}
nsresult
nsUrlClassifierStreamUpdater::FetchUpdate(nsIURI *aUpdateUrl,
                                          const nsACString & aRequestBody,
                                          const nsACString & aStreamTable)
{

#ifdef DEBUG
  {
    nsCString spec;
    aUpdateUrl->GetSpec(spec);
    LOG(("Fetching update %s from %s", aRequestBody.Data(), spec.get()));
  }
#endif

  nsresult rv;
  uint32_t loadFlags = nsIChannel::INHIBIT_CACHING |
                       nsIChannel::LOAD_BYPASS_CACHE;
  rv = NS_NewChannel(getter_AddRefs(mChannel),
                     aUpdateUrl,
                     nsContentUtils::GetSystemPrincipal(),
                     nsILoadInfo::SEC_ALLOW_CROSS_ORIGIN_DATA_IS_NULL,
                     nsIContentPolicy::TYPE_OTHER,
                     nullptr,  // aLoadGroup
                     this,     // aInterfaceRequestor
                     loadFlags);

  NS_ENSURE_SUCCESS(rv, rv);

  nsCOMPtr<nsILoadInfo> loadInfo = mChannel->GetLoadInfo();
  loadInfo->SetOriginAttributes(mozilla::OriginAttributes(NECKO_SAFEBROWSING_APP_ID, false));

  mBeganStream = false;

  // If aRequestBody is empty, construct it for the test.
  if (!aRequestBody.IsEmpty()) {
    rv = AddRequestBody(aRequestBody);
    NS_ENSURE_SUCCESS(rv, rv);
  }

  // Set the appropriate content type for file/data URIs, for unit testing
  // purposes.
  // This is only used for testing and should be deleted.
  bool match;
  if ((NS_SUCCEEDED(aUpdateUrl->SchemeIs("file", &match)) && match) ||
      (NS_SUCCEEDED(aUpdateUrl->SchemeIs("data", &match)) && match)) {
    mChannel->SetContentType(NS_LITERAL_CSTRING("application/vnd.google.safebrowsing-update"));
  } else {
    // We assume everything else is an HTTP request.

    // Disable keepalive.
    nsCOMPtr<nsIHttpChannel> httpChannel = do_QueryInterface(mChannel, &rv);
    NS_ENSURE_SUCCESS(rv, rv);
    rv = httpChannel->SetRequestHeader(NS_LITERAL_CSTRING("Connection"), NS_LITERAL_CSTRING("close"), false);
    NS_ENSURE_SUCCESS(rv, rv);
  }

  // Create a custom LoadContext for SafeBrowsing, so we can use callbacks on
  // the channel to query the appId which allows separation of safebrowsing
  // cookies in a separate jar.
  nsCOMPtr<nsIInterfaceRequestor> sbContext =
    new mozilla::LoadContext(NECKO_SAFEBROWSING_APP_ID);
  rv = mChannel->SetNotificationCallbacks(sbContext);
  NS_ENSURE_SUCCESS(rv, rv);

  // Make the request.
  rv = mChannel->AsyncOpen2(this);
  NS_ENSURE_SUCCESS(rv, rv);

  mStreamTable = aStreamTable;

  return NS_OK;
}
NS_IMETHODIMP
nsXULTemplateQueryProcessorStorage::GetDatasource(nsIArray* aDataSources,
                                                  nsIDOMNode* aRootNode,
                                                  bool aIsTrusted,
                                                  nsIXULTemplateBuilder* aBuilder,
                                                  bool* aShouldDelayBuilding,
                                                  nsISupports** aReturn)
{
    *aReturn = nullptr;
    *aShouldDelayBuilding = false;

    if (!aIsTrusted) {
        return NS_OK;
    }

    uint32_t length;
    nsresult rv = aDataSources->GetLength(&length);
    NS_ENSURE_SUCCESS(rv, rv);

    if (length == 0) {
        return NS_OK;
    }

    // We get only the first uri. This query processor supports
    // only one database at a time.
    nsCOMPtr<nsIURI> uri;
    uri = do_QueryElementAt(aDataSources, 0);

    if (!uri) {
        // No uri in the list of datasources
        return NS_OK;
    }

    nsCOMPtr<mozIStorageService> storage =
        do_GetService("@mozilla.org/storage/service;1", &rv);
    NS_ENSURE_SUCCESS(rv, rv);

    nsCOMPtr<nsIFile> databaseFile;
    nsAutoCString scheme;
    rv = uri->GetScheme(scheme);
    NS_ENSURE_SUCCESS(rv, rv);

    if (scheme.EqualsLiteral("profile")) {

        nsAutoCString path;
        rv = uri->GetPath(path);
        NS_ENSURE_SUCCESS(rv, rv);

        if (path.IsEmpty()) {
            return NS_ERROR_FAILURE;
        }

        rv = NS_GetSpecialDirectory(NS_APP_USER_PROFILE_50_DIR,
                                             getter_AddRefs(databaseFile));
        NS_ENSURE_SUCCESS(rv, rv);

        rv = databaseFile->AppendNative(path);
        NS_ENSURE_SUCCESS(rv, rv);
    }
    else {
        nsCOMPtr<nsIChannel> channel;
        nsCOMPtr<nsINode> node = do_QueryInterface(aRootNode);

        rv = NS_NewChannel(getter_AddRefs(channel),
                           uri,
                           node,
                           nsILoadInfo::SEC_NORMAL,
                           nsIContentPolicy::TYPE_OTHER);
        NS_ENSURE_SUCCESS(rv, rv);

        nsCOMPtr<nsIFileChannel> fileChannel = do_QueryInterface(channel, &rv);
        if (NS_FAILED(rv)) { // if it fails, not a file url
            nsXULContentUtils::LogTemplateError(ERROR_TEMPLATE_STORAGE_BAD_URI);
            return rv;
        }

        nsCOMPtr<nsIFile> file;
        rv = fileChannel->GetFile(getter_AddRefs(databaseFile));
        NS_ENSURE_SUCCESS(rv, rv);
    }

    // ok now we have an URI of a sqlite file
    nsCOMPtr<mozIStorageConnection> connection;
    rv = storage->OpenDatabase(databaseFile, getter_AddRefs(connection));
    if (NS_FAILED(rv)) {
        nsXULContentUtils::LogTemplateError(ERROR_TEMPLATE_STORAGE_CANNOT_OPEN_DATABASE);
        return rv;
    }

    NS_ADDREF(*aReturn = connection);
    return NS_OK;
}
Ejemplo n.º 4
0
nsresult
nsPluginStreamListenerPeer::RequestRead(NPByteRange* rangeList)
{
    nsAutoCString rangeString;
    int32_t numRequests;

    MakeByteRangeString(rangeList, rangeString, &numRequests);

    if (numRequests == 0)
        return NS_ERROR_FAILURE;

    nsresult rv = NS_OK;

    nsRefPtr<nsPluginInstanceOwner> owner = mPluginInstance->GetOwner();
    nsCOMPtr<nsIDOMElement> element;
    nsCOMPtr<nsIDocument> doc;
    if (owner) {
        rv = owner->GetDOMElement(getter_AddRefs(element));
        NS_ENSURE_SUCCESS(rv, rv);
        rv = owner->GetDocument(getter_AddRefs(doc));
        NS_ENSURE_SUCCESS(rv, rv);
    }

    nsCOMPtr<nsIInterfaceRequestor> callbacks = do_QueryReferent(mWeakPtrChannelCallbacks);
    nsCOMPtr<nsILoadGroup> loadGroup = do_QueryReferent(mWeakPtrChannelLoadGroup);

    nsCOMPtr<nsIChannel> channel;
    nsCOMPtr<nsINode> requestingNode(do_QueryInterface(element));
    if (requestingNode) {
        rv = NS_NewChannel(getter_AddRefs(channel),
                           mURL,
                           requestingNode,
                           nsILoadInfo::SEC_NORMAL,
                           nsIContentPolicy::TYPE_OTHER,
                           loadGroup,
                           callbacks);
    }
    else {
        // in this else branch we really don't know where the load is coming
        // from and in fact should use something better than just using
        // a nullPrincipal as the loadingPrincipal.
        nsCOMPtr<nsIPrincipal> principal =
            do_CreateInstance("@mozilla.org/nullprincipal;1", &rv);
        NS_ENSURE_SUCCESS(rv, rv);
        rv = NS_NewChannel(getter_AddRefs(channel),
                           mURL,
                           principal,
                           nsILoadInfo::SEC_NORMAL,
                           nsIContentPolicy::TYPE_OTHER,
                           loadGroup,
                           callbacks);
    }

    if (NS_FAILED(rv))
        return rv;

    nsCOMPtr<nsIHttpChannel> httpChannel(do_QueryInterface(channel));
    if (!httpChannel)
        return NS_ERROR_FAILURE;

    httpChannel->SetRequestHeader(NS_LITERAL_CSTRING("Range"), rangeString, false);

    mAbort = true; // instruct old stream listener to cancel
    // the request on the next ODA.

    nsCOMPtr<nsIStreamListener> converter;

    if (numRequests == 1) {
        converter = this;
        // set current stream offset equal to the first offset in the range list
        // it will work for single byte range request
        // for multy range we'll reset it in ODA
        SetStreamOffset(rangeList->offset);
    } else {
        nsWeakPtr weakpeer =
            do_GetWeakReference(static_cast<nsISupportsWeakReference*>(this));
        nsPluginByteRangeStreamListener *brrListener =
            new nsPluginByteRangeStreamListener(weakpeer);
        if (brrListener)
            converter = brrListener;
        else
            return NS_ERROR_OUT_OF_MEMORY;
    }

    mPendingRequests += numRequests;

    nsCOMPtr<nsISupportsPRUint32> container = do_CreateInstance(NS_SUPPORTS_PRUINT32_CONTRACTID, &rv);
    if (NS_FAILED(rv))
        return rv;
    rv = container->SetData(MAGIC_REQUEST_CONTEXT);
    if (NS_FAILED(rv))
        return rv;

    rv = channel->AsyncOpen(converter, container);
    if (NS_SUCCEEDED(rv))
        TrackRequest(channel);
    return rv;
}
Ejemplo n.º 5
0
nsresult nsAutoConfig::downloadAutoConfig()
{
    nsresult rv;
    nsCAutoString emailAddr;
    nsXPIDLCString urlName;
    static bool firstTime = true;
    
    if (mConfigURL.IsEmpty()) {
        PR_LOG(MCD, PR_LOG_DEBUG, ("global config url is empty - did you set autoadmin.global_config_url?\n"));
        NS_WARNING("AutoConfig called without global_config_url");
        return NS_OK;
    }
    
    // If there is an email address appended as an argument to the ConfigURL
    // in the previous read, we need to remove it when timer kicks in and 
    // downloads the autoconfig file again. 
    // If necessary, the email address will be added again as an argument.
    PRInt32 index = mConfigURL.RFindChar((PRUnichar)'?');
    if (index != -1)
        mConfigURL.Truncate(index);

    // Clean up the previous read, the new read is going to use the same buffer
    if (!mBuf.IsEmpty())
        mBuf.Truncate(0);

    // Get the preferences branch and save it to the member variable
    if (!mPrefBranch) {
        nsCOMPtr<nsIPrefService> prefs =
            do_GetService(NS_PREFSERVICE_CONTRACTID, &rv);
        if (NS_FAILED(rv)) 
            return rv;
    
        rv = prefs->GetBranch(nsnull,getter_AddRefs(mPrefBranch));
        if (NS_FAILED(rv))
            return rv;
    }
    
    // Check to see if the network is online/offline 
    nsCOMPtr<nsIIOService> ios = do_GetService(NS_IOSERVICE_CONTRACTID, &rv);
    if (NS_FAILED(rv)) 
        return rv;
    
    bool offline;
    rv = ios->GetOffline(&offline);
    if (NS_FAILED(rv)) 
        return rv;
    
    if (offline) {
        bool offlineFailover;
        rv = mPrefBranch->GetBoolPref("autoadmin.offline_failover", 
                                      &offlineFailover);
        // Read the failover.jsc if the network is offline and the pref says so
        if (NS_SUCCEEDED(rv) && offlineFailover)
            return readOfflineFile();
    }

    /* Append user's identity at the end of the URL if the pref says so.
       First we are checking for the user's email address but if it is not
       available in the case where the client is used without messenger, user's
       profile name will be used as an unique identifier
    */
    bool appendMail;
    rv = mPrefBranch->GetBoolPref("autoadmin.append_emailaddr", &appendMail);
    if (NS_SUCCEEDED(rv) && appendMail) {
        rv = getEmailAddr(emailAddr);
        if (NS_SUCCEEDED(rv) && emailAddr.get()) {
            /* Adding the unique identifier at the end of autoconfig URL. 
               In this case the autoconfig URL is a script and 
               emailAddr as passed as an argument 
            */
            mConfigURL.Append("?");
            mConfigURL.Append(emailAddr); 
        }
    }
    
    // create a new url 
    nsCOMPtr<nsIURI> url;
    nsCOMPtr<nsIChannel> channel;
    
    rv = NS_NewURI(getter_AddRefs(url), mConfigURL.get(), nsnull, nsnull);
    if (NS_FAILED(rv))
    {
        PR_LOG(MCD, PR_LOG_DEBUG, ("failed to create URL - is autoadmin.global_config_url valid? - %s\n", mConfigURL.get()));
        return rv;
    }

    PR_LOG(MCD, PR_LOG_DEBUG, ("running MCD url %s\n", mConfigURL.get()));
    // open a channel for the url
    rv = NS_NewChannel(getter_AddRefs(channel),url, nsnull, nsnull, nsnull, nsIRequest::INHIBIT_PERSISTENT_CACHING | nsIRequest::LOAD_BYPASS_CACHE);
    if (NS_FAILED(rv)) 
        return rv;

    rv = channel->AsyncOpen(this, nsnull); 
    if (NS_FAILED(rv)) {
        readOfflineFile();
        return rv;
    }
    
    // Set a repeating timer if the pref is set.
    // This is to be done only once.
    // Also We are having the event queue processing only for the startup
    // It is not needed with the repeating timer.
    if (firstTime) {
        firstTime = PR_FALSE;
    
        // Getting the current thread. If we start an AsyncOpen, the thread
        // needs to wait before the reading of autoconfig is done

        nsCOMPtr<nsIThread> thread = do_GetCurrentThread();
        NS_ENSURE_STATE(thread);
    
        /* process events until we're finished. AutoConfig.jsc reading needs
           to be finished before the browser starts loading up
           We are waiting for the mLoaded which will be set through 
           onStopRequest or readOfflineFile methods
           There is a possibility of deadlock so we need to make sure
           that mLoaded will be set to true in any case (success/failure)
        */
        
        while (!mLoaded)
            NS_ENSURE_STATE(NS_ProcessNextEvent(thread));
        
        PRInt32 minutes;
        rv = mPrefBranch->GetIntPref("autoadmin.refresh_interval", 
                                     &minutes);
        if (NS_SUCCEEDED(rv) && minutes > 0) {
            // Create a new timer and pass this nsAutoConfig 
            // object as a timer callback. 
            mTimer = do_CreateInstance("@mozilla.org/timer;1",&rv);
            if (NS_FAILED(rv)) 
                return rv;
            rv = mTimer->InitWithCallback(this, minutes * 60 * 1000, 
                             nsITimer::TYPE_REPEATING_SLACK);
            if (NS_FAILED(rv)) 
                return rv;
        }
    } //first_time
    
    return NS_OK;
} // nsPref::downloadAutoConfig()
Ejemplo n.º 6
0
int
main(int argc, char* argv[])
{
  if (test_common_init(&argc, &argv) != 0)
    return -1;

  nsresult ret;

  nsCOMPtr<nsIServiceManager> servMan;
  NS_InitXPCOM2(getter_AddRefs(servMan), nullptr, nullptr);

  nsIInputStream* in = nullptr;

  nsCOMPtr<nsIScriptSecurityManager> secman =
    do_GetService(NS_SCRIPTSECURITYMANAGER_CONTRACTID, &ret);
  if (NS_FAILED(ret)) return 1;
  nsCOMPtr<nsIPrincipal> systemPrincipal;
    ret = secman->GetSystemPrincipal(getter_AddRefs(systemPrincipal));
   if (NS_FAILED(ret)) return 1;

  nsCOMPtr<nsIURI> uri;
  ret = NS_NewURI(getter_AddRefs(uri), NS_LITERAL_CSTRING(TEST_URL));
  if (NS_FAILED(ret)) return 1;

  nsIChannel *channel = nullptr;
  ret = NS_NewChannel(&channel,
                      uri,
                      systemPrincipal,
                      nsILoadInfo::SEC_ALLOW_CROSS_ORIGIN_DATA_IS_NULL,
                      nsIContentPolicy::TYPE_OTHER);
  if (NS_FAILED(ret)) return 1;

  ret = channel->Open2(&in);
  if (NS_FAILED(ret)) return 1;

  nsIPersistentProperties* props;
  ret = CallCreateInstance(kPersistentPropertiesCID, &props);
  if (NS_FAILED(ret) || (!props)) {
    printf("create nsIPersistentProperties failed\n");
    return 1;
  }
  ret = props->Load(in);
  if (NS_FAILED(ret)) {
    printf("cannot load properties\n");
    return 1;
  }
  int i = 1;
  while (1) {
    char name[16];
    name[0] = 0;
    SprintfLiteral(name, "%d", i);
    nsAutoString v;
    ret = props->GetStringProperty(nsDependentCString(name), v);
    if (NS_FAILED(ret) || (!v.Length())) {
      break;
    }
    printf("\"%d\"=\"%s\"\n", i, NS_ConvertUTF16toUTF8(v).get());
    i++;
  }

  nsCOMPtr<nsISimpleEnumerator> propEnum;
  ret = props->Enumerate(getter_AddRefs(propEnum));

  if (NS_FAILED(ret)) {
    printf("cannot enumerate properties\n");
    return 1;
  }
  

  printf("\nKey\tValue\n");
  printf(  "---\t-----\n");
  
  bool hasMore;
  while (NS_SUCCEEDED(propEnum->HasMoreElements(&hasMore)) &&
         hasMore) {
    nsCOMPtr<nsISupports> sup;
    ret = propEnum->GetNext(getter_AddRefs(sup));
    
    nsCOMPtr<nsIPropertyElement> propElem = do_QueryInterface(sup, &ret);
	  if (NS_FAILED(ret)) {
      printf("failed to get current item\n");
      return 1;
	  }

    nsAutoCString key;
    nsAutoString value;

    ret = propElem->GetKey(key);
	  if (NS_FAILED(ret)) {
		  printf("failed to get current element's key\n");
		  return 1;
	  }
    ret = propElem->GetValue(value);
	  if (NS_FAILED(ret)) {
		  printf("failed to get current element's value\n");
		  return 1;
	  }

    printf("%s\t%s\n", key.get(), NS_ConvertUTF16toUTF8(value).get());
  }
  return 0;
}
Ejemplo n.º 7
0
nsresult PeerConnectionMedia::Init(const std::vector<NrIceStunServer>& stun_servers,
                                   const std::vector<NrIceTurnServer>& turn_servers,
                                   NrIceCtx::Policy policy)
{
  nsresult rv;
  nsCOMPtr<nsIProtocolProxyService> pps =
    do_GetService(NS_PROTOCOLPROXYSERVICE_CONTRACTID, &rv);
  if (NS_FAILED(rv)) {
    CSFLogError(logTag, "%s: Failed to get proxy service: %d", __FUNCTION__, (int)rv);
    return NS_ERROR_FAILURE;
  }

  // We use the following URL to find the "default" proxy address for all HTTPS
  // connections.  We will only attempt one HTTP(S) CONNECT per peer connection.
  // "example.com" is guaranteed to be unallocated and should return the best default.
  nsCOMPtr<nsIURI> fakeHttpsLocation;
  rv = NS_NewURI(getter_AddRefs(fakeHttpsLocation), "https://example.com");
  if (NS_FAILED(rv)) {
    CSFLogError(logTag, "%s: Failed to set URI: %d", __FUNCTION__, (int)rv);
    return NS_ERROR_FAILURE;
  }

  nsCOMPtr<nsIScriptSecurityManager> secMan(
      do_GetService(NS_SCRIPTSECURITYMANAGER_CONTRACTID, &rv));
  if (NS_FAILED(rv)) {
    CSFLogError(logTag, "%s: Failed to get IOService: %d",
        __FUNCTION__, (int)rv);
    CSFLogError(logTag, "%s: Failed to get securityManager: %d", __FUNCTION__, (int)rv);
    return NS_ERROR_FAILURE;
  }

  nsCOMPtr<nsIPrincipal> systemPrincipal;
  rv = secMan->GetSystemPrincipal(getter_AddRefs(systemPrincipal));
  if (NS_FAILED(rv)) {
    CSFLogError(logTag, "%s: Failed to get systemPrincipal: %d", __FUNCTION__, (int)rv);
    return NS_ERROR_FAILURE;
  }

  nsCOMPtr<nsIChannel> channel;
  rv = NS_NewChannel(getter_AddRefs(channel),
                     fakeHttpsLocation,
                     systemPrincipal,
                     nsILoadInfo::SEC_ALLOW_CROSS_ORIGIN_DATA_IS_NULL,
                     nsIContentPolicy::TYPE_OTHER);

  if (NS_FAILED(rv)) {
    CSFLogError(logTag, "%s: Failed to get channel from URI: %d",
                __FUNCTION__, (int)rv);
    return NS_ERROR_FAILURE;
  }

  RefPtr<ProtocolProxyQueryHandler> handler = new ProtocolProxyQueryHandler(this);
  rv = pps->AsyncResolve(channel,
                         nsIProtocolProxyService::RESOLVE_PREFER_HTTPS_PROXY |
                         nsIProtocolProxyService::RESOLVE_ALWAYS_TUNNEL,
                         handler, getter_AddRefs(mProxyRequest));
  if (NS_FAILED(rv)) {
    CSFLogError(logTag, "%s: Failed to resolve protocol proxy: %d", __FUNCTION__, (int)rv);
    return NS_ERROR_FAILURE;
  }

#if !defined(MOZILLA_EXTERNAL_LINKAGE)
  bool ice_tcp = Preferences::GetBool("media.peerconnection.ice.tcp", false);
  if (!XRE_IsParentProcess()) {
    CSFLogError(logTag, "%s: ICE TCP not support on e10s", __FUNCTION__);
    ice_tcp = false;
  }
  bool default_address_only = Preferences::GetBool(
    "media.peerconnection.ice.default_address_only", false);
#else
  bool ice_tcp = false;
  bool default_address_only = false;
#endif


  // TODO([email protected]): need some way to set not offerer later
  // Looks like a bug in the NrIceCtx API.
  mIceCtx = NrIceCtx::Create("PC:" + mParentName,
                             true, // Offerer
                             mParent->GetAllowIceLoopback(),
                             ice_tcp,
                             mParent->GetAllowIceLinkLocal(),
                             default_address_only,
                             policy);
  if(!mIceCtx) {
    CSFLogError(logTag, "%s: Failed to create Ice Context", __FUNCTION__);
    return NS_ERROR_FAILURE;
  }

  if (NS_FAILED(rv = mIceCtx->SetStunServers(stun_servers))) {
    CSFLogError(logTag, "%s: Failed to set stun servers", __FUNCTION__);
    return rv;
  }
  // Give us a way to globally turn off TURN support
#if !defined(MOZILLA_EXTERNAL_LINKAGE)
  bool disabled = Preferences::GetBool("media.peerconnection.turn.disable", false);
#else
  bool disabled = false;
#endif
  if (!disabled) {
    if (NS_FAILED(rv = mIceCtx->SetTurnServers(turn_servers))) {
      CSFLogError(logTag, "%s: Failed to set turn servers", __FUNCTION__);
      return rv;
    }
  } else if (turn_servers.size() != 0) {
    CSFLogError(logTag, "%s: Setting turn servers disabled", __FUNCTION__);
  }
  if (NS_FAILED(rv = mDNSResolver->Init())) {
    CSFLogError(logTag, "%s: Failed to initialize dns resolver", __FUNCTION__);
    return rv;
  }
  if (NS_FAILED(rv = mIceCtx->SetResolver(mDNSResolver->AllocateResolver()))) {
    CSFLogError(logTag, "%s: Failed to get dns resolver", __FUNCTION__);
    return rv;
  }
  mIceCtx->SignalGatheringStateChange.connect(
      this,
      &PeerConnectionMedia::IceGatheringStateChange_s);
  mIceCtx->SignalConnectionStateChange.connect(
      this,
      &PeerConnectionMedia::IceConnectionStateChange_s);

  return NS_OK;
}
Ejemplo n.º 8
0
void txMozillaTextOutput::createResultDocument(nsIDOMDocument* aSourceDocument,
                                               nsIDOMDocument* aResultDocument)
{
    nsresult rv = NS_OK;
    
    /*
     * Create an XHTML document to hold the text.
     *
     * <html>
     *   <head />
     *   <body>
     *     <pre> * The text comes here * </pre>
     *   <body>
     * </html>
     *
     * Except if we are transforming into a non-displayed document we create
     * the following DOM
     *
     * <transformiix:result> * The text comes here * </transformiix:result>
     */
     
    nsCOMPtr<nsIDocument> doc;
    if (!aResultDocument) {
        // Create the document
        doc = do_CreateInstance(kXMLDocumentCID, &rv);
        NS_ASSERTION(NS_SUCCEEDED(rv), "Couldn't create document");
        nsCOMPtr<nsIDocument_MOZILLA_1_8_BRANCH3> source =
          do_QueryInterface(aSourceDocument);
        if (!source) {
          return;
        }
        PRBool hasHadScriptObject = PR_FALSE;
        nsIScriptGlobalObject* sgo =
          source->GetScriptHandlingObject(hasHadScriptObject);
        if (!sgo && hasHadScriptObject) {
          return;
        }
        nsCOMPtr<nsIDocument_MOZILLA_1_8_BRANCH3> doc18 =
          do_QueryInterface(doc);
        if (!doc18) {
          return;
        }
        doc18->SetScriptHandlingObject(sgo);
        mDocument = do_QueryInterface(doc);
    }
    else {
        mDocument = aResultDocument;
        doc = do_QueryInterface(aResultDocument);
        NS_ASSERTION(doc, "Couldn't QI to nsIDocument");
    }

    if (!doc) {
        return;
    }

    NS_ASSERTION(mDocument, "Need document");

    nsCOMPtr<nsIDOMNSDocument> nsDoc = do_QueryInterface(mDocument);
    if (nsDoc) {
        nsDoc->SetTitle(EmptyString());
    }

    // Reset and set up document
    nsCOMPtr<nsIDocument> sourceDoc = do_QueryInterface(aSourceDocument);
    nsIPrincipal* sourcePrincipal = sourceDoc->GetPrincipal();
    if (!sourcePrincipal) {
        return;
    }

    nsCOMPtr<nsILoadGroup> loadGroup = sourceDoc->GetDocumentLoadGroup();
    nsCOMPtr<nsIChannel> channel = sourceDoc->GetChannel();
    if (!channel) {
        // Need to synthesize one
        if (NS_FAILED(NS_NewChannel(getter_AddRefs(channel),
                                    sourceDoc->GetDocumentURI(),
                                    nsnull,
                                    loadGroup))) {
            return;
        }
        channel->SetOwner(sourcePrincipal);
    }
    // Copy the channel and loadgroup from the source document.
    doc->Reset(channel, loadGroup);
    doc->SetPrincipal(sourcePrincipal);
    doc->SetBaseURI(sourceDoc->GetBaseURI());

    // Set the charset
    if (!mOutputFormat.mEncoding.IsEmpty()) {
        NS_LossyConvertUTF16toASCII charset(mOutputFormat.mEncoding);
        nsCAutoString canonicalCharset;
        nsCOMPtr<nsICharsetAlias> calias =
            do_GetService("@mozilla.org/intl/charsetalias;1");

        if (calias &&
            NS_SUCCEEDED(calias->GetPreferred(charset, canonicalCharset))) {
            doc->SetDocumentCharacterSet(canonicalCharset);
            doc->SetDocumentCharacterSetSource(kCharsetFromOtherComponent);
        }
    }
    else {
        doc->SetDocumentCharacterSet(sourceDoc->GetDocumentCharacterSet());
        doc->SetDocumentCharacterSetSource(
            sourceDoc->GetDocumentCharacterSetSource());
    }

    // Notify the contentsink that the document is created
    nsCOMPtr<nsITransformObserver> observer = do_QueryReferent(mObserver);
    if (observer) {
        observer->OnDocumentCreated(mDocument);
    }

    // Create the content

    // When transforming into a non-displayed document (i.e. when there is no
    // observer) we only create a transformiix:result root element.
    // Don't do this when called through nsIXSLTProcessorObsolete (i.e. when
    // aResultDocument is set) for compability reasons
    nsCOMPtr<nsIDOMNode> textContainer;
    if (!aResultDocument && !observer) {
        nsCOMPtr<nsIDOMElement> docElement;
        mDocument->CreateElementNS(NS_LITERAL_STRING(kTXNameSpaceURI),
                                   NS_LITERAL_STRING(kTXWrapper),
                                   getter_AddRefs(docElement));
        NS_ASSERTION(docElement, "Failed to create wrapper element");
        if (!docElement) {
            return;
        }

        rv = mDocument->AppendChild(docElement, getter_AddRefs(textContainer));
        NS_ASSERTION(NS_SUCCEEDED(rv), "Failed to append the wrapper element");
        if (NS_FAILED(rv)) {
            return;
        }
    }
    else {
        nsCOMPtr<nsIDOMElement> element, docElement;
        nsCOMPtr<nsIDOMNode> parent, pre;

        NS_NAMED_LITERAL_STRING(XHTML_NSURI, "http://www.w3.org/1999/xhtml");

        mDocument->CreateElementNS(XHTML_NSURI,
                                   NS_LITERAL_STRING("html"),
                                   getter_AddRefs(docElement));
        nsCOMPtr<nsIContent> rootContent = do_QueryInterface(docElement);
        NS_ASSERTION(rootContent, "Need root element");
        if (!rootContent) {
            return;
        }

        // XXXbz what to do on failure here?
        rv = doc->SetRootContent(rootContent);
        if (NS_FAILED(rv)) {
            NS_ERROR("Failed to set root content");
            return;
        }
            

        mDocument->CreateElementNS(XHTML_NSURI,
                                   NS_LITERAL_STRING("head"),
                                   getter_AddRefs(element));
        NS_ASSERTION(element, "Failed to create head element");
        if (!element) {
            return;
        }

        rv = docElement->AppendChild(element, getter_AddRefs(parent));
        NS_ASSERTION(NS_SUCCEEDED(rv), "Failed to append the head element");
        if (NS_FAILED(rv)) {
            return;
        }

        mDocument->CreateElementNS(XHTML_NSURI,
                                   NS_LITERAL_STRING("body"),
                                   getter_AddRefs(element));
        NS_ASSERTION(element, "Failed to create body element");
        if (!element) {
            return;
        }

        rv = docElement->AppendChild(element, getter_AddRefs(parent));
        NS_ASSERTION(NS_SUCCEEDED(rv), "Failed to append the body element");
        if (NS_FAILED(rv)) {
            return;
        }

        mDocument->CreateElementNS(XHTML_NSURI,
                                   NS_LITERAL_STRING("pre"),
                                   getter_AddRefs(element));
        NS_ASSERTION(element, "Failed to create pre element");
        if (!element) {
            return;
        }

        rv = parent->AppendChild(element, getter_AddRefs(pre));
        NS_ASSERTION(NS_SUCCEEDED(rv), "Failed to append the pre element");
        if (NS_FAILED(rv)) {
            return;
        }

        nsCOMPtr<nsIDOMHTMLElement> htmlElement = do_QueryInterface(pre);
        htmlElement->SetId(NS_LITERAL_STRING("transformiixResult"));
        NS_ASSERTION(NS_SUCCEEDED(rv), "Failed to append the id");
        
        textContainer = pre;
    }

    nsCOMPtr<nsIDOMText> textNode;
    mDocument->CreateTextNode(EmptyString(),
                              getter_AddRefs(textNode));
    NS_ASSERTION(textNode, "Failed to create the text node");
    if (!textNode) {
        return;
    }

    nsCOMPtr<nsIDOMNode> dummy;
    rv = textContainer->AppendChild(textNode, getter_AddRefs(dummy));
    NS_ASSERTION(NS_SUCCEEDED(rv), "Failed to append the text node");
    if (NS_FAILED(rv)) {
        return;
    }

    mTextNode = textNode;
}
Ejemplo n.º 9
0
int main (int argc, char* argv[]) 
{
  nsresult                     rv;
  nsCOMPtr<nsIURI>             pURI;
  nsCOMPtr<nsIChannel>         pChannel;
  nsCOMPtr<nsIInputStream>     pInputStream;
  PRUint32                     uiContentLength;
  nsCOMPtr<nsIDOMParser>       pDOMParser;
  nsCOMPtr<nsIDOMDocument>     pDOMDocument;
  nsCOMPtr<nsIXMLHttpRequest>  pXMLHttpRequest;

  nsIServiceManager *servMgr;

  rv = NS_InitXPCOM2(&servMgr, nsnull, nsnull);
  if (NS_FAILED(rv)) return rv;

  if (argc > 2) {
    if (nsCRT::strcasecmp( argv[1], "parsestr" ) == 0) {
      pDOMParser = do_CreateInstance( NS_DOMPARSER_CONTRACTID,
                                     &rv );

      if (NS_SUCCEEDED( rv )) {
        nsString str; str.AssignWithConversion(argv[2]);
        rv = pDOMParser->ParseFromString(str.get(), "application/xml",
                                          getter_AddRefs( pDOMDocument ) );

        if (NS_SUCCEEDED( rv )) {
          printf( "DOM parse string of\n\n%s\n\nsuccessful\n", argv[2] );
        }
        else {
          printf( "DOM parse of \n%s\n NOT successful\n", argv[2] );
        }
      }
      else {
        printf( "do_CreateInstance of DOMParser failed for %s - %08X\n", argv[2], rv );
      }
    } else if (nsCRT::strcasecmp( argv[1], "parse" ) == 0) {
      // DOM Parser
      rv = NS_NewURI( getter_AddRefs( pURI ),
                      argv[2] );

      if (NS_SUCCEEDED( rv )) {
        rv = NS_NewChannel( getter_AddRefs( pChannel ),
                         pURI,
                         nsnull,
                         nsnull );

        if (NS_SUCCEEDED( rv )) {
          rv = pChannel->Open( getter_AddRefs( pInputStream ) );

          if (NS_SUCCEEDED( rv )) {
            rv = pInputStream->Available(&uiContentLength );

            if (NS_SUCCEEDED( rv )) {
              pDOMParser = do_CreateInstance( NS_DOMPARSER_CONTRACTID,
                                             &rv );

              if (NS_SUCCEEDED( rv )) {
                pDOMParser->SetBaseURI(pURI);

                rv = pDOMParser->ParseFromStream( pInputStream,
                                                  "UTF-8",
                                                  uiContentLength,
                                                  "application/xml",
                                                  getter_AddRefs( pDOMDocument ) );
                if (NS_SUCCEEDED( rv )) {
                  printf( "DOM parse of %s successful\n", argv[2] );
                }
                else {
                  printf( "DOM parse of %s NOT successful\n", argv[2] );
                }
              }
              else {
                printf( "do_CreateInstance of DOMParser failed for %s - %08X\n", argv[2], rv );
              }
            }
            else {
              printf( "pInputSteam->Available failed for %s - %08X\n", argv[2], rv );
            }
          }
          else {
            printf( "pChannel->OpenInputStream failed for %s - %08X\n", argv[2], rv );
          }
        }
        else {
          printf( "NS_NewChannel failed for %s - %08X\n", argv[2], rv );
        }
      }
      else {
        printf( "NS_NewURI failed for %s - %08X\n", argv[2], rv );
      }
    }
    else if (nsCRT::strcasecmp( argv[1], "syncread" ) == 0) {
      // Synchronous Read
      pXMLHttpRequest = do_CreateInstance( NS_XMLHTTPREQUEST_CONTRACTID,
                                          &rv );

      if (NS_SUCCEEDED( rv )) {
        const nsAString& emptyStr = EmptyString();
        rv = pXMLHttpRequest->OpenRequest( NS_LITERAL_CSTRING("GET"),
                                           nsDependentCString(argv[2]),
                                           PR_FALSE, emptyStr, emptyStr );

        if (NS_SUCCEEDED( rv )) {
          rv = pXMLHttpRequest->Send( nsnull );

          if (NS_SUCCEEDED( rv )) {
            rv = pXMLHttpRequest->GetResponseXML( getter_AddRefs( pDOMDocument ) );

            if (NS_SUCCEEDED( rv )) {

              if (pDOMDocument) {
                printf( "Synchronous read of %s successful, DOMDocument created\n", argv[2] );
              }
              else {
                printf( "Synchronous read of %s NOT successful, DOMDocument NOT created\n", argv[2] );
              }
            }
            else {
              printf( "pXMLHttpRequest->GetResponseXML failed for %s - %08X\n", argv[2], rv );
            }
          }
          else {
            printf( "pXMLHttpRequest->Send failed for %s - %08X\n", argv[2], rv );
          }
        }
        else {
          printf( "pXMLHttpRequest->OpenRequest failed for %s - %08X\n", argv[2], rv );
        }
      }
      else {
        printf( "do_CreateInstance of XMLHttpRequest failed for %s - %08X\n", argv[2], rv );
      }
    }
#if 0
    else if (nsCRT::strcasecmp( argv[1], "load" ) == 0) {
      nsMyListener * listener = new nsMyListener();
      listener->Start(argv[2]);
    }
#endif
    else {
      usage( );
    }
  }
  else {
    usage( );
  }

  if (pDOMDocument) {
    nsCOMPtr<nsIDOMElement> element;
    pDOMDocument->GetDocumentElement(getter_AddRefs(element));
    nsAutoString tagName;
    if (element) element->GetTagName(tagName);
    char *s = ToNewCString(tagName);
    printf("Document element=\"%s\"\n",s);
    nsCRT::free(s);
    nsCOMPtr<nsIDocument> doc = do_QueryInterface(pDOMDocument);
    if (doc) {
      nsCAutoString spec;
      doc->GetDocumentURI()->GetSpec(spec);
      printf("Document URI=\"%s\"\n",spec.get());
    }
  }

  pURI = nsnull;
  pChannel = nsnull;
  pInputStream = nsnull;
  pDOMParser = nsnull;
  pDOMDocument = nsnull;
  pXMLHttpRequest = nsnull;

  if (servMgr)
    rv = NS_ShutdownXPCOM(servMgr);
  
  return rv;
}
Ejemplo n.º 10
0
void
nsHTTPIndex::FireTimer(nsITimer* aTimer, void* aClosure)
{
  nsHTTPIndex *httpIndex = static_cast<nsHTTPIndex *>(aClosure);
  if (!httpIndex)	return;
  
  // don't return out of this loop as mTimer may need to be cancelled afterwards
  PRUint32    numItems = 0;
  if (httpIndex->mConnectionList)
  {
        httpIndex->mConnectionList->Count(&numItems);
        if (numItems > 0)
        {
          nsCOMPtr<nsISupports>   isupports;
          httpIndex->mConnectionList->GetElementAt((PRUint32)0, getter_AddRefs(isupports));
          httpIndex->mConnectionList->RemoveElementAt((PRUint32)0);
          
          nsCOMPtr<nsIRDFResource>    aSource;
          if (isupports)  aSource = do_QueryInterface(isupports);
          
          nsXPIDLCString uri;
          if (aSource) {
            httpIndex->GetDestination(aSource, uri);
          }
          
          if (!uri) {
            NS_ERROR("Could not reconstruct uri");
            return;
          }
          
          nsresult            rv = NS_OK;
          nsCOMPtr<nsIURI>	url;
          
          rv = NS_NewURI(getter_AddRefs(url), uri.get());
          nsCOMPtr<nsIChannel>	channel;
          if (NS_SUCCEEDED(rv) && (url)) {
            rv = NS_NewChannel(getter_AddRefs(channel), url, nsnull, nsnull);
          }
          if (NS_SUCCEEDED(rv) && (channel)) {
            channel->SetNotificationCallbacks(httpIndex);
            rv = channel->AsyncOpen(httpIndex, aSource);
          }
        }
  }
    if (httpIndex->mNodeList)
    {
        httpIndex->mNodeList->Count(&numItems);
        if (numItems > 0)
        {
            // account for order required: src, prop, then target
            numItems /=3;
            if (numItems > 10)  numItems = 10;
          
            PRInt32 loop;
            for (loop=0; loop<(PRInt32)numItems; loop++)
            {
                nsCOMPtr<nsISupports>   isupports;
                httpIndex->mNodeList->GetElementAt((PRUint32)0, getter_AddRefs(isupports));
                httpIndex->mNodeList->RemoveElementAt((PRUint32)0);
                nsCOMPtr<nsIRDFResource>    src;
                if (isupports)  src = do_QueryInterface(isupports);
                httpIndex->mNodeList->GetElementAt((PRUint32)0, getter_AddRefs(isupports));
                httpIndex->mNodeList->RemoveElementAt((PRUint32)0);
                nsCOMPtr<nsIRDFResource>    prop;
                if (isupports)  prop = do_QueryInterface(isupports);
                
                httpIndex->mNodeList->GetElementAt((PRUint32)0, getter_AddRefs(isupports));
                httpIndex->mNodeList->RemoveElementAt((PRUint32)0);
                nsCOMPtr<nsIRDFNode>    target;
                if (isupports)  target = do_QueryInterface(isupports);
                
                if (src && prop && target)
                {
                    if (prop.get() == httpIndex->kNC_Loading)
                    {
                        httpIndex->Unassert(src, prop, target);
                    }
                    else
                    {
                        httpIndex->Assert(src, prop, target, PR_TRUE);
                    }
                }
            }                
        }
    }

    PRBool refireTimer = PR_FALSE;
    // check both lists to see if the timer needs to continue firing
    if (httpIndex->mConnectionList)
    {
        httpIndex->mConnectionList->Count(&numItems);
        if (numItems > 0)
        {
            refireTimer = PR_TRUE;
        }
        else
        {
            httpIndex->mConnectionList->Clear();
        }
    }
    if (httpIndex->mNodeList)
    {
        httpIndex->mNodeList->Count(&numItems);
        if (numItems > 0)
        {
            refireTimer = PR_TRUE;
        }
        else
        {
            httpIndex->mNodeList->Clear();
        }
    }

    // be sure to cancel the timer, as it holds a
    // weak reference back to nsHTTPIndex
    httpIndex->mTimer->Cancel();
    httpIndex->mTimer = nsnull;
    
    // after firing off any/all of the connections be sure
    // to cancel the timer if we don't need to refire it
    if (refireTimer)
    {
      httpIndex->mTimer = do_CreateInstance("@mozilla.org/timer;1");
      if (httpIndex->mTimer)
      {
        httpIndex->mTimer->InitWithFuncCallback(nsHTTPIndex::FireTimer, aClosure, 10,
                                                nsITimer::TYPE_ONE_SHOT);
        // Note: don't addref "this" as we'll cancel the
        // timer in the httpIndex destructor
      }
    }
}
Ejemplo n.º 11
0
NS_IMETHODIMP
nsXMLDocument::Load(const nsAString& aUrl, bool *aReturn)
{
  bool hasHadScriptObject = true;
  nsIScriptGlobalObject* scriptObject =
    GetScriptHandlingObject(hasHadScriptObject);
  NS_ENSURE_STATE(scriptObject || !hasHadScriptObject);

  ReportUseOfDeprecatedMethod(this, "UseOfDOM3LoadMethodWarning");

  NS_ENSURE_ARG_POINTER(aReturn);
  *aReturn = false;

  nsCOMPtr<nsIDocument> callingDoc =
    do_QueryInterface(nsContentUtils::GetDocumentFromContext());

  nsIURI *baseURI = mDocumentURI;
  nsAutoCString charset;

  if (callingDoc) {
    baseURI = callingDoc->GetDocBaseURI();
    charset = callingDoc->GetDocumentCharacterSet();
  }

  // Create a new URI
  nsCOMPtr<nsIURI> uri;
  nsresult rv = NS_NewURI(getter_AddRefs(uri), aUrl, charset.get(), baseURI);
  if (NS_FAILED(rv)) {
    return rv;
  }

  // Check to see whether the current document is allowed to load this URI.
  // It's important to use the current document's principal for this check so
  // that we don't end up in a case where code with elevated privileges is
  // calling us and changing the principal of this document.

  // Enforce same-origin even for chrome loaders to avoid someone accidentally
  // using a document that content has a reference to and turn that into a
  // chrome document.
  nsCOMPtr<nsIPrincipal> principal = NodePrincipal();
  if (!nsContentUtils::IsSystemPrincipal(principal)) {
    rv = principal->CheckMayLoad(uri, false, false);
    NS_ENSURE_SUCCESS(rv, rv);

    int16_t shouldLoad = nsIContentPolicy::ACCEPT;
    rv = NS_CheckContentLoadPolicy(nsIContentPolicy::TYPE_XMLHTTPREQUEST,
                                   uri,
                                   principal,
                                   callingDoc ? callingDoc.get() :
                                     static_cast<nsIDocument*>(this),
                                   NS_LITERAL_CSTRING("application/xml"),
                                   nullptr,
                                   &shouldLoad,
                                   nsContentUtils::GetContentPolicy(),
                                   nsContentUtils::GetSecurityManager());
    NS_ENSURE_SUCCESS(rv, rv);
    if (NS_CP_REJECTED(shouldLoad)) {
      return NS_ERROR_CONTENT_BLOCKED;
    }
  } else {
    // We're called from chrome, check to make sure the URI we're
    // about to load is also chrome.

    bool isChrome = false;
    if (NS_FAILED(uri->SchemeIs("chrome", &isChrome)) || !isChrome) {
      nsAutoCString spec;
      if (mDocumentURI)
        mDocumentURI->GetSpec(spec);

      nsAutoString error;
      error.AssignLiteral("Cross site loading using document.load is no "
                          "longer supported. Use XMLHttpRequest instead.");
      nsCOMPtr<nsIScriptError> errorObject =
          do_CreateInstance(NS_SCRIPTERROR_CONTRACTID, &rv);
      NS_ENSURE_SUCCESS(rv, rv);

      rv = errorObject->InitWithWindowID(error,
                                         NS_ConvertUTF8toUTF16(spec),
                                         EmptyString(),
                                         0, 0, nsIScriptError::warningFlag,
                                         "DOM",
                                         callingDoc ?
                                           callingDoc->InnerWindowID() :
                                           this->InnerWindowID());

      NS_ENSURE_SUCCESS(rv, rv);

      nsCOMPtr<nsIConsoleService> consoleService =
        do_GetService(NS_CONSOLESERVICE_CONTRACTID);
      if (consoleService) {
        consoleService->LogMessage(errorObject);
      }

      return NS_ERROR_DOM_SECURITY_ERR;
    }
  }

  // Partial Reset, need to restore principal for security reasons and
  // event listener manager so that load listeners etc. will
  // remain. This should be done before the security check is done to
  // ensure that the document is reset even if the new document can't
  // be loaded.  Note that we need to hold a strong ref to |principal|
  // here, because ResetToURI will null out our node principal before
  // setting the new one.
  nsRefPtr<nsEventListenerManager> elm(mListenerManager);
  mListenerManager = nullptr;

  // When we are called from JS we can find the load group for the page,
  // and add ourselves to it. This way any pending requests
  // will be automatically aborted if the user leaves the page.

  nsCOMPtr<nsILoadGroup> loadGroup;
  if (callingDoc) {
    loadGroup = callingDoc->GetDocumentLoadGroup();
  }

  ResetToURI(uri, loadGroup, principal);

  mListenerManager = elm;

  // Create a channel
  nsCOMPtr<nsIInterfaceRequestor> req = nsContentUtils::GetSameOriginChecker();
  NS_ENSURE_TRUE(req, NS_ERROR_OUT_OF_MEMORY);  

  nsCOMPtr<nsIChannel> channel;
  // nsIRequest::LOAD_BACKGROUND prevents throbber from becoming active,
  // which in turn keeps STOP button from becoming active  
  rv = NS_NewChannel(getter_AddRefs(channel), uri, nullptr, loadGroup, req, 
                     nsIRequest::LOAD_BACKGROUND);
  if (NS_FAILED(rv)) {
    return rv;
  }

  // StartDocumentLoad asserts that readyState is uninitialized, so
  // uninitialize it. SetReadyStateInternal make this transition invisible to
  // Web content. But before doing that, assert that the current readyState
  // is complete as it should be after the call to ResetToURI() above.
  MOZ_ASSERT(GetReadyStateEnum() == nsIDocument::READYSTATE_COMPLETE,
             "Bad readyState");
  SetReadyStateInternal(nsIDocument::READYSTATE_UNINITIALIZED);

  // Prepare for loading the XML document "into oneself"
  nsCOMPtr<nsIStreamListener> listener;
  if (NS_FAILED(rv = StartDocumentLoad(kLoadAsData, channel, 
                                       loadGroup, nullptr, 
                                       getter_AddRefs(listener),
                                       false))) {
    NS_ERROR("nsXMLDocument::Load: Failed to start the document load.");
    return rv;
  }

  // After this point, if we error out of this method we should clear
  // mChannelIsPending.

  // Start an asynchronous read of the XML document
  rv = channel->AsyncOpen(listener, nullptr);
  if (NS_FAILED(rv)) {
    mChannelIsPending = false;
    return rv;
  }

  if (!mAsync) {
    nsCOMPtr<nsIThread> thread = do_GetCurrentThread();

    nsAutoSyncOperation sync(this);
    mLoopingForSyncLoad = true;
    while (mLoopingForSyncLoad) {
      if (!NS_ProcessNextEvent(thread))
        break;
    }

    // We set return to true unless there was a parsing error
    nsCOMPtr<nsIDOMNode> node = do_QueryInterface(GetRootElement());
    if (node) {
      nsAutoString name, ns;      
      if (NS_SUCCEEDED(node->GetLocalName(name)) &&
          name.EqualsLiteral("parsererror") &&
          NS_SUCCEEDED(node->GetNamespaceURI(ns)) &&
          ns.EqualsLiteral("http://www.mozilla.org/newlayout/xml/parsererror.xml")) {
        //return is already false
      } else {
        *aReturn = true;
      }
    }
  } else {
    *aReturn = true;
  }

  return NS_OK;
}
Ejemplo n.º 12
0
NS_IMETHODIMP
nsDirectoryViewerFactory::CreateInstance(const char *aCommand,
                                         nsIChannel* aChannel,
                                         nsILoadGroup* aLoadGroup,
                                         const char* aContentType, 
                                         nsISupports* aContainer,
                                         nsISupports* aExtraInfo,
                                         nsIStreamListener** aDocListenerResult,
                                         nsIContentViewer** aDocViewerResult)
{
  nsresult rv;

  // OK - are we going to be using the html listing or not?
  nsCOMPtr<nsIPrefBranch> prefSrv = do_GetService(NS_PREFSERVICE_CONTRACTID, &rv);
  if (NS_FAILED(rv)) return rv;

  PRBool viewSource = (PL_strstr(aContentType,"view-source") != 0);
  
#ifdef MOZ_RDF
  PRBool useXUL = PR_FALSE;

  PRInt32 dirPref;
  rv = prefSrv->GetIntPref("network.dir.format", &dirPref);
  if (NS_SUCCEEDED(rv) && dirPref == FORMAT_XUL) {
    useXUL = PR_TRUE;
  }

  if ((NS_FAILED(rv) || useXUL) && !viewSource) {
    // ... and setup the original channel's content type
    (void)aChannel->SetContentType(NS_LITERAL_CSTRING("application/vnd.mozilla.xul+xml"));

    // This is where we shunt the HTTP/Index stream into our datasource,
    // and open the directory viewer XUL file as the content stream to
    // load in its place.
    
    // Create a dummy loader that will load a stub XUL document.
    nsCOMPtr<nsICategoryManager> catMan(do_GetService(NS_CATEGORYMANAGER_CONTRACTID, &rv));
    if (NS_FAILED(rv))
      return rv;
    nsXPIDLCString contractID;
    rv = catMan->GetCategoryEntry("Gecko-Content-Viewers", "application/vnd.mozilla.xul+xml",
                                  getter_Copies(contractID));
    if (NS_FAILED(rv))
      return rv;

    nsCOMPtr<nsIDocumentLoaderFactory> factory(do_GetService(contractID, &rv));
    if (NS_FAILED(rv)) return rv;
    
    nsCOMPtr<nsIURI> uri;
    rv = NS_NewURI(getter_AddRefs(uri), "chrome://communicator/content/directory/directory.xul");
    if (NS_FAILED(rv)) return rv;
    
    nsCOMPtr<nsIChannel> channel;
    rv = NS_NewChannel(getter_AddRefs(channel), uri, nsnull, aLoadGroup);
    if (NS_FAILED(rv)) return rv;
    
    nsCOMPtr<nsIStreamListener> listener;
    rv = factory->CreateInstance(aCommand, channel, aLoadGroup, "application/vnd.mozilla.xul+xml",
                                 aContainer, aExtraInfo, getter_AddRefs(listener),
                                 aDocViewerResult);
    if (NS_FAILED(rv)) return rv;

    rv = channel->AsyncOpen(listener, nsnull);
    if (NS_FAILED(rv)) return rv;
    
    // Create an HTTPIndex object so that we can stuff it into the script context
    nsCOMPtr<nsIURI> baseuri;
    rv = aChannel->GetURI(getter_AddRefs(baseuri));
    if (NS_FAILED(rv)) return rv;
    
    nsCOMPtr<nsIInterfaceRequestor> requestor = do_QueryInterface(aContainer,&rv);
    if (NS_FAILED(rv)) return rv;
    
    nsCOMPtr<nsIHTTPIndex> httpindex;
    rv = nsHTTPIndex::Create(baseuri, requestor, getter_AddRefs(httpindex));
    if (NS_FAILED(rv)) return rv;
    
    // Now shanghai the stream into our http-index parsing datasource
    // wrapper beastie.
    listener = do_QueryInterface(httpindex,&rv);
    *aDocListenerResult = listener.get();
    NS_ADDREF(*aDocListenerResult);
    
    return NS_OK;
  }
#endif

  // setup the original channel's content type
  (void)aChannel->SetContentType(NS_LITERAL_CSTRING("text/html"));

  // Otherwise, lets use the html listing
  nsCOMPtr<nsICategoryManager> catMan(do_GetService(NS_CATEGORYMANAGER_CONTRACTID, &rv));
  if (NS_FAILED(rv))
    return rv;
  nsXPIDLCString contractID;
  rv = catMan->GetCategoryEntry("Gecko-Content-Viewers", "text/html",
                                getter_Copies(contractID));
  if (NS_FAILED(rv))
    return rv;

  nsCOMPtr<nsIDocumentLoaderFactory> factory(do_GetService(contractID, &rv));
  if (NS_FAILED(rv)) return rv;
  
  nsCOMPtr<nsIStreamListener> listener;

  if (viewSource) {
    rv = factory->CreateInstance("view-source", aChannel, aLoadGroup, "text/html; x-view-type=view-source",
                                 aContainer, aExtraInfo, getter_AddRefs(listener),
                                 aDocViewerResult);
  } else {
    rv = factory->CreateInstance("view", aChannel, aLoadGroup, "text/html",
                                 aContainer, aExtraInfo, getter_AddRefs(listener),
                                 aDocViewerResult);
  }

  if (NS_FAILED(rv)) return rv;

  nsCOMPtr<nsIStreamConverterService> scs = do_GetService("@mozilla.org/streamConverters;1", &rv);
  if (NS_FAILED(rv)) return rv;

  rv = scs->AsyncConvertData("application/http-index-format",
                             "text/html",
                             listener,
                             nsnull,
                             aDocListenerResult);

  if (NS_FAILED(rv)) return rv;

  return NS_OK;
}
Ejemplo n.º 13
0
nsresult runTest(uint32_t aExpectedPolicyCount, // this should be 0 for policies which should fail to parse
                 const char* aPolicy,
                 const char* aExpextedResult) {

  // we init the csp with http://www.selfuri.com
  nsCOMPtr<nsIURI> selfURI;
  nsresult rv = NS_NewURI(getter_AddRefs(selfURI), "http://www.selfuri.com");
  NS_ENSURE_SUCCESS(rv, rv);

  // we also init the csp with a dummyChannel, which is unused
  // for the parser tests but surpresses assertions in SetRequestContext.
  nsCOMPtr<nsIChannel> dummyChannel;
  rv = NS_NewChannel(getter_AddRefs(dummyChannel), selfURI);
  NS_ENSURE_SUCCESS(rv, rv);

  // create a CSP object
  nsCOMPtr<nsIContentSecurityPolicy> csp =
    do_CreateInstance(NS_CSPCONTEXT_CONTRACTID, &rv);
  NS_ENSURE_SUCCESS(rv, rv);

  // for testing the parser we only need to set selfURI which is needed
  // to translate the keyword 'self' into an actual URI. All other
  // arguments can be nullptrs.
  csp->SetRequestContext(selfURI,
                         nullptr,  // nsIURI* aReferrer
                         dummyChannel);
  NS_ENSURE_SUCCESS(rv, rv);

  // append a policy
  nsString policyStr;
  policyStr.AssignASCII(aPolicy);
  rv = csp->AppendPolicy(policyStr, false);
  NS_ENSURE_SUCCESS(rv, rv);

  // when executing fuzzy tests we do not care about the actual output
  // of the parser, we just want to make sure that the parser is not crashing.
  if (aExpectedPolicyCount == kFuzzyExpectedPolicyCount) {
    return NS_OK;
  }

  // verify that the expected number of policies exists
  uint32_t actualPolicyCount;
  rv = csp->GetPolicyCount(&actualPolicyCount);
  NS_ENSURE_SUCCESS(rv, rv);
  if (actualPolicyCount != aExpectedPolicyCount) {
    fail("Actual policy count not equal to expected policy count (%d != %d) for policy: %s",
          actualPolicyCount, aExpectedPolicyCount, aPolicy);
    return NS_ERROR_UNEXPECTED;
  }

  // if the expected policy count is 0, we can return, because
  // we can not compare any output anyway. Used when parsing
  // errornous policies.
  if (aExpectedPolicyCount == 0) {
    return NS_OK;
  }

  // compare the parsed policy against the expected result
  nsString parsedPolicyStr;
  // checking policy at index 0, which is the one what we appended.
  rv = csp->GetPolicy(0, parsedPolicyStr);
  NS_ENSURE_SUCCESS(rv, rv);

  if (!NS_ConvertUTF16toUTF8(parsedPolicyStr).EqualsASCII(aExpextedResult)) {
    fail("Actual policy does not match expected policy  (%s != %s)",
          NS_ConvertUTF16toUTF8(parsedPolicyStr).get(), aExpextedResult);
    return NS_ERROR_UNEXPECTED;
  }

  return NS_OK;
}
Ejemplo n.º 14
0
nsresult
nsIncrementalDownload::ProcessTimeout()
{
  NS_ASSERTION(!mChannel, "how can we have a channel?");

  // Handle existing error conditions
  if (NS_FAILED(mStatus)) {
    CallOnStopRequest();
    return NS_OK;
  }

  // Fetch next chunk
  
  nsCOMPtr<nsIChannel> channel;
  nsresult rv = NS_NewChannel(getter_AddRefs(channel),
                              mFinalURI,
                              nsContentUtils::GetSystemPrincipal(),
                              nsILoadInfo::SEC_NORMAL,
                              nsIContentPolicy::TYPE_OTHER,
                              nullptr,   // loadGroup
                              this,      // aCallbacks
                              mLoadFlags);

  if (NS_FAILED(rv))
    return rv;

  nsCOMPtr<nsIHttpChannel> http = do_QueryInterface(channel, &rv);
  if (NS_FAILED(rv))
    return rv;

  NS_ASSERTION(mCurrentSize != int64_t(-1),
      "we should know the current file size by now");

  rv = ClearRequestHeader(http);
  if (NS_FAILED(rv))
    return rv;

  // Don't bother making a range request if we are just going to fetch the
  // entire document.
  if (mInterval || mCurrentSize != int64_t(0)) {
    nsAutoCString range;
    MakeRangeSpec(mCurrentSize, mTotalSize, mChunkSize, mInterval == 0, range);

    rv = http->SetRequestHeader(NS_LITERAL_CSTRING("Range"), range, false);
    if (NS_FAILED(rv))
      return rv;

    if (!mPartialValidator.IsEmpty())
      http->SetRequestHeader(NS_LITERAL_CSTRING("If-Range"),
                             mPartialValidator, false);

    if (mCacheBust) {
      http->SetRequestHeader(NS_LITERAL_CSTRING("Cache-Control"),
                             NS_LITERAL_CSTRING("no-cache"), false);
      http->SetRequestHeader(NS_LITERAL_CSTRING("Pragma"),
                             NS_LITERAL_CSTRING("no-cache"), false);
    }
  }

  rv = channel->AsyncOpen(this, nullptr);
  if (NS_FAILED(rv))
    return rv;

  // Wait to assign mChannel when we know we are going to succeed.  This is
  // important because we don't want to introduce a reference cycle between
  // mChannel and this until we know for a fact that AsyncOpen has succeeded,
  // thus ensuring that our stream listener methods will be invoked.
  mChannel = channel;
  return NS_OK;
}
Ejemplo n.º 15
0
nsresult
nsFileChannel::OpenContentStream(bool async, nsIInputStream **result,
                                 nsIChannel** channel)
{
  // NOTE: the resulting file is a clone, so it is safe to pass it to the
  //       file input stream which will be read on a background thread.
  nsCOMPtr<nsIFile> file;
  nsresult rv = GetFile(getter_AddRefs(file));
  if (NS_FAILED(rv))
    return rv;

  nsCOMPtr<nsIFileProtocolHandler> fileHandler;
  rv = NS_GetFileProtocolHandler(getter_AddRefs(fileHandler));
  if (NS_FAILED(rv))
    return rv;
    
  nsCOMPtr<nsIURI> newURI;
  rv = fileHandler->ReadURLFile(file, getter_AddRefs(newURI));
  if (NS_SUCCEEDED(rv)) {
    nsCOMPtr<nsIChannel> newChannel;
    rv = NS_NewChannel(getter_AddRefs(newChannel), newURI);
    if (NS_FAILED(rv))
      return rv;

    *result = nullptr;
    newChannel.forget(channel);
    return NS_OK;
  }

  nsCOMPtr<nsIInputStream> stream;

  if (mUploadStream) {
    // Pass back a nsFileUploadContentStream instance that knows how to perform
    // the file copy when "read" (the resulting stream in this case does not
    // actually return any data).

    nsCOMPtr<nsIOutputStream> fileStream;
    rv = NS_NewLocalFileOutputStream(getter_AddRefs(fileStream), file,
                                     PR_WRONLY | PR_CREATE_FILE | PR_TRUNCATE,
                                     PR_IRUSR | PR_IWUSR);
    if (NS_FAILED(rv))
      return rv;

    nsFileUploadContentStream *uploadStream =
        new nsFileUploadContentStream(async, fileStream, mUploadStream,
                                      mUploadLength, this);
    if (!uploadStream || !uploadStream->IsInitialized()) {
      delete uploadStream;
      return NS_ERROR_OUT_OF_MEMORY;
    }
    stream = uploadStream;

    mContentLength = 0;

    // Since there isn't any content to speak of we just set the content-type
    // to something other than "unknown" to avoid triggering the content-type
    // sniffer code in nsBaseChannel.
    // However, don't override explicitly set types.
    if (!HasContentTypeHint())
      SetContentType(NS_LITERAL_CSTRING(APPLICATION_OCTET_STREAM));
  } else {
    nsAutoCString contentType;
    rv = MakeFileInputStream(file, stream, contentType);
    if (NS_FAILED(rv))
      return rv;

    EnableSynthesizedProgressEvents(true);

    // fixup content length and type
    if (mContentLength < 0) {
      int64_t size;
      rv = file->GetFileSize(&size);
      if (NS_FAILED(rv))
        return rv;
      mContentLength = size;
    }
    if (!contentType.IsEmpty())
      SetContentType(contentType);
  }

  *result = nullptr;
  stream.swap(*result);
  return NS_OK;
}
Ejemplo n.º 16
0
nsresult
EventSource::InitChannelAndRequestEventSource()
{
  if (mReadyState == CLOSED) {
    return NS_ERROR_ABORT;
  }

  bool isValidScheme =
    (NS_SUCCEEDED(mSrc->SchemeIs("http", &isValidScheme)) && isValidScheme) ||
    (NS_SUCCEEDED(mSrc->SchemeIs("https", &isValidScheme)) && isValidScheme);

  nsresult rv = CheckInnerWindowCorrectness();
  if (NS_FAILED(rv) || !isValidScheme) {
    DispatchFailConnection();
    return NS_ERROR_DOM_SECURITY_ERR;
  }

  nsLoadFlags loadFlags;
  loadFlags = nsIRequest::LOAD_BACKGROUND | nsIRequest::LOAD_BYPASS_CACHE;

  nsIScriptContext* sc = GetContextForEventHandlers(&rv);
  nsCOMPtr<nsIDocument> doc =
    nsContentUtils::GetDocumentFromScriptContext(sc);

  nsSecurityFlags securityFlags =
    nsILoadInfo::SEC_REQUIRE_CORS_DATA_INHERITS;

  if (mWithCredentials) {
    securityFlags |= nsILoadInfo::SEC_COOKIES_INCLUDE;
  }

  nsCOMPtr<nsIChannel> channel;
  // If we have the document, use it
  if (doc) {
    rv = NS_NewChannel(getter_AddRefs(channel),
                       mSrc,
                       doc,
                       securityFlags,
                       nsIContentPolicy::TYPE_INTERNAL_EVENTSOURCE,
                       mLoadGroup,       // loadGroup
                       nullptr,          // aCallbacks
                       loadFlags);       // aLoadFlags
  } else {
    // otherwise use the principal
    rv = NS_NewChannel(getter_AddRefs(channel),
                       mSrc,
                       mPrincipal,
                       securityFlags,
                       nsIContentPolicy::TYPE_INTERNAL_EVENTSOURCE,
                       mLoadGroup,       // loadGroup
                       nullptr,          // aCallbacks
                       loadFlags);       // aLoadFlags
  }

  NS_ENSURE_SUCCESS(rv, rv);

  mHttpChannel = do_QueryInterface(channel);
  NS_ENSURE_TRUE(mHttpChannel, NS_ERROR_NO_INTERFACE);

  rv = SetupHttpChannel();
  NS_ENSURE_SUCCESS(rv, rv);

#ifdef DEBUG
  {
    nsCOMPtr<nsIInterfaceRequestor> notificationCallbacks;
    mHttpChannel->GetNotificationCallbacks(getter_AddRefs(notificationCallbacks));
    MOZ_ASSERT(!notificationCallbacks);
  }
#endif
  mHttpChannel->SetNotificationCallbacks(this);

  // Start reading from the channel
  rv = mHttpChannel->AsyncOpen2(this);
  if (NS_FAILED(rv)) {
    DispatchFailConnection();
    return rv;
  }
  mWaitingForOnStopRequest = true;
  return rv;
}
Ejemplo n.º 17
0
void
HTMLTrackElement::LoadResource()
{
  // Find our 'src' url
  nsAutoString src;
  if (!GetAttr(kNameSpaceID_None, nsGkAtoms::src, src)) {
    return;
  }

  nsCOMPtr<nsIURI> uri;
  nsresult rv = NewURIFromString(src, getter_AddRefs(uri));
  NS_ENSURE_TRUE_VOID(NS_SUCCEEDED(rv));
  LOG(PR_LOG_ALWAYS, ("%p Trying to load from src=%s", this,
      NS_ConvertUTF16toUTF8(src).get()));

  if (mChannel) {
    mChannel->Cancel(NS_BINDING_ABORTED);
    mChannel = nullptr;
  }

  rv = nsContentUtils::GetSecurityManager()->
    CheckLoadURIWithPrincipal(NodePrincipal(), uri,
                              nsIScriptSecurityManager::STANDARD);
  NS_ENSURE_TRUE_VOID(NS_SUCCEEDED(rv));

  int16_t shouldLoad = nsIContentPolicy::ACCEPT;
  rv = NS_CheckContentLoadPolicy(nsIContentPolicy::TYPE_MEDIA,
                                 uri,
                                 NodePrincipal(),
                                 static_cast<nsGenericHTMLElement*>(this),
                                 NS_LITERAL_CSTRING("text/vtt"), // mime type
                                 nullptr, // extra
                                 &shouldLoad,
                                 nsContentUtils::GetContentPolicy(),
                                 nsContentUtils::GetSecurityManager());
  NS_ENSURE_TRUE_VOID(NS_SUCCEEDED(rv));
  if (NS_CP_REJECTED(shouldLoad)) {
    return;
  }

  CreateTextTrack();

  // Check for a Content Security Policy to pass down to the channel
  // created to load the media content.
  nsCOMPtr<nsIChannelPolicy> channelPolicy;
  nsCOMPtr<nsIContentSecurityPolicy> csp;
  rv = NodePrincipal()->GetCsp(getter_AddRefs(csp));
  NS_ENSURE_TRUE_VOID(NS_SUCCEEDED(rv));
  if (csp) {
    channelPolicy = do_CreateInstance("@mozilla.org/nschannelpolicy;1");
    if (!channelPolicy) {
      return;
    }
    channelPolicy->SetContentSecurityPolicy(csp);
    channelPolicy->SetLoadType(nsIContentPolicy::TYPE_MEDIA);
  }
  nsCOMPtr<nsIChannel> channel;
  nsCOMPtr<nsILoadGroup> loadGroup = OwnerDoc()->GetDocumentLoadGroup();
  rv = NS_NewChannel(getter_AddRefs(channel),
                     uri,
                     nullptr,
                     loadGroup,
                     nullptr,
                     nsIRequest::LOAD_NORMAL,
                     channelPolicy);
  NS_ENSURE_TRUE_VOID(NS_SUCCEEDED(rv));

  mLoadListener = new WebVTTLoadListener(this);
  rv = mLoadListener->LoadResource();
  NS_ENSURE_TRUE_VOID(NS_SUCCEEDED(rv));
  channel->SetNotificationCallbacks(mLoadListener);

  LOG(PR_LOG_DEBUG, ("opening webvtt channel"));
  rv = channel->AsyncOpen(mLoadListener, nullptr);
  NS_ENSURE_TRUE_VOID(NS_SUCCEEDED(rv));

  mChannel = channel;
}
Ejemplo n.º 18
0
nsresult
nsExpatDriver::OpenInputStreamFromExternalDTD(const PRUnichar* aFPIStr,
                                              const PRUnichar* aURLStr,
                                              const PRUnichar* aBaseURL,
                                              nsIInputStream** aStream,
                                              nsAString& aAbsURL)
{
  nsCOMPtr<nsIURI> baseURI;
  nsresult rv = NS_NewURI(getter_AddRefs(baseURI),
                          NS_ConvertUTF16toUTF8(aBaseURL));
  NS_ENSURE_SUCCESS(rv, rv);

  nsCOMPtr<nsIURI> uri;
  rv = NS_NewURI(getter_AddRefs(uri), NS_ConvertUTF16toUTF8(aURLStr), nullptr,
                 baseURI);
  NS_ENSURE_SUCCESS(rv, rv);

  // check if it is alright to load this uri
  bool isChrome = false;
  uri->SchemeIs("chrome", &isChrome);
  if (!isChrome) {
    // since the url is not a chrome url, check to see if we can map the DTD
    // to a known local DTD, or if a DTD file of the same name exists in the
    // special DTD directory
    if (aFPIStr) {
      // see if the Formal Public Identifier (FPI) maps to a catalog entry
      mCatalogData = LookupCatalogData(aFPIStr);
    }

    nsCOMPtr<nsIURI> localURI;
    GetLocalDTDURI(mCatalogData, uri, getter_AddRefs(localURI));
    if (!localURI) {
      return NS_ERROR_NOT_IMPLEMENTED;
    }

    localURI.swap(uri);
  }

  nsCOMPtr<nsIDocument> doc;
  NS_ASSERTION(mSink == nsCOMPtr<nsIExpatSink>(do_QueryInterface(mOriginalSink)),
               "In nsExpatDriver::OpenInputStreamFromExternalDTD: "
               "mOriginalSink not the same object as mSink?");
  if (mOriginalSink)
    doc = do_QueryInterface(mOriginalSink->GetTarget());
  int16_t shouldLoad = nsIContentPolicy::ACCEPT;
  rv = NS_CheckContentLoadPolicy(nsIContentPolicy::TYPE_DTD,
                                uri,
                                (doc ? doc->NodePrincipal() : nullptr),
                                doc,
                                EmptyCString(), //mime guess
                                nullptr,         //extra
                                &shouldLoad);
  if (NS_FAILED(rv)) return rv;
  if (NS_CP_REJECTED(shouldLoad)) {
    // Disallowed by content policy
    return NS_ERROR_CONTENT_BLOCKED;
  }

  nsAutoCString absURL;
  uri->GetSpec(absURL);

  CopyUTF8toUTF16(absURL, aAbsURL);

  nsCOMPtr<nsIChannel> channel;
  rv = NS_NewChannel(getter_AddRefs(channel), uri);
  NS_ENSURE_SUCCESS(rv, rv);

  channel->SetContentType(NS_LITERAL_CSTRING("application/xml"));
  return channel->Open(aStream);
}
Ejemplo n.º 19
0
NS_IMETHODIMP nsXPInstallManager::DownloadNext()
{
    nsresult rv;
    mContentLength = 0;

    if (mCancelled)
    {
        // Don't download any more if we were cancelled
        Shutdown();
        return NS_OK;
    }

    if ( mNextItem < mTriggers->Size() )
    {
        //-------------------------------------------------
        // There are items to download, get the next one
        //-------------------------------------------------
        mItem = (nsXPITriggerItem*)mTriggers->Get(mNextItem++);

        NS_ASSERTION( mItem, "bogus Trigger slipped through" );
        NS_ASSERTION( !mItem->mURL.IsEmpty(), "bogus trigger");
        if ( !mItem || mItem->mURL.IsEmpty() )
        {
            // serious problem with trigger! Can't notify anyone of the
            // error without the URL, just try to carry on.
            return DownloadNext();
        }

        // --- Tell the dialog we're starting a download
        if (mDlg)
            mDlg->OnStateChange( mNextItem-1, nsIXPIProgressDialog::DOWNLOAD_START, 0 );

        if ( mItem->IsFileURL() && mChromeType == NOT_CHROME )
        {
            //--------------------------------------------------
            // Already local, we can open it where it is
            //--------------------------------------------------
            nsCOMPtr<nsIURI> pURL;
            rv = NS_NewURI(getter_AddRefs(pURL), mItem->mURL);

            if (NS_SUCCEEDED(rv))
            {
                nsCOMPtr<nsIFileURL> fileURL = do_QueryInterface(pURL,&rv);
                if (fileURL)
                {
                    nsCOMPtr<nsIFile> localFile;
                    rv = fileURL->GetFile(getter_AddRefs(localFile));
                    if (NS_SUCCEEDED(rv))
                    {
                        mItem->mFile = do_QueryInterface(localFile,&rv);
                    }
                }
            }

            if ( NS_FAILED(rv) || !mItem->mFile )
            {
                // send error status back
                if (mDlg)
                    mDlg->OnStateChange( mNextItem-1,
                                         nsIXPIProgressDialog::INSTALL_DONE,
                                         nsInstall::UNEXPECTED_ERROR );
                mTriggers->SendStatus( mItem->mURL.get(),
                                       nsInstall::UNEXPECTED_ERROR );
                mItem->mFile = 0;
            }
            else if (mDlg)
            {
                mDlg->OnStateChange( mNextItem-1,
                                     nsIXPIProgressDialog::DOWNLOAD_DONE, 0);
            }

            // --- on to the next one
            return DownloadNext();
        }
        else
        {
            //--------------------------------------------------
            // We have one to download
            //--------------------------------------------------
            rv = GetDestinationFile(mItem->mURL, getter_AddRefs(mItem->mFile));
            if (NS_SUCCEEDED(rv))
            {
                nsCOMPtr<nsIURI> pURL;
                rv = NS_NewURI(getter_AddRefs(pURL), mItem->mURL);
                if (NS_SUCCEEDED(rv))
                {
                    nsCOMPtr<nsIChannel> channel;

                    rv = NS_NewChannel(getter_AddRefs(channel), pURL, nsnull, nsnull, this);
                    if (NS_SUCCEEDED(rv))
                    {
                        rv = channel->AsyncOpen(this, nsnull);
                    }
                }
            }

            if (NS_FAILED(rv))
            {
                // announce failure
                if (mDlg)
                    mDlg->OnStateChange( mNextItem-1,
                                         nsIXPIProgressDialog::INSTALL_DONE,
                                         nsInstall::DOWNLOAD_ERROR );
                mTriggers->SendStatus( mItem->mURL.get(),
                                       nsInstall::DOWNLOAD_ERROR );
                mItem->mFile = 0;

                // We won't get Necko callbacks so start the next one now
                return DownloadNext();
            }
        }
    }
    else
    {
        //------------------------------------------------------
        // all downloaded, install them
        //------------------------------------------------------
        InstallItems();
        Shutdown();
    }

    return rv;
}
Ejemplo n.º 20
0
// This function implements the "HTTP Fetch" algorithm from the Fetch spec.
// Functionality is often split between here, the CORS listener proxy and the
// Necko HTTP implementation.
nsresult
FetchDriver::HttpFetch(bool aCORSFlag, bool aCORSPreflightFlag, bool aAuthenticationFlag)
{
  // Step 1. "Let response be null."
  mResponse = nullptr;
  nsresult rv;

  nsCOMPtr<nsIIOService> ios = do_GetIOService(&rv);
  if (NS_WARN_IF(NS_FAILED(rv))) {
    FailWithNetworkError();
    return rv;
  }

  nsAutoCString url;
  mRequest->GetURL(url);
  nsCOMPtr<nsIURI> uri;
  rv = NS_NewURI(getter_AddRefs(uri),
                          url,
                          nullptr,
                          nullptr,
                          ios);
  if (NS_WARN_IF(NS_FAILED(rv))) {
    FailWithNetworkError();
    return rv;
  }

  // Step 2 deals with letting ServiceWorkers intercept requests. This is
  // handled by Necko after the channel is opened.
  // FIXME(nsm): Bug 1119026: The channel's skip service worker flag should be
  // set based on the Request's flag.

  // Step 3.1 "If the CORS preflight flag is set and one of these conditions is
  // true..." is handled by the CORS proxy.
  //
  // Step 3.2 "Set request's skip service worker flag." This isn't required
  // since Necko will fall back to the network if the ServiceWorker does not
  // respond with a valid Response.
  //
  // NS_StartCORSPreflight() will automatically kick off the original request
  // if it succeeds, so we need to have everything setup for the original
  // request too.

  // Step 3.3 "Let credentials flag be set if either request's credentials mode
  // is include, or request's credentials mode is same-origin and the CORS flag
  // is unset, and unset otherwise."
  bool useCredentials = false;
  if (mRequest->GetCredentialsMode() == RequestCredentials::Include ||
      (mRequest->GetCredentialsMode() == RequestCredentials::Same_origin && !aCORSFlag)) {
    useCredentials = true;
  }

  // This is effectivetly the opposite of the use credentials flag in "HTTP
  // network or cache fetch" in the spec and decides whether to transmit
  // cookies and other identifying information. LOAD_ANONYMOUS also prevents
  // new cookies sent by the server from being stored.
  const nsLoadFlags credentialsFlag = useCredentials ? 0 : nsIRequest::LOAD_ANONYMOUS;

  // From here on we create a channel and set its properties with the
  // information from the InternalRequest. This is an implementation detail.
  MOZ_ASSERT(mLoadGroup);
  nsCOMPtr<nsIChannel> chan;
  rv = NS_NewChannel(getter_AddRefs(chan),
                     uri,
                     mPrincipal,
                     nsILoadInfo::SEC_NORMAL,
                     mRequest->ContentPolicyType(),
                     mLoadGroup,
                     nullptr, /* aCallbacks */
                     nsIRequest::LOAD_NORMAL | credentialsFlag,
                     ios);
  mLoadGroup = nullptr;
  if (NS_WARN_IF(NS_FAILED(rv))) {
    FailWithNetworkError();
    return rv;
  }

  // Insert ourselves into the notification callbacks chain so we can handle
  // cross-origin redirects.
  chan->GetNotificationCallbacks(getter_AddRefs(mNotificationCallbacks));
  chan->SetNotificationCallbacks(this);

  // FIXME(nsm): Bug 1120715.
  // Step 3.4 "If request's cache mode is default and request's header list
  // contains a header named `If-Modified-Since`, `If-None-Match`,
  // `If-Unmodified-Since`, `If-Match`, or `If-Range`, set request's cache mode
  // to no-store."

  // Step 3.5 begins "HTTP network or cache fetch".
  // HTTP network or cache fetch
  // ---------------------------
  // Step 1 "Let HTTPRequest..." The channel is the HTTPRequest.
  nsCOMPtr<nsIHttpChannel> httpChan = do_QueryInterface(chan);
  if (httpChan) {
    // Copy the method.
    nsAutoCString method;
    mRequest->GetMethod(method);
    rv = httpChan->SetRequestMethod(method);
    if (NS_WARN_IF(NS_FAILED(rv))) {
      FailWithNetworkError();
      return rv;
    }

    // Set the same headers.
    nsAutoTArray<InternalHeaders::Entry, 5> headers;
    mRequest->Headers()->GetEntries(headers);
    for (uint32_t i = 0; i < headers.Length(); ++i) {
      httpChan->SetRequestHeader(headers[i].mName, headers[i].mValue, false /* merge */);
    }

    // Step 2. Set the referrer.
    nsAutoString referrer;
    mRequest->GetReferrer(referrer);
    // The referrer should have already been resolved to a URL by the caller.
    MOZ_ASSERT(!referrer.EqualsLiteral(kFETCH_CLIENT_REFERRER_STR));
    if (!referrer.IsEmpty()) {
      nsCOMPtr<nsIURI> refURI;
      rv = NS_NewURI(getter_AddRefs(refURI), referrer, nullptr, nullptr);
      if (NS_WARN_IF(NS_FAILED(rv))) {
        return FailWithNetworkError();
      }

      net::ReferrerPolicy referrerPolicy = net::RP_Default;
      if (mDocument) {
        referrerPolicy = mDocument->GetReferrerPolicy();
      }

      rv = httpChan->SetReferrerWithPolicy(refURI, referrerPolicy);
      if (NS_WARN_IF(NS_FAILED(rv))) {
        return FailWithNetworkError();
      }
    }

    // Step 3 "If HTTPRequest's force Origin header flag is set..."
    if (mRequest->ForceOriginHeader()) {
      nsAutoString origin;
      rv = nsContentUtils::GetUTFOrigin(mPrincipal, origin);
      if (NS_WARN_IF(NS_FAILED(rv))) {
        return FailWithNetworkError();
      }
      httpChan->SetRequestHeader(NS_LITERAL_CSTRING("origin"),
                                 NS_ConvertUTF16toUTF8(origin),
                                 false /* merge */);
    }
    // Bug 1120722 - Authorization will be handled later.
    // Auth may require prompting, we don't support it yet.
    // The next patch in this same bug prevents this from aborting the request.
    // Credentials checks for CORS are handled by nsCORSListenerProxy,
  }

  // Step 5. Proxy authentication will be handled by Necko.
  // FIXME(nsm): Bug 1120715.
  // Step 7-10. "If request's cache mode is neither no-store nor reload..."

  // Continue setting up 'HTTPRequest'. Content-Type and body data.
  nsCOMPtr<nsIUploadChannel2> uploadChan = do_QueryInterface(chan);
  if (uploadChan) {
    nsAutoCString contentType;
    ErrorResult result;
    mRequest->Headers()->Get(NS_LITERAL_CSTRING("content-type"), contentType, result);
    // This is an error because the Request constructor explicitly extracts and
    // sets a content-type per spec.
    if (result.Failed()) {
      return FailWithNetworkError();
    }

    nsCOMPtr<nsIInputStream> bodyStream;
    mRequest->GetBody(getter_AddRefs(bodyStream));
    if (bodyStream) {
      nsAutoCString method;
      mRequest->GetMethod(method);
      rv = uploadChan->ExplicitSetUploadStream(bodyStream, contentType, -1, method, false /* aStreamHasHeaders */);
      if (NS_WARN_IF(NS_FAILED(rv))) {
        return FailWithNetworkError();
      }
    }
  }

  // Set skip serviceworker flag.
  // While the spec also gates on the client being a ServiceWorker, we can't
  // infer that here. Instead we rely on callers to set the flag correctly.
  if (mRequest->SkipServiceWorker()) {
    if (httpChan) {
      nsCOMPtr<nsIHttpChannelInternal> internalChan = do_QueryInterface(httpChan);
      internalChan->ForceNoIntercept();
    }
  }

  nsCOMPtr<nsIStreamListener> listener = this;

  // Unless the cors mode is explicitly no-cors, we set up a cors proxy even in
  // the same-origin case, since the proxy does not enforce cors header checks
  // in the same-origin case.
  if (mRequest->Mode() != RequestMode::No_cors) {
    // Set up a CORS proxy that will handle the various requirements of the CORS
    // protocol. It handles the preflight cache and CORS response headers.
    // If the request is allowed, it will start our original request
    // and our observer will be notified. On failure, our observer is notified
    // directly.
    nsRefPtr<nsCORSListenerProxy> corsListener =
      new nsCORSListenerProxy(this, mPrincipal, useCredentials);
    rv = corsListener->Init(chan, DataURIHandling::Allow);
    if (NS_WARN_IF(NS_FAILED(rv))) {
      return FailWithNetworkError();
    }
    listener = corsListener.forget();
  }

  // If preflight is required, start a "CORS preflight fetch"
  // https://fetch.spec.whatwg.org/#cors-preflight-fetch-0. All the
  // implementation is handled by NS_StartCORSPreflight, we just set up the
  // unsafeHeaders so they can be verified against the response's
  // "Access-Control-Allow-Headers" header.
  if (aCORSPreflightFlag) {
    nsCOMPtr<nsIChannel> preflightChannel;
    nsAutoTArray<nsCString, 5> unsafeHeaders;
    mRequest->Headers()->GetUnsafeHeaders(unsafeHeaders);

    rv = NS_StartCORSPreflight(chan, listener, mPrincipal,
                               useCredentials,
                               unsafeHeaders,
                               getter_AddRefs(preflightChannel));
  } else {
    rv = chan->AsyncOpen(listener, nullptr);
  }

  if (NS_WARN_IF(NS_FAILED(rv))) {
    return FailWithNetworkError();
  }

  // Step 4 onwards of "HTTP Fetch" is handled internally by Necko.
  return NS_OK;
}
NS_IMETHODIMP
nsPluginStreamListenerPeer::RequestRead(NPByteRange* rangeList)
{
  nsCAutoString rangeString;
  PRInt32 numRequests;
  
  MakeByteRangeString(rangeList, rangeString, &numRequests);
  
  if (numRequests == 0)
    return NS_ERROR_FAILURE;
  
  nsresult rv = NS_OK;
  
  nsCOMPtr<nsIInterfaceRequestor> callbacks = do_QueryReferent(mWeakPtrChannelCallbacks);
  nsCOMPtr<nsILoadGroup> loadGroup = do_QueryReferent(mWeakPtrChannelLoadGroup);
  nsCOMPtr<nsIChannel> channel;
  rv = NS_NewChannel(getter_AddRefs(channel), mURL, nsnull, loadGroup, callbacks);
  if (NS_FAILED(rv))
    return rv;
  
  nsCOMPtr<nsIHttpChannel> httpChannel(do_QueryInterface(channel));
  if (!httpChannel)
    return NS_ERROR_FAILURE;
  
  httpChannel->SetRequestHeader(NS_LITERAL_CSTRING("Range"), rangeString, false);
  
  mAbort = true; // instruct old stream listener to cancel
  // the request on the next ODA.
  
  nsCOMPtr<nsIStreamListener> converter;
  
  if (numRequests == 1) {
    converter = this;
    // set current stream offset equal to the first offset in the range list
    // it will work for single byte range request
    // for multy range we'll reset it in ODA
    SetStreamOffset(rangeList->offset);
  } else {
    nsWeakPtr weakpeer =
    do_GetWeakReference(static_cast<nsISupportsWeakReference*>(this));
    nsPluginByteRangeStreamListener *brrListener =
    new nsPluginByteRangeStreamListener(weakpeer);
    if (brrListener)
      converter = brrListener;
    else
      return NS_ERROR_OUT_OF_MEMORY;
  }
  
  mPendingRequests += numRequests;
  
  nsCOMPtr<nsISupportsPRUint32> container = do_CreateInstance(NS_SUPPORTS_PRUINT32_CONTRACTID, &rv);
  if (NS_FAILED(rv))
    return rv;
  rv = container->SetData(MAGIC_REQUEST_CONTEXT);
  if (NS_FAILED(rv))
    return rv;
  
  rv = channel->AsyncOpen(converter, container);
  if (NS_SUCCEEDED(rv))
    TrackRequest(channel);
  return rv;
}
Ejemplo n.º 22
0
nsresult
TestOpenInputStream(const char* url)
{
    nsresult rv;

    nsCOMPtr<nsIScriptSecurityManager> secman =
      do_GetService(NS_SCRIPTSECURITYMANAGER_CONTRACTID, &rv);
    if (NS_FAILED(rv)) return rv;
    nsCOMPtr<nsIPrincipal> systemPrincipal;
    rv = secman->GetSystemPrincipal(getter_AddRefs(systemPrincipal));
    if (NS_FAILED(rv)) return rv;
    nsCOMPtr<nsIURI> uri;
    rv = NS_NewURI(getter_AddRefs(uri), url);
    if (NS_FAILED(rv)) return rv;

    nsCOMPtr<nsIChannel> channel;
    rv = NS_NewChannel(getter_AddRefs(channel),
                       uri,
                       systemPrincipal,
                       nsILoadInfo::SEC_NORMAL,
                       nsIContentPolicy::TYPE_OTHER);
    if (NS_FAILED(rv)) return rv;

    nsCOMPtr<nsIInputStream> in;
    rv = channel->Open(getter_AddRefs(in));
    if (NS_FAILED(rv)) {
        fprintf(stdout, "failed to OpenInputStream for %s\n", url);
        return NS_OK;
    }

    char buf[1024];
    while (1) {
        uint32_t amt;
        rv = in->Read(buf, sizeof(buf), &amt);
        if (NS_FAILED(rv)) return rv;
        if (amt == 0) break;    // eof

        char* str = buf;
        while (amt-- > 0) {
            fputc(*str++, stdout);
        }
    }
    nsCOMPtr<nsIURI> uri;
    char* str;

    rv = channel->GetOriginalURI(getter_AddRefs(uri));
    if (NS_FAILED(rv)) return rv;
    rv = uri->GetSpec(&str);
    if (NS_FAILED(rv)) return rv;
    fprintf(stdout, "%s resolved to ", str);
    free(str);

    rv = channel->GetURI(getter_AddRefs(uri));
    if (NS_FAILED(rv)) return rv;
    rv = uri->GetSpec(&str);
    if (NS_FAILED(rv)) return rv;
    fprintf(stdout, "%s\n", str);
    free(str);

    return NS_OK;
}