Exemple #1
0
nsresult nsAbBoolExprToLDAPFilter::FilterExpression (
    nsIAbLDAPAttributeMap* map,
    nsIAbBooleanExpression* expression,
    nsCString& filter,
    int flags)
{
    nsCOMPtr<nsIArray> childExpressions;
    nsresult rv = expression->GetExpressions(getter_AddRefs(childExpressions));
    NS_ENSURE_SUCCESS(rv, rv);
    
    PRUint32 count;
    rv = childExpressions->GetLength(&count);
    NS_ENSURE_SUCCESS(rv, rv);

    if (count == 0)
        return NS_OK;

    nsAbBooleanOperationType operation;
    rv = expression->GetOperation(&operation);
    NS_ENSURE_SUCCESS(rv, rv);

    /*
     * 3rd party query integration with Mozilla is achieved 
     * by calling nsAbLDAPDirectoryQuery::DoQuery(). Thus
     * we can arrive here with a query asking for all the
     * ldap attributes using the card:nsIAbCard interface.
     *
     * So we need to check that we are not creating a condition 
     * filter against this expression otherwise we will end up with an invalid 
     * filter equal to "(|)".
    */
    
    if (count == 1 )
    {
        nsCOMPtr<nsIAbBooleanConditionString>
            childCondition(do_QueryElementAt(childExpressions, 1, &rv));
        if (NS_SUCCEEDED(rv))
        {
            nsCString name;
            rv = childCondition->GetName (getter_Copies (name));
            NS_ENSURE_SUCCESS(rv, rv);

            if(name.Equals("card:nsIAbCard"))
                return NS_OK;
        }
    }

    filter.AppendLiteral("(");
    switch (operation)
    {
        case nsIAbBooleanOperationTypes::AND:
            filter.AppendLiteral("&");
            rv = FilterExpressions (map, childExpressions, filter, flags);
            break;
        case nsIAbBooleanOperationTypes::OR:
            filter.AppendLiteral("|");
            rv = FilterExpressions (map, childExpressions, filter, flags);
            break;
        case nsIAbBooleanOperationTypes::NOT:
            if (count > 1)
                return NS_ERROR_FAILURE;
            filter.AppendLiteral("!");
            rv = FilterExpressions (map, childExpressions, filter, flags);
            break;
        default:
            break;
    }
    filter.AppendLiteral(")");

    return rv;
}
// Finds the base domain for a host, with requested number of additional parts.
// This will fail, generating an error, if the host is an IPv4/IPv6 address,
// if more subdomain parts are requested than are available, or if the hostname
// includes characters that are not valid in a URL. Normalization is performed
// on the host string and the result will be in UTF8.
nsresult
nsEffectiveTLDService::GetBaseDomainInternal(nsCString  &aHostname,
                                             int32_t    aAdditionalParts,
                                             nsACString &aBaseDomain)
{
  if (aHostname.IsEmpty())
    return NS_ERROR_INSUFFICIENT_DOMAIN_LEVELS;

  // chomp any trailing dot, and keep track of it for later
  bool trailingDot = aHostname.Last() == '.';
  if (trailingDot)
    aHostname.Truncate(aHostname.Length() - 1);

  // check the edge cases of the host being '.' or having a second trailing '.',
  // since subsequent checks won't catch it.
  if (aHostname.IsEmpty() || aHostname.Last() == '.')
    return NS_ERROR_INVALID_ARG;

  // Check if we're dealing with an IPv4/IPv6 hostname, and return
  PRNetAddr addr;
  PRStatus result = PR_StringToNetAddr(aHostname.get(), &addr);
  if (result == PR_SUCCESS)
    return NS_ERROR_HOST_IS_IP_ADDRESS;

  // Walk up the domain tree, most specific to least specific,
  // looking for matches at each level.  Note that a given level may
  // have multiple attributes (e.g. IsWild() and IsNormal()).
  const char *prevDomain = nullptr;
  const char *currDomain = aHostname.get();
  const char *nextDot = strchr(currDomain, '.');
  const char *end = currDomain + aHostname.Length();
  // Default value of *eTLD is currDomain as set in the while loop below
  const char *eTLD = nullptr;
  while (1) {
    // sanity check the string we're about to look up: it should not begin with
    // a '.'; this would mean the hostname began with a '.' or had an
    // embedded '..' sequence.
    if (*currDomain == '.')
      return NS_ERROR_INVALID_ARG;

    // Perform the lookup.
    const ETLDEntry* entry = ETLDEntry::GetEntry(currDomain);
    if (entry) {
      if (entry->IsWild() && prevDomain) {
        // wildcard rules imply an eTLD one level inferior to the match.
        eTLD = prevDomain;
        break;

      } else if (entry->IsNormal() || !nextDot) {
        // specific match, or we've hit the top domain level
        eTLD = currDomain;
        break;

      } else if (entry->IsException()) {
        // exception rules imply an eTLD one level superior to the match.
        eTLD = nextDot + 1;
        break;
      }
    }

    if (!nextDot) {
      // we've hit the top domain level; use it by default.
      eTLD = currDomain;
      break;
    }

    prevDomain = currDomain;
    currDomain = nextDot + 1;
    nextDot = strchr(currDomain, '.');
  }

  const char *begin, *iter;
  if (aAdditionalParts < 0) {
    NS_ASSERTION(aAdditionalParts == -1,
                 "aAdditionalParts can't be negative and different from -1");

    for (iter = aHostname.get(); iter != eTLD && *iter != '.'; iter++);

    if (iter != eTLD) {
      iter++;
    }
    if (iter != eTLD) {
      aAdditionalParts = 0;
    }
  } else {
    // count off the number of requested domains.
    begin = aHostname.get();
    iter = eTLD;

    while (1) {
      if (iter == begin)
        break;

      if (*(--iter) == '.' && aAdditionalParts-- == 0) {
        ++iter;
        ++aAdditionalParts;
        break;
      }
    }
  }

  if (aAdditionalParts != 0)
    return NS_ERROR_INSUFFICIENT_DOMAIN_LEVELS;

  aBaseDomain = Substring(iter, end);
  // add on the trailing dot, if applicable
  if (trailingDot)
    aBaseDomain.Append('.');

  return NS_OK;
}
Exemple #3
0
void
UnixSocketImpl::Connect()
{
  MOZ_ASSERT(!NS_IsMainThread());

  if (!mConnector) {
    NS_WARNING("No connector object available!");
    return;
  }

  if(mFd.get() < 0)
  {
    mFd = mConnector->Create();
    if (mFd.get() < 0) {
      return;
    }
  }

  int ret;

  if (!mConnector->CreateAddr(false, mAddrSize, mAddr, mAddress.get())) {
    NS_WARNING("Cannot create socket address!");
    return;
  }

  // Select non-blocking IO.
  if (!SetNonblockFlags()) {
    nsRefPtr<OnSocketEventTask> t =
      new OnSocketEventTask(this, OnSocketEventTask::CONNECT_ERROR);
    NS_DispatchToMainThread(t);
    return;
  }

  ret = connect(mFd.get(), (struct sockaddr*)&mAddr, mAddrSize);

  if (ret) {
    if (errno == EINPROGRESS) {
      // Select blocking IO again, since we've now at least queue'd the connect
      // as nonblock.
      int current_opts = fcntl(mFd.get(), F_GETFL, 0);
      if (-1 == current_opts) {
        NS_WARNING("Cannot get socket opts!");
        nsRefPtr<OnSocketEventTask> t =
          new OnSocketEventTask(this, OnSocketEventTask::CONNECT_ERROR);
        NS_DispatchToMainThread(t);
        return;
      }
      if (-1 == fcntl(mFd.get(), F_SETFL, current_opts & ~O_NONBLOCK)) {
        NS_WARNING("Cannot set socket opts to blocking!");
        nsRefPtr<OnSocketEventTask> t =
          new OnSocketEventTask(this, OnSocketEventTask::CONNECT_ERROR);
        NS_DispatchToMainThread(t);
        return;
      }

      // Set up a write watch to make sure we receive the connect signal
      MessageLoopForIO::current()->WatchFileDescriptor(
        mFd.get(),
        false,
        MessageLoopForIO::WATCH_WRITE,
        &mWriteWatcher,
        this);

#ifdef DEBUG
      LOG("UnixSocket Connection delayed!");
#endif
      return;
    }
#if DEBUG
    LOG("Socket connect errno=%d\n", errno);
#endif
    mFd.reset(-1);
    nsRefPtr<OnSocketEventTask> t =
      new OnSocketEventTask(this, OnSocketEventTask::CONNECT_ERROR);
    NS_DispatchToMainThread(t);
    return;
  }

  if (!mConnector->SetUp(mFd)) {
    NS_WARNING("Could not set up socket!");
    return;
  }

  nsRefPtr<OnSocketEventTask> t =
    new OnSocketEventTask(this, OnSocketEventTask::CONNECT_SUCCESS);
  NS_DispatchToMainThread(t);

  SetUpIO();
}
void
CreateDirectoryTaskParent::GetPermissionAccessType(nsCString& aAccess) const
{
  aAccess.AssignLiteral(CREATE_DIRECTORY_TASK_PERMISSION);
}
/**
 * Start file open operation, mount volume when needed and according to file type
 * create file output stream or read directory content.
 * @return NS_OK when file or directory opened successfully, error code otherwise
 */
