GnomeKeyringResult
GnomeKeyring::findLogins(const nsAString & aHostname,
                         const nsAString & aActionURL,
                         const nsAString & aHttpRealm,
                         GList** found)
{
  AutoAttributeList attributes;
  newLoginInfoAttributes(&attributes);

  addAttribute(attributes, kHostnameAttr, aHostname);
  if (!aActionURL.IsVoid() && !aActionURL.IsEmpty()) {
    addAttribute(attributes, kFormSubmitURLAttr, aActionURL);
  }
  if (!aHttpRealm.IsVoid() && !aHttpRealm.IsEmpty()) {
    addAttribute(attributes, kHttpRealmAttr, aHttpRealm);
  }

  GnomeKeyringResult result = findLoginItems(attributes, found);

  if (aActionURL.IsVoid()) {
    // TODO: filter out items with a kFormSubmitURLAttr
    // practically, this is not necessary since actionURL/httpRealm are
    // mutually exclusive, but this is not enforced by the interface
  }
  if (aHttpRealm.IsVoid()) {
    // TODO: filter out items with a kHttpRealmAttr
    // practically, this is not necessary since actionURL/httpRealm are
    // mutually exclusive, but this is not enforced by the interface
  }

  return result;
}
Exemplo n.º 2
0
/* static */ bool
HTMLImageElement::SelectSourceForTagWithAttrs(nsIDocument *aDocument,
                                              bool aIsSourceTag,
                                              const nsAString& aSrcAttr,
                                              const nsAString& aSrcsetAttr,
                                              const nsAString& aSizesAttr,
                                              const nsAString& aTypeAttr,
                                              const nsAString& aMediaAttr,
                                              nsAString& aResult)
{
  MOZ_ASSERT(aIsSourceTag || (aTypeAttr.IsEmpty() && aMediaAttr.IsEmpty()),
             "Passing type or media attrs makes no sense without aIsSourceTag");
  MOZ_ASSERT(!aIsSourceTag || aSrcAttr.IsEmpty(),
             "Passing aSrcAttr makes no sense with aIsSourceTag set");

  if (aSrcsetAttr.IsEmpty()) {
    if (!aIsSourceTag) {
      // For an <img> with no srcset, we would always select the src attr.
      aResult.Assign(aSrcAttr);
      return true;
    }
    // Otherwise, a <source> without srcset is never selected
    return false;
  }

  // Would not consider source tags with unsupported media or type
  if (aIsSourceTag &&
      ((!aMediaAttr.IsVoid() &&
       !HTMLSourceElement::WouldMatchMediaForDocument(aMediaAttr, aDocument)) ||
      (!aTypeAttr.IsVoid() &&
       !SupportedPictureSourceType(aTypeAttr)))) {
    return false;
  }

  // Using srcset or picture <source>, build a responsive selector for this tag.
  RefPtr<ResponsiveImageSelector> sel =
    new ResponsiveImageSelector(aDocument);

  sel->SetCandidatesFromSourceSet(aSrcsetAttr);
  if (!aSizesAttr.IsEmpty()) {
    sel->SetSizesFromDescriptor(aSizesAttr);
  }
  if (!aIsSourceTag) {
    sel->SetDefaultSource(aSrcAttr);
  }

  if (sel->GetSelectedImageURLSpec(aResult)) {
    return true;
  }

  if (!aIsSourceTag) {
    // <img> tag with no match would definitively load nothing.
    aResult.Truncate();
    return true;
  }

  // <source> tags with no match would leave source yet-undetermined.
  return false;
}
Exemplo n.º 3
0
QString generateQueryWalletKey( const nsAString & aHostname,
                                const nsAString & aActionURL,
                                const nsAString & aHttpRealm,
                                const nsAString & aUsername ) {
    QString key = (aUsername.IsVoid() || aUsername.IsEmpty() ) ? "*" : NSString2QtString(aUsername);
    key += ",";
    key += (aActionURL.IsVoid() || aActionURL.IsEmpty() ) ? "*" : NSString2QtString(aActionURL);
    key += ",";
    key += (aHttpRealm.IsVoid() || aHttpRealm.IsEmpty() ) ? "*" : NSString2QtString(aHttpRealm);
    key += ",";
    key += (aHostname.IsVoid() || aHostname.IsEmpty() ) ? "*" : NSString2QtString(aHostname);
    return key;
}
/**
 * Asks the Property Manager whether or not the value is valid for the given
 * property.
 */
