NS_IMETHODIMP
nsChannelClassifier::OnClassifyComplete(nsresult aErrorCode)
{
    // Should only be called in the parent process.
    MOZ_ASSERT(XRE_IsParentProcess());

    if (aErrorCode == NS_ERROR_TRACKING_URI &&
        NS_SUCCEEDED(IsTrackerWhitelisted())) {
      LOG(("nsChannelClassifier[%p]:OnClassifyComplete tracker found "
           "in whitelist so we won't block it", this));
      aErrorCode = NS_OK;
    }

    if (mSuspendedChannel) {
      nsAutoCString errorName;
      if (LOG_ENABLED()) {
        GetErrorName(aErrorCode, errorName);
        LOG(("nsChannelClassifier[%p]:OnClassifyComplete %s (suspended channel)",
             this, errorName.get()));
      }
      MarkEntryClassified(aErrorCode);

      if (NS_FAILED(aErrorCode)) {
        if (LOG_ENABLED()) {
          nsCOMPtr<nsIURI> uri;
          mChannel->GetURI(getter_AddRefs(uri));
          LOG(("nsChannelClassifier[%p]: cancelling channel %p for %s "
               "with error code %s", this, mChannel.get(),
               uri->GetSpecOrDefault().get(), errorName.get()));
        }

        // Channel will be cancelled (page element blocked) due to tracking.
        // Do update the security state of the document and fire a security
        // change event.
        if (aErrorCode == NS_ERROR_TRACKING_URI) {
          SetBlockedTrackingContent(mChannel);
        }

        mChannel->Cancel(aErrorCode);
      }
      LOG(("nsChannelClassifier[%p]: resuming channel %p from "
           "OnClassifyComplete", this, mChannel.get()));
      mChannel->Resume();
    }

    mChannel = nullptr;

    return NS_OK;
}
NS_IMETHODIMP
nsWebDAVService::MakeCollection(nsIWebDAVResource *resource,
                                nsIWebDAVOperationListener *listener,
                                nsIInterfaceRequestor *notificationCallbacks,
                                nsISupports *closure)
{
    nsCOMPtr<nsIHttpChannel> channel;
    nsresult rv = ChannelFromResource(resource, notificationCallbacks, getter_AddRefs(channel));
    NS_ENSURE_SUCCESS(rv, rv);

    nsCOMPtr<nsIStreamListener> streamListener;
    rv = NS_WD_NewOperationStreamListener(resource, listener, closure,
                                          nsIWebDAVOperationListener::MAKE_COLLECTION,
                                          getter_AddRefs(streamListener));
    NS_ENSURE_SUCCESS(rv, rv);

    channel->SetRequestMethod(NS_LITERAL_CSTRING("MKCOL"));

#ifdef PR_LOGGING
    if (LOG_ENABLED()) {
        nsCOMPtr<nsIURI> uri;
        channel->GetURI(getter_AddRefs(uri));
        nsCAutoString spec;
        uri->GetSpec(spec);
        LOG(("MKCOL starting for %s", spec.get()));
    }
#endif

    return channel->AsyncOpen(streamListener, channel);
}
NS_IMETHODIMP
OfflineCacheUpdateGlue::ApplicationCacheAvailable(nsIApplicationCache *aApplicationCache)
{
    NS_ENSURE_ARG(aApplicationCache);

    // Check that the document that requested this update was
    // previously associated with an application cache.  If not, it
    // should be associated with the new one.
    nsCOMPtr<nsIApplicationCacheContainer> container =
        do_QueryInterface(mDocument);
    if (!container)
        return NS_OK;

    nsCOMPtr<nsIApplicationCache> existingCache;
    nsresult rv = container->GetApplicationCache(getter_AddRefs(existingCache));
    NS_ENSURE_SUCCESS(rv, rv);

    if (!existingCache) {
        if (LOG_ENABLED()) {
            nsAutoCString clientID;
            if (aApplicationCache) {
                aApplicationCache->GetClientID(clientID);
            }
            LOG(("Update %p: associating app cache %s to document %p",
                 this, clientID.get(), mDocument.get()));
        }

        rv = container->SetApplicationCache(aApplicationCache);
        NS_ENSURE_SUCCESS(rv, rv);
    }

    return NS_OK;
}
Example #4
0
void
nsPrefetchService::ProcessNextURI()
{
    nsresult rv;
    nsCOMPtr<nsIURI> uri, referrer;

    mCurrentNode = nsnull;

    do {
        rv = DequeueNode(getter_AddRefs(mCurrentNode));

        if (NS_FAILED(rv)) break;

#if defined(PR_LOGGING)
        if (LOG_ENABLED()) {
            nsCAutoString spec;
            mCurrentNode->mURI->GetSpec(spec);
            LOG(("ProcessNextURI [%s]\n", spec.get()));
        }
#endif

        //
        // if opening the channel fails, then just skip to the next uri
        //
        rv = mCurrentNode->OpenChannel();
    }
    while (NS_FAILED(rv));
}
Example #5
0
NS_IMETHODIMP
nsFontFaceLoader::OnStreamComplete(nsIStreamLoader* aLoader,
                                   nsISupports* aContext,
                                   nsresult aStatus,
                                   PRUint32 aStringLen,
                                   const PRUint8* aString)
{
  if (!mFontSet) {
    // We've been canceled
    return aStatus;
  }

  mFontSet->RemoveLoader(this);

#ifdef PR_LOGGING
  if (LOG_ENABLED()) {
    nsCAutoString fontURI;
    mFontURI->GetSpec(fontURI);
    if (NS_SUCCEEDED(aStatus)) {
      LOG(("fontdownloader (%p) download completed - font uri: (%s)\n", 
           this, fontURI.get()));
    } else {
      LOG(("fontdownloader (%p) download failed - font uri: (%s) error: %8.8x\n", 
           this, fontURI.get(), aStatus));
    }
  }
#endif

  nsPresContext *ctx = mFontSet->GetPresContext();
  NS_ASSERTION(ctx && !ctx->PresShell()->IsDestroying(),
               "We should have been canceled already");

  // whether an error occurred or not, notify the user font set of the completion
  gfxUserFontSet *userFontSet = ctx->GetUserFontSet();
  if (!userFontSet) {
    return aStatus;
  }

  // The userFontSet is responsible for freeing the downloaded data
  // (aString) when finished with it; the pointer is no longer valid
  // after OnLoadComplete returns.
  PRBool fontUpdate = userFontSet->OnLoadComplete(mFontEntry,
                                                  aString, aStringLen,
                                                  aStatus);

  // when new font loaded, need to reflow
  if (fontUpdate) {
    // Update layout for the presence of the new font.  Since this is
    // asynchronous, reflows will coalesce.
    ctx->UserFontSetUpdated();
    LOG(("fontdownloader (%p) reflow\n", this));
  }

  return NS_SUCCESS_ADOPTED_DATA;
}
NS_IMETHODIMP
nsWebDAVService::CopyTo(nsIWebDAVResource *resource,
                        const nsACString &destination,
                        PRBool recursive, PRBool overwrite,
                        nsIWebDAVOperationListener *listener,
                        nsIInterfaceRequestor *notificationCallbacks,
                        nsISupports *closure)