nsresult
nsGIOInputStream::DoOpen()
{
  nsresult rv;
  GError *error = NULL;

  NS_ASSERTION(mHandle == nullptr, "already open");

  mHandle = g_file_new_for_uri( mSpec.get() );

  GFileInfo *info = g_file_query_info(mHandle,
                                      "standard::*",
                                      G_FILE_QUERY_INFO_NONE,
                                      NULL,
                                      &error);

  if (error) {
    if (error->domain == G_IO_ERROR && error->code == G_IO_ERROR_NOT_MOUNTED) {
      // location is not yet mounted, try to mount
      g_error_free(error);
      if (NS_IsMainThread()) 
        return NS_ERROR_NOT_CONNECTED;
      error = NULL;
      rv = MountVolume();
      if (rv != NS_OK) {
        return rv;
      }
      // get info again
      info = g_file_query_info(mHandle,
                               "standard::*",
                               G_FILE_QUERY_INFO_NONE,
                               NULL,
                               &error);
      // second try to get file info from remote files after media mount
      if (!info) {
        g_warning("Unable to get file info: %s", error->message);
        rv = MapGIOResult(error);
        g_error_free(error);
        return rv;
      }
    } else {
      g_warning("Unable to get file info: %s", error->message);
      rv = MapGIOResult(error);
      g_error_free(error);
      return rv;
    }
  }
  // Get file type to handle directories and file differently
  GFileType f_type = g_file_info_get_file_type(info);
  if (f_type == G_FILE_TYPE_DIRECTORY) {
    // directory
    rv = DoOpenDirectory();
  } else if (f_type != G_FILE_TYPE_UNKNOWN) {
    // file
    rv = DoOpenFile(info);
  } else {
    g_warning("Unable to get file type.");
    rv = NS_ERROR_FILE_NOT_FOUND;
  }
  if (info)
    g_object_unref(info);
  return rv;
}
PRBool
SetOperator(OperatorData*   aOperatorData,
            nsOperatorFlags aForm,
            const nsCString& aOperator,
            nsString&        aAttributes)

