Esempio n. 1
0
already_AddRefed<nsITransferable>
DataTransfer::GetTransferable(uint32_t aIndex, nsILoadContext* aLoadContext)
{
  if (aIndex >= mItems.Length()) {
    return nullptr;
  }

  nsTArray<TransferItem>& item = mItems[aIndex];
  uint32_t count = item.Length();
  if (!count) {
    return nullptr;
  }

  nsCOMPtr<nsITransferable> transferable =
    do_CreateInstance("@mozilla.org/widget/transferable;1");
  if (!transferable) {
    return nullptr;
  }
  transferable->Init(aLoadContext);

  nsCOMPtr<nsIStorageStream> storageStream;
  nsCOMPtr<nsIBinaryOutputStream> stream;

  bool added = false;
  bool handlingCustomFormats = true;
  uint32_t totalCustomLength = 0;

  const char* knownFormats[] = {
    kTextMime, kHTMLMime, kNativeHTMLMime, kRTFMime,
    kURLMime, kURLDataMime, kURLDescriptionMime, kURLPrivateMime,
    kPNGImageMime, kJPEGImageMime, kGIFImageMime, kNativeImageMime,
    kFileMime, kFilePromiseMime, kFilePromiseURLMime,
    kFilePromiseDestFilename, kFilePromiseDirectoryMime,
    kMozTextInternal, kHTMLContext, kHTMLInfo };

  /*
   * Two passes are made here to iterate over all of the types. First, look for
   * any types that are not in the list of known types. For this pass,
   * handlingCustomFormats will be true. Data that corresponds to unknown types
   * will be pulled out and inserted into a single type (kCustomTypesMime) by
   * writing the data into a stream.
   *
   * The second pass will iterate over the formats looking for known types.
   * These are added as is. The unknown types are all then inserted as a single
   * type (kCustomTypesMime) in the same position of the first custom type. This
   * model is used to maintain the format order as best as possible.
   *
   * The format of the kCustomTypesMime type is one or more of the following
   * stored sequentially:
   *   <32-bit> type (only none or string is supported)
   *   <32-bit> length of format
   *   <wide string> format
   *   <32-bit> length of data
   *   <wide string> data
   * A type of eCustomClipboardTypeId_None ends the list, without any following
   * data.
   */
  do {
    for (uint32_t f = 0; f < count; f++) {
      const TransferItem& formatitem = item[f];
      if (!formatitem.mData) { // skip empty items
        continue;
      }

      // If the data is of one of the well-known formats, use it directly.
      bool isCustomFormat = true;
      for (uint32_t f = 0; f < ArrayLength(knownFormats); f++) {
        if (formatitem.mFormat.EqualsASCII(knownFormats[f])) {
          isCustomFormat = false;
          break;
        }
      }

      uint32_t lengthInBytes;
      nsCOMPtr<nsISupports> convertedData;

      if (handlingCustomFormats) {
        if (!ConvertFromVariant(formatitem.mData, getter_AddRefs(convertedData),
                                &lengthInBytes)) {
          continue;
        }

        // When handling custom types, add the data to the stream if this is a
        // custom type.
        if (isCustomFormat) {
          // If it isn't a string, just ignore it. The dataTransfer is cached in
          // the drag sesion during drag-and-drop, so non-strings will be
          // available when dragging locally.
          nsCOMPtr<nsISupportsString> str(do_QueryInterface(convertedData));
          if (str) {
            nsAutoString data;
            str->GetData(data);

            if (!stream) {
              // Create a storage stream to write to.
              NS_NewStorageStream(1024, UINT32_MAX, getter_AddRefs(storageStream));

              nsCOMPtr<nsIOutputStream> outputStream;
              storageStream->GetOutputStream(0, getter_AddRefs(outputStream));

              stream = do_CreateInstance("@mozilla.org/binaryoutputstream;1");
              stream->SetOutputStream(outputStream);
            }

            int32_t formatLength =
              formatitem.mFormat.Length() * sizeof(nsString::char_type);

            stream->Write32(eCustomClipboardTypeId_String);
            stream->Write32(formatLength);
            stream->WriteBytes((const char *)formatitem.mFormat.get(),
                               formatLength);
            stream->Write32(lengthInBytes);
            stream->WriteBytes((const char *)data.get(), lengthInBytes);

            // The total size of the stream is the format length, the data
            // length, two integers to hold the lengths and one integer for the
            // string flag.
            totalCustomLength +=
              formatLength + lengthInBytes + (sizeof(uint32_t) * 3);
          }
        }
      } else if (isCustomFormat && stream) {
        // This is the second pass of the loop (handlingCustomFormats is false).
        // When encountering the first custom format, append all of the stream
        // at this position.

        // Write out a terminator.
        totalCustomLength += sizeof(uint32_t);
        stream->Write32(eCustomClipboardTypeId_None);

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

        RefPtr<nsStringBuffer> stringBuffer =
          nsStringBuffer::Alloc(totalCustomLength + 1);

        // Read the data from the string and add a null-terminator as ToString
        // needs it.
        uint32_t amountRead;
        inputStream->Read(static_cast<char*>(stringBuffer->Data()),
                          totalCustomLength, &amountRead);
        static_cast<char*>(stringBuffer->Data())[amountRead] = 0;

        nsCString str;
        stringBuffer->ToString(totalCustomLength, str);
        nsCOMPtr<nsISupportsCString>
          strSupports(do_CreateInstance(NS_SUPPORTS_CSTRING_CONTRACTID));
        strSupports->SetData(str);

        nsresult rv = transferable->SetTransferData(kCustomTypesMime,
                                                    strSupports,
                                                    totalCustomLength);
        if (NS_FAILED(rv)) {
          return nullptr;
        }

        added = true;

        // Clear the stream so it doesn't get used again.
        stream = nullptr;
      } else {
        // This is the second pass of the loop and a known type is encountered.
        // Add it as is.
        if (!ConvertFromVariant(formatitem.mData, getter_AddRefs(convertedData),
                                &lengthInBytes)) {
          continue;
        }

        // The underlying drag code uses text/unicode, so use that instead of
        // text/plain
        const char* format;
        NS_ConvertUTF16toUTF8 utf8format(formatitem.mFormat);
        if (utf8format.EqualsLiteral(kTextMime)) {
          format = kUnicodeMime;
        } else {
          format = utf8format.get();
        }

        // If a converter is set for a format, set the converter for the
        // transferable and don't add the item
        nsCOMPtr<nsIFormatConverter> converter =
          do_QueryInterface(convertedData);
        if (converter) {
          transferable->AddDataFlavor(format);
          transferable->SetConverter(converter);
          continue;
        }

        nsresult rv = transferable->SetTransferData(format, convertedData,
                                                    lengthInBytes);
        if (NS_FAILED(rv)) {
          return nullptr;
        }

        added = true;
      }
    }

    handlingCustomFormats = !handlingCustomFormats;
  } while (!handlingCustomFormats);

  // only return the transferable if data was successfully added to it
  if (added) {
    return transferable.forget();
  }

  return nullptr;
}
Esempio n. 2
0
NS_IMETHODIMP
nsNSSDialogs::ChooseCertificate(nsIInterfaceRequestor *ctx, const char16_t *cn, const char16_t *organization, const char16_t *issuer, const char16_t **certNickList, const char16_t **certDetailsList, uint32_t count, int32_t *selectedIndex, bool *canceled) 
{
  nsresult rv;
  uint32_t i;

  *canceled = false;

  // Get the parent window for the dialog
  nsCOMPtr<nsIDOMWindow> parent = do_GetInterface(ctx);

  nsCOMPtr<nsIDialogParamBlock> block =
           do_CreateInstance(NS_DIALOGPARAMBLOCK_CONTRACTID);
  if (!block) return NS_ERROR_FAILURE;

  block->SetNumberStrings(4+count*2);

  rv = block->SetString(0, cn);
  if (NS_FAILED(rv)) return rv;

  rv = block->SetString(1, organization);
  if (NS_FAILED(rv)) return rv;

  rv = block->SetString(2, issuer);
  if (NS_FAILED(rv)) return rv;

  for (i = 0; i < count; i++) {
    rv = block->SetString(i+3, certNickList[i]);
    if (NS_FAILED(rv)) return rv;
  }

  for (i = 0; i < count; i++) {
    rv = block->SetString(i+count+3, certDetailsList[i]);
    if (NS_FAILED(rv)) return rv;
  }

  rv = block->SetInt(0, count);
  if (NS_FAILED(rv)) return rv;

  rv = nsNSSDialogHelper::openDialog(nullptr,
                                "chrome://pippki/content/clientauthask.xul",
                                block);
  if (NS_FAILED(rv)) return rv;

  int32_t status;
  rv = block->GetInt(0, &status);
  if (NS_FAILED(rv)) return rv;

  nsCOMPtr<nsIClientAuthUserDecision> extraResult = do_QueryInterface(ctx);
  if (extraResult) {
    int32_t rememberSelection;
    rv = block->GetInt(2, &rememberSelection);
    if (NS_SUCCEEDED(rv)) {
      extraResult->SetRememberClientAuthCertificate(rememberSelection!=0);
    }
  }

  *canceled = (status == 0)?true:false;
  if (!*canceled) {
    // retrieve the nickname
    rv = block->GetInt(1, selectedIndex);
  }
  return rv;
}
Esempio n. 3
0
already_AddRefed<nsIPrincipal>
PrincipalInfoToPrincipal(const PrincipalInfo& aPrincipalInfo,
                         nsresult* aOptionalResult)
{
  MOZ_ASSERT(NS_IsMainThread());
  MOZ_ASSERT(aPrincipalInfo.type() != PrincipalInfo::T__None);

  nsresult stackResult;
  nsresult& rv = aOptionalResult ? *aOptionalResult : stackResult;

  nsCOMPtr<nsIScriptSecurityManager> secMan =
    do_GetService(NS_SCRIPTSECURITYMANAGER_CONTRACTID, &rv);
  if (NS_WARN_IF(NS_FAILED(rv))) {
    return nullptr;
  }

  nsCOMPtr<nsIPrincipal> principal;

  switch (aPrincipalInfo.type()) {
    case PrincipalInfo::TSystemPrincipalInfo: {
      rv = secMan->GetSystemPrincipal(getter_AddRefs(principal));
      if (NS_WARN_IF(NS_FAILED(rv))) {
        return nullptr;
      }

      return principal.forget();
    }

    case PrincipalInfo::TNullPrincipalInfo: {
      principal = do_CreateInstance(NS_NULLPRINCIPAL_CONTRACTID, &rv);
      if (NS_WARN_IF(NS_FAILED(rv))) {
        return nullptr;
      }

      return principal.forget();
    }

    case PrincipalInfo::TContentPrincipalInfo: {
      const ContentPrincipalInfo& info =
        aPrincipalInfo.get_ContentPrincipalInfo();

      nsCOMPtr<nsIURI> uri;
      rv = NS_NewURI(getter_AddRefs(uri), info.spec());
      if (NS_WARN_IF(NS_FAILED(rv))) {
        return nullptr;
      }

      if (info.appId() == nsIScriptSecurityManager::UNKNOWN_APP_ID) {
        rv = secMan->GetSimpleCodebasePrincipal(uri, getter_AddRefs(principal));
      } else {
        rv = secMan->GetAppCodebasePrincipal(uri,
                                             info.appId(),
                                             info.isInBrowserElement(),
                                             getter_AddRefs(principal));
      }
      if (NS_WARN_IF(NS_FAILED(rv))) {
        return nullptr;
      }

      return principal.forget();
    }

    case PrincipalInfo::TExpandedPrincipalInfo: {
      const ExpandedPrincipalInfo& info = aPrincipalInfo.get_ExpandedPrincipalInfo();

      nsTArray< nsCOMPtr<nsIPrincipal> > whitelist;
      nsCOMPtr<nsIPrincipal> wlPrincipal;

      for (uint32_t i = 0; i < info.whitelist().Length(); i++) {
        wlPrincipal = PrincipalInfoToPrincipal(info.whitelist()[i], &rv);
        if (NS_WARN_IF(NS_FAILED(rv))) {
          return nullptr;
        }
        // append that principal to the whitelist
        whitelist.AppendElement(wlPrincipal);
      }

      nsRefPtr<nsExpandedPrincipal> expandedPrincipal = new nsExpandedPrincipal(whitelist);
      if (!expandedPrincipal) {
        NS_WARNING("could not instantiate expanded principal");
        return nullptr;
      }

      principal = expandedPrincipal;
      return principal.forget();
    }

    default:
      MOZ_CRASH("Unknown PrincipalInfo type!");
  }

  MOZ_CRASH("Should never get here!");
}
Esempio n. 4
0
NS_IMETHODIMP nsAutoSyncState::GetNextGroupOfMessages(uint32_t aSuggestedGroupSizeLimit, 
                                                      uint32_t *aActualGroupSize, 
                                                      nsIMutableArray **aMessagesList)
{
  NS_ENSURE_ARG_POINTER(aMessagesList);
  NS_ENSURE_ARG_POINTER(aActualGroupSize);

  *aActualGroupSize = 0;

  nsresult rv;
  nsCOMPtr <nsIMsgFolder> folder = do_QueryReferent(mOwnerFolder, &rv);
  NS_ENSURE_SUCCESS(rv, rv);

  nsCOMPtr<nsIMsgDatabase> database;
  folder->GetMsgDatabase(getter_AddRefs(database));

  nsCOMPtr<nsIMutableArray> group = do_CreateInstance(NS_ARRAY_CONTRACTID);
  if (database)
  {
    if (!mDownloadQ.IsEmpty())
    {
      // sort the download queue if new items are added since the last time
      if (mIsDownloadQChanged)
      {
        // we want to sort only pending messages. mOffset is
        // the position of the first pending message in the download queue
        rv = (mOffset > 0)
          ? SortSubQueueBasedOnStrategy(mDownloadQ, mOffset)
          : SortQueueBasedOnStrategy(mDownloadQ);

        if (NS_SUCCEEDED(rv))
          mIsDownloadQChanged = false;
      }

      nsCOMPtr<nsIAutoSyncManager> autoSyncMgr = do_GetService(NS_AUTOSYNCMANAGER_CONTRACTID, &rv);
      NS_ENSURE_SUCCESS(rv, rv);

      uint32_t msgCount = mDownloadQ.Length();
      uint32_t idx = mOffset;

      nsCOMPtr<nsIAutoSyncMsgStrategy> msgStrategy;
      autoSyncMgr->GetMsgStrategy(getter_AddRefs(msgStrategy));

      for (; idx < msgCount; idx++)
      {
        bool containsKey = false;
        database->ContainsKey(mDownloadQ[idx], &containsKey);
        if (!containsKey)
        {
          mDownloadQ.RemoveElementAt(idx--);
          msgCount--;
          continue;
        }
        nsCOMPtr<nsIMsgDBHdr> qhdr;
        database->GetMsgHdrForKey(mDownloadQ[idx], getter_AddRefs(qhdr));
        if(!qhdr)
          continue; //maybe deleted, skip it!

        // ensure that we don't have this message body offline already,
        // possible if the user explicitly selects this message prior
        // to auto-sync kicks in
        uint32_t msgFlags = 0;
        qhdr->GetFlags(&msgFlags);
        if (msgFlags & nsMsgMessageFlags::Offline)
          continue;

        // this check point allows msg strategy function
        // to do last minute decisions based on the current
        // state of TB such as the size of the message store etc.
        if (msgStrategy)
        {
          bool excluded = false;
          if (NS_SUCCEEDED(msgStrategy->IsExcluded(folder, qhdr, &excluded)) && excluded)
            continue;
        }

        uint32_t msgSize;
        qhdr->GetMessageSize(&msgSize);
        // ignore 0 byte messages; the imap parser asserts when we try 
        // to download them, and there's no point anyway.
        if (!msgSize)
          continue;

        if (!*aActualGroupSize && msgSize >= aSuggestedGroupSizeLimit) 
        {
          *aActualGroupSize = msgSize;
          group->AppendElement(qhdr, false);
          idx++;
          break;
        }
        else if ((*aActualGroupSize) + msgSize > aSuggestedGroupSizeLimit)
          break;
        else
        {
          group->AppendElement(qhdr, false);
          *aActualGroupSize += msgSize;
        }
      }// endfor

      mLastOffset = mOffset;
      mOffset = idx;
    }

    LogOwnerFolderName("Next group of messages to be downloaded.");
    LogQWithSize(group.get(), 0);
  } //endif

   // return it to the caller
  NS_IF_ADDREF(*aMessagesList = group);

  return NS_OK;
}
Esempio n. 5
0
// short cut function for creating a mailto url...
nsresult NS_MsgBuildSmtpUrl(nsIFile * aFilePath,
                            nsISmtpServer *aSmtpServer,
                            const char * aRecipients, 
                            nsIMsgIdentity * aSenderIdentity,
                            nsIUrlListener * aUrlListener, 
                            nsIMsgStatusFeedback *aStatusFeedback,
                            nsIInterfaceRequestor* aNotificationCallbacks,
                            nsIURI ** aUrl,
                            PRBool aRequestDSN)
{
  // mscott: this function is a convience hack until netlib actually dispatches
  // smtp urls. in addition until we have a session to get a password, host and
  // other stuff from, we need to use default values....
  // ..for testing purposes....

    nsCString smtpHostName;
    nsCString smtpUserName;
    PRInt32 smtpPort;
    PRInt32 trySSL;

    aSmtpServer->GetHostname(smtpHostName);
    aSmtpServer->GetUsername(smtpUserName);
    aSmtpServer->GetPort(&smtpPort);
    aSmtpServer->GetTrySSL(&trySSL);

    if (!smtpPort)
      smtpPort = (trySSL == PREF_SECURE_ALWAYS_SMTPS) ? 
        nsISmtpUrl::DEFAULT_SMTPS_PORT :  nsISmtpUrl::DEFAULT_SMTP_PORT;

  nsresult rv;
  nsCOMPtr<nsISmtpUrl> smtpUrl(do_CreateInstance(kCSmtpUrlCID, &rv));
  NS_ENSURE_SUCCESS(rv, rv);

  nsCAutoString urlSpec("smtp://");

  if (!smtpUserName.IsEmpty())
  {
    nsCString escapedUsername;
    MsgEscapeString(smtpUserName, nsINetUtil::ESCAPE_XALPHAS,
                    escapedUsername);
    urlSpec.Append(escapedUsername);
    urlSpec.Append('@');
  }

  urlSpec.Append(smtpHostName);
  if (smtpHostName.FindChar(':') == -1)
  {
    urlSpec.Append(':');
    urlSpec.AppendInt(smtpPort);
  }

  nsCOMPtr<nsIMsgMailNewsUrl> url(do_QueryInterface(smtpUrl, &rv));
  NS_ENSURE_SUCCESS(rv, rv);

  url->SetSpec(urlSpec);
  smtpUrl->SetRecipients(aRecipients);
  smtpUrl->SetRequestDSN(aRequestDSN);
  smtpUrl->SetPostMessageFile(aFilePath);
  smtpUrl->SetSenderIdentity(aSenderIdentity);
  smtpUrl->SetNotificationCallbacks(aNotificationCallbacks);
  smtpUrl->SetSmtpServer(aSmtpServer);

  nsCOMPtr<nsIPrompt> smtpPrompt(do_GetInterface(aNotificationCallbacks));
  nsCOMPtr<nsIAuthPrompt> smtpAuthPrompt(do_GetInterface(aNotificationCallbacks));
  if (!smtpPrompt || !smtpAuthPrompt)
  {
    nsCOMPtr<nsIWindowWatcher> wwatch(do_GetService(NS_WINDOWWATCHER_CONTRACTID, &rv));
    NS_ENSURE_SUCCESS(rv, rv);

    if (!smtpPrompt)
      wwatch->GetNewPrompter(0, getter_AddRefs(smtpPrompt));
    if (!smtpAuthPrompt)
      wwatch->GetNewAuthPrompter(0, getter_AddRefs(smtpAuthPrompt));
  }

  smtpUrl->SetPrompt(smtpPrompt);            
  smtpUrl->SetAuthPrompt(smtpAuthPrompt);

  url->RegisterListener(aUrlListener);
  if (aStatusFeedback)
    url->SetStatusFeedback(aStatusFeedback);

  return CallQueryInterface(smtpUrl, aUrl);
}
NS_IMETHODIMP nsDeviceContextSpecQt::GetSurfaceForPrinter(
        gfxASurface** aSurface)
{
    NS_ENSURE_ARG_POINTER(aSurface);
    *aSurface = nullptr;

    double width, height;
    mPrintSettings->GetEffectivePageSize(&width, &height);

    // If we're in landscape mode, we'll be rotating the output --
    // need to swap width & height.
    int32_t orientation;
    mPrintSettings->GetOrientation(&orientation);
    if (nsIPrintSettings::kLandscapeOrientation == orientation) {
        double tmp = width;
        width = height;
        height = tmp;
    }

    // convert twips to points
    width  /= TWIPS_PER_POINT_FLOAT;
    height /= TWIPS_PER_POINT_FLOAT;

    DO_PR_DEBUG_LOG(("\"%s\", %f, %f\n", mPath, width, height));

    QTemporaryFile file;
    if(!file.open()) {
        return NS_ERROR_GFX_PRINTER_COULD_NOT_OPEN_FILE;
    }
    file.setAutoRemove(false);

    nsresult rv = NS_NewNativeLocalFile(
            nsDependentCString(file.fileName().toUtf8().constData()),
            false,
            getter_AddRefs(mSpoolFile));
    if (NS_FAILED(rv)) {
        file.remove();
        return NS_ERROR_GFX_PRINTER_COULD_NOT_OPEN_FILE;
    }

    mSpoolName = file.fileName().toUtf8().constData();

    mSpoolFile->SetPermissions(0600);

    nsCOMPtr<nsIFileOutputStream> stream =
        do_CreateInstance("@mozilla.org/network/file-output-stream;1");

    rv = stream->Init(mSpoolFile, -1, -1, 0);
    if (NS_FAILED(rv))
        return rv;

    int16_t format;
    mPrintSettings->GetOutputFormat(&format);

    nsRefPtr<gfxASurface> surface;
    gfxSize surfaceSize(width, height);

    if (format == nsIPrintSettings::kOutputFormatNative) {
        if (mIsPPreview) {
            // There is nothing to detect on Print Preview, use PS.
            // TODO: implement for Qt?
            //format = nsIPrintSettings::kOutputFormatPS;
            return NS_ERROR_NOT_IMPLEMENTED;
        }
        format = nsIPrintSettings::kOutputFormatPDF;
    }
    if (format == nsIPrintSettings::kOutputFormatPDF) {
        surface = new gfxPDFSurface(stream, surfaceSize);
    } else {
        return NS_ERROR_NOT_IMPLEMENTED;
    }

    NS_ABORT_IF_FALSE(surface, "valid address expected");

    surface.swap(*aSurface);
    return NS_OK;
}
NS_IMETHODIMP
DOMStorageObserver::Observe(nsISupports* aSubject,
                            const char* aTopic,
                            const char16_t* aData)
{
  nsresult rv;

  // Start the thread that opens the database.
  if (!strcmp(aTopic, kStartupTopic)) {
    nsCOMPtr<nsIObserverService> obs = mozilla::services::GetObserverService();
    obs->RemoveObserver(this, kStartupTopic);

    mDBThreadStartDelayTimer = do_CreateInstance(NS_TIMER_CONTRACTID);
    if (!mDBThreadStartDelayTimer) {
      return NS_ERROR_UNEXPECTED;
    }

    mDBThreadStartDelayTimer->Init(this, nsITimer::TYPE_ONE_SHOT, kStartupDelay);

    return NS_OK;
  }

  // Timer callback used to start the database a short timer after startup
  if (!strcmp(aTopic, NS_TIMER_CALLBACK_TOPIC)) {
    nsCOMPtr<nsITimer> timer = do_QueryInterface(aSubject);
    if (!timer) {
      return NS_ERROR_UNEXPECTED;
    }

    if (timer == mDBThreadStartDelayTimer) {
      mDBThreadStartDelayTimer = nullptr;

      DOMStorageDBBridge* db = DOMStorageCache::StartDatabase();
      NS_ENSURE_TRUE(db, NS_ERROR_FAILURE);
    }

    return NS_OK;
  }

  // Clear everything, caches + database
  if (!strcmp(aTopic, "cookie-changed")) {
    if (!NS_LITERAL_STRING("cleared").Equals(aData)) {
      return NS_OK;
    }

    DOMStorageDBBridge* db = DOMStorageCache::StartDatabase();
    NS_ENSURE_TRUE(db, NS_ERROR_FAILURE);

    db->AsyncClearAll();

    Notify("cookie-cleared");

    return NS_OK;
  }

  // Clear from caches everything that has been stored
  // while in session-only mode
  if (!strcmp(aTopic, "perm-changed")) {
    // Check for cookie permission change
    nsCOMPtr<nsIPermission> perm(do_QueryInterface(aSubject));
    if (!perm) {
      return NS_OK;
    }

    nsAutoCString type;
    perm->GetType(type);
    if (type != NS_LITERAL_CSTRING("cookie")) {
      return NS_OK;
    }

    uint32_t cap = 0;
    perm->GetCapability(&cap);
    if (!(cap & nsICookiePermission::ACCESS_SESSION) ||
        !NS_LITERAL_STRING("deleted").Equals(nsDependentString(aData))) {
      return NS_OK;
    }

    nsCOMPtr<nsIPrincipal> principal;
    perm->GetPrincipal(getter_AddRefs(principal));
    if (!principal) {
      return NS_OK;
    }

    nsAutoCString originSuffix;
    BasePrincipal::Cast(principal)->OriginAttributesRef().CreateSuffix(originSuffix);

    nsCOMPtr<nsIURI> origin;
    principal->GetURI(getter_AddRefs(origin));
    if (!origin) {
      return NS_OK;
    }

    nsAutoCString host;
    origin->GetHost(host);
    if (host.IsEmpty()) {
      return NS_OK;
    }

    nsAutoCString originScope;
    rv = CreateReversedDomain(host, originScope);
    NS_ENSURE_SUCCESS(rv, rv);

    Notify("session-only-cleared", NS_ConvertUTF8toUTF16(originSuffix), originScope);

    return NS_OK;
  }

  // Clear everything (including so and pb data) from caches and database
  // for the gived domain and subdomains.
  if (!strcmp(aTopic, "browser:purge-domain-data")) {
    // Convert the domain name to the ACE format
    nsAutoCString aceDomain;
    nsCOMPtr<nsIIDNService> converter = do_GetService(NS_IDNSERVICE_CONTRACTID);
    if (converter) {
      rv = converter->ConvertUTF8toACE(NS_ConvertUTF16toUTF8(aData), aceDomain);
      NS_ENSURE_SUCCESS(rv, rv);
    } else {
      // In case the IDN service is not available, this is the best we can come up with!
      rv = NS_EscapeURL(NS_ConvertUTF16toUTF8(aData),
                        esc_OnlyNonASCII | esc_AlwaysCopy,
                        aceDomain,
                        fallible);
      NS_ENSURE_SUCCESS(rv, rv);
    }

    nsAutoCString originScope;
    rv = CreateReversedDomain(aceDomain, originScope);
    NS_ENSURE_SUCCESS(rv, rv);

    DOMStorageDBBridge* db = DOMStorageCache::StartDatabase();
    NS_ENSURE_TRUE(db, NS_ERROR_FAILURE);

    db->AsyncClearMatchingOrigin(originScope);

    Notify("domain-data-cleared", EmptyString(), originScope);

    return NS_OK;
  }

  // Clear all private-browsing caches
  if (!strcmp(aTopic, "last-pb-context-exited")) {
    Notify("private-browsing-data-cleared");

    return NS_OK;
  }

  // Clear data of the origins whose prefixes will match the suffix.
  if (!strcmp(aTopic, "clear-origin-attributes-data")) {
    OriginAttributesPattern pattern;
    if (!pattern.Init(nsDependentString(aData))) {
      NS_ERROR("Cannot parse origin attributes pattern");
      return NS_ERROR_FAILURE;
    }

    DOMStorageDBBridge* db = DOMStorageCache::StartDatabase();
    NS_ENSURE_TRUE(db, NS_ERROR_FAILURE);

    db->AsyncClearMatchingOriginAttributes(pattern);

    Notify("origin-attr-pattern-cleared", nsDependentString(aData));

    return NS_OK;
  }

  if (!strcmp(aTopic, "profile-after-change")) {
    Notify("profile-change");

    return NS_OK;
  }

  if (!strcmp(aTopic, "profile-before-change") ||
      !strcmp(aTopic, "xpcom-shutdown")) {
    rv = DOMStorageCache::StopDatabase();
    if (NS_FAILED(rv)) {
      NS_WARNING("Error while stopping DOMStorage DB background thread");
    }

    return NS_OK;
  }

  if (!strcmp(aTopic, "disk-space-watcher")) {
    if (NS_LITERAL_STRING("full").Equals(aData)) {
      Notify("low-disk-space");
    } else if (NS_LITERAL_STRING("free").Equals(aData)) {
      Notify("no-low-disk-space");
    }

    return NS_OK;
  }

#ifdef DOM_STORAGE_TESTS
  if (!strcmp(aTopic, "domstorage-test-flush-force")) {
    DOMStorageDBBridge* db = DOMStorageCache::GetDatabase();
    if (db) {
      db->AsyncFlush();
    }

    return NS_OK;
  }

  if (!strcmp(aTopic, "domstorage-test-flushed")) {
    // Only used to propagate to IPC children
    Notify("test-flushed");

    return NS_OK;
  }

  if (!strcmp(aTopic, "domstorage-test-reload")) {
    Notify("test-reload");

    return NS_OK;
  }
#endif

  NS_ERROR("Unexpected topic");
  return NS_ERROR_UNEXPECTED;
}
Esempio n. 8
0
NS_IMETHODIMP
nsTypeAheadFind::Find(const nsAString& aSearchString, bool aLinksOnly,
                      PRUint16* aResult)
{
  *aResult = FIND_NOTFOUND;

  nsCOMPtr<nsIPresShell> presShell (GetPresShell());
  if (!presShell) {    
    nsCOMPtr<nsIDocShell> ds (do_QueryReferent(mDocShell));
    NS_ENSURE_TRUE(ds, NS_ERROR_FAILURE);

    ds->GetPresShell(getter_AddRefs(presShell));
    mPresShell = do_GetWeakReference(presShell);    
  }  
  nsCOMPtr<nsISelection> selection;
  nsCOMPtr<nsISelectionController> selectionController = 
    do_QueryReferent(mSelectionController);
  if (!selectionController) {
    GetSelection(presShell, getter_AddRefs(selectionController),
                 getter_AddRefs(selection)); // cache for reuse
    mSelectionController = do_GetWeakReference(selectionController);
  } else {
    selectionController->GetSelection(
      nsISelectionController::SELECTION_NORMAL, getter_AddRefs(selection));
  }

  if (selection)
    selection->CollapseToStart();

  if (aSearchString.IsEmpty()) {
    mTypeAheadBuffer.Truncate();

    // These will be initialized to their true values after the first character
    // is typed
    mStartFindRange = nsnull;
    mSelectionController = nsnull;

    *aResult = FIND_FOUND;
    return NS_OK;
  }

  bool atEnd = false;    
  if (mTypeAheadBuffer.Length()) {
    const nsAString& oldStr = Substring(mTypeAheadBuffer, 0, mTypeAheadBuffer.Length());
    const nsAString& newStr = Substring(aSearchString, 0, mTypeAheadBuffer.Length());
    if (oldStr.Equals(newStr))
      atEnd = true;
  
    const nsAString& newStr2 = Substring(aSearchString, 0, aSearchString.Length());
    const nsAString& oldStr2 = Substring(mTypeAheadBuffer, 0, aSearchString.Length());
    if (oldStr2.Equals(newStr2))
      atEnd = true;
    
    if (!atEnd)
      mStartFindRange = nsnull;
  }

  if (!mIsSoundInitialized && !mNotFoundSoundURL.IsEmpty()) {
    // This makes sure system sound library is loaded so that
    // there's no lag before the first sound is played
    // by waiting for the first keystroke, we still get the startup time benefits.
    mIsSoundInitialized = true;
    mSoundInterface = do_CreateInstance("@mozilla.org/sound;1");
    if (mSoundInterface && !mNotFoundSoundURL.Equals(NS_LITERAL_CSTRING("beep"))) {
      mSoundInterface->Init();
    }
  }

#ifdef XP_WIN
  // After each keystroke, ensure sound object is destroyed, to free up memory 
  // allocated for error sound, otherwise Windows' nsISound impl 
  // holds onto the last played sound, using up memory.
  mSoundInterface = nsnull;
#endif

  PRInt32 bufferLength = mTypeAheadBuffer.Length();

  mTypeAheadBuffer = aSearchString;

  bool isFirstVisiblePreferred = false;

  // --------- Initialize find if 1st char ----------
  if (bufferLength == 0) {
    // If you can see the selection (not collapsed or thru caret browsing),
    // or if already focused on a page element, start there.
    // Otherwise we're going to start at the first visible element
    bool isSelectionCollapsed = true;
    if (selection)
      selection->GetIsCollapsed(&isSelectionCollapsed);

    // If true, we will scan from top left of visible area
    // If false, we will scan from start of selection
    isFirstVisiblePreferred = !atEnd && !mCaretBrowsingOn && isSelectionCollapsed;
    if (isFirstVisiblePreferred) {
      // Get the focused content. If there is a focused node, ensure the
      // selection is at that point. Otherwise, we will just want to start
      // from the caret position or the beginning of the document.
      nsPresContext* presContext = presShell->GetPresContext();
      NS_ENSURE_TRUE(presContext, NS_OK);

      nsCOMPtr<nsIDocument> document =
        do_QueryInterface(presShell->GetDocument());
      if (!document)
        return NS_ERROR_UNEXPECTED;

      nsCOMPtr<nsIDOMWindow> window = do_QueryInterface(document->GetWindow());

      nsCOMPtr<nsIFocusManager> fm = do_GetService(FOCUSMANAGER_CONTRACTID);
      if (fm) {
        nsCOMPtr<nsIDOMElement> focusedElement;
        nsCOMPtr<nsIDOMWindow> focusedWindow;
        fm->GetFocusedElementForWindow(window, false, getter_AddRefs(focusedWindow),
                                       getter_AddRefs(focusedElement));
        // If the root element is focused, then it's actually the document
        // that has the focus, so ignore this.
        if (focusedElement &&
            !SameCOMIdentity(focusedElement, document->GetRootElement())) {
          fm->MoveCaretToFocus(window);
          isFirstVisiblePreferred = false;
        }
      }
    }
  }

  // ----------- Find the text! ---------------------
  // Beware! This may flush notifications via synchronous
  // ScrollSelectionIntoView.
  nsresult rv = FindItNow(nsnull, aLinksOnly, isFirstVisiblePreferred,
                          false, aResult);

  // ---------Handle success or failure ---------------
  if (NS_SUCCEEDED(rv)) {
    if (mTypeAheadBuffer.Length() == 1) {
      // If first letter, store where the first find succeeded
      // (mStartFindRange)

      mStartFindRange = nsnull;
      if (selection) {
        nsCOMPtr<nsIDOMRange> startFindRange;
        selection->GetRangeAt(0, getter_AddRefs(startFindRange));
        if (startFindRange)
          startFindRange->CloneRange(getter_AddRefs(mStartFindRange));
      }
    }
  }
  else {
    // Error sound
    if (mTypeAheadBuffer.Length() > mLastFindLength)
      PlayNotFoundSound();
  }

  SaveFind();
  return NS_OK;
}
Esempio n. 9
0
// The "real" name of a given helper app (as specified by the path to the 
// executable file held in various registry keys) is stored n the VERSIONINFO
// block in the file's resources. We need to find the path to the executable
// and then retrieve the "FileDescription" field value from the file. 
nsresult
nsOSHelperAppService::GetDefaultAppInfo(const nsAString& aAppInfo,
                                        nsAString& aDefaultDescription, 
                                        nsIFile** aDefaultApplication)
{
  nsAutoString handlerCommand;

  // If all else fails, use the file type key name, which will be 
  // something like "pngfile" for .pngs, "WMVFile" for .wmvs, etc. 
  aDefaultDescription = aAppInfo;
  *aDefaultApplication = nullptr;

  if (aAppInfo.IsEmpty())
    return NS_ERROR_FAILURE;

  // aAppInfo may be a file, file path, program id, or
  // Applications reference -
  // c:\dir\app.exe
  // Applications\appfile.exe/dll (shell\open...)
  // ProgID.progid (shell\open...)

  nsAutoString handlerKeyName(aAppInfo);

  nsCOMPtr<nsIWindowsRegKey> chkKey = 
    do_CreateInstance("@mozilla.org/windows-registry-key;1");
  if (!chkKey) 
    return NS_ERROR_FAILURE;
      
  nsresult rv = chkKey->Open(nsIWindowsRegKey::ROOT_KEY_CLASSES_ROOT,
                             handlerKeyName, 
                             nsIWindowsRegKey::ACCESS_QUERY_VALUE);
  if (NS_FAILED(rv)) {
    // It's a file system path to a handler 
    handlerCommand.Assign(aAppInfo);
  }
  else {
    handlerKeyName.AppendLiteral("\\shell\\open\\command");
    nsCOMPtr<nsIWindowsRegKey> regKey = 
      do_CreateInstance("@mozilla.org/windows-registry-key;1");
    if (!regKey) 
      return NS_ERROR_FAILURE;

    nsresult rv = regKey->Open(nsIWindowsRegKey::ROOT_KEY_CLASSES_ROOT,
                               handlerKeyName, 
                               nsIWindowsRegKey::ACCESS_QUERY_VALUE);
    if (NS_FAILED(rv))
      return NS_ERROR_FAILURE;
     
    // OK, the default value here is the description of the type.
    rv = regKey->ReadStringValue(EmptyString(), handlerCommand);
    if (NS_FAILED(rv)) {

      // Check if there is a DelegateExecute string
      nsAutoString delegateExecute;
      rv = regKey->ReadStringValue(NS_LITERAL_STRING("DelegateExecute"), delegateExecute);
      NS_ENSURE_SUCCESS(rv, rv);

      // Look for InProcServer32
      nsAutoString delegateExecuteRegPath;
      delegateExecuteRegPath.AssignLiteral("CLSID\\");
      delegateExecuteRegPath.Append(delegateExecute);
      delegateExecuteRegPath.AppendLiteral("\\InProcServer32");
      rv = chkKey->Open(nsIWindowsRegKey::ROOT_KEY_CLASSES_ROOT,
                        delegateExecuteRegPath, 
                        nsIWindowsRegKey::ACCESS_QUERY_VALUE);
      if (NS_SUCCEEDED(rv)) {
        rv = chkKey->ReadStringValue(EmptyString(), handlerCommand);
      }

      if (NS_FAILED(rv)) {
        // Look for LocalServer32
        delegateExecuteRegPath.AssignLiteral("CLSID\\");
        delegateExecuteRegPath.Append(delegateExecute);
        delegateExecuteRegPath.AppendLiteral("\\LocalServer32");
        rv = chkKey->Open(nsIWindowsRegKey::ROOT_KEY_CLASSES_ROOT,
                          delegateExecuteRegPath, 
                          nsIWindowsRegKey::ACCESS_QUERY_VALUE);
        NS_ENSURE_SUCCESS(rv, rv);
        rv = chkKey->ReadStringValue(EmptyString(), handlerCommand);
        NS_ENSURE_SUCCESS(rv, rv);
      }
    }
  }

  if (!CleanupCmdHandlerPath(handlerCommand))
    return NS_ERROR_FAILURE;

  // XXX FIXME: If this fails, the UI will display the full command
  // string.
  // There are some rare cases this can happen - ["url.dll" -foo]
  // for example won't resolve correctly to the system dir. The 
  // subsequent launch of the helper app will work though.
  nsCOMPtr<nsIFile> lf;
  NS_NewLocalFile(handlerCommand, true, getter_AddRefs(lf));
  if (!lf)
    return NS_ERROR_FILE_NOT_FOUND;

  nsILocalFileWin* lfw = nullptr;
  CallQueryInterface(lf, &lfw);

  if (lfw) {
    // The "FileDescription" field contains the actual name of the application.
    lfw->GetVersionInfoField("FileDescription", aDefaultDescription);
    // QI addref'ed for us.
    *aDefaultApplication = lfw;
  }

  return NS_OK;
}
nsresult
nsPluginStreamListenerPeer::RequestRead(NPByteRange* rangeList)
{
  nsAutoCString rangeString;
  int32_t numRequests;
  
  MakeByteRangeString(rangeList, rangeString, &numRequests);
  
  if (numRequests == 0)
    return NS_ERROR_FAILURE;
  
  nsresult rv = NS_OK;
  
  nsCOMPtr<nsIInterfaceRequestor> callbacks = do_QueryReferent(mWeakPtrChannelCallbacks);
  nsCOMPtr<nsILoadGroup> loadGroup = do_QueryReferent(mWeakPtrChannelLoadGroup);
  nsCOMPtr<nsIChannel> channel;
  rv = NS_NewChannel(getter_AddRefs(channel), mURL, nullptr, loadGroup, callbacks);
  if (NS_FAILED(rv))
    return rv;
  
  nsCOMPtr<nsIHttpChannel> httpChannel(do_QueryInterface(channel));
  if (!httpChannel)
    return NS_ERROR_FAILURE;
  
  httpChannel->SetRequestHeader(NS_LITERAL_CSTRING("Range"), rangeString, false);
  
  mAbort = true; // instruct old stream listener to cancel
  // the request on the next ODA.
  
  nsCOMPtr<nsIStreamListener> converter;
  
  if (numRequests == 1) {
    converter = this;
    // set current stream offset equal to the first offset in the range list
    // it will work for single byte range request
    // for multy range we'll reset it in ODA
    SetStreamOffset(rangeList->offset);
  } else {
    nsWeakPtr weakpeer =
    do_GetWeakReference(static_cast<nsISupportsWeakReference*>(this));
    nsPluginByteRangeStreamListener *brrListener =
    new nsPluginByteRangeStreamListener(weakpeer);
    if (brrListener)
      converter = brrListener;
    else
      return NS_ERROR_OUT_OF_MEMORY;
  }
  
  mPendingRequests += numRequests;
  
  nsCOMPtr<nsISupportsPRUint32> container = do_CreateInstance(NS_SUPPORTS_PRUINT32_CONTRACTID, &rv);
  if (NS_FAILED(rv))
    return rv;
  rv = container->SetData(MAGIC_REQUEST_CONTEXT);
  if (NS_FAILED(rv))
    return rv;
  
  rv = channel->AsyncOpen(converter, container);
  if (NS_SUCCEEDED(rv))
    TrackRequest(channel);
  return rv;
}
Esempio n. 11
0
bool
nsTypeAheadFind::IsRangeVisible(nsIPresShell *aPresShell,
                                nsPresContext *aPresContext,
                                nsIDOMRange *aRange, bool aMustBeInViewPort,
                                bool aGetTopVisibleLeaf,
                                nsIDOMRange **aFirstVisibleRange,
                                bool *aUsesIndependentSelection)
{
  NS_ASSERTION(aPresShell && aPresContext && aRange && aFirstVisibleRange, 
               "params are invalid");

  // We need to know if the range start is visible.
  // Otherwise, return the first visible range start 
  // in aFirstVisibleRange

  aRange->CloneRange(aFirstVisibleRange);
  nsCOMPtr<nsIDOMNode> node;
  aRange->GetStartContainer(getter_AddRefs(node));

  nsCOMPtr<nsIContent> content(do_QueryInterface(node));
  if (!content)
    return false;

  nsIFrame *frame = content->GetPrimaryFrame();
  if (!frame)    
    return false;  // No frame! Not visible then.

  if (!frame->GetStyleVisibility()->IsVisible())
    return false;

  // Detect if we are _inside_ a text control, or something else with its own
  // selection controller.
  if (aUsesIndependentSelection) {
    *aUsesIndependentSelection = 
      (frame->GetStateBits() & NS_FRAME_INDEPENDENT_SELECTION);
  }

  // ---- We have a frame ----
  if (!aMustBeInViewPort)   
    return true; //  Don't need it to be on screen, just in rendering tree

  // Get the next in flow frame that contains the range start
  PRInt32 startRangeOffset, startFrameOffset, endFrameOffset;
  aRange->GetStartOffset(&startRangeOffset);
  while (true) {
    frame->GetOffsets(startFrameOffset, endFrameOffset);
    if (startRangeOffset < endFrameOffset)
      break;

    nsIFrame *nextContinuationFrame = frame->GetNextContinuation();
    if (nextContinuationFrame)
      frame = nextContinuationFrame;
    else
      break;
  }

  // Set up the variables we need, return true if we can't get at them all
  const PRUint16 kMinPixels  = 12;
  nscoord minDistance = nsPresContext::CSSPixelsToAppUnits(kMinPixels);

  // Get the bounds of the current frame, relative to the current view.
  // We don't use the more accurate AccGetBounds, because that is
  // more expensive and the STATE_OFFSCREEN flag that this is used
  // for only needs to be a rough indicator
  nsRectVisibility rectVisibility = nsRectVisibility_kAboveViewport;

  if (!aGetTopVisibleLeaf && !frame->GetRect().IsEmpty()) {
    rectVisibility =
      aPresShell->GetRectVisibility(frame,
                                    nsRect(nsPoint(0,0), frame->GetSize()),
                                    minDistance);

    if (rectVisibility != nsRectVisibility_kAboveViewport) {
      return true;
    }
  }

  // We know that the target range isn't usable because it's not in the
  // view port. Move range forward to first visible point,
  // this speeds us up a lot in long documents
  nsCOMPtr<nsIFrameEnumerator> frameTraversal;
  nsCOMPtr<nsIFrameTraversal> trav(do_CreateInstance(kFrameTraversalCID));
  if (trav)
    trav->NewFrameTraversal(getter_AddRefs(frameTraversal),
                            aPresContext, frame,
                            eLeaf,
                            false, // aVisual
                            false, // aLockInScrollView
                            false     // aFollowOOFs
                            );

  if (!frameTraversal)
    return false;

  while (rectVisibility == nsRectVisibility_kAboveViewport) {
    frameTraversal->Next();
    frame = frameTraversal->CurrentItem();
    if (!frame)
      return false;

    if (!frame->GetRect().IsEmpty()) {
      rectVisibility =
        aPresShell->GetRectVisibility(frame,
                                      nsRect(nsPoint(0,0), frame->GetSize()),
                                      minDistance);
    }
  }

  if (frame) {
    nsCOMPtr<nsIDOMNode> firstVisibleNode = do_QueryInterface(frame->GetContent());

    if (firstVisibleNode) {
      (*aFirstVisibleRange)->SelectNode(firstVisibleNode);
      frame->GetOffsets(startFrameOffset, endFrameOffset);
      (*aFirstVisibleRange)->SetStart(firstVisibleNode, startFrameOffset);
      (*aFirstVisibleRange)->Collapse(true);  // Collapse to start
    }
  }

  return false;
}
Esempio n. 12
0
NS_IMETHODIMP
nsStatusReporterManager::DumpReports()
{
    static unsigned number = 1;
    nsresult rv;

    nsCString filename("status-reports-");
    filename.AppendInt(getpid());
    filename.AppendLiteral("-");
    filename.AppendInt(number++);
    filename.AppendLiteral(".json");

    // Open a file in NS_OS_TEMP_DIR for writing.
    // The file is initialized as "incomplete-status-reports-pid-number.json" in the
    // begining, it will be rename as "status-reports-pid-number.json" in the end.
    nsCOMPtr<nsIFile> tmpFile;
    rv = nsDumpUtils::OpenTempFile(NS_LITERAL_CSTRING("incomplete-") +
                                   filename,
                                   getter_AddRefs(tmpFile),
                                   NS_LITERAL_CSTRING("status-reports"));
    if (NS_WARN_IF(NS_FAILED(rv))) {
        return rv;
    }

    nsCOMPtr<nsIFileOutputStream> ostream =
        do_CreateInstance("@mozilla.org/network/file-output-stream;1");
    rv = ostream->Init(tmpFile, -1, -1, 0);
    if (NS_WARN_IF(NS_FAILED(rv))) {
        return rv;
    }

    //Write the reports to the file

    DUMP(ostream, "{\n\"subject\":\"about:service reports\",\n");
    DUMP(ostream, "\"reporters\": [ ");

    nsCOMPtr<nsISimpleEnumerator> e;
    bool more, first = true;
    EnumerateReporters(getter_AddRefs(e));
    while (NS_SUCCEEDED(e->HasMoreElements(&more)) && more) {
        nsCOMPtr<nsISupports> supports;
        e->GetNext(getter_AddRefs(supports));
        nsCOMPtr<nsIStatusReporter> r = do_QueryInterface(supports);

        nsCString process;
        rv = r->GetProcess(process);
        if (NS_WARN_IF(NS_FAILED(rv))) {
            return rv;
        }

        nsCString name;
        rv = r->GetName(name);
        if (NS_WARN_IF(NS_FAILED(rv))) {
            return rv;
        }

        nsCString description;
        rv = r->GetDescription(description);
        if (NS_WARN_IF(NS_FAILED(rv))) {
            return rv;
        }

        if (first) {
            first = false;
        } else {
            DUMP(ostream, ",");
        }

        rv = DumpReport(ostream, process, name, description);
        if (NS_WARN_IF(NS_FAILED(rv))) {
            return rv;
        }
    }
    DUMP(ostream, "\n]\n}\n");

    rv = ostream->Close();
    if (NS_WARN_IF(NS_FAILED(rv))) {
        return rv;
    }

    // Rename the status reports file
    nsCOMPtr<nsIFile> srFinalFile;
    rv = NS_GetSpecialDirectory(NS_OS_TEMP_DIR, getter_AddRefs(srFinalFile));
    if (NS_WARN_IF(NS_FAILED(rv))) {
        return rv;
    }

#ifdef ANDROID
    rv = srFinalFile->AppendNative(NS_LITERAL_CSTRING("status-reports"));
    if (NS_WARN_IF(NS_FAILED(rv))) {
        return rv;
    }
#endif

    rv = srFinalFile->AppendNative(filename);
    if (NS_WARN_IF(NS_FAILED(rv))) {
        return rv;
    }

    rv = srFinalFile->CreateUnique(nsIFile::NORMAL_FILE_TYPE, 0600);
    if (NS_WARN_IF(NS_FAILED(rv))) {
        return rv;
    }

    nsAutoString srActualFinalFilename;
    rv = srFinalFile->GetLeafName(srActualFinalFilename);
    if (NS_WARN_IF(NS_FAILED(rv))) {
        return rv;
    }

    rv = tmpFile->MoveTo(/* directory */ nullptr, srActualFinalFilename);

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

    return NS_OK;
}
nsAutoCompleteResults::nsAutoCompleteResults() :
    mItems(do_CreateInstance(NS_SUPPORTSARRAY_CONTRACTID)),
    mDefaultItemIndex(0)
{
}
Esempio n. 14
0
nsresult
BackgroundFileSaver::ExtractSignatureInfo(const nsAString& filePath)
{
  MOZ_ASSERT(!NS_IsMainThread(), "Cannot extract signature on main thread");

  nsNSSShutDownPreventionLock nssLock;
  if (isAlreadyShutDown()) {
    return NS_ERROR_NOT_AVAILABLE;
  }
  {
    MutexAutoLock lock(mLock);
    if (!mSignatureInfoEnabled) {
      return NS_OK;
    }
  }
  nsresult rv;
  nsCOMPtr<nsIX509CertDB> certDB = do_GetService(NS_X509CERTDB_CONTRACTID, &rv);
  NS_ENSURE_SUCCESS(rv, rv);
#ifdef XP_WIN
  // Setup the file to check.
  WINTRUST_FILE_INFO fileToCheck = {0};
  fileToCheck.cbStruct = sizeof(WINTRUST_FILE_INFO);
  fileToCheck.pcwszFilePath = filePath.Data();
  fileToCheck.hFile = nullptr;
  fileToCheck.pgKnownSubject = nullptr;

  // We want to check it is signed and trusted.
  WINTRUST_DATA trustData = {0};
  trustData.cbStruct = sizeof(trustData);
  trustData.pPolicyCallbackData = nullptr;
  trustData.pSIPClientData = nullptr;
  trustData.dwUIChoice = WTD_UI_NONE;
  trustData.fdwRevocationChecks = WTD_REVOKE_NONE;
  trustData.dwUnionChoice = WTD_CHOICE_FILE;
  trustData.dwStateAction = WTD_STATEACTION_VERIFY;
  trustData.hWVTStateData = nullptr;
  trustData.pwszURLReference = nullptr;
  // Disallow revocation checks over the network
  trustData.dwProvFlags = WTD_CACHE_ONLY_URL_RETRIEVAL;
  // no UI
  trustData.dwUIContext = 0;
  trustData.pFile = &fileToCheck;

  // The WINTRUST_ACTION_GENERIC_VERIFY_V2 policy verifies that the certificate
  // chains up to a trusted root CA and has appropriate permissions to sign
  // code.
  GUID policyGUID = WINTRUST_ACTION_GENERIC_VERIFY_V2;
  // Check if the file is signed by something that is trusted. If the file is
  // not signed, this is a no-op.
  LONG ret = WinVerifyTrust(nullptr, &policyGUID, &trustData);
  CRYPT_PROVIDER_DATA* cryptoProviderData = nullptr;
  // According to the Windows documentation, we should check against 0 instead
  // of ERROR_SUCCESS, which is an HRESULT.
  if (ret == 0) {
    cryptoProviderData = WTHelperProvDataFromStateData(trustData.hWVTStateData);
  }
  if (cryptoProviderData) {
    // Lock because signature information is read on the main thread.
    MutexAutoLock lock(mLock);
    LOG(("Downloaded trusted and signed file [this = %p].", this));
    // A binary may have multiple signers. Each signer may have multiple certs
    // in the chain.
    for (DWORD i = 0; i < cryptoProviderData->csSigners; ++i) {
      const CERT_CHAIN_CONTEXT* certChainContext =
        cryptoProviderData->pasSigners[i].pChainContext;
      if (!certChainContext) {
        break;
      }
      for (DWORD j = 0; j < certChainContext->cChain; ++j) {
        const CERT_SIMPLE_CHAIN* certSimpleChain =
          certChainContext->rgpChain[j];
        if (!certSimpleChain) {
          break;
        }
        nsCOMPtr<nsIX509CertList> nssCertList =
          do_CreateInstance(NS_X509CERTLIST_CONTRACTID);
        if (!nssCertList) {
          break;
        }
        bool extractionSuccess = true;
        for (DWORD k = 0; k < certSimpleChain->cElement; ++k) {
          CERT_CHAIN_ELEMENT* certChainElement = certSimpleChain->rgpElement[k];
          if (certChainElement->pCertContext->dwCertEncodingType !=
            X509_ASN_ENCODING) {
              continue;
          }
          nsCOMPtr<nsIX509Cert> nssCert = nullptr;
          rv = certDB->ConstructX509(
            reinterpret_cast<char *>(
              certChainElement->pCertContext->pbCertEncoded),
            certChainElement->pCertContext->cbCertEncoded,
            getter_AddRefs(nssCert));
          if (!nssCert) {
            extractionSuccess = false;
            LOG(("Couldn't create NSS cert [this = %p]", this));
            break;
          }
          nssCertList->AddCert(nssCert);
          nsString subjectName;
          nssCert->GetSubjectName(subjectName);
          LOG(("Adding cert %s [this = %p]",
               NS_ConvertUTF16toUTF8(subjectName).get(), this));
        }
        if (extractionSuccess) {
          mSignatureInfo.AppendObject(nssCertList);
        }
      }
    }
    // Free the provider data if cryptoProviderData is not null.
    trustData.dwStateAction = WTD_STATEACTION_CLOSE;
    WinVerifyTrust(nullptr, &policyGUID, &trustData);
  } else {
    LOG(("Downloaded unsigned or untrusted file [this = %p].", this));
  }
#endif
  return NS_OK;
}
Esempio n. 15
0
void
DataTransfer::FillInExternalData(TransferItem& aItem, uint32_t aIndex)
{
  NS_PRECONDITION(mIsExternal, "Not an external data transfer");

  if (aItem.mData) {
    return;
  }

  // only drag and paste events should be calling FillInExternalData
  NS_ASSERTION(mEventMessage != eCut && mEventMessage != eCopy,
               "clipboard event with empty data");

    NS_ConvertUTF16toUTF8 utf8format(aItem.mFormat);
    const char* format = utf8format.get();
    if (strcmp(format, "text/plain") == 0)
      format = kUnicodeMime;
    else if (strcmp(format, "text/uri-list") == 0)
      format = kURLDataMime;

    nsCOMPtr<nsITransferable> trans =
      do_CreateInstance("@mozilla.org/widget/transferable;1");
    if (!trans)
      return;

  trans->Init(nullptr);
  trans->AddDataFlavor(format);

  if (mEventMessage == ePaste) {
    MOZ_ASSERT(aIndex == 0, "index in clipboard must be 0");

    nsCOMPtr<nsIClipboard> clipboard = do_GetService("@mozilla.org/widget/clipboard;1");
    if (!clipboard || mClipboardType < 0) {
      return;
    }

    clipboard->GetData(trans, mClipboardType);
  } else {
    nsCOMPtr<nsIDragSession> dragSession = nsContentUtils::GetDragSession();
    if (!dragSession) {
      return;
    }

#ifdef DEBUG
    // Since this is an external drag, the source document will always be null.
    nsCOMPtr<nsIDOMDocument> domDoc;
    dragSession->GetSourceDocument(getter_AddRefs(domDoc));
    MOZ_ASSERT(!domDoc);
#endif

    dragSession->GetData(trans, aIndex);
  }

    uint32_t length = 0;
    nsCOMPtr<nsISupports> data;
    trans->GetTransferData(format, getter_AddRefs(data), &length);
    if (!data)
      return;

    nsCOMPtr<nsIWritableVariant> variant = do_CreateInstance(NS_VARIANT_CONTRACTID);
    if (!variant)
      return;

    nsCOMPtr<nsISupportsString> supportsstr = do_QueryInterface(data);
    if (supportsstr) {
      nsAutoString str;
      supportsstr->GetData(str);
      variant->SetAsAString(str);
    }
    else {
      variant->SetAsISupports(data);
    }

    aItem.mData = variant;
  }