{
    nsCOMPtr<nsIHttpChannel> channel;
    nsresult rv = ChannelFromResource(resource, notificationCallbacks, getter_AddRefs(channel));
    NS_ENSURE_SUCCESS(rv, rv);

    nsCOMPtr<nsIStreamListener> streamListener;
    rv = NS_WD_NewOperationStreamListener(resource, listener, closure,
                                          nsIWebDAVOperationListener::COPY,
                                          getter_AddRefs(streamListener));
    NS_ENSURE_SUCCESS(rv, rv);

    channel->SetRequestMethod(NS_LITERAL_CSTRING("COPY"));
    if (!overwrite) {
        channel->SetRequestHeader(NS_LITERAL_CSTRING("Overwrite"),
                                  NS_LITERAL_CSTRING("F"),
                                  PR_FALSE);
    } else {
        channel->SetRequestHeader(NS_LITERAL_CSTRING("Overwrite"),
                                  NS_LITERAL_CSTRING("F"),
                                  PR_FALSE);
    }

    if (recursive) {
        channel->SetRequestHeader(NS_LITERAL_CSTRING("Depth"),
                                  NS_LITERAL_CSTRING("infinity"), PR_FALSE);
    } else {
        channel->SetRequestHeader(NS_LITERAL_CSTRING("Depth"),
                                  NS_LITERAL_CSTRING("0"), PR_FALSE);
    }

    channel->SetRequestHeader(NS_LITERAL_CSTRING("Destination"),
                              destination, PR_FALSE);

#ifdef PR_LOGGING
    if (LOG_ENABLED()) {
        nsCOMPtr<nsIURI> uri;
        channel->GetURI(getter_AddRefs(uri));
        nsCAutoString spec;
        uri->GetSpec(spec);
        LOG(("COPY starting for %s -> %s", spec.get(),
             nsCAutoString(destination).get()));
    }
#endif

    return channel->AsyncOpen(streamListener, channel);
}
Example #7
0
nsresult
Classifier::ApplyUpdates(nsTArray<TableUpdate*>* aUpdates)
{
  Telemetry::AutoTimer<Telemetry::URLCLASSIFIER_CL_UPDATE_TIME> timer;

#if defined(PR_LOGGING)
  PRIntervalTime clockStart = 0;
  if (LOG_ENABLED() || true) {
    clockStart = PR_IntervalNow();
  }
#endif

  LOG(("Applying table updates."));

  nsresult rv;

  for (uint32 i = 0; i < aUpdates->Length(); i++) {
    // Previous ApplyTableUpdates() may have consumed this update..
    if ((*aUpdates)[i]) {
      // Run all updates for one table
      rv = ApplyTableUpdates(aUpdates, aUpdates->ElementAt(i)->TableName());
      if (NS_FAILED(rv)) {
        Reset();
        return rv;
      }
    }
  }
  aUpdates->Clear();
  RegenActiveTables();
  LOG(("Done applying updates."));

#if defined(PR_LOGGING)
  if (LOG_ENABLED() || true) {
    PRIntervalTime clockEnd = PR_IntervalNow();
    LOG(("update took %dms\n",
         PR_IntervalToMilliseconds(clockEnd - clockStart)));
  }
#endif

  return NS_OK;
}
Example #8
0
void
LookupCache::Dump()
{
  if (!LOG_ENABLED())
    return;

  for (uint32_t i = 0; i < mCompletions.Length(); i++) {
    nsAutoCString str;
    mCompletions[i].ToHexString(str);
    LOG(("Completion: %s", str.get()));
  }
}
/**
 * Print base64-encoded token to the NSPR Log.
 * @param name Description of the token, will be printed in front
 * @param token The token to print
 * @param tokenLen length of the data in token
 */
