NS_METHOD nsSound::Play(nsIURL *aURL)
{
    if (!mInited)
        Init();

    if (!libcanberra)
        return NS_ERROR_NOT_AVAILABLE;

    bool isFile;
    nsresult rv = aURL->SchemeIs("file", &isFile);
    if (NS_SUCCEEDED(rv) && isFile) {
        ca_context* ctx = ca_context_get_default();
        if (!ctx) {
            return NS_ERROR_OUT_OF_MEMORY;
        }

        nsAutoCString spec;
        rv = aURL->GetSpec(spec);
        if (NS_FAILED(rv)) {
            return rv;
        }
        gchar *path = g_filename_from_uri(spec.get(), NULL, NULL);
        if (!path) {
            return NS_ERROR_FILE_UNRECOGNIZED_PATH;
        }

        ca_context_play(ctx, 0, "media.filename", path, NULL);
        g_free(path);
    } else {
        nsCOMPtr<nsIStreamLoader> loader;
        rv = NS_NewStreamLoader(getter_AddRefs(loader), aURL, this);
    }

    return rv;
}
Esempio n. 2
0
NS_METHOD nsSound::Play(nsIURL *aURL)
{//printf("%s\n", __PRETTY_FUNCTION__);
	nsresult rv;
	nsCOMPtr<nsIStreamLoader> loader;
	rv = NS_NewStreamLoader(getter_AddRefs(loader), aURL, this);
	return rv;
}
Esempio n. 3
0
NS_METHOD nsSound::Play(nsIURL *aURL)
{
    if (!mInited)
        Init();

    if (!libcanberra)
        return NS_ERROR_NOT_AVAILABLE;

    bool isFile;
    nsresult rv = aURL->SchemeIs("file", &isFile);
    if (NS_SUCCEEDED(rv) && isFile) {
        ca_context* ctx = ca_context_get_default();
        if (!ctx) {
            return NS_ERROR_OUT_OF_MEMORY;
        }

        nsCAutoString path;
        rv = aURL->GetPath(path);
        if (NS_FAILED(rv)) {
            return rv;
        }

        ca_context_play(ctx, 0, "media.filename", path.get(), NULL);
    } else {
        nsCOMPtr<nsIStreamLoader> loader;
        rv = NS_NewStreamLoader(getter_AddRefs(loader), aURL, this);
    }

    return rv;
}
int main(int argc, char **argv)
{
  if (test_common_init(&argc, &argv) != 0)
    return -1;

  if (argc < 2) {
    printf("usage: %s <url>\n", argv[0]);
    return -1;
  }

  gTestLog = PR_NewLogModule("Test");

  nsresult rv = NS_InitXPCOM2(nullptr, nullptr, nullptr);
  if (NS_FAILED(rv))
    return -1;

  {
    nsCOMPtr<nsIURI> uri;
    rv = NS_NewURI(getter_AddRefs(uri), nsDependentCString(argv[1]));
    if (NS_FAILED(rv))
      return -1;

    nsCOMPtr<nsIScriptSecurityManager> secman =
      do_GetService(NS_SCRIPTSECURITYMANAGER_CONTRACTID, &rv);
    NS_ENSURE_SUCCESS(rv, -1);
       nsCOMPtr<nsIPrincipal> systemPrincipal;
    rv = secman->GetSystemPrincipal(getter_AddRefs(systemPrincipal));
    NS_ENSURE_SUCCESS(rv, -1);

    nsCOMPtr<nsIChannel> chan;
    rv = NS_NewChannel(getter_AddRefs(chan),
                       uri,
                       systemPrincipal,
                       nsILoadInfo::SEC_NORMAL,
                       nsIContentPolicy::TYPE_OTHER);

    if (NS_FAILED(rv))
      return -1;

    nsCOMPtr<nsIStreamLoaderObserver> observer = new MyStreamLoaderObserver();
    if (!observer)
      return -1;

    nsCOMPtr<nsIStreamLoader> loader;
    rv = NS_NewStreamLoader(getter_AddRefs(loader), observer);
    if (NS_FAILED(rv))
      return -1;

    rv = chan->AsyncOpen(loader, nullptr);
    if (NS_FAILED(rv))
      return -1;

    PumpEvents();
  } // this scopes the nsCOMPtrs
  // no nsCOMPtrs are allowed to be alive when you call NS_ShutdownXPCOM
  NS_ShutdownXPCOM(nullptr);
  return 0;
}
Esempio n. 5
0
int main(int argc, char **argv)
{
  if (test_common_init(&argc, &argv) != 0)
    return -1;

  if (argc < 2) {
    printf("usage: %s <url>\n", argv[0]);
    return -1;
  }

#if defined(PR_LOGGING)
  gTestLog = PR_NewLogModule("Test");
#endif

  nsresult rv = NS_InitXPCOM2(nsnull, nsnull, nsnull);
  if (NS_FAILED(rv))
    return -1;

  {
    // Create the Event Queue for this thread...
    rv = NS_GetMainEventQ(&gEventQ);
    if (NS_FAILED(rv))
      return -1;

    nsCOMPtr<nsIURI> uri;
    rv = NS_NewURI(getter_AddRefs(uri), nsDependentCString(argv[1]));
    if (NS_FAILED(rv))
      return -1;

    nsCOMPtr<nsIChannel> chan;
    rv = NS_NewChannel(getter_AddRefs(chan), uri);
    if (NS_FAILED(rv))
      return -1;

    nsCOMPtr<nsIStreamLoaderObserver> observer = new MyStreamLoaderObserver();
    if (!observer)
      return -1;

    nsCOMPtr<nsIStreamLoader> loader;
    rv = NS_NewStreamLoader(getter_AddRefs(loader), chan, observer, nsnull);
    if (NS_FAILED(rv))
      return -1;

    // Enter the message pump to allow the URL load to proceed.
    while (gKeepRunning) {
      PLEvent *e;
      gEventQ->WaitForEvent(&e);
      gEventQ->HandleEvent(e);
    }
  } // this scopes the nsCOMPtrs
  // no nsCOMPtrs are allowed to be alive when you call NS_ShutdownXPCOM
  NS_ShutdownXPCOM(nsnull);
  return rv;
}
Esempio n. 6
0
NS_METHOD nsSound::Play(nsIURL *aURL)
{
    nsresult rv;

    if (!mInited)
        Init();

    if (!elib) 
        return NS_ERROR_NOT_AVAILABLE;

    nsCOMPtr<nsIStreamLoader> loader;
    rv = NS_NewStreamLoader(getter_AddRefs(loader), aURL, this);

    return rv;
}
Esempio n. 7
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;
}
Esempio n. 8
0
nsresult
nsScriptLoader::ProcessScriptElement(nsIScriptElement *aElement)
{
    // We need a document to evaluate scripts.
    NS_ENSURE_TRUE(mDocument, NS_ERROR_FAILURE);

    // Check to see if scripts has been turned off.
    if (!mEnabled || !mDocument->IsScriptEnabled()) {
        return NS_ERROR_NOT_AVAILABLE;
    }

    NS_ASSERTION(!aElement->IsMalformed(), "Executing malformed script");

    // Check that the script is not an eventhandler
    if (IsScriptEventHandler(aElement)) {
        return NS_CONTENT_SCRIPT_IS_EVENTHANDLER;
    }

    // Script evaluation can also be disabled in the current script
    // context even though it's enabled in the document.
    // XXX - still hard-coded for JS here, even though another language
    // may be specified.  Should this check be made *after* we examine
    // the attributes to locate the script-type?
    // For now though, if JS is disabled we assume every language is
    // disabled.
    // XXX is this different from the mDocument->IsScriptEnabled() call?
    nsIScriptGlobalObject *globalObject = mDocument->GetScriptGlobalObject();
    if (!globalObject) {
        return NS_ERROR_NOT_AVAILABLE;
    }

    nsIScriptContext *context = globalObject->GetScriptContext(
                                    nsIProgrammingLanguage::JAVASCRIPT);

    // If scripts aren't enabled in the current context, there's no
    // point in going on.
    if (!context || !context->GetScriptsEnabled()) {
        return NS_ERROR_NOT_AVAILABLE;
    }

    // Default script language is whatever the root content specifies
    // (which may come from a header or http-meta tag), or if there
    // is no root content, from the script global object.
    nsCOMPtr<nsIContent> rootContent = mDocument->GetRootContent();
    PRUint32 typeID = rootContent ? rootContent->GetScriptTypeID() :
                      context->GetScriptTypeID();
    PRUint32 version = 0;
    nsAutoString language, type, src;
    nsresult rv = NS_OK;

    // Check the type attribute to determine language and version.
    // If type exists, it trumps the deprecated 'language='
    aElement->GetScriptType(type);
    if (!type.IsEmpty()) {
        nsCOMPtr<nsIMIMEHeaderParam> mimeHdrParser =
            do_GetService("@mozilla.org/network/mime-hdrparam;1");
        NS_ENSURE_TRUE(mimeHdrParser, NS_ERROR_FAILURE);

        NS_ConvertUTF16toUTF8 typeAndParams(type);

        nsAutoString mimeType;
        rv = mimeHdrParser->GetParameter(typeAndParams, nsnull,
                                         EmptyCString(), PR_FALSE, nsnull,
                                         mimeType);
        NS_ENSURE_SUCCESS(rv, rv);

        // Javascript keeps the fast path, optimized for most-likely type
        // Table ordered from most to least likely JS MIME types.
        // See bug 62485, feel free to add <script type="..."> survey data to it,
        // or to a new bug once 62485 is closed.
        static const char *jsTypes[] = {
            "text/javascript",
            "text/ecmascript",
            "application/javascript",
            "application/ecmascript",
            "application/x-javascript",
            nsnull
        };

        PRBool isJavaScript = PR_FALSE;
        for (PRInt32 i = 0; jsTypes[i]; i++) {
            if (mimeType.LowerCaseEqualsASCII(jsTypes[i])) {
                isJavaScript = PR_TRUE;
                break;
            }
        }
        if (isJavaScript)
            typeID = nsIProgrammingLanguage::JAVASCRIPT;
        else {
            // Use the object factory to locate a matching language.
            nsCOMPtr<nsIScriptRuntime> runtime;
            rv = NS_GetScriptRuntime(mimeType, getter_AddRefs(runtime));
            if (NS_FAILED(rv) || runtime == nsnull) {
                // Failed to get the explicitly specified language
                NS_WARNING("Failed to find a scripting language");
                typeID = nsIProgrammingLanguage::UNKNOWN;
            } else
                typeID = runtime->GetScriptTypeID();
        }
        if (typeID != nsIProgrammingLanguage::UNKNOWN) {
            // Get the version string, and ensure the language supports it.
            nsAutoString versionName;
            rv = mimeHdrParser->GetParameter(typeAndParams, "version",
                                             EmptyCString(), PR_FALSE, nsnull,
                                             versionName);
            if (NS_FAILED(rv)) {
                // no version attribute - version remains 0.
                if (rv != NS_ERROR_INVALID_ARG)
                    return rv;
            } else {
                nsCOMPtr<nsIScriptRuntime> runtime;
                rv = NS_GetScriptRuntimeByID(typeID, getter_AddRefs(runtime));
                if (NS_FAILED(rv)) {
                    NS_ERROR("Failed to locate the language with this ID");
                    return rv;
                }
                rv = runtime->ParseVersion(versionName, &version);
                if (NS_FAILED(rv)) {
                    NS_WARNING("This script language version is not supported - ignored");
                    typeID = nsIProgrammingLanguage::UNKNOWN;
                }
            }
        }

        // Some js specifics yet to be abstracted.
        if (typeID == nsIProgrammingLanguage::JAVASCRIPT) {
            nsAutoString value;

            rv = mimeHdrParser->GetParameter(typeAndParams, "e4x",
                                             EmptyCString(), PR_FALSE, nsnull,
                                             value);
            if (NS_FAILED(rv)) {
                if (rv != NS_ERROR_INVALID_ARG)
                    return rv;
            } else {
                if (value.Length() == 1 && value[0] == '1')
                    // This means that we need to set JSOPTION_XML in the JS options.
                    // We re-use our knowledge of the implementation to reuse
                    // JSVERSION_HAS_XML as a safe version flag.
                    // If version has JSVERSION_UNKNOWN (-1), then this is still OK.
                    version |= JSVERSION_HAS_XML;
            }
        }
    } else {
        // no 'type=' element
        // "language" is a deprecated attribute of HTML, so we check it only for
        // HTML script elements.
        nsCOMPtr<nsIDOMHTMLScriptElement> htmlScriptElement =
            do_QueryInterface(aElement);
        if (htmlScriptElement) {
            htmlScriptElement->GetAttribute(NS_LITERAL_STRING("language"), language);
            if (!language.IsEmpty()) {
                if (nsParserUtils::IsJavaScriptLanguage(language, &version))
                    typeID = nsIProgrammingLanguage::JAVASCRIPT;
                else
                    typeID = nsIProgrammingLanguage::UNKNOWN;
                // IE, Opera, etc. do not respect language version, so neither should
                // we at this late date in the browser wars saga.  Note that this change
                // affects HTML but not XUL or SVG (but note also that XUL has its own
                // code to check nsParserUtils::IsJavaScriptLanguage -- that's probably
                // a separate bug, one we may not be able to fix short of XUL2).  See
                // bug 255895 (https://bugzilla.mozilla.org/show_bug.cgi?id=255895).
                NS_ASSERTION(JSVERSION_DEFAULT == 0,
                             "We rely on all languages having 0 as a version default");
                version = 0;
            }
        }
    }

    // If we don't know the language, we don't know how to evaluate
    if (typeID == nsIProgrammingLanguage::UNKNOWN) {
        return NS_ERROR_NOT_AVAILABLE;
    }
    // If not from a chrome document (which is always trusted), we need some way
    // of checking the language is "safe".  Currently the only other language
    // impl is Python, and that is *not* safe in untrusted code - so fixing
    // this isn't a priority.!
    // See also similar code in nsXULContentSink.cpp
    if (typeID != nsIProgrammingLanguage::JAVASCRIPT &&
            !nsContentUtils::IsChromeDoc(mDocument)) {
        NS_WARNING("Untrusted language called from non-chrome - ignored");
        return NS_ERROR_NOT_AVAILABLE;
    }

    nsCOMPtr<nsIContent> eltContent(do_QueryInterface(aElement));
    eltContent->SetScriptTypeID(typeID);

    // Create a request object for this script
    nsRefPtr<nsScriptLoadRequest> request = new nsScriptLoadRequest(aElement, version);
    NS_ENSURE_TRUE(request, NS_ERROR_OUT_OF_MEMORY);

    // First check to see if this is an external script
    nsCOMPtr<nsIURI> scriptURI = aElement->GetScriptURI();
    if (scriptURI) {
        // Check that the containing page is allowed to load this URI.
        rv = nsContentUtils::GetSecurityManager()->
             CheckLoadURIWithPrincipal(mDocument->NodePrincipal(), scriptURI,
                                       nsIScriptSecurityManager::ALLOW_CHROME);

        NS_ENSURE_SUCCESS(rv, rv);

        // After the security manager, the content-policy stuff gets a veto
        PRInt16 shouldLoad = nsIContentPolicy::ACCEPT;
        rv = NS_CheckContentLoadPolicy(nsIContentPolicy::TYPE_SCRIPT,
                                       scriptURI,
                                       mDocument->NodePrincipal(),
                                       aElement,
                                       NS_LossyConvertUTF16toASCII(type),
                                       nsnull,    //extra
                                       &shouldLoad,
                                       nsContentUtils::GetContentPolicy(),
                                       nsContentUtils::GetSecurityManager());
        if (NS_FAILED(rv) || NS_CP_REJECTED(shouldLoad)) {
            if (NS_FAILED(rv) || shouldLoad != nsIContentPolicy::REJECT_TYPE) {
                return NS_ERROR_CONTENT_BLOCKED;
            }
            return NS_ERROR_CONTENT_BLOCKED_SHOW_ALT;
        }

        request->mURI = scriptURI;
        request->mIsInline = PR_FALSE;
        request->mLoading = PR_TRUE;

        nsCOMPtr<nsILoadGroup> loadGroup = mDocument->GetDocumentLoadGroup();
        nsCOMPtr<nsIStreamLoader> loader;

        nsCOMPtr<nsPIDOMWindow> window(do_QueryInterface(globalObject));
        nsIDocShell *docshell = window->GetDocShell();

        nsCOMPtr<nsIInterfaceRequestor> prompter(do_QueryInterface(docshell));

        nsCOMPtr<nsIChannel> channel;
        rv = NS_NewChannel(getter_AddRefs(channel),
                           scriptURI, nsnull, loadGroup,
                           prompter, nsIRequest::LOAD_NORMAL);
        NS_ENSURE_SUCCESS(rv, rv);

        nsCOMPtr<nsIHttpChannel> httpChannel(do_QueryInterface(channel));
        if (httpChannel) {
            // HTTP content negotation has little value in this context.
            httpChannel->SetRequestHeader(NS_LITERAL_CSTRING("Accept"),
                                          NS_LITERAL_CSTRING("*/*"),
                                          PR_FALSE);
            httpChannel->SetReferrer(mDocument->GetDocumentURI());
        }

        rv = NS_NewStreamLoader(getter_AddRefs(loader), this);
        NS_ENSURE_SUCCESS(rv, rv);

        rv = channel->AsyncOpen(loader, request);
        NS_ENSURE_SUCCESS(rv, rv);
    } else {
        request->mLoading = PR_FALSE;
        request->mIsInline = PR_TRUE;
        request->mURI = mDocument->GetDocumentURI();

        request->mLineNo = aElement->GetScriptLineNumber();

        // If we've got existing pending requests, add ourselves
        // to this list.
        if (mPendingRequests.Count() == 0 && ReadyToExecuteScripts() &&
                nsContentUtils::IsSafeToRunScript()) {
            return ProcessRequest(request);
        }
    }

    // Add the request to our pending requests list
    NS_ENSURE_TRUE(mPendingRequests.AppendObject(request),
                   NS_ERROR_OUT_OF_MEMORY);

    // If there weren't any pending requests before, and this one is
    // ready to execute, do that as soon as it's safe.
    if (mPendingRequests.Count() == 1 && !request->mLoading &&
            ReadyToExecuteScripts()) {
        nsContentUtils::AddScriptRunner(new nsRunnableMethod<nsScriptLoader>(this,
                                        &nsScriptLoader::ProcessPendingRequests));
    }

    // Added as pending request, now we can send blocking back
    return NS_ERROR_HTMLPARSER_BLOCK;
}
NS_IMETHODIMP
nsAbContentHandler::HandleContent(const char *aContentType,
                                  nsIInterfaceRequestor *aWindowContext,
                                  nsIRequest *request)
{
  NS_ENSURE_ARG_POINTER(request);

  nsresult rv = NS_OK;

  // First of all, get the content type and make sure it is a content type we know how to handle!
  if (PL_strcasecmp(aContentType, "application/x-addvcard") == 0) {
    nsCOMPtr<nsIURI> uri;
    nsCOMPtr<nsIChannel> aChannel = do_QueryInterface(request);
    if (!aChannel) return NS_ERROR_FAILURE;

    rv = aChannel->GetURI(getter_AddRefs(uri));
    if (uri)
    {
        nsCAutoString path;
        rv = uri->GetPath(path);
        NS_ENSURE_SUCCESS(rv,rv);

        const char *startOfVCard = strstr(path.get(), "add?vcard=");
        if (startOfVCard)
        {
            nsCString unescapedData;
            
            // XXX todo, explain why we is escaped twice
            MsgUnescapeString(nsDependentCString(startOfVCard + strlen("add?vcard=")), 
                                                 0, unescapedData);

            if (!aWindowContext)
                return NS_ERROR_FAILURE;

            nsCOMPtr<nsIDOMWindow> parentWindow = do_GetInterface(aWindowContext);
            if (!parentWindow)
                return NS_ERROR_FAILURE;

            nsCOMPtr<nsIAbManager> ab =
              do_GetService(NS_ABMANAGER_CONTRACTID, &rv);
            NS_ENSURE_SUCCESS(rv, rv);

            nsCOMPtr <nsIAbCard> cardFromVCard;
            rv = ab->EscapedVCardToAbCard(unescapedData.get(),
                                          getter_AddRefs(cardFromVCard));
            NS_ENSURE_SUCCESS(rv, rv);

            nsCOMPtr<nsISupportsInterfacePointer> ifptr =
                do_CreateInstance(NS_SUPPORTS_INTERFACE_POINTER_CONTRACTID, &rv);
            NS_ENSURE_SUCCESS(rv, rv);

            ifptr->SetData(cardFromVCard);
            ifptr->SetDataIID(&NS_GET_IID(nsIAbCard));

            nsCOMPtr<nsIDOMWindow> dialogWindow;

            rv = parentWindow->OpenDialog(
                NS_LITERAL_STRING("chrome://messenger/content/addressbook/abNewCardDialog.xul"),
                EmptyString(),
                NS_LITERAL_STRING("chrome,resizable=no,titlebar,modal,centerscreen"),
                ifptr, getter_AddRefs(dialogWindow));
            NS_ENSURE_SUCCESS(rv, rv);
        }
        rv = NS_OK;
    }
  }
  else if (PL_strcasecmp(aContentType, "text/x-vcard") == 0) {
    // create a vcard stream listener that can parse the data stream
    // and bring up the appropriate UI

    // (1) cancel the current load operation. We'll restart it
    request->Cancel(NS_ERROR_ABORT);
    // get the url we were trying to open
    nsCOMPtr<nsIURI> uri;
    nsCOMPtr<nsIChannel> channel = do_QueryInterface(request);
    NS_ENSURE_TRUE(channel, NS_ERROR_FAILURE);

    rv = channel->GetURI(getter_AddRefs(uri));
    NS_ENSURE_SUCCESS(rv, rv);

    // create a stream loader to handle the v-card data
    nsCOMPtr<nsIStreamLoader> streamLoader;
    rv = NS_NewStreamLoader(getter_AddRefs(streamLoader), uri, this, aWindowContext);
    NS_ENSURE_SUCCESS(rv, rv);

  }
  else // The content-type was not application/x-addvcard...
    return NS_ERROR_WONT_HANDLE_CONTENT;

  return rv;
}
nsresult
nsDOMWorkerScriptLoader::RunInternal()
{
  NS_ASSERTION(NS_IsMainThread(), "Wrong thread!");

  // Things we need to make all this work...
  nsCOMPtr<nsIDocument> parentDoc = mWorker->Pool()->ParentDocument();
  if (!parentDoc) {
    // Must have been canceled.
    return NS_ERROR_ABORT;
  }

  nsIPrincipal* principal;
  nsIURI* baseURI;

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

    nsRefPtr<nsDOMWorker> parentWorker = mWorker->GetParent();
    if (parentWorker) {
      principal = parentWorker->GetPrincipal();
      NS_ENSURE_STATE(principal);

      baseURI = parentWorker->GetURI();
      NS_ENSURE_STATE(baseURI);
    }
    else {
      principal = parentDoc->NodePrincipal();
      NS_ENSURE_STATE(principal);

      baseURI = parentDoc->GetDocBaseURI();
    }
  }
  else {
    principal = mWorker->GetPrincipal();
    baseURI = mWorker->GetURI();

    NS_ASSERTION(principal && baseURI, "Should have been set already!");
  }

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

  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;
    }

    nsIScriptSecurityManager* secMan = nsContentUtils::GetSecurityManager();
    NS_ENSURE_TRUE(secMan, NS_ERROR_FAILURE);

    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 NS_ERROR_CONTENT_BLOCKED;
      }
      return 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.
    if (mForWorker) {
      rv = principal->CheckMayLoad(uri, PR_FALSE);
      NS_ENSURE_SUCCESS(rv, rv);

      // Set the principal and URI on the new worker.
      mWorker->SetPrincipal(principal);

      rv = mWorker->SetURI(uri);
      NS_ENSURE_SUCCESS(rv, rv);
    }
    else {
      rv = 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<nsIChannelPolicy> channelPolicy;
    nsCOMPtr<nsIContentSecurityPolicy> csp;
    rv = parentDoc->NodePrincipal()->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_SCRIPT);
    }

    rv = NS_NewChannel(getter_AddRefs(loadInfo.channel),
                       uri,
                       ios,
                       loadGroup,
                       nsnull,                            // callbacks
                       nsIRequest::LOAD_NORMAL |
                       nsIChannel::LOAD_CLASSIFY_URI,     // loadFlags
                       channelPolicy);                    // CSP info
    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;
}
Esempio n. 11
0
NS_IMETHODIMP
nsHTTPDownloadEvent::Run()
{
  if (!mListener)
    return NS_OK;

  nsresult rv;

  nsCOMPtr<nsIIOService> ios = do_GetIOService();
  NS_ENSURE_STATE(ios);

  nsCOMPtr<nsIChannel> chan;
  ios->NewChannel(mRequestSession->mURL, nsnull, nsnull, getter_AddRefs(chan));
  NS_ENSURE_STATE(chan);

  // Create a loadgroup for this new channel.  This way if the channel
  // is redirected, we'll have a way to cancel the resulting channel.
  nsCOMPtr<nsILoadGroup> lg = do_CreateInstance(NS_LOADGROUP_CONTRACTID);
  chan->SetLoadGroup(lg);

  if (mRequestSession->mHasPostData)
  {
    nsCOMPtr<nsIInputStream> uploadStream;
    rv = NS_NewPostDataStream(getter_AddRefs(uploadStream),
                              PR_FALSE,
                              mRequestSession->mPostData,
                              0, ios);
    NS_ENSURE_SUCCESS(rv, rv);

    nsCOMPtr<nsIUploadChannel> uploadChannel(do_QueryInterface(chan));
    NS_ENSURE_STATE(uploadChannel);

    rv = uploadChannel->SetUploadStream(uploadStream, 
                                        mRequestSession->mPostContentType,
                                        -1);
    NS_ENSURE_SUCCESS(rv, rv);
  }

  nsCOMPtr<nsIHttpChannel> hchan = do_QueryInterface(chan);
  NS_ENSURE_STATE(hchan);

  rv = hchan->SetRequestMethod(mRequestSession->mRequestMethod);
  NS_ENSURE_SUCCESS(rv, rv);

  mResponsibleForDoneSignal = PR_FALSE;
  mListener->mResponsibleForDoneSignal = PR_TRUE;

  mListener->mLoadGroup = lg.get();
  NS_ADDREF(mListener->mLoadGroup);
  mListener->mLoadGroupOwnerThread = PR_GetCurrentThread();

  rv = NS_NewStreamLoader(getter_AddRefs(mListener->mLoader), 
                          mListener);

  if (NS_SUCCEEDED(rv))
    rv = hchan->AsyncOpen(mListener->mLoader, nsnull);

  if (NS_FAILED(rv)) {
    mListener->mResponsibleForDoneSignal = PR_FALSE;
    mResponsibleForDoneSignal = PR_TRUE;

    NS_RELEASE(mListener->mLoadGroup);
    mListener->mLoadGroup = nsnull;
    mListener->mLoadGroupOwnerThread = nsnull;
  }

  return NS_OK;
}