nsresult
sbPropertyArray::ValueIsValid(const nsAString& aID,
                              const nsAString& aValue,
                              bool* _retval)
{
  NS_ASSERTION(!aID.IsEmpty(), "Don't pass an empty property id!");
  NS_ASSERTION(_retval, "Don't hand me a null!");

  if (aValue.IsVoid()) {
    *_retval = PR_TRUE;
    return NS_OK;
  }

  nsresult rv;

  if (!mPropManager) {
    mPropManager = do_GetService(SB_PROPERTYMANAGER_CONTRACTID, &rv);
    NS_ENSURE_SUCCESS(rv, rv);
  }

  // This will actually *create* a new sbIPropertyInfo if one has not been
  // registered already...
  nsCOMPtr<sbIPropertyInfo> propInfo;
  rv = mPropManager->GetPropertyInfo(aID, getter_AddRefs(propInfo));
  NS_ENSURE_SUCCESS(rv, rv);

  bool valid;
  rv = propInfo->Validate(aValue, &valid);
  NS_ENSURE_SUCCESS(rv, rv);

  *_retval = valid;
  return NS_OK;
}
Exemplo n.º 5
0
static void
ConvertString(const nsAString& aUTF16String, nsACString& aUTF8String)
{
  if (aUTF16String.IsVoid()) {
    aUTF8String.SetIsVoid(true);
  } else {
    CopyUTF16toUTF8(aUTF16String, aUTF8String);
  }
}
/* If no source has been defined, compileShader() has not been called,
 * or the translation has failed for shader, an empty string is
 * returned; otherwise, return the translated source.
 */
void
WebGLExtensionDebugShaders::GetTranslatedShaderSource(WebGLShader* shader,
                                                      nsAString& retval)
{
    mContext->GetShaderTranslatedSource(shader, retval);

    if (retval.IsVoid()) {
        CopyASCIItoUTF16("", retval);
    }
}
Exemplo n.º 7
0
nsresult
sbProcess::SetStdinString(const nsAString& aStdinString)
{
  // Operate under the process lock.
  NS_ENSURE_TRUE(mProcessLock, NS_ERROR_NOT_INITIALIZED);
  nsAutoLock autoProcessLock(mProcessLock);

  // Set the stdin string.
  mStdinString.Assign(aStdinString);
  mPipeStdinString = !aStdinString.IsVoid();

  return NS_OK;
}
Exemplo n.º 8
0
PRBool
nsXTFElementWrapper::GetAttr(PRInt32 aNameSpaceID, nsIAtom* aName, 
                             nsAString& aResult) const
{
  if (aNameSpaceID==kNameSpaceID_None && HandledByInner(aName)) {
    // XXX we don't do namespaced attributes yet
    nsresult rv = mAttributeHandler->GetAttribute(aName, aResult);
    return NS_SUCCEEDED(rv) && !aResult.IsVoid();
  }
  else { // try wrapper
    return nsXTFElementWrapperBase::GetAttr(aNameSpaceID, aName, aResult);
  }
}
/* If no source has been defined, compileShader() has not been called,
 * or the translation has failed for shader, an empty string is
 * returned; otherwise, return the translated source.
 */