{
  // aOperator is in the expanded format \uNNNN\uNNNN ...
  // First compress these Unicode points to the internal nsString format
  PRInt32 i = 0;
  nsAutoString name, value;
  PRInt32 len = aOperator.Length();
  PRUnichar c = aOperator[i++];
  PRUint32 state  = 0;
  PRUnichar uchar = 0;
  while (i <= len) {
    if (0 == state) {
      if (c != '\\')
        return PR_FALSE;
      if (i < len)
        c = aOperator[i];
      i++;
      if (('u' != c) && ('U' != c))
        return PR_FALSE;
      if (i < len)
        c = aOperator[i];
      i++;
      state++;
    }
    else {
      if (('0' <= c) && (c <= '9'))
         uchar = (uchar << 4) | (c - '0');
      else if (('a' <= c) && (c <= 'f'))
         uchar = (uchar << 4) | (c - 'a' + 0x0a);
      else if (('A' <= c) && (c <= 'F'))
         uchar = (uchar << 4) | (c - 'A' + 0x0a);
      else return PR_FALSE;
      if (i < len)
        c = aOperator[i];
      i++;
      state++;
      if (5 == state) {
        value.Append(uchar);
        uchar = 0;
        state = 0;
      }
    }
  }
  if (0 != state) return PR_FALSE;

  // Quick return when the caller doesn't care about the attributes and just wants
  // to know if this is a valid operator (this is the case at the first pass of the
  // parsing of the dictionary in InitOperators())
  if (!aForm) return PR_TRUE;

  // Add operator to hash table (symmetric="true" by default for all operators)
  aOperatorData->mFlags |= aForm | NS_MATHML_OPERATOR_SYMMETRIC;
  aOperatorData->mStr.Assign(value);
  value.AppendInt(aForm, 10);
  nsStringKey key(value);
  gOperatorTable->Put(&key, aOperatorData);

#ifdef NS_DEBUG
  NS_LossyConvertUTF16toASCII str(aAttributes);
#endif
  // Loop over the space-delimited list of attributes to get the name:value pairs
  aAttributes.Append(kNullCh);  // put an extra null at the end
  PRUnichar* start = aAttributes.BeginWriting();
  PRUnichar* end   = start;
  while ((kNullCh != *start) && (kDashCh != *start)) {
    name.SetLength(0);
    value.SetLength(0);
    // skip leading space, the dash amounts to the end of the line
    while ((kNullCh!=*start) && (kDashCh!=*start) && nsCRT::IsAsciiSpace(*start)) {
      ++start;
    }
    end = start;
    // look for ':' or '='
    while ((kNullCh!=*end) && (kDashCh!=*end) && (kColonCh!=*end) && (kEqualCh!=*end)) {
      ++end;
    }
    if ((kColonCh!=*end) && (kEqualCh!=*end)) {
#ifdef NS_DEBUG
      printf("Bad MathML operator: %s\n", str.get());
#endif
      return PR_TRUE;
    }
    *end = kNullCh; // end segment here
    // this segment is the name
    if (start < end) {
      name.Assign(start);
    }
    start = ++end;
    // look for space or end of line
    while ((kNullCh!=*end) && (kDashCh!=*start) && !nsCRT::IsAsciiSpace(*end)) {
      ++end;
    }
    *end = kNullCh; // end segment here
    // this segment is the value
    if (start < end) {
      value.Assign(start);
    }
    SetProperty(aOperatorData, name, value);
    start = ++end;
  }
  return PR_TRUE;
}
nsresult
PendingLookup::OnStopRequestInternal(nsIRequest *aRequest,
                                     nsISupports *aContext,
                                     nsresult aResult,
                                     bool* aShouldBlock,
                                     uint32_t* aVerdict) {
  if (NS_FAILED(aResult)) {
    Accumulate(mozilla::Telemetry::APPLICATION_REPUTATION_SERVER,
      SERVER_RESPONSE_FAILED);
    return aResult;
  }

  *aShouldBlock = false;
  *aVerdict = nsIApplicationReputationService::VERDICT_SAFE;
  nsresult rv;
  nsCOMPtr<nsIHttpChannel> channel = do_QueryInterface(aRequest, &rv);
  if (NS_FAILED(rv)) {
    Accumulate(mozilla::Telemetry::APPLICATION_REPUTATION_SERVER,
      SERVER_RESPONSE_FAILED);
    return rv;
  }

  uint32_t status = 0;
  rv = channel->GetResponseStatus(&status);
  if (NS_FAILED(rv)) {
    Accumulate(mozilla::Telemetry::APPLICATION_REPUTATION_SERVER,
      SERVER_RESPONSE_FAILED);
    return rv;
  }

  if (status != 200) {
    Accumulate(mozilla::Telemetry::APPLICATION_REPUTATION_SERVER,
      SERVER_RESPONSE_FAILED);
    return NS_ERROR_NOT_AVAILABLE;
  }

  std::string buf(mResponse.Data(), mResponse.Length());
  safe_browsing::ClientDownloadResponse response;
  if (!response.ParseFromString(buf)) {
    LOG(("Invalid protocol buffer response [this = %p]: %s", this, buf.c_str()));
    Accumulate(mozilla::Telemetry::APPLICATION_REPUTATION_SERVER,
                                   SERVER_RESPONSE_INVALID);
    return NS_ERROR_CANNOT_CONVERT_DATA;
  }

  Accumulate(mozilla::Telemetry::APPLICATION_REPUTATION_SERVER,
    SERVER_RESPONSE_VALID);
  // Clamp responses 0-7, we only know about 0-4 for now.
  Accumulate(mozilla::Telemetry::APPLICATION_REPUTATION_SERVER_VERDICT,
    std::min<uint32_t>(response.verdict(), 7));
  switch(response.verdict()) {
    case safe_browsing::ClientDownloadResponse::DANGEROUS:
      *aShouldBlock = Preferences::GetBool(PREF_BLOCK_DANGEROUS, true);
      *aVerdict = nsIApplicationReputationService::VERDICT_DANGEROUS;
      break;
    case safe_browsing::ClientDownloadResponse::DANGEROUS_HOST:
      *aShouldBlock = Preferences::GetBool(PREF_BLOCK_DANGEROUS_HOST, true);
      *aVerdict = nsIApplicationReputationService::VERDICT_DANGEROUS_HOST;
      break;
    case safe_browsing::ClientDownloadResponse::POTENTIALLY_UNWANTED:
      *aShouldBlock = Preferences::GetBool(PREF_BLOCK_POTENTIALLY_UNWANTED, false);
      *aVerdict = nsIApplicationReputationService::VERDICT_POTENTIALLY_UNWANTED;
      break;
    case safe_browsing::ClientDownloadResponse::UNCOMMON:
      *aShouldBlock = Preferences::GetBool(PREF_BLOCK_UNCOMMON, false);
      *aVerdict = nsIApplicationReputationService::VERDICT_UNCOMMON;
      break;
    default:
      // Treat everything else as safe
      break;
  }

  return NS_OK;
}
Exemple #8
0
void nsEudoraWin32::GetMimeTypeFromExtension( nsCString& ext, nsCString& mimeType)
{
  HKEY  sKey;
  if (::RegOpenKeyEx( HKEY_CLASSES_ROOT, ext.get(), 0, KEY_QUERY_VALUE, &sKey) == ERROR_SUCCESS)
  {
    // get the value of "Current"
    BYTE *pBytes = GetValueBytes( sKey, "Content Type");
    if (pBytes)
    {
      mimeType = (const char *)pBytes;
      delete [] pBytes;
    }
    ::RegCloseKey( sKey);
  }

  if (!mimeType.IsEmpty() || !m_mailImportLocation || (ext.Length() > 10))
    return;

  // TLR: FIXME: We should/could cache the extension to mime type maps we find
  // and check the cache first before scanning all of eudora's mappings?

  // It's not in the registry, try and find the .ini file for Eudora's private
  // mime type list
  if (!m_pMimeSection)
  {
    nsCOMPtr <nsILocalFile> pFile = do_CreateInstance(NS_LOCAL_FILE_CONTRACTID);
    if (!pFile)
      return;

    pFile->InitWithFile(m_mailImportLocation);

    pFile->AppendNative(NS_LITERAL_CSTRING("eudora.ini"));
    bool exists = false;
    bool isFile = false;
    nsresult rv = pFile->Exists( &exists);
    if (NS_SUCCEEDED( rv))
      rv = pFile->IsFile( &isFile);
    if (!isFile || !exists)
    {
      rv = pFile->InitWithFile( m_mailImportLocation);
      if (NS_FAILED( rv))
        return;
      if (!FindMimeIniFile( pFile))
        return;
    }

    nsCAutoString fileName;
    pFile->GetNativePath(fileName);
    if (fileName.IsEmpty())
      return;
    // Read the mime map section
    DWORD  size = 1024;
    DWORD  dSize = size - 2;
    while (dSize == (size - 2))
    {
      if (m_pMimeSection)
        delete [] m_pMimeSection;
      size += 1024;
      m_pMimeSection = new char[size];
      dSize = ::GetPrivateProfileSection( "Mappings", m_pMimeSection, size, fileName.get());
    }
  }

  if (!m_pMimeSection)
    return;

  IMPORT_LOG1( "Looking for mime type for extension: %s\n", ext.get());

  // out/in/both=extension,mac creator,mac type,mime type1,mime type2
  const char *pExt = ext.get();
  pExt++;

  char  *  pChar = m_pMimeSection;
  char  *  pStart;
  int      len;
  nsCString  tStr;
  for(;;)
  {
    while (*pChar != '=')
    {
      if (!(*pChar) && !(*(pChar + 1)))
        return;
      pChar++;
    }
    if (*pChar)
      pChar++;
    pStart = pChar;
    len = 0;
    while (*pChar && (*pChar != ','))
    {
      pChar++;
      len++;
    }
    if (!*pChar)
      return;

    tStr.Truncate();
    tStr.Append( pStart, len);
    tStr.Trim( kWhitespace);
    if (!PL_strcasecmp( tStr.get(), pExt))
    {
      // skip the mac creator and type
      pChar++;
      while (*pChar && (*pChar != ','))
        pChar++;
      if (!*pChar)
        return;

      pChar++;
      while (*pChar && (*pChar != ','))
        pChar++;
      if (!*pChar)
        return;

      pChar++;
      // Get the first mime type
      len = 0;
      pStart = pChar;
      while (*pChar && (*pChar != ','))
      {
        pChar++;
        len++;
      }
      if (!*pChar)
        return;

      pChar++;
      if (!len)
        continue;

      tStr.Truncate();
      tStr.Append( pStart, len);
      tStr.Trim( kWhitespace);
      if (tStr.IsEmpty())
        continue;

      mimeType.Truncate();
      mimeType.Append( tStr.get());
      mimeType.Append( "/");
      pStart = pChar;
      len = 0;
      // Skip to next end of line.
      while (*pChar && (*pChar != nsCRT::CR) && (*pChar != nsCRT::LF))
      {
        pChar++;
        len++;
      }
      if (!len)
        continue;

      tStr.Truncate();
      tStr.Append( pStart, len);
      tStr.Trim( kWhitespace);
      if (tStr.IsEmpty())
        continue;

      mimeType.Append( tStr.get());

      IMPORT_LOG1( "Found Mime Type: %s\n", mimeType.get());

      return;
    }
  }
}
/* static */ already_AddRefed<Image>
ImageFactory::CreateRasterImage(nsIRequest* aRequest,
                                ProgressTracker* aProgressTracker,
                                const nsCString& aMimeType,
                                ImageURL* aURI,
                                uint32_t aImageFlags,
                                uint32_t aInnerWindowId)
{
  nsresult rv;

  nsRefPtr<RasterImage> newImage = new RasterImage(aProgressTracker, aURI);

  rv = newImage->Init(aMimeType.get(), aImageFlags);
  NS_ENSURE_SUCCESS(rv, BadImage(newImage));

  newImage->SetInnerWindowID(aInnerWindowId);

  uint32_t len = GetContentSize(aRequest);

  // Pass anything usable on so that the RasterImage can preallocate
  // its source buffer.
  if (len > 0) {
    // Bound by something reasonable
    uint32_t sizeHint = std::min<uint32_t>(len, 20000000);
    rv = newImage->SetSourceSizeHint(sizeHint);
    if (NS_FAILED(rv)) {
      // Flush memory, try to get some back, and try again.
      rv = nsMemory::HeapMinimize(true);
      nsresult rv2 = newImage->SetSourceSizeHint(sizeHint);
      // If we've still failed at this point, things are going downhill.
      if (NS_FAILED(rv) || NS_FAILED(rv2)) {
        NS_WARNING("About to hit OOM in imagelib!");
      }
    }
  }

  nsAutoCString ref;
  aURI->GetRef(ref);
  net::nsMediaFragmentURIParser parser(ref);
  if (parser.HasResolution()) {
    newImage->SetRequestedResolution(parser.GetResolution());
  }

  if (parser.HasSampleSize()) {
      /* Get our principal */
      nsCOMPtr<nsIChannel> chan(do_QueryInterface(aRequest));
      nsCOMPtr<nsIPrincipal> principal;
      if (chan) {
        nsContentUtils::GetSecurityManager()
          ->GetChannelResultPrincipal(chan, getter_AddRefs(principal));
      }

      if ((principal &&
           principal->GetAppStatus() == nsIPrincipal::APP_STATUS_CERTIFIED) ||
          gfxPrefs::ImageMozSampleSizeEnabled()) {
        newImage->SetRequestedSampleSize(parser.GetSampleSize());
      }
  }

  return newImage.forget();
}
bool CAliasData::Process(const char *pLine, int32_t len)
{
  // Extract any comments first!
  nsCString  str;

  const char *pStart = pLine;
  int32_t    tCnt = 0;
  int32_t    cnt = 0;
  int32_t    max = len;
  bool      endCollect = false;

    // Keep track of the full entry without any processing for potential alias
    // nickname resolution. Previously alias resolution was done with m_email,
    // but unfortunately that doesn't work for nicknames with spaces.
    // For example for the nickname "Joe Smith", "Smith" was being interpreted
    // as the potential email address and placed in m_email, but routines like
    // ResolveAlias were failing because "Smith" is not the full nickname.
    // Now we just stash the full entry for nickname resolution before processing
    // the line as a potential entry in its own right.
    m_fullEntry.Append(pLine, len);

  while (max) {
    if (*pLine == '"') {
      if (tCnt && !endCollect) {
        str.Trim(kWhitespace);
        if (!str.IsEmpty())
          str.Append(" ", 1);
        str.Append(pStart, tCnt);
      }
      cnt = nsEudoraAddress::CountQuote(pLine, max);
      if ((cnt > 2) && m_realName.IsEmpty()) {
        m_realName.Append(pLine + 1, cnt - 2);
      }
      pLine += cnt;
      max -= cnt;
      pStart = pLine;
      tCnt = 0;
    }
    else if (*pLine == '<') {
      if (tCnt && !endCollect) {
        str.Trim(kWhitespace);
        if (!str.IsEmpty())
          str.Append(" ", 1);
        str.Append(pStart, tCnt);
      }
      cnt = nsEudoraAddress::CountAngle(pLine, max);
      if ((cnt > 2) && m_email.IsEmpty()) {
        m_email.Append(pLine + 1, cnt - 2);
      }
      pLine += cnt;
      max -= cnt;
      pStart = pLine;
      tCnt = 0;
      endCollect = true;
    }
    else if (*pLine == '(') {
      if (tCnt && !endCollect) {
        str.Trim(kWhitespace);
        if (!str.IsEmpty())
          str.Append(" ", 1);
        str.Append(pStart, tCnt);
      }
      cnt = nsEudoraAddress::CountComment(pLine, max);
      if (cnt > 2) {
        if (!m_realName.IsEmpty() && m_nickName.IsEmpty())
          m_nickName = m_realName;
        m_realName.Truncate();
        m_realName.Append(pLine + 1, cnt - 2);
      }
      pLine += cnt;
      max -= cnt;
      pStart = pLine;
      tCnt = 0;
    }
    else {
      tCnt++;
      pLine++;
      max--;
    }
  }

  if (tCnt) {
    str.Trim(kWhitespace);
    if (!str.IsEmpty())
      str.Append(" ", 1);
    str.Append(pStart, tCnt);
  }

  str.Trim(kWhitespace);

  if (!m_realName.IsEmpty() && !m_email.IsEmpty())
    return true;

  // now we should have a string with any remaining non-delimitted text
  // we assume that the last token is the email
  // anything before that is realName
  if (!m_email.IsEmpty()) {
    m_realName = str;
    return true;
  }

  tCnt = str.RFindChar(' ');
  if (tCnt == -1) {
    if (!str.IsEmpty()) {
      m_email = str;
      return true;
    }
    return false;
  }

  m_email = Substring(str, tCnt + 1);
  m_realName = StringHead(str, tCnt);
  m_realName.Trim(kWhitespace);
  m_email.Trim(kWhitespace);

  return !m_email.IsEmpty();
}
Exemple #11
0
nsresult nsEudoraWin32::GetAttachmentInfo( const char *pFileName, nsIFile *pFile, nsCString& mimeType, nsCString& aAttachmentName)
{
  nsresult  rv;
  mimeType.Truncate();
  nsCOMPtr <nsILocalFile> pLocalFile = do_QueryInterface(pFile, &rv);
  NS_ENSURE_SUCCESS(rv, rv);
  pLocalFile->InitWithNativePath(nsDependentCString(pFileName));
  bool      isFile = false;
  bool      exists = false;
  if (NS_FAILED( rv = pFile->Exists( &exists)))
    return( rv);
  if ( exists && NS_FAILED( rv = pFile->IsFile(&isFile) ) )
    return( rv);

  if (!exists || !isFile)
  {
    // Windows Eudora writes the full path to the attachment when the message
    // is received, but doesn't update that path if the attachment directory
    // changes (e.g. if email directory is moved). When operating on an
    // attachment (opening, etc.) Eudora will first check the full path
    // and then if the file doesn't exist there Eudora will check the
    // current attachment directory for a file with the same name.
    //
    // Check to see if we have any better luck looking for the attachment
    // in the current attachment directory.
    nsCAutoString name;
    pFile->GetNativeLeafName(name);
    if (name.IsEmpty())
      return( NS_ERROR_FAILURE);

    nsCOMPtr <nsIFile> altFile;
    rv = m_mailImportLocation->Clone(getter_AddRefs(altFile));
    NS_ENSURE_SUCCESS(rv, rv);
    // For now, we'll do that using a hard coded name and location for the
    // attachment directory on Windows (the default location) "attach" inside
    // of the Eudora mail directory. Once settings from Eudora are imported
    // better, we'll want to check where the settings say attachments are stored.
    altFile->AppendNative(NS_LITERAL_CSTRING("attach"));
    altFile->AppendNative(name);

    // Did we come up with a different path or was the original path already
    // in the current attachment directory?
    bool    isSamePath = true;
    rv = altFile->Equals(pFile, &isSamePath);

    if (NS_SUCCEEDED(rv) && !isSamePath)
    {
      // We came up with a different path - check the new path.
      if (NS_FAILED( rv = altFile->Exists( &exists)))
        return( rv);
      if ( exists && NS_FAILED( rv = altFile->IsFile( &isFile) ) )
        return( rv);

      // Keep the new path if it helped us.
      if (exists && isFile)
      {
        nsCString   nativePath;
        altFile->GetNativePath(nativePath);
        pLocalFile->InitWithNativePath(nativePath);
      }
    }
  }

  if (exists && isFile)
  {
    nsCAutoString name;
    pFile->GetNativeLeafName(name);
    if (name.IsEmpty())
      return( NS_ERROR_FAILURE);
    if (name.Length() > 4)
    {
      nsCString ext;
      PRInt32 idx = name.RFindChar( '.');
      if (idx != -1)
      {
        ext = Substring(name, idx);
        GetMimeTypeFromExtension(ext, mimeType);
      }
    }
    if (mimeType.IsEmpty())
      mimeType = "application/octet-stream";

    nsAutoString description;
    rv = NS_CopyNativeToUnicode(name, description);
 
    if (NS_SUCCEEDED(rv))
      aAttachmentName = NS_ConvertUTF16toUTF8(description);
    else
      aAttachmentName = name;

    return( NS_OK);
  }

  return( NS_ERROR_FAILURE);
}
static inline bool
IsEndOfMessage(const nsCString &aLine)
{
  return aLine.Equals(".");
}
static inline bool
IsEndOfHeaders(const nsCString &aLine)
{
  return aLine.IsEmpty();
}
Exemple #14
0
void PyXPCOM_Log(const char *level, const nsCString &msg)
{
	DoLogMessage(level, msg.get());
}
Exemple #15
0
void
gfxFT2FontList::AppendFacesFromFontFile(nsCString& aFileName,
                                        bool aStdFile,
                                        FontNameCache *aCache)
{
    nsCString faceList;
    uint32_t filesize = 0, timestamp = 0;
    if (aCache) {
        aCache->GetInfoForFile(aFileName, faceList, &timestamp, &filesize);
    }

    struct stat s;
    int statRetval = stat(aFileName.get(), &s);
    if (!faceList.IsEmpty() && 0 == statRetval &&
        s.st_mtime == timestamp && s.st_size == filesize)
    {
        LOG(("using cached font info for %s", aFileName.get()));
        AppendFacesFromCachedFaceList(aFileName, aStdFile, faceList);
        return;
    }

#ifdef XP_WIN
    FT_Library ftLibrary = gfxWindowsPlatform::GetPlatform()->GetFTLibrary();
#elif defined(ANDROID)
    FT_Library ftLibrary = gfxAndroidPlatform::GetPlatform()->GetFTLibrary();
#endif
    FT_Face dummy;
    if (FT_Err_Ok == FT_New_Face(ftLibrary, aFileName.get(), -1, &dummy)) {
        LOG(("reading font info via FreeType for %s", aFileName.get()));
        nsCString faceList;
        timestamp = s.st_mtime;
        filesize = s.st_size;
        for (FT_Long i = 0; i < dummy->num_faces; i++) {
            FT_Face face;
            if (FT_Err_Ok != FT_New_Face(ftLibrary, aFileName.get(), i, &face)) {
                continue;
            }
            if (FT_Err_Ok != FT_Select_Charmap(face, FT_ENCODING_UNICODE)) {
                FT_Done_Face(face);
                continue;
            }
            FT2FontEntry* fe =
                CreateNamedFontEntry(face, aFileName.get(), i);
            if (fe) {
                NS_ConvertUTF8toUTF16 name(face->family_name);
                BuildKeyNameFromFontName(name);       
                gfxFontFamily *family = mFontFamilies.GetWeak(name);
                if (!family) {
                    family = new FT2FontFamily(name);
                    mFontFamilies.Put(name, family);
                    if (mBadUnderlineFamilyNames.Contains(name)) {
                        family->SetBadUnderlineFamily();
                    }
                }
                fe->mStandardFace = aStdFile;
                family->AddFontEntry(fe);

                // this depends on the entry having been added to its family
                fe->CheckForBrokenFont();

                AppendToFaceList(faceList, name, fe);
#ifdef PR_LOGGING
                if (LOG_ENABLED()) {
                    LOG(("(fontinit) added (%s) to family (%s)"
                         " with style: %s weight: %d stretch: %d",
                         NS_ConvertUTF16toUTF8(fe->Name()).get(), 
                         NS_ConvertUTF16toUTF8(family->Name()).get(), 
                         fe->IsItalic() ? "italic" : "normal",
                         fe->Weight(), fe->Stretch()));
                }
#endif
            }
        }
        FT_Done_Face(dummy);
        if (aCache && 0 == statRetval && !faceList.IsEmpty()) {
            aCache->CacheFileInfo(aFileName, faceList, timestamp, filesize);
        }
    }
}
Exemple #16
0
NS_IMETHODIMP
PicoCallbackRunnable::Run()
{
  MOZ_ASSERT(!NS_IsMainThread());
  PicoApi::pico_Status status = 0;

  if (mService->CurrentVoice() != mVoice) {
    mService->LoadEngine(mVoice);
  } else {
    status = sPicoApi.pico_resetEngine(mService->mPicoEngine, PICO_RESET_SOFT);
    PICO_ENSURE_SUCCESS("pico_unloadResource", status, NS_ERROR_FAILURE);
  }

  // Add SSML markup for pitch and rate. Pico uses a minimal parser,
  // so no namespace is needed.
  nsPrintfCString markedUpText(
    "<pitch level=\"%0.0f\"><speed level=\"%0.0f\">%s</speed></pitch>",
    std::min(std::max(50.0f, mPitch * 100), 200.0f),
    std::min(std::max(20.0f, mRate * 100), 500.0f),
    mText.get());

  const char* text = markedUpText.get();
  size_t buffer_size = 512, buffer_offset = 0;
  RefPtr<SharedBuffer> buffer = SharedBuffer::Create(buffer_size);
  int16_t text_offset = 0, bytes_recv = 0, bytes_sent = 0, out_data_type = 0;
  int16_t text_remaining = markedUpText.Length() + 1;

  // Run this loop while this is the current task
  while (IsCurrentTask()) {
    if (text_remaining) {
      status = sPicoApi.pico_putTextUtf8(mService->mPicoEngine,
                                         text + text_offset, text_remaining,
                                         &bytes_sent);
      PICO_ENSURE_SUCCESS("pico_putTextUtf8", status, NS_ERROR_FAILURE);
      // XXX: End speech task on error
      text_remaining -= bytes_sent;
      text_offset += bytes_sent;
    } else {
      // If we already fed all the text to the engine, send a zero length buffer
      // and quit.
      DispatchSynthDataRunnable(already_AddRefed<SharedBuffer>(), 0);
      break;
    }

    do {
      // Run this loop while the result of getData is STEP_BUSY, when it finishes
      // synthesizing audio for the given text, it returns STEP_IDLE. We then
      // break to the outer loop and feed more text, if there is any left.
      if (!IsCurrentTask()) {
        // If the task has changed, quit.
        break;
      }

      if (buffer_size - buffer_offset < PICO_MAX_CHUNK_SIZE) {
        // The next audio chunk retrieved may be bigger than our buffer,
        // so send the data and flush the buffer.
        DispatchSynthDataRunnable(buffer.forget(), buffer_offset);
        buffer_offset = 0;
        buffer = SharedBuffer::Create(buffer_size);
      }

      status = sPicoApi.pico_getData(mService->mPicoEngine,
                                     (uint8_t*)buffer->Data() + buffer_offset,
                                     PICO_MAX_CHUNK_SIZE,
                                     &bytes_recv, &out_data_type);
      PICO_ENSURE_SUCCESS("pico_getData", status, NS_ERROR_FAILURE);
      buffer_offset += bytes_recv;
    } while (status == PICO_STEP_BUSY);
  }

  return NS_OK;
}
Exemple #17
0
void
HttpChannelChild::OnTransportAndData(const nsresult& status,
                                     const PRUint64 progress,
                                     const PRUint64& progressMax,
                                     const nsCString& data,
                                     const PRUint32& offset,
                                     const PRUint32& count)
{
    LOG(("HttpChannelChild::OnTransportAndData [this=%x]\n", this));

    if (mCanceled)
        return;

    // cache the progress sink so we don't have to query for it each time.
    if (!mProgressSink)
        GetCallback(mProgressSink);

    // Hold queue lock throughout all three calls, else we might process a later
    // necko msg in between them.
    AutoEventEnqueuer ensureSerialDispatch(this);

    // block status/progress after Cancel or OnStopRequest has been called,
    // or if channel has LOAD_BACKGROUND set.
    // - JDUELL: may not need mStatus/mIsPending checks, given this is always called
    //   during OnDataAvailable, and we've already checked mCanceled.  Code
    //   dupe'd from nsHttpChannel
    if (mProgressSink && NS_SUCCEEDED(mStatus) && mIsPending &&
            !(mLoadFlags & LOAD_BACKGROUND))
    {
        // OnStatus
        //
        NS_ASSERTION(status == nsISocketTransport::STATUS_RECEIVING_FROM ||
                     status == nsITransport::STATUS_READING,
                     "unexpected status code");

        nsCAutoString host;
        mURI->GetHost(host);
        mProgressSink->OnStatus(this, nsnull, status,
                                NS_ConvertUTF8toUTF16(host).get());
        // OnProgress
        //
        if (progress > 0) {
            NS_ASSERTION(progress <= progressMax, "unexpected progress values");
            mProgressSink->OnProgress(this, nsnull, progress, progressMax);
        }
    }

    // OnDataAvailable
    //
    // NOTE: the OnDataAvailable contract requires the client to read all the data
    // in the inputstream.  This code relies on that ('data' will go away after
    // this function).  Apparently the previous, non-e10s behavior was to actually
    // support only reading part of the data, allowing later calls to read the
    // rest.
    nsCOMPtr<nsIInputStream> stringStream;
    nsresult rv = NS_NewByteInputStream(getter_AddRefs(stringStream), data.get(),
                                        count, NS_ASSIGNMENT_DEPEND);
    if (NS_FAILED(rv)) {
        Cancel(rv);
        return;
    }

    rv = mListener->OnDataAvailable(this, mListenerContext,
                                    stringStream, offset, count);
    stringStream->Close();
    if (NS_FAILED(rv)) {
        Cancel(rv);
    }
}
Exemple #18
0
// use the flagState to determine if the gaps in the msgUids correspond to gaps in the mailbox,
// in which case we can still use ranges. If flagState is null, we won't do this.
void AllocateImapUidString(PRUint32 *msgUids, PRUint32 &msgCount, 
                           nsImapFlagAndUidState *flagState, nsCString &returnString)
{
  PRUint32 startSequence = (msgCount > 0) ? msgUids[0] : 0xFFFFFFFF;
  PRUint32 curSequenceEnd = startSequence;
  PRUint32 total = msgCount;
  PRInt32  curFlagStateIndex = -1;

  // a partial fetch flag state doesn't help us, so don't use it.
  if (flagState && flagState->GetPartialUIDFetch())
    flagState = nsnull;

  
  for (PRUint32 keyIndex = 0; keyIndex < total; keyIndex++)
  {
    PRUint32 curKey = msgUids[keyIndex];
    PRUint32 nextKey = (keyIndex + 1 < total) ? msgUids[keyIndex + 1] : 0xFFFFFFFF;
    bool lastKey = (nextKey == 0xFFFFFFFF);

    if (lastKey)
      curSequenceEnd = curKey;

    if (!lastKey)
    {
      if (nextKey == curSequenceEnd + 1)
      {
        curSequenceEnd = nextKey;
        curFlagStateIndex++;
        continue;
      }
      if (flagState)
      {
        if (curFlagStateIndex == -1)
        {
          bool foundIt;
          flagState->GetMessageFlagsFromUID(curSequenceEnd, &foundIt, &curFlagStateIndex);
          if (!foundIt)
          {
            NS_WARNING("flag state missing key");
            // The start of this sequence is missing from flag state, so move
            // on to the next key.
            curFlagStateIndex = -1;
            curSequenceEnd = startSequence = nextKey;
            continue;
          }
        }
        curFlagStateIndex++;
        PRUint32 nextUidInFlagState;
        nsresult rv = flagState->GetUidOfMessage(curFlagStateIndex, &nextUidInFlagState);
        if (NS_SUCCEEDED(rv) && nextUidInFlagState == nextKey)
        {
          curSequenceEnd = nextKey;
          continue;
        }
      }
    }
    if (curSequenceEnd > startSequence)
    {
      returnString.AppendInt((PRInt64) startSequence);
      returnString += ':';
      returnString.AppendInt((PRInt64) curSequenceEnd);
      startSequence = nextKey;
      curSequenceEnd = startSequence;
      curFlagStateIndex = -1;
    }
    else
    {
      startSequence = nextKey;
      curSequenceEnd = startSequence;
      returnString.AppendInt((PRInt64) msgUids[keyIndex]);
      curFlagStateIndex = -1;
    }
    // check if we've generated too long a string - if there's no flag state,
    // it means we just need to go ahead and generate a too long string
    // because the calling code won't handle breaking up the strings.
    if (flagState && returnString.Length() > 950) 
    {
      msgCount = keyIndex;
      break;
    }
    // If we are not the last item then we need to add the comma 
    // but it's important we do it here, after the length check 
    if (!lastKey) 
      returnString += ','; 
  }
}
nsresult
PendingLookup::OnStopRequestInternal(nsIRequest *aRequest,
                                     nsISupports *aContext,
                                     nsresult aResult,
                                     bool* aShouldBlock) {
  if (NS_FAILED(aResult)) {
    Accumulate(mozilla::Telemetry::APPLICATION_REPUTATION_SERVER,
      SERVER_RESPONSE_FAILED);
    return aResult;
  }

  *aShouldBlock = false;
  nsresult rv;
  nsCOMPtr<nsIHttpChannel> channel = do_QueryInterface(aRequest, &rv);
  if (NS_FAILED(rv)) {
    Accumulate(mozilla::Telemetry::APPLICATION_REPUTATION_SERVER,
      SERVER_RESPONSE_FAILED);
    return rv;
  }

  uint32_t status = 0;
  rv = channel->GetResponseStatus(&status);
  if (NS_FAILED(rv)) {
    Accumulate(mozilla::Telemetry::APPLICATION_REPUTATION_SERVER,
      SERVER_RESPONSE_FAILED);
    return rv;
  }

  if (status != 200) {
    Accumulate(mozilla::Telemetry::APPLICATION_REPUTATION_SERVER,
      SERVER_RESPONSE_FAILED);
    return NS_ERROR_NOT_AVAILABLE;
  }

  std::string buf(mResponse.Data(), mResponse.Length());
  safe_browsing::ClientDownloadResponse response;
  if (!response.ParseFromString(buf)) {
    LOG(("Invalid protocol buffer response [this = %p]: %s", this, buf.c_str()));
    Accumulate(mozilla::Telemetry::APPLICATION_REPUTATION_SERVER,
                                   SERVER_RESPONSE_INVALID);
    return NS_ERROR_CANNOT_CONVERT_DATA;
  }

  // There are several more verdicts, but we only respect DANGEROUS and
  // DANGEROUS_HOST for now and treat everything else as SAFE.
  Accumulate(mozilla::Telemetry::APPLICATION_REPUTATION_SERVER,
    SERVER_RESPONSE_VALID);
  // Clamp responses 0-7, we only know about 0-4 for now.
  Accumulate(mozilla::Telemetry::APPLICATION_REPUTATION_SERVER_VERDICT,
    std::min<uint32_t>(response.verdict(), 7));
  switch(response.verdict()) {
    case safe_browsing::ClientDownloadResponse::DANGEROUS:
    case safe_browsing::ClientDownloadResponse::DANGEROUS_HOST:
      *aShouldBlock = true;
      break;
    default:
      break;
  }

  return NS_OK;
}
Exemple #20
0
void AppendUid(nsCString &msgIds, PRUint32 uid)
{
  char buf[20];
  PR_snprintf(buf, sizeof(buf), "%u", uid);
  msgIds.Append(buf);
}
static nsresult
SplitURL(nsIURI *aChromeURI, nsCString& aPackage, nsCString& aProvider, nsCString& aFile,
         PRBool *aModified = nsnull)
{
  // Splits a "chrome:" URL into its package, provider, and file parts.
  // Here are the current portions of a
  // chrome: url that make up the chrome-
  //
  //     chrome://global/skin/foo?bar
  //     \------/ \----/\---/ \-----/
  //         |       |     |     |
  //         |       |     |     `-- RemainingPortion
  //         |       |     |
  //         |       |     `-- Provider
  //         |       |
  //         |       `-- Package
  //         |
  //         `-- Always "chrome://"
  //
  //

  nsresult rv;

  nsCAutoString str;
  rv = aChromeURI->GetSpec(str);
  if (NS_FAILED(rv)) return rv;

  // We only want to deal with "chrome:" URLs here. We could return
  // an error code if the URL isn't properly prefixed here...
  if (PL_strncmp(str.get(), kChromePrefix, sizeof(kChromePrefix) - 1) != 0)
    return NS_ERROR_INVALID_ARG;

  // Cull out the "package" string; e.g., "navigator"
  aPackage = str.get() + sizeof(kChromePrefix) - 1;

  PRInt32 idx;
  idx = aPackage.FindChar('/');
  if (idx < 0)
    return NS_OK;

  // Cull out the "provider" string; e.g., "content"
  aPackage.Right(aProvider, aPackage.Length() - (idx + 1));
  aPackage.Truncate(idx);

  idx = aProvider.FindChar('/');
  if (idx < 0) {
    // Force the provider to end with a '/'
    idx = aProvider.Length();
    aProvider.Append('/');
  }

  // Cull out the "file"; e.g., "navigator.xul"
  aProvider.Right(aFile, aProvider.Length() - (idx + 1));
  aProvider.Truncate(idx);

  PRBool nofile = aFile.IsEmpty();
  if (nofile) {
    // If there is no file, then construct the default file
    aFile = aPackage;

    if (aProvider.Equals("content")) {
      aFile += ".xul";
    }
    else if (aProvider.Equals("skin")) {
      aFile += ".css";
    }
    else if (aProvider.Equals("locale")) {
      aFile += ".dtd";
    }
    else {
      NS_ERROR("unknown provider");
      return NS_ERROR_FAILURE;
    }
  } else {
    // Protect against URIs containing .. that reach up out of the
    // chrome directory to grant chrome privileges to non-chrome files.
    int depth = 0;
    PRBool sawSlash = PR_TRUE;  // .. at the beginning is suspect as well as /..
    for (const char* p=aFile.get(); *p; p++) {
      if (sawSlash) {
        if (p[0] == '.' && p[1] == '.'){
          depth--;    // we have /.., decrement depth.
        } else {
          static const char escape[] = "%2E%2E";
          if (PL_strncasecmp(p, escape, sizeof(escape)-1) == 0)
            depth--;   // we have the HTML-escaped form of /.., decrement depth.
        }
      } else if (p[0] != '/') {
        depth++;        // we have /x for some x that is not /
      }
      sawSlash = (p[0] == '/');

      if (depth < 0) {
        return NS_ERROR_FAILURE;
      }
    }
  }
  if (aModified)
    *aModified = nofile;
  return NS_OK;
}
Exemple #22
0
nsHtml5Parser::GetCommand(nsCString& aCommand)
{
  aCommand.Assign("view");
}
Exemple #23
0
nsresult
nsDataHandler::ParseURI(nsCString& spec,
                        nsCString& contentType,
                        nsCString& contentCharset,
                        bool&    isBase64,
                        nsCString& dataBuffer,
                        nsCString& hashRef) {
    isBase64 = false;

    // move past "data:"
    char *buffer = (char *) PL_strcasestr(spec.BeginWriting(), "data:");
    if (!buffer) {
        // malformed uri
        return NS_ERROR_MALFORMED_URI;
    }
    buffer += 5;

    // First, find the start of the data
    char *comma = strchr(buffer, ',');
    if (!comma)
        return NS_ERROR_MALFORMED_URI;

    *comma = '\0';

    // determine if the data is base64 encoded.
    char *base64 = PL_strcasestr(buffer, BASE64_EXTENSION);
    if (base64) {
        char *beyond = base64 + strlen(BASE64_EXTENSION);
        // per the RFC 2397 grammar, "base64" MUST be followed by a comma
        // previously substituted by '\0', but we also allow it in between
        // parameters so a subsequent ";" is ok as well (this deals with
        // *broken* data URIs, see bug 781693 for an example)
        if (*beyond == '\0' || *beyond == ';') {
            isBase64 = true;
            *base64 = '\0';
        }
    }

    if (comma == buffer) {
        // nothing but data
        contentType.AssignLiteral("text/plain");
        contentCharset.AssignLiteral("US-ASCII");
    } else {
        // everything else is content type
        char *semiColon = (char *) strchr(buffer, ';');
        if (semiColon)
            *semiColon = '\0';
        
        if (semiColon == buffer || base64 == buffer) {
            // there is no content type, but there are other parameters
            contentType.AssignLiteral("text/plain");
        } else {
            contentType = buffer;
            ToLowerCase(contentType);
        }

        if (semiColon) {
            char *charset = PL_strcasestr(semiColon + 1, "charset=");
            if (charset)
                contentCharset = charset + sizeof("charset=") - 1;

            *semiColon = ';';
        }
    }

    *comma = ',';
    if (isBase64)
        *base64 = ';';

    contentType.StripWhitespace();
    contentCharset.StripWhitespace();

    // Split encoded data from terminal "#ref" (if present)
    char *data = comma + 1;
    char *hash = strchr(data, '#');
    if (!hash) {
        dataBuffer.Assign(data);
        hashRef.Truncate();
    } else {
        dataBuffer.Assign(data, hash - data);
        hashRef.Assign(hash);
    }

    return NS_OK;
}
bool
TCPSocketParent::RecvOpenBind(const nsCString& aRemoteHost,
                              const uint16_t& aRemotePort,
                              const nsCString& aLocalAddr,
                              const uint16_t& aLocalPort,
                              const bool&     aUseSSL,
                              const bool&     aUseArrayBuffers,
                              const nsCString& aFilter)
{
  if (net::UsingNeckoIPCSecurity() &&
      !AssertAppProcessPermission(Manager()->Manager(), "tcp-socket")) {
    FireInteralError(this, __LINE__);
    return true;
  }

  nsresult rv;
  nsCOMPtr<nsISocketTransportService> sts =
    do_GetService("@mozilla.org/network/socket-transport-service;1", &rv);
  if (NS_FAILED(rv)) {
    FireInteralError(this, __LINE__);
    return true;
  }

  nsCOMPtr<nsISocketTransport> socketTransport;
  rv = sts->CreateTransport(nullptr, 0,
                            aRemoteHost, aRemotePort,
                            nullptr, getter_AddRefs(socketTransport));
  if (NS_FAILED(rv)) {
    FireInteralError(this, __LINE__);
    return true;
  }

  PRNetAddr prAddr;
  if (PR_SUCCESS != PR_InitializeNetAddr(PR_IpAddrAny, aLocalPort, &prAddr)) {
    FireInteralError(this, __LINE__);
    return true;
  }
  if (PR_SUCCESS != PR_StringToNetAddr(aLocalAddr.BeginReading(), &prAddr)) {
    FireInteralError(this, __LINE__);
    return true;
  }

  mozilla::net::NetAddr addr;
  PRNetAddrToNetAddr(&prAddr, &addr);
  rv = socketTransport->Bind(&addr);
  if (NS_FAILED(rv)) {
    FireInteralError(this, __LINE__);
    return true;
  }

  if (!aFilter.IsEmpty()) {
    nsAutoCString contractId(NS_NETWORK_TCP_SOCKET_FILTER_HANDLER_PREFIX);
    contractId.Append(aFilter);
    nsCOMPtr<nsISocketFilterHandler> filterHandler =
      do_GetService(contractId.get());
    if (!filterHandler) {
      NS_ERROR("Content doesn't have a valid filter");
      FireInteralError(this, __LINE__);
      return true;
    }
    rv = filterHandler->NewFilter(getter_AddRefs(mFilter));
    if (NS_FAILED(rv)) {
      NS_ERROR("Cannot create filter that content specified");
      FireInteralError(this, __LINE__);
      return true;
    }
  }

  // Obtain App ID
  uint32_t appId = nsIScriptSecurityManager::NO_APP_ID;
  bool     inIsolatedMozBrowser = false;
  const PContentParent *content = Manager()->Manager();
  if (PBrowserParent* browser = SingleManagedOrNull(content->ManagedPBrowserParent())) {
    // appId's are for B2G only currently, where managees.Count() == 1
    // This is not guaranteed currently in Desktop, so skip this there.
    TabParent *tab = TabParent::GetFrom(browser);
    appId = tab->OwnAppId();
    inIsolatedMozBrowser = tab->IsIsolatedMozBrowserElement();
  }

  mSocket = new TCPSocket(nullptr, NS_ConvertUTF8toUTF16(aRemoteHost), aRemotePort, aUseSSL, aUseArrayBuffers);
  mSocket->SetAppIdAndBrowser(appId, inIsolatedMozBrowser);
  mSocket->SetSocketBridgeParent(this);
  rv = mSocket->InitWithUnconnectedTransport(socketTransport);
  NS_ENSURE_SUCCESS(rv, true);
  return true;
}
/**
 * Read content of file or create file list from directory
 * @param aBuf read destination buffer
 * @param aCount length of destination buffer
 * @param aCountRead number of read characters
 * @return NS_OK when read successfully, NS_BASE_STREAM_CLOSED when end of file,
 *         error code otherwise
 */