static void LogToken(const char *name, const void *token, uint32_t tokenLen)
{
  if (!LOG_ENABLED())
    return;

  char *b64data = PL_Base64Encode((const char *) token, tokenLen, nullptr);
  if (b64data)
  {
    PR_LogPrint("%s: %s\n", name, b64data);
    PR_Free(b64data);
  }
}
void
gfxFT2FontList::AppendFacesFromFontFile(const char *aFileName)
{
#ifdef XP_WIN
    FT_Library ftLibrary = gfxWindowsPlatform::GetPlatform()->GetFTLibrary();
#elif defined(ANDROID)
    FT_Library ftLibrary = gfxAndroidPlatform::GetPlatform()->GetFTLibrary();
#endif
    FT_Face dummy;
    if (FT_Err_Ok == FT_New_Face(ftLibrary, aFileName, -1, &dummy)) {
        for (FT_Long i = 0; i < dummy->num_faces; i++) {
            FT_Face face;
            if (FT_Err_Ok != FT_New_Face(ftLibrary, aFileName, i, &face))
                continue;

            FontEntry* fe = FontEntry::CreateFontEntryFromFace(face);
            if (fe) {
                NS_ConvertUTF8toUTF16 name(face->family_name);
                BuildKeyNameFromFontName(name);       
                gfxFontFamily *family = mFontFamilies.GetWeak(name);
                if (!family) {
                    family = new gfxFontFamily(name);
                    mFontFamilies.Put(name, family);
                    if (mBadUnderlineFamilyNames.Contains(name))
                        family->SetBadUnderlineFamily();
                }
                family->AddFontEntry(fe);
                family->SetHasStyles(PR_TRUE);
                if (family->IsBadUnderlineFamily())
                    fe->mIsBadUnderlineFont = PR_TRUE;
#ifdef PR_LOGGING
                if (LOG_ENABLED()) {
                    LOG(("(fontinit) added (%s) to family (%s)"
                         " with style: %s weight: %d stretch: %d",
                         NS_ConvertUTF16toUTF8(fe->Name()).get(), 
                         NS_ConvertUTF16toUTF8(family->Name()).get(), 
                         fe->IsItalic() ? "italic" : "normal",
                         fe->Weight(), fe->Stretch()));
                }
#endif
            }
        }
        FT_Done_Face(dummy);
    }
}
ProtocolError DTLSMessageChannel::receive(Message& message)
{
	if (ssl_context.state != MBEDTLS_SSL_HANDSHAKE_OVER)
		return INVALID_STATE;

	create(message);
	uint8_t* buf = message.buf();
	size_t len = message.capacity();

	conf.read_timeout = 0;
	int ret = mbedtls_ssl_read(&ssl_context, buf, len);
	if (ret<0) {
		switch (ret) {
		case MBEDTLS_ERR_SSL_WANT_READ:
			break;
		case MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE:
			ret = 0;
			break;
		case MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY:
			command(CLOSE);
			break;
		default:
			reset_session();
			return IO_ERROR;
		}
	}
	message.set_length(ret);
	if (ret>0) {
		cancel_move_session();
#if defined(DEBUG_BUILD) && 0
		if (LOG_ENABLED(TRACE)) {
		  LOG(TRACE, "message length %d", message.length());
		  for (size_t i=0; i<message.length(); i++)
		  {
				  char buf[3];
				  char c = message.buf()[i];
				  sprintf(buf, "%02x", c);
				  LOG_PRINT(TRACE, buf);
		  }
		  LOG_PRINT(TRACE, "\n");
		}
#endif
	}
	return NO_ERROR;
}
/**
 * Prints a hexdump of buf to the NSPR Log, if enabled.
 * @param tag Description of the data, will be printed in front of the data
 * @param buf the data to print
 * @param bufLen length of the data
 */
static void
LogBuf(const char *tag, const uint8_t *buf, uint32_t bufLen)
{
  int i;

  if (!LOG_ENABLED())
    return;

  PR_LogPrint("%s =\n", tag);
  char line[80];
  while (bufLen > 0)
  {
    int count = bufLen;
    if (count > 8)
      count = 8;

    strcpy(line, "    ");
    for (i=0; i<count; ++i)
    {
      int len = strlen(line);
      PR_snprintf(line + len, sizeof(line) - len, "0x%02x ", int(buf[i]));
    }
    for (; i<8; ++i)
    {
      int len = strlen(line);
      PR_snprintf(line + len, sizeof(line) - len, "     ");
    }

    int len = strlen(line);
    PR_snprintf(line + len, sizeof(line) - len, "   ");
    for (i=0; i<count; ++i)
    {
      len = strlen(line);
      if (isprint(buf[i]))
        PR_snprintf(line + len, sizeof(line) - len, "%c", buf[i]);
      else
        PR_snprintf(line + len, sizeof(line) - len, ".");
    }
    PR_LogPrint("%s\n", line);

    bufLen -= count;
    buf += count;
  }
}
/**
 * Prints a description of flags to the NSPR Log, if enabled.
 */