void
WebGLExtensionDebugShaders::GetTranslatedShaderSource(WebGLShader* shader,
                                                      nsAString& retval)
{
    if (mIsLost) {
        return mContext->ErrorInvalidOperation("getTranslatedShaderSource: "
                                               "Extension is lost.");
    }

    mContext->GetShaderTranslatedSource(shader, retval);

    if (retval.IsVoid()) {
        CopyASCIItoUTF16("", retval);
    }
}
Exemplo n.º 10
0
JSBool
xpc_qsStringToJsval(JSContext *cx, const nsAString &str, jsval *rval)
{
    // From the T_DOMSTRING case in XPCConvert::NativeData2JS.
    if(str.IsVoid())
    {
        *rval = JSVAL_NULL;
        return JS_TRUE;
    }

    jsval jsstr = XPCStringConvert::ReadableToJSVal(cx, str);
    if(!jsstr)
        return JS_FALSE;
    *rval = jsstr;
    return JS_TRUE;
}
NS_IMETHODIMP
sbOriginPageImagePropertyInfo::GetImageSrc(const nsAString& aValue,
                                           nsAString& _retval)
{
  if(aValue.IsEmpty() ||
     aValue.IsVoid() ||
     aValue.EqualsLiteral("unknownOrigin") ||
     aValue.EqualsLiteral("webOrigin")) {
    _retval.Truncate();
    return NS_OK;
  }

  nsCOMPtr<nsIURI> uri;
  nsresult rv = NS_NewURI(getter_AddRefs(uri), aValue);
  NS_ENSURE_SUCCESS(rv, rv);

  nsCOMPtr<nsIURI> imageUri;
  rv = mFaviconService->GetFaviconForPage(uri, getter_AddRefs(imageUri));
  
  if(rv == NS_ERROR_NOT_AVAILABLE) {
    _retval.Truncate();
    return NS_OK;
  }

  NS_ENSURE_SUCCESS(rv, rv);

  nsCAutoString spec;
  rv = imageUri->GetSpec(spec);
  NS_ENSURE_SUCCESS(rv, rv);
  
  NS_NAMED_LITERAL_CSTRING(mozAnnoFavicon, "moz-anno:favicon:");
  if(!StringBeginsWith(spec, mozAnnoFavicon)) {
    _retval = NS_ConvertUTF8toUTF16(spec);
    return NS_OK;
  }

  spec.Cut(0, mozAnnoFavicon.Length());
  NS_WARNING(spec.get());
  _retval = NS_ConvertUTF8toUTF16(spec);

  return NS_OK;
}
NS_IMETHODIMP
sbOriginPageImagePropertyInfo::GetCellProperties(const nsAString& aValue,
                                                 nsAString& _retval)
{
  if(aValue.EqualsLiteral("unknownOrigin") ||
     aValue.IsEmpty() ||
     aValue.IsVoid()) {
    _retval.AssignLiteral("image unknownOrigin");
    return NS_OK;
  }

  if(aValue.EqualsLiteral("webOrigin") ||
     StringBeginsWith(aValue, NS_LITERAL_STRING("http://"), CaseInsensitiveCompare) ||
     StringBeginsWith(aValue, NS_LITERAL_STRING("https://"), CaseInsensitiveCompare) ||
     StringBeginsWith(aValue, NS_LITERAL_STRING("ftp://"), CaseInsensitiveCompare)) {
    
    _retval.AssignLiteral("image webOrigin");
    return NS_OK;
  }

  _retval.AssignLiteral("image");

  return NS_OK;
}
Exemplo n.º 13
0
nsresult
mozJSSubScriptLoader::ReadScript(nsIURI *uri, JSContext *cx, JSObject *targetObjArg,
                                 const nsAString& charset, const char *uriStr,
                                 nsIIOService *serv, nsIPrincipal *principal,
                                 bool reuseGlobal, JSScript **scriptp,
                                 JSFunction **functionp)
{
    RootedObject target_obj(cx, targetObjArg);

    nsCOMPtr<nsIChannel>     chan;
    nsCOMPtr<nsIInputStream> instream;
    JSErrorReporter  er;

    *scriptp = nullptr;
    *functionp = nullptr;

    nsresult rv;
    // Instead of calling NS_OpenURI, we create the channel ourselves and call
    // SetContentType, to avoid expensive MIME type lookups (bug 632490).
    rv = NS_NewChannel(getter_AddRefs(chan), uri, serv,
                       nullptr, nullptr, nsIRequest::LOAD_NORMAL);
    if (NS_SUCCEEDED(rv)) {
        chan->SetContentType(NS_LITERAL_CSTRING("application/javascript"));
        rv = chan->Open(getter_AddRefs(instream));
    }

    if (NS_FAILED(rv)) {
        return ReportError(cx, LOAD_ERROR_NOSTREAM);
    }

    int64_t len = -1;

    rv = chan->GetContentLength(&len);
    if (NS_FAILED(rv) || len == -1) {
        return ReportError(cx, LOAD_ERROR_NOCONTENT);
    }

    if (len > INT32_MAX) {
        return ReportError(cx, LOAD_ERROR_CONTENTTOOBIG);
    }

    nsCString buf;
    rv = NS_ReadInputStreamToString(instream, buf, len);
    if (NS_FAILED(rv))
        return rv;

    /* set our own error reporter so we can report any bad things as catchable
     * exceptions, including the source/line number */
    er = JS_SetErrorReporter(cx, mozJSLoaderErrorReporter);

    JS::CompileOptions options(cx);
    options.setPrincipals(nsJSPrincipals::get(principal))
           .setFileAndLine(uriStr, 1);
    if (!charset.IsVoid()) {
        nsString script;
        rv = nsScriptLoader::ConvertToUTF16(nullptr, reinterpret_cast<const uint8_t*>(buf.get()), len,
                                            charset, nullptr, script);

        if (NS_FAILED(rv)) {
            return ReportError(cx, LOAD_ERROR_BADCHARSET);
        }

        if (!reuseGlobal) {
            *scriptp = JS::Compile(cx, target_obj, options,
                                   reinterpret_cast<const jschar*>(script.get()),
                                   script.Length());
        } else {
            *functionp = JS::CompileFunction(cx, target_obj, options,
                                             nullptr, 0, nullptr,
                                             reinterpret_cast<const jschar*>(script.get()),
                                             script.Length());
        }
    } else {
        // We only use LAZY_SOURCE when no special encoding is specified because
        // the lazy source loader doesn't know the encoding.
        if (!reuseGlobal) {
            options.setSourcePolicy(JS::CompileOptions::LAZY_SOURCE);
            *scriptp = JS::Compile(cx, target_obj, options, buf.get(), len);
        } else {
            *functionp = JS::CompileFunction(cx, target_obj, options,
                                             nullptr, 0, nullptr, buf.get(),
                                             len);
        }
    }

    /* repent for our evil deeds */
    JS_SetErrorReporter(cx, er);

    return NS_OK;
}
Exemplo n.º 14
0
NS_IMETHODIMP
PresentationService::StartSession(const nsAString& aUrl,
                                  const nsAString& aSessionId,
                                  const nsAString& aOrigin,
                                  const nsAString& aDeviceId,
                                  uint64_t aWindowId,
                                  nsIPresentationServiceCallback* aCallback)
{
  MOZ_ASSERT(NS_IsMainThread());
  MOZ_ASSERT(aCallback);
  MOZ_ASSERT(!aSessionId.IsEmpty());

  // Create session info  and set the callback. The callback is called when the
  // request is finished.
  RefPtr<PresentationSessionInfo> info =
    new PresentationControllingInfo(aUrl, aSessionId, aCallback);
  mSessionInfoAtController.Put(aSessionId, info);

  // Only track the info when an actual window ID, which would never be 0, is
  // provided (for an in-process sender page).
  if (aWindowId != 0) {
    mRespondingSessionIds.Put(aWindowId, new nsString(aSessionId));
    mRespondingWindowIds.Put(aSessionId, aWindowId);
  }

  nsCOMPtr<nsIPresentationDeviceRequest> request =
    new PresentationDeviceRequest(aUrl, aSessionId, aOrigin);

  if (aDeviceId.IsVoid()) {
    // Pop up a prompt and ask user to select a device.
    nsCOMPtr<nsIPresentationDevicePrompt> prompt =
      do_GetService(PRESENTATION_DEVICE_PROMPT_CONTRACTID);
    if (NS_WARN_IF(!prompt)) {
      return info->ReplyError(NS_ERROR_DOM_OPERATION_ERR);
    }

    nsresult rv = prompt->PromptDeviceSelection(request);
    if (NS_WARN_IF(NS_FAILED(rv))) {
      return info->ReplyError(NS_ERROR_DOM_OPERATION_ERR);
    }

    return NS_OK;
  }

  // Find the designated device from available device list.
  nsCOMPtr<nsIPresentationDeviceManager> deviceManager =
    do_GetService(PRESENTATION_DEVICE_MANAGER_CONTRACTID);
  if (NS_WARN_IF(!deviceManager)) {
    return info->ReplyError(NS_ERROR_DOM_OPERATION_ERR);
  }

  nsCOMPtr<nsIArray> devices;
  nsresult rv = deviceManager->GetAvailableDevices(getter_AddRefs(devices));
  if (NS_WARN_IF(NS_FAILED(rv))) {
    return info->ReplyError(NS_ERROR_DOM_OPERATION_ERR);
  }

  nsCOMPtr<nsISimpleEnumerator> enumerator;
  rv = devices->Enumerate(getter_AddRefs(enumerator));
  if (NS_WARN_IF(NS_FAILED(rv))) {
    return info->ReplyError(NS_ERROR_DOM_OPERATION_ERR);
  }

  NS_ConvertUTF16toUTF8 utf8DeviceId(aDeviceId);
  bool hasMore;
  while(NS_SUCCEEDED(enumerator->HasMoreElements(&hasMore)) && hasMore){
    nsCOMPtr<nsISupports> isupports;
    rv = enumerator->GetNext(getter_AddRefs(isupports));

    nsCOMPtr<nsIPresentationDevice> device(do_QueryInterface(isupports));
    MOZ_ASSERT(device);

    nsAutoCString id;
    if (NS_SUCCEEDED(device->GetId(id)) && id.Equals(utf8DeviceId)) {
      request->Select(device);
      return NS_OK;
    }
  }

  // Reject if designated device is not available.
  return info->ReplyError(NS_ERROR_DOM_NOT_FOUND_ERR);
}
Exemplo n.º 15
0
NS_StringGetIsVoid(const nsAString& aStr)
{
  return aStr.IsVoid();
}
Exemplo n.º 16
0
NS_IMETHODIMP
PresentationService::StartSession(
               const nsTArray<nsString>& aUrls,
               const nsAString& aSessionId,
               const nsAString& aOrigin,
               const nsAString& aDeviceId,
               uint64_t aWindowId,
               nsIDOMEventTarget* aEventTarget,
               nsIPrincipal* aPrincipal,
               nsIPresentationServiceCallback* aCallback,
               nsIPresentationTransportBuilderConstructor* aBuilderConstructor)
{
  PRES_DEBUG("%s:id[%s]\n", __func__, NS_ConvertUTF16toUTF8(aSessionId).get());

  MOZ_ASSERT(NS_IsMainThread());
  MOZ_ASSERT(aCallback);
  MOZ_ASSERT(!aSessionId.IsEmpty());
  MOZ_ASSERT(!aUrls.IsEmpty());

  nsCOMPtr<nsIPresentationDeviceRequest> request =
    new PresentationDeviceRequest(aUrls,
                                  aSessionId,
                                  aOrigin,
                                  aWindowId,
                                  aEventTarget,
                                  aPrincipal,
                                  aCallback,
                                  aBuilderConstructor);

  if (aDeviceId.IsVoid()) {
    // Pop up a prompt and ask user to select a device.
    nsCOMPtr<nsIPresentationDevicePrompt> prompt =
      do_GetService(PRESENTATION_DEVICE_PROMPT_CONTRACTID);
    if (NS_WARN_IF(!prompt)) {
      return aCallback->NotifyError(NS_ERROR_DOM_OPERATION_ERR);
    }

    nsresult rv = prompt->PromptDeviceSelection(request);
    if (NS_WARN_IF(NS_FAILED(rv))) {
      return aCallback->NotifyError(NS_ERROR_DOM_OPERATION_ERR);
    }

    return NS_OK;
  }

  // Find the designated device from available device list.
  nsCOMPtr<nsIPresentationDeviceManager> deviceManager =
    do_GetService(PRESENTATION_DEVICE_MANAGER_CONTRACTID);
  if (NS_WARN_IF(!deviceManager)) {
    return aCallback->NotifyError(NS_ERROR_DOM_OPERATION_ERR);
  }

  nsCOMPtr<nsIArray> presentationUrls;
  if (NS_WARN_IF(NS_FAILED(
    ConvertURLArrayHelper(aUrls, getter_AddRefs(presentationUrls))))) {
    return aCallback->NotifyError(NS_ERROR_DOM_OPERATION_ERR);
  }

  nsCOMPtr<nsIArray> devices;
  nsresult rv = deviceManager->GetAvailableDevices(presentationUrls, getter_AddRefs(devices));
  if (NS_WARN_IF(NS_FAILED(rv))) {
    return aCallback->NotifyError(NS_ERROR_DOM_OPERATION_ERR);
  }

  nsCOMPtr<nsISimpleEnumerator> enumerator;
  rv = devices->Enumerate(getter_AddRefs(enumerator));
  if (NS_WARN_IF(NS_FAILED(rv))) {
    return aCallback->NotifyError(NS_ERROR_DOM_OPERATION_ERR);
  }

  NS_ConvertUTF16toUTF8 utf8DeviceId(aDeviceId);
  bool hasMore;
  while (NS_SUCCEEDED(enumerator->HasMoreElements(&hasMore)) && hasMore) {
    nsCOMPtr<nsISupports> isupports;
    rv = enumerator->GetNext(getter_AddRefs(isupports));

    nsCOMPtr<nsIPresentationDevice> device(do_QueryInterface(isupports));
    MOZ_ASSERT(device);

    nsAutoCString id;
    if (NS_SUCCEEDED(device->GetId(id)) && id.Equals(utf8DeviceId)) {
      request->Select(device);
      return NS_OK;
    }
  }

  // Reject if designated device is not available.
  return aCallback->NotifyError(NS_ERROR_DOM_NOT_FOUND_ERR);
}
nsresult
mozJSSubScriptLoader::ReadScript(nsIURI *uri, JSContext *cx, JSObject *target_obj,
                                 const nsAString& charset, const char *uriStr,
                                 nsIIOService *serv, nsIPrincipal *principal,
                                 JSScript **scriptp)
{
    nsCOMPtr<nsIChannel>     chan;
    nsCOMPtr<nsIInputStream> instream;
    JSErrorReporter  er;

    nsresult rv;
    // Instead of calling NS_OpenURI, we create the channel ourselves and call
    // SetContentType, to avoid expensive MIME type lookups (bug 632490).
    rv = NS_NewChannel(getter_AddRefs(chan), uri, serv,
                       nsnull, nsnull, nsIRequest::LOAD_NORMAL);
    if (NS_SUCCEEDED(rv)) {
        chan->SetContentType(NS_LITERAL_CSTRING("application/javascript"));
        rv = chan->Open(getter_AddRefs(instream));
    }

    if (NS_FAILED(rv)) {
        return ReportError(cx, LOAD_ERROR_NOSTREAM);
    }

    PRInt32 len = -1;

    rv = chan->GetContentLength(&len);
    if (NS_FAILED(rv) || len == -1) {
        return ReportError(cx, LOAD_ERROR_NOCONTENT);
    }

    nsCString buf;
    rv = NS_ReadInputStreamToString(instream, buf, len);
    if (NS_FAILED(rv))
        return rv;

    /* set our own error reporter so we can report any bad things as catchable
     * exceptions, including the source/line number */
    er = JS_SetErrorReporter(cx, mozJSLoaderErrorReporter);

    if (!charset.IsVoid()) {
        nsString script;
        rv = nsScriptLoader::ConvertToUTF16(nsnull, reinterpret_cast<const PRUint8*>(buf.get()), len,
                                            charset, nsnull, script);

        if (NS_FAILED(rv)) {
            return ReportError(cx, LOAD_ERROR_BADCHARSET);
        }

        *scriptp =
            JS_CompileUCScriptForPrincipals(cx, target_obj, nsJSPrincipals::get(principal),
                                            reinterpret_cast<const jschar*>(script.get()),
                                            script.Length(), uriStr, 1);
    } else {
        *scriptp = JS_CompileScriptForPrincipals(cx, target_obj, nsJSPrincipals::get(principal),
                                                 buf.get(), len, uriStr, 1);
    }

    /* repent for our evil deeds */
    JS_SetErrorReporter(cx, er);

    return NS_OK;
}
Exemplo n.º 18
0
/**
 * Validates a custom content security policy string for use by an add-on.
 * In particular, ensures that:
 *
 *  - Both object-src and script-src directives are present, and meet
 *    the policies required by the CSPValidator class
 *
 *  - The script-src directive includes the source 'self'
 */