Esempio n. 16
0
already_AddRefed<nsMIMEInfoWin> nsOSHelperAppService::GetByExtension(const nsAFlatString& aFileExt, const char *aTypeHint)
{
  if (aFileExt.IsEmpty())
    return nullptr;

  // windows registry assumes your file extension is going to include the '.'.
  // so make sure it's there...
  nsAutoString fileExtToUse;
  if (aFileExt.First() != char16_t('.'))
    fileExtToUse = char16_t('.');

  fileExtToUse.Append(aFileExt);

  // Try to get an entry from the windows registry.
  nsCOMPtr<nsIWindowsRegKey> regKey = 
    do_CreateInstance("@mozilla.org/windows-registry-key;1");
  if (!regKey) 
    return nullptr; 

  nsresult rv = regKey->Open(nsIWindowsRegKey::ROOT_KEY_CLASSES_ROOT,
                             fileExtToUse,
                             nsIWindowsRegKey::ACCESS_QUERY_VALUE);
  if (NS_FAILED(rv))
    return nullptr; 

  nsAutoCString typeToUse;
  if (aTypeHint && *aTypeHint) {
    typeToUse.Assign(aTypeHint);
  }
  else {
    nsAutoString temp;
    if (NS_FAILED(regKey->ReadStringValue(NS_LITERAL_STRING("Content Type"),
                  temp)) || temp.IsEmpty()) {
      return nullptr; 
    }
    // Content-Type is always in ASCII
    LossyAppendUTF16toASCII(temp, typeToUse);
  }

  nsRefPtr<nsMIMEInfoWin> mimeInfo = new nsMIMEInfoWin(typeToUse);

  // don't append the '.'
  mimeInfo->AppendExtension(NS_ConvertUTF16toUTF8(Substring(fileExtToUse, 1)));
  mimeInfo->SetPreferredAction(nsIMIMEInfo::useSystemDefault);

  nsAutoString appInfo;
  bool found;

  // Retrieve the default application for this extension
  if (mAppAssoc) {
    // Vista: use the new application association COM interfaces
    // for resolving helpers.
    nsString assocType(fileExtToUse);
    wchar_t * pResult = nullptr;
    HRESULT hr = mAppAssoc->QueryCurrentDefault(assocType.get(),
                                                AT_FILEEXTENSION, AL_EFFECTIVE,
                                                &pResult);
    if (SUCCEEDED(hr)) {
      found = true;
      appInfo.Assign(pResult);
      CoTaskMemFree(pResult);
    } 
    else {
      found = false;
    }
  } 
  else
  {
    found = NS_SUCCEEDED(regKey->ReadStringValue(EmptyString(), 
                                                 appInfo));
  }

  // Bug 358297 - ignore the default handler, force the user to choose app
  if (appInfo.EqualsLiteral("XPSViewer.Document"))
    found = false;

  if (!found) {
    return nullptr;
  }

  // Get other nsIMIMEInfo fields from registry, if possible.
  nsAutoString defaultDescription;
  nsCOMPtr<nsIFile> defaultApplication;
  
  if (NS_FAILED(GetDefaultAppInfo(appInfo, defaultDescription,
                                  getter_AddRefs(defaultApplication)))) {
    return nullptr;
  }

  mimeInfo->SetDefaultDescription(defaultDescription);
  mimeInfo->SetDefaultApplicationHandler(defaultApplication);

  // Grab the general description
  GetMIMEInfoFromRegistry(appInfo, mimeInfo);

  return mimeInfo.forget();
}
NS_IMETHODIMP
nsCookiePromptService::CookieDialog(nsIDOMWindow *aParent,
                                    nsICookie *aCookie,
                                    const nsACString &aHostname,
                                    PRInt32 aCookiesFromHost,
                                    bool aChangingCookie,
                                    bool *aRememberDecision,
                                    PRInt32 *aAccept)
{
  nsresult rv;

  nsCOMPtr<nsIDialogParamBlock> block = do_CreateInstance(NS_DIALOGPARAMBLOCK_CONTRACTID,&rv);
  if (NS_FAILED(rv)) return rv;

  block->SetInt(nsICookieAcceptDialog::ACCEPT_COOKIE, 1);
  block->SetString(nsICookieAcceptDialog::HOSTNAME, NS_ConvertUTF8toUTF16(aHostname).get());
  block->SetInt(nsICookieAcceptDialog::COOKIESFROMHOST, aCookiesFromHost);
  block->SetInt(nsICookieAcceptDialog::CHANGINGCOOKIE, aChangingCookie ? 1 : 0);
  
  nsCOMPtr<nsIMutableArray> objects =
    do_CreateInstance(NS_ARRAY_CONTRACTID, &rv);
  if (NS_FAILED(rv)) return rv;

  rv = objects->AppendElement(aCookie, false);
  if (NS_FAILED(rv)) return rv;

  block->SetObjects(objects);

  nsCOMPtr<nsIWindowWatcher> wwatcher = do_GetService(NS_WINDOWWATCHER_CONTRACTID, &rv);
  if (NS_FAILED(rv)) return rv;

  nsCOMPtr<nsISupports> arguments = do_QueryInterface(block);
  nsCOMPtr<nsIDOMWindow> dialog;

  nsCOMPtr<nsIDOMWindow> parent(aParent);
  if (!parent) // if no parent provided, consult the window watcher:
    wwatcher->GetActiveWindow(getter_AddRefs(parent));

  if (parent) {
    nsCOMPtr<nsPIDOMWindow> privateParent(do_QueryInterface(parent));
    if (privateParent)
      privateParent = privateParent->GetPrivateRoot();
    parent = do_QueryInterface(privateParent);
  }

  // The cookie dialog will be modal for the root chrome window rather than the
  // tab containing the permission-requesting page.  This removes confusion
  // about which monitor is displaying the dialog (see bug 470356), but also
  // avoids unwanted tab switches (see bug 405239).
  rv = wwatcher->OpenWindow(parent, "chrome://cookie/content/cookieAcceptDialog.xul", "_blank",
                            "centerscreen,chrome,modal,titlebar", arguments,
                            getter_AddRefs(dialog));

  if (NS_FAILED(rv)) return rv;

  // get back output parameters
  PRInt32 tempValue;
  block->GetInt(nsICookieAcceptDialog::ACCEPT_COOKIE, &tempValue);
  *aAccept = tempValue;
  
  // GetInt returns a PRInt32; we need to sanitize it into bool
  block->GetInt(nsICookieAcceptDialog::REMEMBER_DECISION, &tempValue);
  *aRememberDecision = (tempValue == 1);

  return rv;
}
nsresult sbDeviceXMLInfo::Read(nsIFile *          aDeviceXMLInfoFile,
                               const nsAString &  aExtensionsList)
{
  NS_ENSURE_ARG_POINTER(aDeviceXMLInfoFile);

  nsresult rv;

  nsString path;
  rv = aDeviceXMLInfoFile->GetPath(path);
  if (NS_FAILED(rv)) {
    path = NS_LITERAL_STRING("Unknown path");
  }

  // If aDeviceXMLInfoFile is a directory, scan it recursively for
  // device XML info files:
  bool isDir = PR_FALSE;
  rv = aDeviceXMLInfoFile->IsDirectory(&isDir);
  NS_ENSURE_SUCCESS(rv, rv);
  if (isDir) {
    Log("Searching directory %s",
        NS_LossyConvertUTF16toASCII(path).BeginReading());
    // aExtensionsList is a space-delimited list of extensions
    // (e.g., "ex1 ex2 ex3").  Trim any surrounding spaces and
    // don't scan the directory if the result is empty:
    nsString acceptExts(aExtensionsList);
    acceptExts.Trim(" ");
    Log("Extension List: %s",
        NS_LossyConvertUTF16toASCII(acceptExts).BeginReading());
    if (acceptExts.IsEmpty()) {
      return NS_OK;
    }

    // Normalize the extensions list for the comparison logic below.
    // That is, lower case with spaces before the first extension and
    // after the last:
    ToLowerCase(acceptExts);
    acceptExts.Insert(' ', 0);
    acceptExts.Append(' ');

    // Prepare to recursively enumerate all files in the directory:
    nsCOMPtr<sbIDirectoryEnumerator> scanner =
      do_CreateInstance(SB_DIRECTORYENUMERATOR_CONTRACTID, &rv);
    NS_ENSURE_SUCCESS(rv, rv);

    rv = scanner->SetFilesOnly(PR_TRUE);
    NS_ENSURE_SUCCESS(rv, rv);
    rv = scanner->Enumerate(aDeviceXMLInfoFile);
    NS_ENSURE_SUCCESS(rv, rv);

    // Enumerate files and filter by extension:
    bool more = PR_FALSE;
    while(NS_SUCCEEDED(rv = scanner->HasMoreElements(&more)) && more)
    {
      // Get the next file:
      nsCOMPtr<nsIFile> child;
      rv = scanner->GetNext(getter_AddRefs(child));
      NS_ENSURE_SUCCESS(rv, rv);

      // Get its extension and normalize it for comparison:
      nsString extension;
      rv = child->GetLeafName(extension);
      NS_ENSURE_SUCCESS(rv, rv);
      extension.Cut(0, extension.RFindChar('.') + 1);
      ToLowerCase(extension);
      extension.Insert(' ', 0);
      extension.Append(' ');

      // Read the file if its extension is on the accept list.
      // Warn about errors, but keep looping:
      if (acceptExts.Find(extension) != -1) {
        rv = Read(child, aExtensionsList);
        NS_WARN_IF_FALSE(
          NS_SUCCEEDED(rv),
          "Could not read device XML info from file in search directory");
      }
    }
    NS_ENSURE_SUCCESS(rv, rv);
    return NS_OK;
  }

  // Open a stream to parse:
  nsCOMPtr<nsIInputStream> inputStream;
  rv = sbOpenInputStream(aDeviceXMLInfoFile, getter_AddRefs(inputStream));
  NS_ENSURE_SUCCESS(rv, rv);

  Log("Parsing file %s",
      NS_LossyConvertUTF16toASCII(path).BeginReading());
  // Parse the stream and close it:
  rv = Read(inputStream);
  inputStream->Close();
  NS_ENSURE_SUCCESS(rv, rv);

  return NS_OK;
}
Esempio n. 19
0
nsresult TestMCTransport(const char *filename)
{
    nsresult rv = NS_OK;
    nsCOMPtr<nsITransport> transport;

#ifdef USE_CREATE_INSTANCE
    transport = do_CreateInstance(
            "@mozilla.org/network/memory-cache-transport;1", &rv);
    if (NS_FAILED(rv))
        return rv;
#else
    nsCOMPtr<nsICacheService> serv(do_GetService(kCacheServiceCID, &rv));
    if (NS_FAILED(rv)) return rv;

    rv = serv->CreateSession("TestMCTransport",
                             nsICache::STORE_IN_MEMORY, true,
                             &session);
    if (NS_FAILED(rv)) return rv;

    rv = session->OpenCacheEntry(nsDependentCString(filename),
                                 nsICache::ACCESS_READ_WRITE,
                                 nsICache::BLOCKING,
                                 &desc);
    if (NS_FAILED(rv)) return rv;

    rv = desc->MarkValid();
    if (NS_FAILED(rv)) return rv;

    rv = desc->GetTransport(getter_AddRefs(transport));
    if (NS_FAILED(rv)) return rv;
#endif

    nsCOMPtr<nsIOutputStream> os;
    rv = transport->OpenOutputStream(0, (uint32_t) -1, 0, getter_AddRefs(os));
    if (NS_FAILED(rv)) return rv;

    char *out = PR_smprintf("%s.out", filename);
    nsCOMPtr<nsIStreamListener> listener = new TestListener(out);
    if (!listener)
        return NS_ERROR_OUT_OF_MEMORY;

    nsCOMPtr<nsIRequest> req;
    rv = transport->AsyncRead(listener, nullptr, 0, (uint32_t) -1, 0, getter_AddRefs(req));
    if (NS_FAILED(rv)) return rv;

    FILE *file = fopen(filename, "r");
    if (!file)
        return NS_ERROR_FILE_NOT_FOUND;

    char buf[256];
    uint32_t count, total=0;

    while ((count = fread(buf, 1, sizeof(buf), file)) > 0) {
        printf("writing %u bytes\n", count);
        total += count;
        rv = os->Write(buf, count, &count);
        if (NS_FAILED(rv)) return rv;

        // process an event
        PLEvent *event = nullptr;
        gEventQ->GetEvent(&event);
        if (event) gEventQ->HandleEvent(event);
    }

    printf("wrote %u bytes\n", total);

    return rv;
}
nsresult sbDeviceXMLInfo::Read(nsIDOMDocument* aDeviceXMLInfoDocument)
{
  // Validate arguments.
  NS_ENSURE_ARG_POINTER(aDeviceXMLInfoDocument);

  // Function variables.
  nsresult rv;

  // Get the list of all device info elements.
  nsCOMPtr<nsIDOMNodeList> nodeList;
  rv = aDeviceXMLInfoDocument->GetElementsByTagNameNS
                                 (NS_LITERAL_STRING(SB_DEVICE_INFO_NS),
                                  NS_LITERAL_STRING("deviceinfo"),
                                  getter_AddRefs(nodeList));
  NS_ENSURE_SUCCESS(rv, rv);

  // Search all device info elements for one that matches target device.
  PRUint32 nodeCount;
  rv = nodeList->GetLength(&nodeCount);
  NS_ENSURE_SUCCESS(rv, rv);
  for (PRUint32 i = 0; i < nodeCount; i++) {
    // Get the next device info element.
    nsCOMPtr<nsIDOMNode> node;
    rv = nodeList->Item(i, getter_AddRefs(node));
    NS_ENSURE_SUCCESS(rv, rv);

    // Use device info node if it matches target device and is
    // newer than any previous match
    nsString foundVersion;
    nsCOMPtr<nsIDOMNode> deviceNode;
    rv = DeviceMatchesDeviceInfoNode(node,
                                     foundVersion,
                                     getter_AddRefs(deviceNode));
    NS_ENSURE_SUCCESS(rv, rv);
    if (foundVersion.IsEmpty()) {
      // Not a match
      continue;
    }

    if (mDeviceInfoVersion.IsEmpty() ||
        NS_CompareVersions(
          NS_LossyConvertUTF16toASCII(foundVersion).get(),
          NS_LossyConvertUTF16toASCII(mDeviceInfoVersion).get()) > 0)
    {
      // Found version is greater than current version, if any.  Keep this
      // node and replace any previously found node

      // Log the found device info if logging enabled
      if (mLogDeviceInfo) {
        nsCOMPtr<nsIDOMSerializer> serializer =
            do_CreateInstance("@mozilla.org/xmlextras/xmlserializer;1");

        // Translate the found deviceinfo element to XML
        nsString fullXml(NS_LITERAL_STRING("<ERROR PRINTING deviceinfo NODE>"));
        if (serializer) {
          serializer->SerializeToString(node, fullXml);
        }

        // Translate the device element matching this device to XML, if any
        nsString deviceXml(NS_LITERAL_STRING("<ERROR PRINTING device NODE>"));
        if (deviceNode && serializer) {
          serializer->SerializeToString(deviceNode, deviceXml);
        }

        nsCAutoString curVersUtf8 = NS_ConvertUTF16toUTF8(mDeviceInfoVersion);
        nsCAutoString foundVersUtf8 = NS_ConvertUTF16toUTF8(foundVersion);

        // Log the device info and version.  The first line has two
        // alternate forms, depending on whether the existing device
        // info is being replaced:
        //
        //  FOUND    deviceinfo version                        <found version>:
        // - OR -
        //  REPLACED deviceinfo version <current version> with <found version>:

        Log("%s deviceinfo version %s%s%s:\n%s%s%s",
            mDeviceInfoElement ?      "REPLACED"       :   "FOUND",
            curVersUtf8.get(),    //  current version  OR  blank
            mDeviceInfoElement ?      " with "         :   "",
            foundVersUtf8.get(),  //  found version    OR  found version

            NS_ConvertUTF16toUTF8(fullXml).get(),

            deviceNode ? "\n\nMATCHING device element:\n" : "",
            deviceNode ? NS_ConvertUTF16toUTF8(deviceXml).get() : "");
      }

      mDeviceInfoVersion.Assign(foundVersion);
      mDeviceInfoElement = do_QueryInterface(node, &rv);
      NS_ENSURE_SUCCESS(rv, rv);
      if (deviceNode) {
        mDeviceElement = do_QueryInterface(deviceNode, &rv);
        NS_ENSURE_SUCCESS(rv, rv);
      }
      else {
        mDeviceElement = nsnull;
      }
    }
  }

  return NS_OK;
}
/* Retrieves the changes to the LDAP card and stores them in an LDAP
 * update message.
 *
 * Calling this method changes the LDAP card, it updates the
 * meta-properties (m_*) to reflect what the LDAP contents will be once
 * the update has been performed. This allows you to do multiple (successful)
 * consecutive edits on a card in a search result. If the meta-properties
 * were not updated, incorrect assuptions would be made about what object
 * classes to add, or  what attributes to clear.
 *
 * XXX: We need to take care when integrating this code with the asynchronous
 * update dialogs, as the current code in nsAbLDAPDirectory has a problem
 * when an update fails: the modified card still gets stored and shown to
 * the user instead of being discarded. There is one especially tricky case:
 * when you do an update on a card which changes its DN, you have two
 * operations (rename, then update the other attributes). If the rename
 * operation succeeds and not the update of the attributes, you are 
 * "somewhere in between" the original card and the updated card.
*/
NS_IMETHODIMP nsAbLDAPCard::GetLDAPMessageInfo(
  nsIAbLDAPAttributeMap *aAttributeMap,
  const uint32_t aClassCount,
  const char **aClasses,
  int32_t aType,
  nsIArray **aLDAPAddMessageInfo)
{
  NS_ENSURE_ARG_POINTER(aAttributeMap);
  NS_ENSURE_ARG_POINTER(aClasses);
  NS_ENSURE_ARG_POINTER(aLDAPAddMessageInfo);
  
  nsresult rv;
  nsCOMPtr<nsIMutableArray> modArray =
    do_CreateInstance(NS_ARRAY_CONTRACTID, &rv);
  NS_ENSURE_SUCCESS(rv, rv);
  
  // Add any missing object classes. We never remove any object
  // classes: if an entry has additional object classes, it's probably
  // for a good reason.
  nsAutoCString oclass;
  for (uint32_t i = 0; i < aClassCount; ++i)
  {
    oclass.Assign(nsDependentCString(aClasses[i]));
    ToLowerCase(oclass);
   
    if (m_objectClass.IndexOf(oclass) == nsTArray<nsCString>::NoIndex)
    {
      m_objectClass.AppendElement(oclass);
      printf("LDAP : adding objectClass %s\n", oclass.get());
    }
  }

  nsCOMPtr<nsILDAPModification> mod =
    do_CreateInstance("@mozilla.org/network/ldap-modification;1", &rv);
  NS_ENSURE_SUCCESS(rv, rv);
 
  nsCOMPtr<nsIMutableArray> values =
    do_CreateInstance(NS_ARRAY_CONTRACTID, &rv);
  NS_ENSURE_SUCCESS(rv, rv);
  
  for (uint32_t i = 0; i < m_objectClass.Length(); ++i)
  {
    nsCOMPtr<nsILDAPBERValue> value =
      do_CreateInstance("@mozilla.org/network/ldap-ber-value;1", &rv);
    NS_ENSURE_SUCCESS(rv, rv);

    rv = value->SetFromUTF8(m_objectClass.ElementAt(i));
    NS_ENSURE_SUCCESS(rv, rv);

    rv = values->AppendElement(value, false);
    NS_ENSURE_SUCCESS(rv, rv);
  }
  
  rv = mod->SetUpModification(aType, NS_LITERAL_CSTRING("objectClass"), values);
  NS_ENSURE_SUCCESS(rv, rv);

  modArray->AppendElement(mod, false);

  // Add card properties
  CharPtrArrayGuard props;
  rv = aAttributeMap->GetAllCardProperties(props.GetSizeAddr(),
    props.GetArrayAddr());
  NS_ENSURE_SUCCESS(rv, rv);

  nsAutoCString attr;
  nsCString propvalue;
  for (uint32_t i = 0; i < props.GetSize(); ++i)
  {
    // Skip some attributes that don't map to LDAP.
    //
    // BirthYear : by default this is mapped to 'birthyear',
    // which is not part of mozillaAbPersonAlpha
    //
    // LastModifiedDate : by default this is mapped to 'modifytimestamp',
    // which cannot be modified
    //
    // PreferMailFormat : by default this is mapped to 'mozillaUseHtmlMail',
    // which is a boolean, not plaintext/html/unknown
    if (!strcmp(props[i], kBirthYearProperty) ||
        !strcmp(props[i], kLastModifiedDateProperty) ||
        !strcmp(props[i], kPreferMailFormatProperty))
      continue;
    
    rv = aAttributeMap->GetFirstAttribute(nsDependentCString(props[i]),
      attr);
    NS_ENSURE_SUCCESS(rv, rv);
    ToLowerCase(attr);

    // If the property is not mapped to an attribute, skip it.
    if (attr.IsEmpty())
      continue;
 
    nsCOMPtr<nsILDAPModification> mod =
      do_CreateInstance("@mozilla.org/network/ldap-modification;1", &rv);
    NS_ENSURE_SUCCESS(rv, rv);
   
    uint32_t index = m_attributes.IndexOf(attr);

    rv = GetPropertyAsAUTF8String(props[i], propvalue);

    if (NS_SUCCEEDED(rv) &&!propvalue.IsEmpty())
    {
      // If the new value is not empty, add/update it
      nsCOMPtr<nsILDAPBERValue> value =
        do_CreateInstance("@mozilla.org/network/ldap-ber-value;1", &rv);
      NS_ENSURE_SUCCESS(rv, rv);

      rv = value->SetFromUTF8(propvalue);
      NS_ENSURE_SUCCESS(rv, rv);
 
      rv = mod->SetUpModificationOneValue(aType, attr, value);
      NS_ENSURE_SUCCESS(rv, rv);
    
      printf("LDAP : setting attribute %s (%s) to '%s'\n", attr.get(),
        props[i], propvalue.get());
      modArray->AppendElement(mod, false);
      if (index != nsTArray<nsCString>::NoIndex)
        m_attributes.AppendElement(attr);

    }
    else if (aType == nsILDAPModification::MOD_REPLACE &&
             index != nsTArray<nsCString>::NoIndex)
    {
      // If the new value is empty, we are performing an update
      // and the attribute was previously set, clear it
      nsCOMPtr<nsIMutableArray> novalues =
        do_CreateInstance(NS_ARRAY_CONTRACTID, &rv);
      NS_ENSURE_SUCCESS(rv, rv);

      rv = mod->SetUpModification(aType, attr, novalues);
      NS_ENSURE_SUCCESS(rv, rv);
      
      printf("LDAP : removing attribute %s (%s)\n", attr.get(), props[i]);
      modArray->AppendElement(mod, false);
      m_attributes.RemoveElementAt(index);
    }
  }

  NS_ADDREF(*aLDAPAddMessageInfo = modArray);

  return NS_OK;
}
nsresult
sbDeviceXMLInfo::GetImportRules(nsIArray ** aImportRules)
{
  NS_ENSURE_ARG_POINTER(aImportRules);

  nsresult rv;

  // Default to no rules:
  *aImportRules = NULL;

  // Do nothing more if no device info element.
  if (!mDeviceInfoElement) {
    return NS_OK;
  }

  // Each import rule is defined by an element of the form
  //
  //    <import  url="..."  type="..." />
  //
  // Get the list of import nodes:
  nsTArray< nsCOMPtr<nsIDOMNode> > importNodeList;
  rv = GetDeviceInfoNodes(NS_LITERAL_STRING("import"), importNodeList);
  NS_ENSURE_SUCCESS(rv, rv);

  // Create the result array.  The result will be an array of import
  // rules, where each rule is itself an array of two strings: a path
  // and the import type of files residing (recursively) within that
  // path:
  nsCOMPtr<nsIMutableArray> rules =
    do_CreateInstance(NS_ARRAY_CONTRACTID, &rv);
  NS_ENSURE_SUCCESS(rv, rv);

  // Iterate through the import nodes and assemble the result array:
  PRUint32 nodeCount = importNodeList.Length();
  for (PRUint32 i = 0; i < nodeCount; i++) {
    // Get the next import element:
    nsCOMPtr<nsIDOMElement> importElement;
    importElement = do_QueryInterface(importNodeList[i], &rv);
    if (NS_FAILED(rv))
      continue;

    // Get the folder path from the url attribute.  Skip if
    // empty or unavailable:
    nsAutoString urlAttr;
    rv = importElement->GetAttribute(NS_LITERAL_STRING("url"), urlAttr);
    if (NS_FAILED(rv))
      continue;
    if (urlAttr.IsEmpty())
      continue;

    // Get the import type.  Skip if empty or unavailable:
    nsAutoString typeAttr;
    rv = importElement->GetAttribute(NS_LITERAL_STRING("type"), typeAttr);
    if (NS_FAILED(rv))
      continue;
    if (typeAttr.IsEmpty())
      continue;

    // Create an array for this import rule:
    nsCOMPtr<nsIMutableArray> rule =
      do_CreateInstance(NS_ARRAY_CONTRACTID, &rv);
    NS_ENSURE_SUCCESS(rv, rv);

    // Append the folder path as the first element of the rule:
    nsCOMPtr<nsISupportsString> folder =
      do_CreateInstance("@mozilla.org/supports-string;1", &rv);
    NS_ENSURE_SUCCESS(rv, rv);
    rv = folder->SetData(urlAttr);
    NS_ENSURE_SUCCESS(rv, rv);
    rv = rule->AppendElement(folder, PR_FALSE);
    NS_ENSURE_SUCCESS(rv, rv);

    // Append the import type as the second element of the rule:
    nsCOMPtr<nsISupportsString> importType =
      do_CreateInstance("@mozilla.org/supports-string;1", &rv);
    NS_ENSURE_SUCCESS(rv, rv);
    rv = importType->SetData(typeAttr);
    NS_ENSURE_SUCCESS(rv, rv);
    rv = rule->AppendElement(importType, PR_FALSE);
    NS_ENSURE_SUCCESS(rv, rv);

    // Append this rule to the result:
    rv = rules->AppendElement(rule, PR_FALSE);
    NS_ENSURE_SUCCESS(rv, rv);
  }

  // Return the result array:
  NS_ADDREF(*aImportRules = rules.get());

  return NS_OK;
}
Esempio n. 23
0
NS_IMETHODIMP nsOutlookImport::GetImportInterface(const char *pImportType, nsISupports **ppInterface)
{
  NS_PRECONDITION(pImportType != nsnull, "null ptr");
  if (! pImportType)
    return NS_ERROR_NULL_POINTER;
  NS_PRECONDITION(ppInterface != nsnull, "null ptr");
  if (! ppInterface)
    return NS_ERROR_NULL_POINTER;

  *ppInterface = nsnull;
  nsresult  rv;
  if (!strcmp(pImportType, "mail")) {
    // create the nsIImportMail interface and return it!
    nsIImportMail *  pMail = nsnull;
    nsIImportGeneric *pGeneric = nsnull;
    rv = ImportOutlookMailImpl::Create(&pMail);
    if (NS_SUCCEEDED(rv)) {
      nsCOMPtr<nsIImportService> impSvc(do_GetService(NS_IMPORTSERVICE_CONTRACTID, &rv));
      if (NS_SUCCEEDED(rv)) {
        rv = impSvc->CreateNewGenericMail(&pGeneric);
        if (NS_SUCCEEDED(rv)) {
          pGeneric->SetData("mailInterface", pMail);
          nsString name;
          nsOutlookStringBundle::GetStringByID(OUTLOOKIMPORT_NAME, name);
          nsCOMPtr<nsISupportsString> nameString (do_CreateInstance(NS_SUPPORTS_STRING_CONTRACTID, &rv));
          if (NS_SUCCEEDED(rv)) {
            nameString->SetData(name);
            pGeneric->SetData("name", nameString);
            rv = pGeneric->QueryInterface(kISupportsIID, (void **)ppInterface);
          }
        }
      }
    }
    NS_IF_RELEASE(pMail);
    NS_IF_RELEASE(pGeneric);
    return rv;
  }

  if (!strcmp(pImportType, "addressbook")) {
    // create the nsIImportAddressBook interface and return it!
    nsIImportAddressBooks *  pAddress = nsnull;
    nsIImportGeneric *    pGeneric = nsnull;
    rv = ImportOutlookAddressImpl::Create(&pAddress);
    if (NS_SUCCEEDED(rv)) {
      nsCOMPtr<nsIImportService> impSvc(do_GetService(NS_IMPORTSERVICE_CONTRACTID, &rv));
      if (NS_SUCCEEDED(rv)) {
        rv = impSvc->CreateNewGenericAddressBooks(&pGeneric);
        if (NS_SUCCEEDED(rv)) {
          pGeneric->SetData("addressInterface", pAddress);
          rv = pGeneric->QueryInterface(kISupportsIID, (void **)ppInterface);
        }
      }
    }
    NS_IF_RELEASE(pAddress);
    NS_IF_RELEASE(pGeneric);
    return rv;
  }

  if (!strcmp(pImportType, "settings")) {
    nsIImportSettings *pSettings = nsnull;
    rv = nsOutlookSettings::Create(&pSettings);
    if (NS_SUCCEEDED(rv))
      pSettings->QueryInterface(kISupportsIID, (void **)ppInterface);
    NS_IF_RELEASE(pSettings);
    return rv;
  }

  return NS_ERROR_NOT_AVAILABLE;
}
nsresult
sbDeviceXMLInfo::GetStorageDeviceInfoList(nsIArray** aStorageDeviceInfoList)
{
  // Validate arguments and ensure this is called on the main thread.
  NS_ENSURE_ARG_POINTER(aStorageDeviceInfoList);
  NS_ASSERTION(NS_IsMainThread(), "not on main thread");

  // Function variables.
  nsresult rv;

  // Check if a device info element is available.  There doesn't have to be, so,
  // if not, just return an error without any warnings.
  if (!mDeviceInfoElement)
    return NS_ERROR_NOT_AVAILABLE;

  // Get the list of storage nodes.
  nsTArray< nsCOMPtr<nsIDOMNode> > storageNodeList;
  rv = GetDeviceInfoNodes(NS_LITERAL_STRING("storage"), storageNodeList);
  NS_ENSURE_SUCCESS(rv, rv);

  // Create the storage device info list.
  nsCOMPtr<nsIMutableArray> storageDeviceInfoList =
    do_CreateInstance("@songbirdnest.com/moz/xpcom/threadsafe-array;1", &rv);
  NS_ENSURE_SUCCESS(rv, rv);

  // Get the storage device info.
  PRUint32 nodeCount = storageNodeList.Length();
  for (PRUint32 nodeIndex = 0; nodeIndex < nodeCount; ++nodeIndex) {
    // Get the storage device node.
    nsCOMPtr<nsIDOMNode> storageDeviceNode = storageNodeList[nodeIndex];

    // Get the storage device attributes.
    nsCOMPtr<nsIDOMNamedNodeMap> attributes;
    PRUint32                     attributeCount;
    rv = storageDeviceNode->GetAttributes(getter_AddRefs(attributes));
    NS_ENSURE_SUCCESS(rv, rv);
    rv = attributes->GetLength(&attributeCount);
    NS_ENSURE_SUCCESS(rv, rv);

    // Create the storage device info property bag.
    nsCOMPtr<nsIWritablePropertyBag> storageDeviceInfo =
      do_CreateInstance("@mozilla.org/hash-property-bag;1", &rv);
    NS_ENSURE_SUCCESS(rv, rv);

    // Get the storage device info.
    for (PRUint32 attributeIndex = 0;
         attributeIndex < attributeCount;
         ++attributeIndex) {
      // Get the next attribute.
      nsCOMPtr<nsIDOMNode> attribute;
      rv = attributes->Item(attributeIndex, getter_AddRefs(attribute));
      NS_ENSURE_SUCCESS(rv, rv);

      // Get the attribute name.
      nsAutoString attributeName;
      rv = attribute->GetNodeName(attributeName);
      NS_ENSURE_SUCCESS(rv, rv);

      // Get the attribute value.
      nsAutoString attributeValue;
      rv = attribute->GetNodeValue(attributeValue);
      NS_ENSURE_SUCCESS(rv, rv);

      // Set the storage device info.
      storageDeviceInfo->SetProperty(attributeName,
                                     sbNewVariant(attributeValue));
      NS_ENSURE_SUCCESS(rv, rv);
    }

    // Add the storage device info.
    rv = storageDeviceInfoList->AppendElement(storageDeviceInfo, PR_FALSE);
    NS_ENSURE_SUCCESS(rv, rv);
  }

  // Return results.
  rv = CallQueryInterface(storageDeviceInfoList, aStorageDeviceInfoList);
  NS_ENSURE_SUCCESS(rv, rv);

  return NS_OK;
}
Esempio n. 25
0
NS_IMETHODIMP nsAppStartupNotifier::Observe(nsISupports *aSubject, const char *aTopic, const char16_t *someData)
{
    NS_ENSURE_ARG(aTopic);
    nsresult rv;

    // now initialize all startup listeners
    nsCOMPtr<nsICategoryManager> categoryManager =
                    do_GetService(NS_CATEGORYMANAGER_CONTRACTID, &rv);
    NS_ENSURE_SUCCESS(rv, rv);

    nsCOMPtr<nsISimpleEnumerator> enumerator;
    rv = categoryManager->EnumerateCategory(aTopic,
                               getter_AddRefs(enumerator));
    if (NS_FAILED(rv)) return rv;

    nsCOMPtr<nsISupports> entry;
    while (NS_SUCCEEDED(enumerator->GetNext(getter_AddRefs(entry)))) {
        nsCOMPtr<nsISupportsCString> category = do_QueryInterface(entry, &rv);

        if (NS_SUCCEEDED(rv)) {
            nsAutoCString categoryEntry;
            rv = category->GetData(categoryEntry);

            nsXPIDLCString contractId;
            categoryManager->GetCategoryEntry(aTopic, 
                                              categoryEntry.get(),
                                              getter_Copies(contractId));

            if (NS_SUCCEEDED(rv)) {

                // If we see the word "service," in the beginning
                // of the contractId then we create it as a service
                // if not we do a createInstance

                nsCOMPtr<nsISupports> startupInstance;
                if (Substring(contractId, 0, 8).EqualsLiteral("service,"))
                    startupInstance = do_GetService(contractId.get() + 8, &rv);
                else
                    startupInstance = do_CreateInstance(contractId, &rv);

                if (NS_SUCCEEDED(rv)) {
                    // Try to QI to nsIObserver
                    nsCOMPtr<nsIObserver> startupObserver =
                        do_QueryInterface(startupInstance, &rv);
                    if (NS_SUCCEEDED(rv)) {
                        rv = startupObserver->Observe(nullptr, aTopic, nullptr);
     
                        // mainly for debugging if you want to know if your observer worked.
                        NS_ASSERTION(NS_SUCCEEDED(rv), "Startup Observer failed!\n");
                    }
                }
                else {
                  #ifdef DEBUG
                    nsAutoCString warnStr("Cannot create startup observer : ");
                    warnStr += contractId.get();
                    NS_WARNING(warnStr.get());
                  #endif
                }

            }
        }
    }

    return NS_OK;
}
Esempio n. 26
0
already_AddRefed<nsITransferable>
DataTransfer::GetTransferable(uint32_t aIndex, nsILoadContext* aLoadContext)
{
  if (aIndex >= mItems.Length()) {
    return nullptr;
  }

  nsTArray<TransferItem>& item = mItems[aIndex];
  uint32_t count = item.Length();
  if (!count) {
    return nullptr;
  }

  nsCOMPtr<nsITransferable> transferable =
    do_CreateInstance("@mozilla.org/widget/transferable;1");
  if (!transferable) {
    return nullptr;
  }
  transferable->Init(aLoadContext);

  bool added = false;
  for (uint32_t f = 0; f < count; f++) {
    const TransferItem& formatitem = item[f];
    if (!formatitem.mData) { // skip empty items
      continue;
    }

    uint32_t length;
    nsCOMPtr<nsISupports> convertedData;
    if (!ConvertFromVariant(formatitem.mData, getter_AddRefs(convertedData), &length)) {
      continue;
    }

    // the underlying drag code uses text/unicode, so use that instead of text/plain
    const char* format;
    NS_ConvertUTF16toUTF8 utf8format(formatitem.mFormat);
    if (utf8format.EqualsLiteral("text/plain")) {
      format = kUnicodeMime;
    } else {
      format = utf8format.get();
    }

    // if a converter is set for a format, set the converter for the
    // transferable and don't add the item
    nsCOMPtr<nsIFormatConverter> converter = do_QueryInterface(convertedData);
    if (converter) {
      transferable->AddDataFlavor(format);
      transferable->SetConverter(converter);
      continue;
    }

    nsresult rv = transferable->SetTransferData(format, convertedData, length);
    if (NS_FAILED(rv)) {
      return nullptr;
    }

    added = true;
  }

  // only return the transferable if data was successfully added to it
  if (added) {
    return transferable.forget();
  }

  return nullptr;
}
nsresult
nsNetscapeProfileMigratorBase::GetProfileDataFromRegistry(nsILocalFile* aRegistryFile,
                                                          nsISupportsArray* aProfileNames,
                                                          nsISupportsArray* aProfileLocations)
{
  nsresult rv;
  REGERR errCode;

  // Ensure aRegistryFile exists before open it
  PRBool regFileExists = PR_FALSE;
  rv = aRegistryFile->Exists(&regFileExists);
  NS_ENSURE_SUCCESS(rv, rv);
  if (!regFileExists)
    return NS_ERROR_FILE_NOT_FOUND;

  // Open It
  nsCAutoString regPath;
  rv = aRegistryFile->GetNativePath(regPath);
  NS_ENSURE_SUCCESS(rv, rv);

  if ((errCode = NR_StartupRegistry()))
    return regerr2nsresult(errCode);

  HREG reg;
  if ((errCode = NR_RegOpen(regPath.get(), &reg))) {
    NR_ShutdownRegistry();

    return regerr2nsresult(errCode);
  }

  RKEY profilesTree;
  if ((errCode = NR_RegGetKey(reg, ROOTKEY_COMMON, "Profiles", &profilesTree))) {
    NR_RegClose(reg);
    NR_ShutdownRegistry();

    return regerr2nsresult(errCode);
  }

  char profileStr[MAXREGPATHLEN];
  REGENUM enumState = nsnull;

  while (!NR_RegEnumSubkeys(reg, profilesTree, &enumState, profileStr,
                            sizeof(profileStr), REGENUM_CHILDREN))
  {
    RKEY profileKey;
    if (NR_RegGetKey(reg, profilesTree, profileStr, &profileKey))
      continue;

    // "migrated" is "yes" for all valid Seamonkey profiles. It is only "no"
    // for 4.x profiles. 
    char migratedStr[3];
    errCode = NR_RegGetEntryString(reg, profileKey, (char *)"migrated",
                                   migratedStr, sizeof(migratedStr));
    if ((errCode != REGERR_OK && errCode != REGERR_BUFTOOSMALL) ||
        strcmp(migratedStr, "no") == 0)
      continue;

    // Get the profile location and add it to the locations array
    REGINFO regInfo;
    regInfo.size = sizeof(REGINFO);

    if (NR_RegGetEntryInfo(reg, profileKey, (char *)"directory", &regInfo))
      continue;

    nsCAutoString dirStr;
    dirStr.SetLength(regInfo.entryLength);

    errCode = NR_RegGetEntryString(reg, profileKey, (char *)"directory",
                                   dirStr.BeginWriting(), regInfo.entryLength);
    // Remove trailing \0
    dirStr.SetLength(regInfo.entryLength-1);

    nsCOMPtr<nsILocalFile> dir;
#ifdef XP_MACOSX
    rv = NS_NewNativeLocalFile(EmptyCString(), PR_TRUE, getter_AddRefs(dir));
    if (NS_FAILED(rv)) break;
    dir->SetPersistentDescriptor(dirStr);
#else
    rv = NS_NewLocalFile(NS_ConvertUTF8toUTF16(dirStr), PR_TRUE,
                         getter_AddRefs(dir));
    if (NS_FAILED(rv)) break;
#endif

    PRBool exists;
    dir->Exists(&exists);

    if (exists) {
      aProfileLocations->AppendElement(dir);

      // Get the profile name and add it to the names array
      nsString profileName;
      CopyUTF8toUTF16(nsDependentCString(profileStr), profileName);

      nsCOMPtr<nsISupportsString> profileNameString(
        do_CreateInstance("@mozilla.org/supports-string;1"));

      profileNameString->SetData(profileName);
      aProfileNames->AppendElement(profileNameString);
    }
  }
  NR_RegClose(reg);
  NR_ShutdownRegistry();

  return rv;
}
Esempio n. 28
0
bool
DataTransfer::ConvertFromVariant(nsIVariant* aVariant,
                                 nsISupports** aSupports,
                                 uint32_t* aLength)
{
  *aSupports = nullptr;
  *aLength = 0;

  uint16_t type;
  aVariant->GetDataType(&type);
  if (type == nsIDataType::VTYPE_INTERFACE ||
      type == nsIDataType::VTYPE_INTERFACE_IS) {
    nsCOMPtr<nsISupports> data;
    if (NS_FAILED(aVariant->GetAsISupports(getter_AddRefs(data))))
       return false;
 
    nsCOMPtr<nsIFlavorDataProvider> fdp = do_QueryInterface(data);
    if (fdp) {
      // for flavour data providers, use kFlavorHasDataProvider (which has the
      // value 0) as the length.
      fdp.forget(aSupports);
      *aLength = nsITransferable::kFlavorHasDataProvider;
    }
    else {
      // wrap the item in an nsISupportsInterfacePointer
      nsCOMPtr<nsISupportsInterfacePointer> ptrSupports =
        do_CreateInstance(NS_SUPPORTS_INTERFACE_POINTER_CONTRACTID);
      if (!ptrSupports)
        return false;

      ptrSupports->SetData(data);
      ptrSupports.forget(aSupports);

      *aLength = sizeof(nsISupportsInterfacePointer *);
    }

    return true;
  }

  char16_t* chrs;
  uint32_t len = 0;
  nsresult rv = aVariant->GetAsWStringWithSize(&len, &chrs);
  if (NS_FAILED(rv))
    return false;

  nsAutoString str;
  str.Adopt(chrs, len);

  nsCOMPtr<nsISupportsString>
    strSupports(do_CreateInstance(NS_SUPPORTS_STRING_CONTRACTID));
  if (!strSupports)
    return false;

  strSupports->SetData(str);

  strSupports.forget(aSupports);

  // each character is two bytes
  *aLength = str.Length() << 1;

  return true;
}
Esempio n. 29
0
nsresult
nsMorkReader::Read(nsIFile *aFile)
{
    nsCOMPtr<nsIFileInputStream> stream =
        do_CreateInstance(NS_LOCALFILEINPUTSTREAM_CONTRACTID);
    NS_ENSURE_TRUE(stream, NS_ERROR_FAILURE);

    nsresult rv = stream->Init(aFile, PR_RDONLY, 0, 0);
    NS_ENSURE_SUCCESS(rv, rv);

    mStream = do_QueryInterface(stream);
    NS_ASSERTION(mStream, "file input stream must impl nsILineInputStream");

    nsCLineString line;
    rv = ReadLine(line);
    if (!line.EqualsLiteral("// <!-- <mdb:mork:z v=\"1.4\"/> -->")) {
        return NS_ERROR_FAILURE; // unexpected file format
    }

    IndexMap columnMap;
    NS_ENSURE_TRUE(columnMap.Init(), NS_ERROR_OUT_OF_MEMORY);

    while (NS_SUCCEEDED(ReadLine(line))) {
        // Trim off leading spaces
        PRUint32 idx = 0, len = line.Length();
        while (idx < len && line[idx] == ' ') {
            ++idx;
        }
        if (idx >= len) {
            continue;
        }

        const nsCSubstring &l = Substring(line, idx);

        // Look at the line to figure out what section type this is
        if (StringBeginsWith(l, NS_LITERAL_CSTRING("< <(a=c)>"))) {
            // Column map.  We begin by creating a hash of column id to column name.
            StringMap columnNameMap;
            NS_ENSURE_TRUE(columnNameMap.Init(), NS_ERROR_OUT_OF_MEMORY);

            rv = ParseMap(l, &columnNameMap);
            NS_ENSURE_SUCCESS(rv, rv);

            // Now that we have the list of columns, we put them into a flat array.
            // Rows will have value arrays of the same size, with indexes that
            // correspond to the columns array.  As we insert each column into the
            // array, we also make an entry in columnMap so that we can look up the
            // index given the column id.
            mColumns.SetCapacity(columnNameMap.Count());

            AddColumnClosure closure(&mColumns, &columnMap);
            columnNameMap.EnumerateRead(AddColumn, &closure);
            if (NS_FAILED(closure.result)) {
                return closure.result;
            }
        } else if (StringBeginsWith(l, NS_LITERAL_CSTRING("<("))) {
            // Value map
            rv = ParseMap(l, &mValueMap);
            NS_ENSURE_SUCCESS(rv, rv);
        } else if (l[0] == '{' || l[0] == '[') {
            // Table / table row
            rv = ParseTable(l, columnMap);
            NS_ENSURE_SUCCESS(rv, rv);
        } else {
            // Don't know, hopefully don't care
        }
    }

    return NS_OK;
}
NS_IMETHODIMP
sbBaseDevice::ImportFromDevice(sbILibrary * aImportToLibrary,
                               sbILibraryChangeset * aImportChangeset)
{
  NS_ENSURE_ARG_POINTER(aImportToLibrary);
  NS_ENSURE_ARG_POINTER(aImportChangeset);

  nsresult rv;

  // Get the list of all changes.
  nsCOMPtr<nsIArray> changeList;
  rv = aImportChangeset->GetChanges(getter_AddRefs(changeList));
  NS_ENSURE_SUCCESS(rv, rv);

  PRUint32 changeCount;
  rv = changeList->GetLength(&changeCount);
  NS_ENSURE_SUCCESS(rv, rv);

  // If there aren't any changes, don't bother setting up for the import
  if (changeCount == 0) {
    return NS_OK;
  }
  // Accumulators so we can batch the operations
  nsCOMPtr<nsIMutableArray> mediaItemsToAdd =
    do_CreateInstance("@songbirdnest.com/moz/xpcom/threadsafe-array;1", &rv);
  NS_ENSURE_SUCCESS(rv, rv);
  nsCOMPtr<nsIMutableArray> mediaListsToAdd =
    do_CreateInstance("@songbirdnest.com/moz/xpcom/threadsafe-array;1", &rv);
  NS_ENSURE_SUCCESS(rv, rv);
  nsCOMPtr<nsIMutableArray> mediaItemsToRemove =
    do_CreateInstance("@songbirdnest.com/moz/xpcom/threadsafe-array;1", &rv);
  // Determine if playlists are supported
  NS_ENSURE_SUCCESS(rv, rv);
  nsCOMPtr<nsIMutableArray> mediaListsToUpdate =
    do_CreateInstance("@songbirdnest.com/moz/xpcom/threadsafe-array;1", &rv);
  NS_ENSURE_SUCCESS(rv, rv);

  bool const playlistsSupported = sbDeviceUtils::ArePlaylistsSupported(this);


  // Accumulate changes for later processing to take advantage of batching
  for (PRUint32 i = 0; i < changeCount; i++) {
    if (IsRequestAborted()) {
      return NS_ERROR_ABORT;
    }
    // Get the next change.
    nsCOMPtr<sbILibraryChange> change = do_QueryElementAt(changeList, i, &rv);
    NS_ENSURE_SUCCESS(rv, rv);

    // Put the change into the appropriate lists.
    PRUint32 operation;
    rv = change->GetOperation(&operation);
    NS_ENSURE_SUCCESS(rv, rv);

    // Is this a media item list
    bool itemIsList;
    rv = change->GetItemIsList(&itemIsList);
    NS_ENSURE_SUCCESS(rv, rv);

    // if this is a playlist and they're not supported ignore the change
    if (itemIsList && !playlistsSupported) {
      continue;
    }

    switch (operation) {
      case sbIChangeOperation::ADDED: {
        // Get the source item to add.
        nsCOMPtr<sbIMediaItem> mediaItem;
        rv = change->GetSourceItem(getter_AddRefs(mediaItem));
        NS_ENSURE_SUCCESS(rv, rv);

        if (itemIsList) {
          rv = mediaListsToAdd->AppendElement(change, PR_FALSE);
          NS_ENSURE_SUCCESS(rv, rv);
        } else {
          rv = mediaItemsToAdd->AppendElement(mediaItem, PR_FALSE);
          NS_ENSURE_SUCCESS(rv, rv);
        }
      }
      break;
      case sbIChangeOperation::MODIFIED: {
        nsCOMPtr<sbIMediaItem> destItem;
        rv = change->GetDestinationItem(getter_AddRefs(destItem));
        NS_ENSURE_SUCCESS(rv, rv);

        nsCOMPtr<sbIMediaList> destItemAsList =
          do_QueryInterface(destItem);

        if (destItemAsList) {
          // If the change is to a media list, add it to the media list change
          // list.
          bool success = mediaListsToUpdate->AppendElement(change, PR_FALSE);
          NS_ENSURE_SUCCESS(success, NS_ERROR_OUT_OF_MEMORY);

        }
        else {
          rv = mediaItemsToRemove->AppendElement(destItem, PR_FALSE);
          NS_ENSURE_SUCCESS(rv, rv);

          nsCOMPtr<sbIMediaItem> sourceItem;
          rv = change->GetSourceItem(getter_AddRefs(sourceItem));

          rv = mediaItemsToAdd->AppendElement(sourceItem, PR_FALSE);
          NS_ENSURE_SUCCESS(rv, rv);
        }
      }
      break;
      default: {
        NS_WARNING("Unexpected change operation value in sbBaseDevice::Import");
      }
      break;
    }
  }

  // Remove items that need to be removed
  nsCOMPtr<nsISimpleEnumerator> enumerator;
  rv = mediaItemsToRemove->Enumerate(getter_AddRefs(enumerator));
  NS_ENSURE_SUCCESS(rv, rv);

  rv = aImportToLibrary->RemoveSome(enumerator);
  NS_ENSURE_SUCCESS(rv, rv);

  // Add media lists.
  rv = mediaItemsToAdd->Enumerate(getter_AddRefs(enumerator));
  NS_ENSURE_SUCCESS(rv, rv);

  rv = aImportToLibrary->AddSome(enumerator);
  NS_ENSURE_SUCCESS(rv, rv);

  rv = AddMediaLists(aImportToLibrary, mediaListsToAdd);
  NS_ENSURE_SUCCESS(rv, rv);

  rv = UpdateMediaLists(mediaListsToUpdate);
  NS_ENSURE_SUCCESS(rv, rv);

  return NS_OK;
}