static void LogFlags(uint32_t flags)
{
  if (!LOG_ENABLED())
    return;
#define TEST(_flag) \
  if (flags & NTLM_ ## _flag) \
    PR_LogPrint("    0x%08x (" # _flag ")\n", NTLM_ ## _flag)

  TEST(NegotiateUnicode);
  TEST(NegotiateOEM);
  TEST(RequestTarget);
  TEST(Unknown1);
  TEST(NegotiateSign);
  TEST(NegotiateSeal);
  TEST(NegotiateDatagramStyle);
  TEST(NegotiateLanManagerKey);
  TEST(NegotiateNetware);
  TEST(NegotiateNTLMKey);
  TEST(Unknown2);
  TEST(Unknown3);
  TEST(NegotiateDomainSupplied);
  TEST(NegotiateWorkstationSupplied);
  TEST(NegotiateLocalCall);
  TEST(NegotiateAlwaysSign);
  TEST(TargetTypeDomain);
  TEST(TargetTypeServer);
  TEST(TargetTypeShare);
  TEST(NegotiateNTLM2Key);
  TEST(RequestInitResponse);
  TEST(RequestAcceptResponse);
  TEST(RequestNonNTSessionKey);
  TEST(NegotiateTargetInfo);
  TEST(Unknown4);
  TEST(Unknown5);
  TEST(Unknown6);
  TEST(Unknown7);
  TEST(Unknown8);
  TEST(Negotiate128);
  TEST(NegotiateKeyExchange);
  TEST(Negotiate56);

#undef TEST
}
Example #14
0
void
Http2BaseCompressor::DumpState()
{
  if (!LOG_ENABLED()) {
    return;
  }

  LOG(("Header Table"));
  uint32_t i;
  uint32_t length = mHeaderTable.Length();
  uint32_t staticLength = mHeaderTable.StaticLength();
  // NWGH - make i = 1; i <= length; ++i
  for (i = 0; i < length; ++i) {
    const nvPair *pair = mHeaderTable[i];
    // NWGH - make this <= staticLength
    LOG(("%sindex %u: %s %s", i < staticLength ? "static " : "", i,
         pair->mName.get(), pair->mValue.get()));
  }
}
// Note in the cache entry that this URL was classified, so that future
// cached loads don't need to be checked.
void
nsChannelClassifier::MarkEntryClassified(nsresult status)
{
    // Should only be called in the parent process.
    MOZ_ASSERT(XRE_IsParentProcess());

    // Don't cache tracking classifications because we support allowlisting.
    if (status == NS_ERROR_TRACKING_URI || mIsAllowListed) {
        return;
    }

    if (LOG_ENABLED()) {
      nsAutoCString errorName;
      GetErrorName(status, errorName);
      nsCOMPtr<nsIURI> uri;
      mChannel->GetURI(getter_AddRefs(uri));
      nsAutoCString spec;
      uri->GetAsciiSpec(spec);
      LOG(("nsChannelClassifier::MarkEntryClassified[%s] %s",
           errorName.get(), spec.get()));
    }

    nsCOMPtr<nsICachingChannel> cachingChannel = do_QueryInterface(mChannel);
    if (!cachingChannel) {
        return;
    }

    nsCOMPtr<nsISupports> cacheToken;
    cachingChannel->GetCacheToken(getter_AddRefs(cacheToken));
    if (!cacheToken) {
        return;
    }

    nsCOMPtr<nsICacheEntry> cacheEntry =
        do_QueryInterface(cacheToken);
    if (!cacheEntry) {
        return;
    }

    cacheEntry->SetMetaDataElement("necko:classified",
                                   NS_SUCCEEDED(status) ? "1" : nullptr);
}
NS_IMETHODIMP
nsWebDAVService::Put(nsIWebDAVResource *resource,
                     const nsACString& contentType, nsIInputStream *data,
                     nsIWebDAVOperationListener *listener,
                     nsIInterfaceRequestor *notificationCallbacks,
                     nsISupports *closure)
{
    nsCOMPtr<nsIHttpChannel> channel;

    nsresult rv = ChannelFromResource(resource, notificationCallbacks, getter_AddRefs(channel));
    NS_ENSURE_SUCCESS(rv, rv);
    
    nsCOMPtr<nsIUploadChannel> uploadChannel = do_QueryInterface(channel, &rv);
    NS_ENSURE_SUCCESS(rv, rv);

    rv = uploadChannel->SetUploadStream(data, contentType, -1);
    NS_ENSURE_SUCCESS(rv, rv);

    nsCOMPtr<nsIStreamListener> streamListener;
    rv = NS_WD_NewOperationStreamListener(resource, listener, closure,
                                          nsIWebDAVOperationListener::PUT,
                                          getter_AddRefs(streamListener));
    NS_ENSURE_SUCCESS(rv, rv);

    channel->SetRequestMethod(NS_LITERAL_CSTRING("PUT"));

#ifdef PR_LOGGING
    if (LOG_ENABLED()) {
        nsCOMPtr<nsIURI> uri;
        channel->GetURI(getter_AddRefs(uri));
        nsCAutoString spec;
        uri->GetSpec(spec);
        LOG(("PUT starting for %s", spec.get()));
    }
#endif

    return channel->AsyncOpen(streamListener, channel);
}
Example #17
0
NS_IMETHODIMP
nsChannelClassifier::OnClassifyComplete(nsresult aErrorCode)
{
    // Should only be called in the parent process.
    MOZ_ASSERT(XRE_IsParentProcess());

    if (aErrorCode == NS_ERROR_TRACKING_URI &&
        NS_SUCCEEDED(IsTrackerWhitelisted())) {
      LOG(("nsChannelClassifier[%p]:OnClassifyComplete tracker found "
           "in whitelist so we won't block it", this));
      aErrorCode = NS_OK;
    }

    if (mSuspendedChannel) {
      nsAutoCString errorName;
      if (LOG_ENABLED()) {
        GetErrorName(aErrorCode, errorName);
        LOG(("nsChannelClassifier[%p]:OnClassifyComplete %s (suspended channel)",
             this, errorName.get()));
      }
      MarkEntryClassified(aErrorCode);

      // The value of |mTrackingProtectionEnabled| should be assigned at
      // |ShouldEnableTrackingProtection| before.
      MOZ_ASSERT(mTrackingProtectionEnabled, "Should contain a value.");

      if (aErrorCode == NS_ERROR_TRACKING_URI &&
          !mTrackingProtectionEnabled.valueOr(false)) {
        if (sAnnotateChannelEnabled) {
          nsCOMPtr<nsIParentChannel> parentChannel;
          NS_QueryNotificationCallbacks(mChannel, parentChannel);
          if (parentChannel) {
            // This channel is a parent-process proxy for a child process
            // request. We should notify the child process as well.
            parentChannel->NotifyTrackingResource();
          }
          RefPtr<HttpBaseChannel> httpChannel = do_QueryObject(mChannel);
          if (httpChannel) {
            httpChannel->SetIsTrackingResource();
          }
        }

        if (sLowerNetworkPriority) {
          if (LOG_ENABLED()) {
            nsCOMPtr<nsIURI> uri;
            mChannel->GetURI(getter_AddRefs(uri));
            LOG(("nsChannelClassifier[%p]: lower the priority of channel %p"
                 ", since %s is a tracker", this, mChannel.get(),
                 uri->GetSpecOrDefault().get()));
          }
          nsCOMPtr<nsISupportsPriority> p = do_QueryInterface(mChannel);
          if (p) {
            p->SetPriority(nsISupportsPriority::PRIORITY_LOWEST);
          }
        }

        aErrorCode = NS_OK;
      }

      if (NS_FAILED(aErrorCode)) {
        if (LOG_ENABLED()) {
          nsCOMPtr<nsIURI> uri;
          mChannel->GetURI(getter_AddRefs(uri));
          LOG(("nsChannelClassifier[%p]: cancelling channel %p for %s "
               "with error code %s", this, mChannel.get(),
               uri->GetSpecOrDefault().get(), errorName.get()));
        }

        // Channel will be cancelled (page element blocked) due to tracking.
        // Do update the security state of the document and fire a security
        // change event.
        if (aErrorCode == NS_ERROR_TRACKING_URI) {
          SetBlockedTrackingContent(mChannel);
        }

        mChannel->Cancel(aErrorCode);
      }
      LOG(("nsChannelClassifier[%p]: resuming channel %p from "
           "OnClassifyComplete", this, mChannel.get()));
      mChannel->Resume();
    }

    mChannel = nullptr;

    return NS_OK;
}
Example #18
0
nsresult 
nsUserFontSet::StartLoad(gfxFontEntry *aFontToLoad, 
                          const gfxFontFaceSrc *aFontFaceSrc)
{
  nsresult rv;
  
  // check same-site origin
  nsIPresShell *ps = mPresContext->PresShell();
  if (!ps)
    return NS_ERROR_FAILURE;
    
  NS_ASSERTION(aFontFaceSrc && !aFontFaceSrc->mIsLocal, 
               "bad font face url passed to fontloader");
  NS_ASSERTION(aFontFaceSrc->mURI, "null font uri");
  if (!aFontFaceSrc->mURI)
    return NS_ERROR_FAILURE;

  // use document principal, original principal if flag set
  // this enables user stylesheets to load font files via
  // @font-face rules
  nsCOMPtr<nsIPrincipal> principal = ps->GetDocument()->NodePrincipal();

  NS_ASSERTION(aFontFaceSrc->mOriginPrincipal, 
               "null origin principal in @font-face rule");
  if (aFontFaceSrc->mUseOriginPrincipal) {
    principal = do_QueryInterface(aFontFaceSrc->mOriginPrincipal);
  }
  
  rv = nsFontFaceLoader::CheckLoadAllowed(principal, aFontFaceSrc->mURI, 
                                          ps->GetDocument());
  if (NS_FAILED(rv)) {
#ifdef PR_LOGGING
    if (LOG_ENABLED()) {
      nsCAutoString fontURI, referrerURI;
      aFontFaceSrc->mURI->GetSpec(fontURI);
      if (aFontFaceSrc->mReferrer)
        aFontFaceSrc->mReferrer->GetSpec(referrerURI);
      LOG(("fontdownloader download blocked - font uri: (%s) "
           "referrer uri: (%s) err: %8.8x\n", 
          fontURI.get(), referrerURI.get(), rv));
    }
#endif    
    return rv;
  }

  nsCOMPtr<nsIStreamLoader> streamLoader;
  nsCOMPtr<nsILoadGroup> loadGroup(ps->GetDocument()->GetDocumentLoadGroup());

  nsCOMPtr<nsIChannel> channel;
  // get Content Security Policy from principal to pass into channel
  nsCOMPtr<nsIChannelPolicy> channelPolicy;
  nsCOMPtr<nsIContentSecurityPolicy> csp;
  rv = principal->GetCsp(getter_AddRefs(csp));
  NS_ENSURE_SUCCESS(rv, rv);
  if (csp) {
    channelPolicy = do_CreateInstance("@mozilla.org/nschannelpolicy;1");
    channelPolicy->SetContentSecurityPolicy(csp);
    channelPolicy->SetLoadType(nsIContentPolicy::TYPE_FONT);
  }
  rv = NS_NewChannel(getter_AddRefs(channel),
                     aFontFaceSrc->mURI,
                     nsnull,
                     loadGroup,
                     nsnull,
                     nsIRequest::LOAD_NORMAL,
                     channelPolicy);

  NS_ENSURE_SUCCESS(rv, rv);

  nsRefPtr<nsFontFaceLoader> fontLoader =
    new nsFontFaceLoader(aFontToLoad, aFontFaceSrc->mURI, this, channel);

  if (!fontLoader)
    return NS_ERROR_OUT_OF_MEMORY;

#ifdef PR_LOGGING
  if (LOG_ENABLED()) {
    nsCAutoString fontURI, referrerURI;
    aFontFaceSrc->mURI->GetSpec(fontURI);
    if (aFontFaceSrc->mReferrer)
      aFontFaceSrc->mReferrer->GetSpec(referrerURI);
    LOG(("fontdownloader (%p) download start - font uri: (%s) "
         "referrer uri: (%s)\n", 
         fontLoader.get(), fontURI.get(), referrerURI.get()));
  }
#endif  

  nsCOMPtr<nsIHttpChannel> httpChannel(do_QueryInterface(channel));
  if (httpChannel)
    httpChannel->SetReferrer(aFontFaceSrc->mReferrer);
  rv = NS_NewStreamLoader(getter_AddRefs(streamLoader), fontLoader);
  NS_ENSURE_SUCCESS(rv, rv);
  
  PRBool inherits = PR_FALSE;
  rv = NS_URIChainHasFlags(aFontFaceSrc->mURI,
                           nsIProtocolHandler::URI_INHERITS_SECURITY_CONTEXT,
                           &inherits);
  if (NS_SUCCEEDED(rv) && inherits) {
    // allow data, javascript, etc URI's
    rv = channel->AsyncOpen(streamLoader, nsnull);
  } else {
    nsCOMPtr<nsIStreamListener> listener =
      new nsCrossSiteListenerProxy(streamLoader, principal, channel, 
                                   PR_FALSE, &rv);
    if (NS_FAILED(rv)) {
      fontLoader->DropChannel();  // explicitly need to break ref cycle
    }
    NS_ENSURE_TRUE(listener, NS_ERROR_OUT_OF_MEMORY);
    NS_ENSURE_SUCCESS(rv, rv);

    rv = channel->AsyncOpen(listener, nsnull);
  }

  if (NS_SUCCEEDED(rv)) {
    mLoaders.PutEntry(fontLoader);
  }

  return rv;
}
nsresult
nsWebDAVService::PropfindInternal(nsIWebDAVResource *resource,
                                  PRUint32 propCount,
                                  const char **properties,
                                  PRBool withDepth,
                                  nsIWebDAVOperationListener *listener,
                                  nsIInterfaceRequestor *notificationCallbacks,
                                  nsISupports *closure,
                                  PRBool namesOnly)
{
    nsresult rv;

    NS_ENSURE_ARG(resource);
    NS_ENSURE_ARG(listener);

    nsCOMPtr<nsIURI> resourceURI;
    nsCOMPtr<nsIHttpChannel> channel;
    rv = ChannelFromResource(resource, notificationCallbacks, getter_AddRefs(channel),
                             getter_AddRefs(resourceURI));
    if (NS_FAILED(rv))
        return rv;

    nsCOMPtr<nsIDOMDocument> requestDoc;
    nsCOMPtr<nsIDOMElement> propfindElt;
    rv = CreatePropfindDocument(resourceURI, getter_AddRefs(requestDoc),
                                getter_AddRefs(propfindElt));
    NS_ENSURE_SUCCESS(rv, rv);

    if (namesOnly) {
        nsCOMPtr<nsIDOMElement> allpropElt;
        rv = NS_WD_AppendElementWithNS(requestDoc, propfindElt,
                                       mDAVNSString, NS_LITERAL_STRING("propname"),
                                       getter_AddRefs(allpropElt));
        NS_ENSURE_SUCCESS(rv, rv);
    } else if (propCount == 0) {
        nsCOMPtr<nsIDOMElement> allpropElt;
        rv = NS_WD_AppendElementWithNS(requestDoc, propfindElt,
                                       mDAVNSString, NS_LITERAL_STRING("allprop"),
                                       getter_AddRefs(allpropElt));
        NS_ENSURE_SUCCESS(rv, rv);
    } else {
        nsCOMPtr<nsIDOMElement> propElt;
        rv = NS_WD_AppendElementWithNS(requestDoc, propfindElt,
                                       mDAVNSString, NS_LITERAL_STRING("prop"),
                                       getter_AddRefs(propElt));
        NS_ENSURE_SUCCESS(rv, rv);

        for (PRUint32 i = 0; i < propCount; i++) {
            nsDependentCString fullpropName(properties[i]);

            PRInt32 const index = fullpropName.RFindChar(' ');
            if (index < 0) {
                nsCAutoString msg(NS_LITERAL_CSTRING("Illegal property name "));
                msg += fullpropName;
                msg.Append('\n');
                NS_WARNING(msg.get());
                return NS_ERROR_INVALID_ARG;
            }

            nsDependentCSubstring const propNamespace_(fullpropName, 0, index);
            nsDependentCSubstring const propName_(fullpropName, index + 1);
#ifdef PR_LOGGING
            if (LOG_ENABLED()) {
                nsCString const ns(propNamespace_);
                nsCString const name(propName_);
                LOG(("prop ns: '%s', name: '%s'", ns.get(), name.get()));
            }
#endif
            NS_ConvertASCIItoUTF16 const propNamespace(propNamespace_);
            NS_ConvertASCIItoUTF16 const propName(propName_);

            nsCOMPtr<nsIDOMElement> junk;
            rv = NS_WD_AppendElementWithNS(requestDoc, propElt, propNamespace,
                                           propName, getter_AddRefs(junk));
            NS_ENSURE_SUCCESS(rv, rv);
        }
    }

    nsCOMPtr<nsIStreamListener> streamListener = 
        NS_WD_NewPropfindStreamListener(resource, listener, closure,
                                        namesOnly);

    if (!streamListener)
        return NS_ERROR_OUT_OF_MEMORY;
    
    nsCOMPtr<nsIDocument> requestBaseDoc = do_QueryInterface(requestDoc);
    return SendDocumentToChannel(requestBaseDoc, channel, "PROPFIND",
                                 streamListener, withDepth);
}
nsresult
nsWebDAVService::SendDocumentToChannel(nsIDocument *doc,
                                       nsIHttpChannel *channel, 
                                       const char *const method,
                                       nsIStreamListener *listener,
                                       PRBool withDepth)
{
    // Why do I have to pick values for these?  I just want to store some data
    // for stream access!  (And how would script set these?)
    nsresult rv;
    nsCOMPtr<nsIStorageStream> const storageStream(
        do_CreateInstance("@mozilla.org/storagestream;1", &rv));
    NS_ENSURE_SUCCESS(rv, rv);
    rv = storageStream->Init(4096, PR_UINT32_MAX, nsnull);
    NS_ENSURE_SUCCESS(rv, rv);

    nsCOMPtr<nsIOutputStream> storageOutputStream;
    rv = storageStream->GetOutputStream(0,
                                        getter_AddRefs(storageOutputStream));
    NS_ENSURE_SUCCESS(rv, rv);

    nsCOMPtr<nsIDocumentEncoder> encoder =
        do_CreateInstance(NS_DOC_ENCODER_CONTRACTID_BASE "text/xml", &rv);
    NS_ENSURE_SUCCESS(rv, rv);
    
    nsCOMPtr<nsIDOMDocument> domDoc = do_QueryInterface(doc);
    NS_ASSERTION(domDoc, "Need a document");

    rv = encoder->Init(domDoc, NS_LITERAL_STRING("text/xml"),
                       nsIDocumentEncoder::OutputEncodeBasicEntities);
    NS_ENSURE_SUCCESS(rv, rv);

    encoder->SetCharset(NS_LITERAL_CSTRING("UTF-8"));
    rv =  encoder->EncodeToStream(storageOutputStream);
    NS_ENSURE_SUCCESS(rv, rv);

    storageOutputStream->Close();

    // You gotta really want it.
#ifdef PR_LOGGING
    if (PR_LOG_TEST(gDAVLog, 5)) {
        nsCOMPtr<nsIInputStream> logInputStream;
        rv = storageStream->NewInputStream(0, getter_AddRefs(logInputStream));
        NS_ENSURE_SUCCESS(rv, rv);

        PRUint32 len, read;
        logInputStream->Available(&len);

        char *buf = new char[len+1];
        memset(buf, 0, len+1);
        logInputStream->Read(buf, len, &read);
        NS_ASSERTION(len == read, "short read on closed storage stream?");
        LOG(("XML:\n\n%*s\n\n", len, buf));
        
        delete [] buf;
    }
#endif

    nsCOMPtr<nsIInputStream> inputStream;
    rv = storageStream->NewInputStream(0, getter_AddRefs(inputStream));
    NS_ENSURE_SUCCESS(rv, rv);

    nsCOMPtr<nsIUploadChannel> uploadChannel = do_QueryInterface(channel, &rv);
    NS_ENSURE_SUCCESS(rv, rv);
    rv = uploadChannel->SetUploadStream(inputStream,
                                        NS_LITERAL_CSTRING("text/xml"), -1);
    NS_ENSURE_SUCCESS(rv, rv);
    
    channel->SetRequestMethod(nsDependentCString(method));
    channel->SetRequestHeader(NS_LITERAL_CSTRING("Content-Type"),
                              NS_LITERAL_CSTRING("text/xml; charset=utf-8"),
                              PR_FALSE);
    channel->SetRequestHeader(NS_LITERAL_CSTRING("Accept"),
                              NS_LITERAL_CSTRING("text/xml"),
                              PR_FALSE);
    channel->SetRequestHeader(NS_LITERAL_CSTRING("Accept-Charset"),
                              NS_LITERAL_CSTRING("utf-8,*;q=0.1"),
                              PR_FALSE);
    

    if (withDepth) {
        channel->SetRequestHeader(NS_LITERAL_CSTRING("Depth"),
                                  NS_LITERAL_CSTRING("1"), PR_FALSE);
    } else {
        channel->SetRequestHeader(NS_LITERAL_CSTRING("Depth"),
                                  NS_LITERAL_CSTRING("0"), PR_FALSE);
    }

#ifdef PR_LOGGING
    if (LOG_ENABLED()) {
        nsCOMPtr<nsIURI> uri;
        channel->GetURI(getter_AddRefs(uri));
        nsCAutoString spec;
        uri->GetSpec(spec);
        LOG(("%s starting for %s", method, spec.get()));
    }
#endif

    return channel->AsyncOpen(listener, channel);
}
Example #21
0
nsresult
Classifier::Check(const nsACString& aSpec, LookupResultArray& aResults)
{
  Telemetry::AutoTimer<Telemetry::URLCLASSIFIER_CL_CHECK_TIME> timer;

  // Get the set of fragments to look up.
  nsTArray<nsCString> fragments;
  nsresult rv = LookupCache::GetLookupFragments(aSpec, &fragments);
  NS_ENSURE_SUCCESS(rv, rv);

  nsTArray<nsCString> activeTables;
  ActiveTables(activeTables);

  nsTArray<LookupCache*> cacheArray;
  for (PRUint32 i = 0; i < activeTables.Length(); i++) {
    LookupCache *cache = GetLookupCache(activeTables[i]);
    if (cache) {
      cacheArray.AppendElement(cache);
    } else {
      return NS_ERROR_FAILURE;
    }
  }

  // Now check each lookup fragment against the entries in the DB.
  for (PRUint32 i = 0; i < fragments.Length(); i++) {
    Completion lookupHash;
    lookupHash.FromPlaintext(fragments[i], mCryptoHash);

    // Get list of host keys to look up
    Completion hostKey;
    rv = LookupCache::GetKey(fragments[i], &hostKey, mCryptoHash);
    if (NS_FAILED(rv)) {
      // Local host on the network
      continue;
    }

#if DEBUG && defined(PR_LOGGING)
    if (LOG_ENABLED()) {
      nsCAutoString checking;
      lookupHash.ToString(checking);
      LOG(("Checking %s (%X)", checking.get(), lookupHash.ToUint32()));
    }
#endif
    for (PRUint32 i = 0; i < cacheArray.Length(); i++) {
      LookupCache *cache = cacheArray[i];
      bool has, complete;
      Prefix codedPrefix;
      rv = cache->Has(lookupHash, hostKey, mHashKey,
                      &has, &complete, &codedPrefix);
      NS_ENSURE_SUCCESS(rv, rv);
      if (has) {
        LookupResult *result = aResults.AppendElement();
        if (!result)
          return NS_ERROR_OUT_OF_MEMORY;

        PRInt64 age;
        bool found = mTableFreshness.Get(cache->TableName(), &age);
        if (!found) {
          age = 24 * 60 * 60; // just a large number
        } else {
          PRInt64 now = (PR_Now() / PR_USEC_PER_SEC);
          age = now - age;
        }

        LOG(("Found a result in %s: %s (Age: %Lds)",
             cache->TableName().get(),
             complete ? "complete." : "Not complete.",
             age));

        result->hash.complete = lookupHash;
        result->mCodedPrefix = codedPrefix;
        result->mComplete = complete;
        result->mFresh = (age < mFreshTime);
        result->mTableName.Assign(cache->TableName());
      }
    }

  }

  return NS_OK;
}
Example #22
0
nsresult
nsPrefetchService::Prefetch(nsIURI *aURI,
                            nsIURI *aReferrerURI,
                            nsIDOMNode *aSource,
                            PRBool aExplicit)
{
    nsresult rv;

    NS_ENSURE_ARG_POINTER(aURI);
    NS_ENSURE_ARG_POINTER(aReferrerURI);

#if defined(PR_LOGGING)
    if (LOG_ENABLED()) {
        nsCAutoString spec;
        aURI->GetSpec(spec);
        LOG(("PrefetchURI [%s]\n", spec.get()));
    }
#endif

    if (mDisabled) {
        LOG(("rejected: prefetch service is disabled\n"));
        return NS_ERROR_ABORT;
    }

    //
    // XXX we should really be asking the protocol handler if it supports
    // caching, so we can determine if there is any value to prefetching.
    // for now, we'll only prefetch http links since we know that's the 
    // most common case.  ignore https links since https content only goes
    // into the memory cache.
    //
    // XXX we might want to either leverage nsIProtocolHandler::protocolFlags
    // or possibly nsIRequest::loadFlags to determine if this URI should be
    // prefetched.
    //
    PRBool match;
    rv = aURI->SchemeIs("http", &match); 
    if (NS_FAILED(rv) || !match) {
        rv = aURI->SchemeIs("https", &match); 
        if (NS_FAILED(rv) || !match) {
            LOG(("rejected: URL is not of type http/https\n"));
            return NS_ERROR_ABORT;
        }
    }

    // 
    // the referrer URI must be http:
    //
    rv = aReferrerURI->SchemeIs("http", &match);
    if (NS_FAILED(rv) || !match) {
        rv = aReferrerURI->SchemeIs("https", &match);
        if (NS_FAILED(rv) || !match) {
            LOG(("rejected: referrer URL is neither http nor https\n"));
            return NS_ERROR_ABORT;
        }
    }

    // skip URLs that contain query strings, except URLs for which prefetching
    // has been explicitly requested.
    if (!aExplicit) {
        nsCOMPtr<nsIURL> url(do_QueryInterface(aURI, &rv));
        if (NS_FAILED(rv)) return rv;
        nsCAutoString query;
        rv = url->GetQuery(query);
        if (NS_FAILED(rv) || !query.IsEmpty()) {
            LOG(("rejected: URL has a query string\n"));
            return NS_ERROR_ABORT;
        }
    }

    //
    // cancel if being prefetched
    //
    if (mCurrentNode) {
        PRBool equals;
        if (NS_SUCCEEDED(mCurrentNode->mURI->Equals(aURI, &equals)) && equals) {
            LOG(("rejected: URL is already being prefetched\n"));
            return NS_ERROR_ABORT;
        }
    }

    //
    // cancel if already on the prefetch queue
    //
    nsPrefetchNode *node = mQueueHead;
    for (; node; node = node->mNext) {
        PRBool equals;
        if (NS_SUCCEEDED(node->mURI->Equals(aURI, &equals)) && equals) {
            LOG(("rejected: URL is already on prefetch queue\n"));
            return NS_ERROR_ABORT;
        }
    }

    nsRefPtr<nsPrefetchNode> enqueuedNode;
    rv = EnqueueURI(aURI, aReferrerURI, aSource,
                    getter_AddRefs(enqueuedNode));
    NS_ENSURE_SUCCESS(rv, rv);

    NotifyLoadRequested(enqueuedNode);

    // if there are no pages loading, kick off the request immediately
    if (mStopCount == 0 && mHaveProcessed)
        ProcessNextURI();

    return NS_OK;
}
nsresult
nsChannelClassifier::StartInternal()
{
    // Should only be called in the parent process.
    MOZ_ASSERT(XRE_IsParentProcess());

    // Don't bother to run the classifier on a load that has already failed.
    // (this might happen after a redirect)
    nsresult status;
    mChannel->GetStatus(&status);
    if (NS_FAILED(status))
        return status;

    // Don't bother to run the classifier on a cached load that was
    // previously classified as good.
    if (HasBeenClassified(mChannel)) {
        return NS_ERROR_UNEXPECTED;
    }

    nsCOMPtr<nsIURI> uri;
    nsresult rv = mChannel->GetURI(getter_AddRefs(uri));
    NS_ENSURE_SUCCESS(rv, rv);

    // Don't bother checking certain types of URIs.
    bool hasFlags;
    rv = NS_URIChainHasFlags(uri,
                             nsIProtocolHandler::URI_DANGEROUS_TO_LOAD,
                             &hasFlags);
    NS_ENSURE_SUCCESS(rv, rv);
    if (hasFlags) return NS_ERROR_UNEXPECTED;

    rv = NS_URIChainHasFlags(uri,
                             nsIProtocolHandler::URI_IS_LOCAL_FILE,
                             &hasFlags);
    NS_ENSURE_SUCCESS(rv, rv);
    if (hasFlags) return NS_ERROR_UNEXPECTED;

    rv = NS_URIChainHasFlags(uri,
                             nsIProtocolHandler::URI_IS_UI_RESOURCE,
                             &hasFlags);
    NS_ENSURE_SUCCESS(rv, rv);
    if (hasFlags) return NS_ERROR_UNEXPECTED;

    rv = NS_URIChainHasFlags(uri,
                             nsIProtocolHandler::URI_IS_LOCAL_RESOURCE,
                             &hasFlags);
    NS_ENSURE_SUCCESS(rv, rv);
    if (hasFlags) return NS_ERROR_UNEXPECTED;

    // Skip whitelisted hostnames.
    nsAutoCString whitelisted;
    Preferences::GetCString("urlclassifier.skipHostnames", &whitelisted);
    if (!whitelisted.IsEmpty()) {
      ToLowerCase(whitelisted);
      LOG(("nsChannelClassifier[%p]:StartInternal whitelisted hostnames = %s",
           this, whitelisted.get()));
      if (IsHostnameWhitelisted(uri, whitelisted)) {
        return NS_ERROR_UNEXPECTED;
      }
    }

    nsCOMPtr<nsIURIClassifier> uriClassifier =
        do_GetService(NS_URICLASSIFIERSERVICE_CONTRACTID, &rv);
    if (rv == NS_ERROR_FACTORY_NOT_REGISTERED ||
        rv == NS_ERROR_NOT_AVAILABLE) {
        // no URI classifier, ignore this failure.
        return NS_ERROR_NOT_AVAILABLE;
    }
    NS_ENSURE_SUCCESS(rv, rv);

    nsCOMPtr<nsIScriptSecurityManager> securityManager =
        do_GetService(NS_SCRIPTSECURITYMANAGER_CONTRACTID, &rv);
    NS_ENSURE_SUCCESS(rv, rv);

    nsCOMPtr<nsIPrincipal> principal;
    rv = securityManager->GetChannelURIPrincipal(mChannel, getter_AddRefs(principal));
    NS_ENSURE_SUCCESS(rv, rv);

    bool expectCallback;
    bool trackingProtectionEnabled = false;
    (void)ShouldEnableTrackingProtection(mChannel, &trackingProtectionEnabled);

    if (LOG_ENABLED()) {
      nsCOMPtr<nsIURI> principalURI;
      principal->GetURI(getter_AddRefs(principalURI));
      LOG(("nsChannelClassifier[%p]: Classifying principal %s on channel with "
           "uri %s", this, principalURI->GetSpecOrDefault().get(),
           uri->GetSpecOrDefault().get()));
    }
    rv = uriClassifier->Classify(principal, trackingProtectionEnabled, this,
                                 &expectCallback);
    if (NS_FAILED(rv)) {
        return rv;
    }

    if (expectCallback) {
        // Suspend the channel, it will be resumed when we get the classifier
        // callback.
        rv = mChannel->Suspend();
        if (NS_FAILED(rv)) {
            // Some channels (including nsJSChannel) fail on Suspend.  This
            // shouldn't be fatal, but will prevent malware from being
            // blocked on these channels.
            LOG(("nsChannelClassifier[%p]: Couldn't suspend channel", this));
            return rv;
        }

        mSuspendedChannel = true;
        LOG(("nsChannelClassifier[%p]: suspended channel %p",
             this, mChannel.get()));
    } else {
        LOG(("nsChannelClassifier[%p]: not expecting callback", this));
        return NS_ERROR_FAILURE;
    }

    return NS_OK;
}