NS_IMETHODIMP
AddonContentPolicy::ValidateAddonCSP(const nsAString& aPolicyString,
                                     nsAString& aResult)
{
  nsresult rv;

  // Validate against a randomly-generated extension origin.
  // There is no add-on-specific behavior in the CSP code, beyond the ability
  // for add-ons to specify a custom policy, but the parser requires a valid
  // origin in order to operate correctly.
  nsAutoString url(u"moz-extension://");
  {
    nsCOMPtr<nsIUUIDGenerator> uuidgen = services::GetUUIDGenerator();
    NS_ENSURE_TRUE(uuidgen, NS_ERROR_FAILURE);

    nsID id;
    rv = uuidgen->GenerateUUIDInPlace(&id);
    NS_ENSURE_SUCCESS(rv, rv);

    char idString[NSID_LENGTH];
    id.ToProvidedString(idString);

    MOZ_RELEASE_ASSERT(idString[0] == '{' && idString[NSID_LENGTH - 2] == '}',
                       "UUID generator did not return a valid UUID");

    url.AppendASCII(idString + 1, NSID_LENGTH - 3);
  }


  RefPtr<BasePrincipal> principal =
    BasePrincipal::CreateCodebasePrincipal(NS_ConvertUTF16toUTF8(url));

  nsCOMPtr<nsIContentSecurityPolicy> csp;
  rv = principal->EnsureCSP(nullptr, getter_AddRefs(csp));
  NS_ENSURE_SUCCESS(rv, rv);


  csp->AppendPolicy(aPolicyString, false, false);

  const nsCSPPolicy* policy = csp->GetPolicy(0);
  if (!policy) {
    CSPValidator validator(url, nsIContentSecurityPolicy::SCRIPT_SRC_DIRECTIVE);
    aResult.Assign(validator.GetError());
    return NS_OK;
  }

  bool haveValidDefaultSrc = false;
  {
    CSPDirective directive = nsIContentSecurityPolicy::DEFAULT_SRC_DIRECTIVE;
    CSPValidator validator(url, directive);

    haveValidDefaultSrc = policy->visitDirectiveSrcs(directive, &validator);
  }

  aResult.SetIsVoid(true);
  {
    CSPDirective directive = nsIContentSecurityPolicy::SCRIPT_SRC_DIRECTIVE;
    CSPValidator validator(url, directive, !haveValidDefaultSrc);

    if (!policy->visitDirectiveSrcs(directive, &validator)) {
      aResult.Assign(validator.GetError());
    } else if (!validator.FoundSelf()) {
      validator.FormatError("csp.error.missing-source", NS_LITERAL_STRING("'self'"));
      aResult.Assign(validator.GetError());
    }
  }

  if (aResult.IsVoid()) {
    CSPDirective directive = nsIContentSecurityPolicy::OBJECT_SRC_DIRECTIVE;
    CSPValidator validator(url, directive, !haveValidDefaultSrc);

    if (!policy->visitDirectiveSrcs(directive, &validator)) {
      aResult.Assign(validator.GetError());
    }
  }

  return NS_OK;
}