nsresult
nsGIOInputStream::DoRead(char *aBuf, uint32_t aCount, uint32_t *aCountRead)
{
  nsresult rv = NS_ERROR_NOT_AVAILABLE;
  if (mStream) {
    // file read
    GError *error = NULL;    
    uint32_t bytes_read = g_input_stream_read(G_INPUT_STREAM(mStream),
                                              aBuf,
                                              aCount,
                                              NULL,
                                              &error);
    if (error) {
      rv = MapGIOResult(error);
      *aCountRead = 0;
      g_warning("Cannot read from file: %s", error->message);
      g_error_free(error);
      return rv;
    }
    *aCountRead = bytes_read;
    mBytesRemaining -= *aCountRead;
    return NS_OK;
  }
  else if (mDirOpen) {
    // directory read
    while (aCount && rv != NS_BASE_STREAM_CLOSED)
    {
      // Copy data out of our buffer
      uint32_t bufLen = mDirBuf.Length() - mDirBufCursor;
      if (bufLen)
      {
        uint32_t n = NS_MIN(bufLen, aCount);
        memcpy(aBuf, mDirBuf.get() + mDirBufCursor, n);
        *aCountRead += n;
        aBuf += n;
        aCount -= n;
        mDirBufCursor += n;
      }

      if (!mDirListPtr)    // Are we at the end of the directory list?
      {
        rv = NS_BASE_STREAM_CLOSED;
      }
      else if (aCount)     // Do we need more data?
      {
        GFileInfo *info = (GFileInfo *) mDirListPtr->data;

        // Prune '.' and '..' from directory listing.
        const char * fname = g_file_info_get_name(info);
        if (fname && fname[0] == '.' && 
            (fname[1] == '\0' || (fname[1] == '.' && fname[2] == '\0')))
        {
          mDirListPtr = mDirListPtr->next;
          continue;
        }

        mDirBuf.Assign("201: ");

        // The "filename" field
        nsCString escName;
        nsCOMPtr<nsINetUtil> nu = do_GetService(NS_NETUTIL_CONTRACTID);
        if (nu && fname) {
          nu->EscapeString(nsDependentCString(fname),
                           nsINetUtil::ESCAPE_URL_PATH, escName);

          mDirBuf.Append(escName);
          mDirBuf.Append(' ');
        }

        // The "content-length" field
        // XXX truncates size from 64-bit to 32-bit
        mDirBuf.AppendInt(int32_t(g_file_info_get_size(info)));
        mDirBuf.Append(' ');

        // The "last-modified" field
        //
        // NSPR promises: PRTime is compatible with time_t
        // we just need to convert from seconds to microseconds
        GTimeVal gtime;
        g_file_info_get_modification_time(info, &gtime);

        PRExplodedTime tm;
        PRTime pt = ((PRTime) gtime.tv_sec) * 1000000;
        PR_ExplodeTime(pt, PR_GMTParameters, &tm);
        {
          char buf[64];
          PR_FormatTimeUSEnglish(buf, sizeof(buf),
              "%a,%%20%d%%20%b%%20%Y%%20%H:%M:%S%%20GMT ", &tm);
          mDirBuf.Append(buf);
        }

        // The "file-type" field
        switch (g_file_info_get_file_type(info))
        {
          case G_FILE_TYPE_REGULAR:
            mDirBuf.Append("FILE ");
            break;
          case G_FILE_TYPE_DIRECTORY:
            mDirBuf.Append("DIRECTORY ");
            break;
          case G_FILE_TYPE_SYMBOLIC_LINK:
            mDirBuf.Append("SYMBOLIC-LINK ");
            break;
          default:
            break;
        }
        mDirBuf.Append('\n');

        mDirBufCursor = 0;
        mDirListPtr = mDirListPtr->next;
      }
    }
  }
  return rv;
}
// short cut function for creating a mailto url...
nsresult NS_MsgBuildSmtpUrl(nsIFile * aFilePath,
                            const nsCString &aSmtpHostName,
                            PRInt32 aSmtpPort,
                            const nsCString &aSmtpUserName,
                            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....

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

  nsCAutoString urlSpec("smtp://");

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

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

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

  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);
}
  // Determine if this line meets Eudora standards for a separator line
  // This logic is based on Eudora 1.3.1's strict requirements for what
  // makes a valid separator line.  This may need to be relaxed for newer
  // versions of Eudora.
  // A sample from line:
  // From [email protected] Wed Jan 14 12:36:18 1989
int32_t  nsEudoraMailbox::IsEudoraFromSeparator(const char *pChar, int32_t maxLen, nsCString& defaultDate)
{
  if (maxLen < 12)
    return -1;

  int32_t    len = 0;
  if ((*pChar != 'F') || (*(pChar + 1) != 'r') || (*(pChar + 2) != 'o') || (*(pChar + 3) != 'm'))
    return -1;
  pChar += 4;
  len += 4;

  // According to Eudora the next char MUST be a space, and there can only be 1 space
  // before the return mail address.
  // I'll be nicer and allow any amount of whitespace
  while (((*pChar == ' ') || (*pChar == '\t')) && (len < maxLen)) {
    pChar++;
    len++;
  }
  if (len == maxLen)
    return -1;

  // Determine the length of the line
  int32_t      lineLen = len;
  const char *  pTok = pChar;
  // Skip to next end of line.
  while ((lineLen < maxLen) && (*pTok != nsCRT::CR) && (*pTok != nsCRT::LF)) {
    lineLen++;
    pTok++;
  }
  if (len >= lineLen)
    return -1;

  // Eudora allows the return address to be double quoted or not at all..
  // I'll allow single or double quote, but other than that, just skip
  // the return address until you hit a space char (I allow tab as well)
  char  quote = *pChar;
  if ((quote == '"') || (quote == '\'')) {
    pChar++;
    len++;
    while ((len < lineLen) && (*pChar != quote)) {
      pChar++;
      len++;
    }
    if (len == lineLen)
      return -1;
    len++;
    pChar++;
  }
  else {
    while ((len < lineLen) && (*pChar != ' ') && (*pChar != '\t')) {
      pChar++;
      len++;
    }
  }
  while (((*pChar == ' ') || (*pChar == '\t')) && (len < lineLen)) {
    pChar++;
    len++;
  }
  if (len == lineLen)
    return -1;

  // we've passed the address, now check for the remaining data
  // Now it gets really funky!
  // In no particular order, with token separators space, tab, comma, newline
  // a - the phrase "remote from", remote must be first, from is optional.  2 froms or 2 remotes fails
  // b - one and only one time value xx:xx or xx:xx:xx
  // c - one and only one day, 1 to 31
  // d - one and only one year, 2 digit anything or 4 digit > 1900
  // e - one and only one weekday, 3 letter abreviation
  // f - one and only one month, 3 letter abreviation
  // 2 allowable "other" tokens
  // to be valid, day, year, month, & tym must exist and other must be less than 3

  int    day = 0;
  int    month = 0;
  int    year = 0;
  int    weekDay = 0;
  int    other = 0;
  int    result;
  char  tymStr[9];  // Make it a null terminated string (used in PR_snprintf() call()).
  bool    tym = false;
  bool    remote = false;
  bool    from = false;
  int32_t  tokLen;
  int32_t  tokStart;
  int32_t  num;

  while ((len < lineLen) && (other < 3)) {
    pTok = pChar;
    tokStart = len;
    while ((len < lineLen) && (*pChar != ' ') && (*pChar != '\t') && (*pChar != ',')) {
      pChar++;
      len++;
    }
    tokLen = len - tokStart;
    if (tokLen) {
      num = AsciiToLong(pTok, tokLen);
      if ((tokLen == 3) && ((result = IsWeekDayStr(pTok)) != 0)) {
        if (weekDay)
          return -1;
        weekDay = result;
      }
      else if ((tokLen == 3) && ((result = IsMonthStr(pTok)) != 0)) {
        if (month)
          return -1;
        month = result;
      }
      else if ((tokLen == 6) && !PL_strncasecmp(pTok, "remote", 6)) {
        if (remote || from)
          return -1;
        remote = true;
      }
      else if ((tokLen == 4) && !PL_strncasecmp(pTok, "from", 4)) {
        if (!remote || from)
          return -1;
        from = true;
      }
      else if ((tokLen == 4) && ((num > 1900) || !strncmp(pTok, "0000", 4))) {
        if (year)
          return -1;
        year = (int)num;
        if (!year)
          year = 1900;
      }
      else if (!year && day && (tokLen == 2) && (*(pTok + 1) >= '0') && (*(pTok + 1) <= '9')) {
        if (num < 65)
          num += 1900;
        else
           num += 2000;
         year = (int) num;
      }
      else if ((tokLen <= 2) && (*pTok >= '0') && (*pTok <= '9')) {
        day = (int) num;
        if ((day < 1) || (day > 31))
          day = 1;
      }
      else if ((tokLen >= 5) && (pTok[2] == ':') && ((tokLen == 5) || ((tokLen == 8) && (pTok[5] == ':')))) {
        // looks like the tym...
        for (result = 0; result < (int)tokLen; result++) {
          if ((result != 2) && (result != 5)) {
            if ((pTok[result] < '0') || (pTok[result] > '9')) {
              break;
            }
          }
        }
        if (result == tokLen) {
          if (tym)
            return -1;
          tym = true;
          // for future use, get the time value
          memcpy(tymStr, pTok, tokLen);
          if (tokLen == 5) {
            tymStr[5] = ':';
            tymStr[6] = '0';
            tymStr[7] = '0';
          }
          tymStr[8] = 0;
        }
        else {
          other++;
        }
      }
      else
        other++;
    }
    // Skip the space chars...
    while ((len < lineLen) && ((*pChar == ' ') || (*pChar == '\t') || (*pChar == ','))) {
      pChar++;
      len++;
    }
  } // end while (len < lineLen) token loop

  // Now let's see what we found on the line
  if (day && year && month && tym && (other < 3)) {
    // Now we need to make sure the next line
    // isn't blank!
    while (len < lineLen) {
      len++;
      pChar++;
    }
    if (len == maxLen)
      return -1;

    if (*pChar == nsCRT::CR) {
      len++;
      pChar++;
      if (*pChar == nsCRT::LF) {
        len++;
        pChar++;
      }
    }
    else if (*pChar == nsCRT::LF) {
      len++;
      pChar++;
    }
    else
      return -1;

    if (len >= maxLen)
      return -1;

    while (len < maxLen) {
      if ((*pChar == nsCRT::CR) || (*pChar == nsCRT::LF))
        return -1;

      if ((*pChar != ' ') && (*pChar != '\t'))
        break;

      pChar++;
      len++;
    }

    // Whew!, the next line isn't blank.
    // Generate the default date header in case the date header is missing when we
    // write out headers later. The header looks like "Date: Tue, 5 Feb 2002 23:05:04"
    char date_header_str[DATE_STR_LEN];
    PR_snprintf(date_header_str, DATE_STR_LEN, "Date: %s, %2d %s %4d %s", eudoraWeekDays[weekDay-1], day, eudoraMonths[month-1], year, tymStr);
    defaultDate.Assign(date_header_str);

    return lineLen;
  }

  return -1;
}
Exemple #28
0
static void
AppendToFaceList(nsCString& aFaceList,
                 nsAString& aFamilyName, FT2FontEntry* aFontEntry)
{
    aFaceList.Append(NS_ConvertUTF16toUTF8(aFamilyName));
    aFaceList.Append(',');
    aFaceList.Append(NS_ConvertUTF16toUTF8(aFontEntry->Name()));
    aFaceList.Append(',');
    aFaceList.AppendInt(aFontEntry->mFTFontIndex);
    aFaceList.Append(',');
    aFaceList.Append(aFontEntry->IsItalic() ? '1' : '0');
    aFaceList.Append(',');
    aFaceList.AppendInt(aFontEntry->Weight());
    aFaceList.Append(',');
    aFaceList.AppendInt(aFontEntry->Stretch());
    aFaceList.Append(',');
}
void
Http2Session::PrintDiagnostics(nsCString &log)
{
  log.AppendPrintf("     ::: HTTP2\n");
  log.AppendPrintf("     shouldgoaway = %d mClosed = %d CanReuse = %d nextID=0x%X\n",
                   mShouldGoAway, mClosed, CanReuse(), mNextStreamID);

  log.AppendPrintf("     concurrent = %d maxconcurrent = %d\n",
                   mConcurrent, mMaxConcurrent);

  log.AppendPrintf("     roomformorestreams = %d roomformoreconcurrent = %d\n",
                   RoomForMoreStreams(), RoomForMoreConcurrent());

  log.AppendPrintf("     transactionHashCount = %d streamIDHashCount = %d\n",
                   mStreamTransactionHash.Count(),
                   mStreamIDHash.Count());

  log.AppendPrintf("     Queued Stream Size = %d\n", mQueuedStreams.GetSize());

  PRIntervalTime now = PR_IntervalNow();
  log.AppendPrintf("     Ping Threshold = %ums\n",
                   PR_IntervalToMilliseconds(mPingThreshold));
  log.AppendPrintf("     Ping Timeout = %ums\n",
                   PR_IntervalToMilliseconds(gHttpHandler->SpdyPingTimeout()));
  log.AppendPrintf("     Idle for Any Activity (ping) = %ums\n",
                   PR_IntervalToMilliseconds(now - mLastReadEpoch));
  log.AppendPrintf("     Idle for Data Activity = %ums\n",
                   PR_IntervalToMilliseconds(now - mLastDataReadEpoch));
  if (mPingSentEpoch)
    log.AppendPrintf("     Ping Outstanding (ping) = %ums, expired = %d\n",
                     PR_IntervalToMilliseconds(now - mPingSentEpoch),
                     now - mPingSentEpoch >= gHttpHandler->SpdyPingTimeout());
  else
    log.AppendPrintf("     No Ping Outstanding\n");
}
Exemple #30
0
nsresult nsAbBoolExprToLDAPFilter::FilterCondition (
    nsIAbLDAPAttributeMap* map,
    nsIAbBooleanConditionString* condition,
    nsCString& filter,
    int flags)
{
    nsCString name;
    nsresult rv = condition->GetName(getter_Copies (name));
    NS_ENSURE_SUCCESS(rv, rv);

    nsCAutoString ldapAttr(name);
    if (flags & TRANSLATE_CARD_PROPERTY)
    {
        rv = map->GetFirstAttribute (name, ldapAttr);
        if (!(flags & ALLOW_NON_CONVERTABLE_CARD_PROPERTY) && 
            !ATTRMAP_FOUND_ATTR(rv, ldapAttr))
            return NS_OK;
    }

    nsAbBooleanConditionType conditionType;
    rv = condition->GetCondition(&conditionType);
    NS_ENSURE_SUCCESS(rv, rv);

    nsString value;
    rv = condition->GetValue (getter_Copies (value));
    NS_ENSURE_SUCCESS(rv, rv);
    NS_ConvertUTF16toUTF8 vUTF8 (value);

    switch (conditionType)
    {
        case nsIAbBooleanConditionTypes::DoesNotExist:
            filter.AppendLiteral("(!("); 
            filter.Append(ldapAttr);
            filter.AppendLiteral("=*))");
            break;
        case nsIAbBooleanConditionTypes::Exists:
            filter.AppendLiteral("("); 
            filter.Append(ldapAttr);
            filter.AppendLiteral("=*)");
            break;
        case nsIAbBooleanConditionTypes::Contains:
            filter.AppendLiteral("(");
            filter.Append(ldapAttr);
            filter.Append("=*");
            filter.Append(vUTF8);
            filter.AppendLiteral("*)");
            break;
        case nsIAbBooleanConditionTypes::DoesNotContain:
            filter.AppendLiteral("(!(");
            filter.Append(ldapAttr);
            filter.AppendLiteral("=*");
            filter.Append(vUTF8);
            filter.AppendLiteral("*))");
            break;
        case nsIAbBooleanConditionTypes::Is:
            filter.AppendLiteral("(");
            filter.Append(ldapAttr);
            filter.AppendLiteral("=");
            filter.Append(vUTF8);
            filter.AppendLiteral(")");
            break;
        case nsIAbBooleanConditionTypes::IsNot:
            filter.AppendLiteral("(!(");
            filter.Append(ldapAttr);
            filter.AppendLiteral("=");
            filter.Append(vUTF8);
            filter.AppendLiteral("))");
            break;
        case nsIAbBooleanConditionTypes::BeginsWith:
            filter.AppendLiteral("(");
            filter.Append(ldapAttr);
            filter.AppendLiteral("=");
            filter.Append(vUTF8);
            filter.AppendLiteral("*)");
            break;
        case nsIAbBooleanConditionTypes::EndsWith:
            filter.AppendLiteral("(");
            filter.Append(ldapAttr);
            filter.AppendLiteral("=*");
            filter.Append(vUTF8);
            filter.AppendLiteral(")");
            break;
        case nsIAbBooleanConditionTypes::LessThan:
            filter.AppendLiteral("(");
            filter.Append(ldapAttr);
            filter.AppendLiteral("<=");
            filter.Append(vUTF8);
            filter.AppendLiteral(")");
            break;
        case nsIAbBooleanConditionTypes::GreaterThan:
            filter.AppendLiteral("(");
            filter.Append(ldapAttr);
            filter.AppendLiteral(">=");
            filter.Append(vUTF8);
            filter.AppendLiteral(")");
            break;
        case nsIAbBooleanConditionTypes::SoundsLike:
            filter.AppendLiteral("(");
            filter.Append(ldapAttr);
            filter.AppendLiteral("~=");
            filter.Append(vUTF8);
            filter.AppendLiteral(")");
            break;
        case nsIAbBooleanConditionTypes::RegExp:
            break;
        default:
            break;
    }

    return rv;
}