Ejemplo n.º 1
0
/* readonly attribute AUTF8String address; */
NS_IMETHODIMP nsNetAddr::GetAddress(nsACString & aAddress)
{
  switch(mAddr.raw.family) {
  /* PR_NetAddrToString can handle INET and INET6, but not LOCAL. */
  case AF_INET:
    aAddress.SetCapacity(kIPv4CStrBufSize);
    NetAddrToString(&mAddr, aAddress.BeginWriting(), kIPv4CStrBufSize);
    aAddress.SetLength(strlen(aAddress.BeginReading()));
    break;
  case AF_INET6:
    aAddress.SetCapacity(kIPv6CStrBufSize);
    NetAddrToString(&mAddr, aAddress.BeginWriting(), kIPv6CStrBufSize);
    aAddress.SetLength(strlen(aAddress.BeginReading()));
    break;
#if defined(XP_UNIX) || defined(XP_OS2)
  case AF_LOCAL:
    aAddress.Assign(mAddr.local.path);
    break;
#endif
  // PR_AF_LOCAL falls through to default when not XP_UNIX || XP_OS2
  default:
    return NS_ERROR_UNEXPECTED;
  }
  
  return NS_OK;
}
Ejemplo n.º 2
0
bool
AppendUTF16toUTF8( const nsAString& aSource, nsACString& aDest,
                   const mozilla::fallible_t& )
  {
    nsAString::const_iterator source_start, source_end;
    CalculateUTF8Size calculator;
    copy_string(aSource.BeginReading(source_start),
                aSource.EndReading(source_end), calculator);

    uint32_t count = calculator.Size();

    if (count)
      {
        uint32_t old_dest_length = aDest.Length();

        // Grow the buffer if we need to.
        if (!aDest.SetLength(old_dest_length + count, mozilla::fallible_t())) {
          return false;
        }

        // All ready? Time to convert

        ConvertUTF16toUTF8 converter(aDest.BeginWriting() + old_dest_length);
        copy_string(aSource.BeginReading(source_start),
                    aSource.EndReading(source_end), converter);

        NS_ASSERTION(converter.Size() == count,
                     "Unexpected disparity between CalculateUTF8Size and "
                     "ConvertUTF16toUTF8");
      }

    return true;
  }
Ejemplo n.º 3
0
void
nsUrlClassifierUtils::CleanupHostname(const nsACString & hostname,
                                      nsACString & _retval)
{
  _retval.Truncate();

  const char* curChar = hostname.BeginReading();
  const char* end = hostname.EndReading();
  char lastChar = '\0';
  while (curChar != end) {
    unsigned char c = static_cast<unsigned char>(*curChar);
    if (c == '.' && (lastChar == '\0' || lastChar == '.')) {
      // skip
    } else {
      _retval.Append(*curChar);
    }
    lastChar = c;
    ++curChar;
  }

  // cut off trailing dots
  while (_retval.Length() > 0 && _retval[_retval.Length() - 1] == '.') {
    _retval.SetLength(_retval.Length() - 1);
  }
}
Ejemplo n.º 4
0
/** Takes an ASCII string like "foo[i]", turns it into "foo" and returns "[i]" in bracketPart
  * 
  * \param string input/output: the string to split, becomes the string without the bracket part
  * \param bracketPart output: gets the bracket part.
  * 
  * Notice that if there are multiple brackets like "foo[i].bar[j]", only the last bracket is split.
  */
static bool SplitLastSquareBracket(nsACString& string, nsCString& bracketPart)
{
    MOZ_ASSERT(bracketPart.IsEmpty(), "SplitLastSquareBracket must be called with empty bracketPart string");

    if (string.IsEmpty())
        return false;

    char *string_start = string.BeginWriting();
    char *s = string_start + string.Length() - 1;

    if (*s != ']')
        return false;

    while (*s != '[' && s != string_start)
        s--;

    if (*s != '[')
        return false;

    bracketPart.Assign(s);
    *s = 0;
    string.EndWriting();
    string.SetLength(s - string_start);
    return true;
}
Ejemplo n.º 5
0
NS_IMETHODIMP
nsWindowsRegKey::ReadBinaryValue(const nsAString& aName, nsACString& aResult)
{
  if (NS_WARN_IF(!mKey)) {
    return NS_ERROR_NOT_INITIALIZED;
  }

  DWORD size;
  LONG rv = RegQueryValueExW(mKey, PromiseFlatString(aName).get(), 0,
                             nullptr, nullptr, &size);

  if (rv != ERROR_SUCCESS) {
    return NS_ERROR_FAILURE;
  }

  if (!size) {
    aResult.Truncate();
    return NS_OK;
  }

  if (!aResult.SetLength(size, mozilla::fallible)) {
    return NS_ERROR_OUT_OF_MEMORY;
  }

  nsACString::iterator begin;
  aResult.BeginWriting(begin);

  rv = RegQueryValueExW(mKey, PromiseFlatString(aName).get(), 0, nullptr,
                        (LPBYTE)begin.get(), &size);
  return (rv == ERROR_SUCCESS) ? NS_OK : NS_ERROR_FAILURE;
}
Ejemplo n.º 6
0
static bool
ReadSuffixAndSpec(JSStructuredCloneReader* aReader,
                  PrincipalOriginAttributes& aAttrs,
                  nsACString& aSpec)
{
    uint32_t suffixLength, specLength;
    if (!JS_ReadUint32Pair(aReader, &suffixLength, &specLength)) {
        return false;
    }

    nsAutoCString suffix;
    suffix.SetLength(suffixLength);
    if (!JS_ReadBytes(aReader, suffix.BeginWriting(), suffixLength)) {
        return false;
    }

    if (!aAttrs.PopulateFromSuffix(suffix)) {
        return false;
    }

    aSpec.SetLength(specLength);
    if (!JS_ReadBytes(aReader, aSpec.BeginWriting(), specLength)) {
        return false;
    }

    return true;
}
Ejemplo n.º 7
0
static bool ReadPrincipalInfo(JSStructuredCloneReader* aReader,
                              OriginAttributes& aAttrs, nsACString& aSpec,
                              nsACString& aOriginNoSuffix) {
  uint32_t suffixLength, specLength;
  if (!JS_ReadUint32Pair(aReader, &suffixLength, &specLength)) {
    return false;
  }

  nsAutoCString suffix;
  if (!suffix.SetLength(suffixLength, fallible)) {
    return false;
  }

  if (!JS_ReadBytes(aReader, suffix.BeginWriting(), suffixLength)) {
    return false;
  }

  if (!aAttrs.PopulateFromSuffix(suffix)) {
    return false;
  }

  if (!aSpec.SetLength(specLength, fallible)) {
    return false;
  }

  if (!JS_ReadBytes(aReader, aSpec.BeginWriting(), specLength)) {
    return false;
  }

  uint32_t originNoSuffixLength, dummy;
  if (!JS_ReadUint32Pair(aReader, &originNoSuffixLength, &dummy)) {
    return false;
  }

  MOZ_ASSERT(dummy == 0);

  if (!aOriginNoSuffix.SetLength(originNoSuffixLength, fallible)) {
    return false;
  }

  if (!JS_ReadBytes(aReader, aOriginNoSuffix.BeginWriting(),
                    originNoSuffixLength)) {
    return false;
  }

  return true;
}
Ejemplo n.º 8
0
void
ToLowerCase( const nsACString& aSource, nsACString& aDest )
  {
    nsACString::const_iterator fromBegin, fromEnd;
    nsACString::iterator toBegin;
    aDest.SetLength(aSource.Length());

    CopyToLowerCase converter(aDest.BeginWriting(toBegin));
    copy_string(aSource.BeginReading(fromBegin), aSource.EndReading(fromEnd), converter);
  }
NS_IMETHODIMP
HttpBaseChannel::GetRemoteAddress(nsACString& addr)
{
  if (mPeerAddr.raw.family == PR_AF_UNSPEC)
    return NS_ERROR_NOT_AVAILABLE;

  addr.SetCapacity(64);
  PR_NetAddrToString(&mPeerAddr, addr.BeginWriting(), 64);
  addr.SetLength(strlen(addr.BeginReading()));

  return NS_OK;
}
Ejemplo n.º 10
0
NS_IMETHODIMP
HttpBaseChannel::GetLocalAddress(nsACString& addr)
{
  if (mSelfAddr.raw.family == PR_AF_UNSPEC)
    return NS_ERROR_NOT_AVAILABLE;

  addr.SetCapacity(kIPv6CStrBufSize);
  NetAddrToString(&mSelfAddr, addr.BeginWriting(), kIPv6CStrBufSize);
  addr.SetLength(strlen(addr.BeginReading()));

  return NS_OK;
}
Ejemplo n.º 11
0
NS_CStringGetMutableData(nsACString& aStr, uint32_t aDataLength, char** aData)
{
  if (aDataLength != UINT32_MAX) {
    aStr.SetLength(aDataLength);
    if (aStr.Length() != aDataLength) {
      *aData = nullptr;
      return 0;
    }
  }

  *aData = aStr.BeginWriting();
  return aStr.Length();
}
Ejemplo n.º 12
0
void ReverseString(const nsACString& aSource, nsACString& aResult) {
  nsACString::const_iterator sourceBegin, sourceEnd;
  aSource.BeginReading(sourceBegin);
  aSource.EndReading(sourceEnd);

  aResult.SetLength(aSource.Length());
  auto destEnd = aResult.EndWriting();

  while (sourceBegin != sourceEnd) {
    *(--destEnd) = *sourceBegin;
    ++sourceBegin;
  }
}
/* from xpcom/io/nsStreamUtils.cpp
 * (it's hidden in libxul, so we need a copy :( )
 */
nsresult
sbConsumeStream(nsIInputStream *stream, PRUint32 maxCount, nsACString &result)
{
    nsresult rv = NS_OK;
    result.Truncate();

    while (maxCount) {
        PRUint32 avail;
        rv = stream->Available(&avail);
        if (NS_FAILED(rv)) {
            if (rv == NS_BASE_STREAM_CLOSED)
                rv = NS_OK;
            break;
        }
        if (avail == 0)
            break;
        if (avail > maxCount)
            avail = maxCount;

        // resize result buffer
        PRUint32 length = result.Length();
        result.SetLength(length + avail);
        if (result.Length() != (length + avail))
            return NS_ERROR_OUT_OF_MEMORY;
        char *buf = result.BeginWriting() + length;

        PRUint32 n;
        rv = stream->Read(buf, avail, &n);
        if (NS_FAILED(rv))
            break;
        if (n != avail)
            result.SetLength(length + n);
        if (n == 0)
            break;
        maxCount -= n;
    }

    return rv;
}
Ejemplo n.º 14
0
NS_CStringGetMutableData(nsACString &aStr, PRUint32 aDataLength, char **aData)
{
  if (aDataLength != PR_UINT32_MAX) {
    aStr.SetLength(aDataLength);
    if (aStr.Length() != aDataLength) {
      *aData = nsnull;
      return 0;
    }
  }

  nsACString::iterator begin;
  aStr.BeginWriting(begin);
  *aData = begin.get();
  return begin.size_forward();
}
Ejemplo n.º 15
0
nsresult nsMsgFolderCache::RowCellColumnToCharPtr(nsIMdbRow *hdrRow, mdb_token columnToken, nsACString& resultStr)
{
  nsresult err = NS_OK;
  nsIMdbCell *hdrCell;
  if (hdrRow) // ### probably should be an error if hdrRow is NULL...
  {
    err = hdrRow->GetCell(GetEnv(), columnToken, &hdrCell);
    if (NS_SUCCEEDED(err) && hdrCell)
    {
      struct mdbYarn yarn;
      hdrCell->AliasYarn(GetEnv(), &yarn);
      resultStr.Assign((const char *)yarn.mYarn_Buf, yarn.mYarn_Fill);
      resultStr.SetLength(yarn.mYarn_Fill); // ensure the string is null terminated.
      hdrCell->Release(); // always release ref
    }
  }
  return err;
}
Ejemplo n.º 16
0
void
LossyAppendUTF16toASCII( const nsAString& aSource, nsACString& aDest )
  {
    uint32_t old_dest_length = aDest.Length();
    aDest.SetLength(old_dest_length + aSource.Length());

    nsAString::const_iterator fromBegin, fromEnd;

    nsACString::iterator dest;
    aDest.BeginWriting(dest);

    dest.advance(old_dest_length);

    // right now, this won't work on multi-fragment destinations
    LossyConvertEncoding16to8 converter(dest.get());

    copy_string(aSource.BeginReading(fromBegin), aSource.EndReading(fromEnd), converter);
  }
Ejemplo n.º 17
0
NS_IMETHODIMP
nsScriptableInputStream::ReadBytes(uint32_t aCount, nsACString& aResult)
{
  if (!mInputStream) {
    return NS_ERROR_NOT_INITIALIZED;
  }

  if (!aResult.SetLength(aCount, fallible)) {
    return NS_ERROR_OUT_OF_MEMORY;
  }

  MOZ_ASSERT(aResult.Length() == aCount);
  char* ptr = aResult.BeginWriting();
  nsresult rv = ReadHelper(ptr, aCount);
  if (NS_FAILED(rv)) {
    aResult.Truncate();
  }
  return rv;
}
Ejemplo n.º 18
0
nsresult
NS_CopyUnicodeToNative(const nsAString &input, nsACString &output)
{
    size_t inputLen = input.Length();

    nsAString::const_iterator iter;
    input.BeginReading(iter);
    UniChar* inputStr = (UniChar*) const_cast<char16_t*>(iter.get());

    // maximum length of unicode string of length x converted to native
    // codepage is x*2
    size_t resultLen = inputLen * 2;
    if (!output.SetLength(resultLen, fallible_t()))
        return NS_ERROR_OUT_OF_MEMORY;

    nsACString::iterator out_iter;
    output.BeginWriting(out_iter);
    char *result = out_iter.get();

    size_t cSubs = 0;
    size_t resultLeft = resultLen;

    if (!UnicodeConverter)
      NS_StartupNativeCharsetUtils();
  
    int unirc = ::UniUconvFromUcs(UnicodeConverter, &inputStr, &inputLen,
                                  (void**)&result, &resultLeft, &cSubs);

    NS_ASSERTION(unirc != UCONV_E2BIG, "Path too big");
  
    if (unirc != ULS_SUCCESS) {
        output.Truncate();
        return NS_ERROR_FAILURE;
    }

    // Need to update string length to reflect how many bytes were actually
    // written.
    output.Truncate(resultLen - resultLeft);
    return NS_OK;
}
Ejemplo n.º 19
0
static nsresult
ReadFromFile(nsIFile* aPath,
             const nsACString& aFileName,
             nsACString& aOutData,
             int32_t aMaxLength)
{
  nsCOMPtr<nsIFile> path;
  nsresult rv = aPath->Clone(getter_AddRefs(path));
  if (NS_WARN_IF(NS_FAILED(rv))) {
    return rv;
  }

  rv = path->AppendNative(aFileName);
  if (NS_WARN_IF(NS_FAILED(rv))) {
    return rv;
  }

  PRFileDesc* f = nullptr;
  rv = path->OpenNSPRFileDesc(PR_RDONLY | PR_CREATE_FILE, PR_IRWXU, &f);
  if (NS_WARN_IF(NS_FAILED(rv))) {
    return rv;
  }

  auto size = PR_Seek(f, 0, PR_SEEK_END);
  PR_Seek(f, 0, PR_SEEK_SET);

  if (size > aMaxLength) {
    return NS_ERROR_FAILURE;
  }
  aOutData.SetLength(size);

  auto len = PR_Read(f, aOutData.BeginWriting(), size);
  PR_Close(f);
  if (NS_WARN_IF(len != size)) {
    return NS_ERROR_FAILURE;
  }

  return NS_OK;
}
Ejemplo n.º 20
0
nsresult
NS_CopyUnicodeToNative(const nsAString&  aInput, nsACString& aOutput)
{
  uint32_t inputLen = aInput.Length();

  nsAString::const_iterator iter;
  aInput.BeginReading(iter);

  char16ptr_t buf = iter.get();

  // determine length of result
  uint32_t resultLen = 0;

  int n = ::WideCharToMultiByte(CP_ACP, 0, buf, inputLen, nullptr, 0,
                                nullptr, nullptr);
  if (n > 0) {
    resultLen += n;
  }

  // allocate sufficient space
  if (!aOutput.SetLength(resultLen, fallible)) {
    return NS_ERROR_OUT_OF_MEMORY;
  }
  if (resultLen > 0) {
    nsACString::iterator out_iter;
    aOutput.BeginWriting(out_iter);

    // default "defaultChar" is '?', which is an illegal character on windows
    // file system.  That will cause file uncreatable. Change it to '_'
    const char defaultChar = '_';

    char* result = out_iter.get();

    ::WideCharToMultiByte(CP_ACP, 0, buf, inputLen, result, resultLen,
                          &defaultChar, nullptr);
  }
  return NS_OK;
}
Ejemplo n.º 21
0
NS_IMETHODIMP
nsWindowsRegKey::ReadBinaryValue(const nsAString &name, nsACString &result)
{
  NS_ENSURE_TRUE(mKey, NS_ERROR_NOT_INITIALIZED);

  DWORD size;
  LONG rv = RegQueryValueExW(mKey, PromiseFlatString(name).get(), 0,
                             NULL, NULL, &size);

  if (rv != ERROR_SUCCESS)
    return NS_ERROR_FAILURE;

  result.SetLength(size);
  nsACString::iterator begin;
  result.BeginWriting(begin);
  if (begin.size_forward() != size)
    return NS_ERROR_OUT_OF_MEMORY;

  rv = RegQueryValueExW(mKey, PromiseFlatString(name).get(), 0, NULL,
                        (LPBYTE) begin.get(), &size);

  return (rv == ERROR_SUCCESS) ? NS_OK : NS_ERROR_FAILURE;
}
Ejemplo n.º 22
0
static nsresult
GetFileContents(nsIFile* aFile, nsACString& data)
{
  nsCOMPtr<nsILocalFile> localFile = do_QueryInterface(aFile);
  NS_ENSURE_TRUE(localFile, NS_ERROR_FAILURE);

  PRFileDesc* fd;
  nsresult rv = localFile->OpenNSPRFileDesc(PR_RDONLY, 0, &fd);
  NS_ENSURE_SUCCESS(rv, rv);

  rv = NS_OK;
  PRInt32 filesize = PR_Available(fd);
  if (filesize <= 0) {
    rv = NS_ERROR_FILE_NOT_FOUND;
  }
  else {
    data.SetLength(filesize);
    if (PR_Read(fd, data.BeginWriting(), filesize) == -1) {
      rv = NS_ERROR_FAILURE;
    }
  }
  PR_Close(fd);
  return rv;
}
NS_IMETHODIMP
nsScriptableInputStream::ReadBytes(uint32_t aCount, nsACString &_retval) {
    if (!mInputStream) {
      return NS_ERROR_NOT_INITIALIZED;
    }

    _retval.SetLength(aCount);
    if (_retval.Length() != aCount) {
      return NS_ERROR_OUT_OF_MEMORY;
    }

    char *ptr = _retval.BeginWriting();
    uint32_t totalBytesRead = 0;
    while (1) {
      uint32_t bytesRead;
      nsresult rv = mInputStream->Read(ptr + totalBytesRead,
                                       aCount - totalBytesRead,
                                       &bytesRead);
      if (NS_FAILED(rv)) {
        return rv;
      }

      totalBytesRead += bytesRead;
      if (totalBytesRead == aCount) {
        break;
      }

      // If we have read zero bytes, we have hit EOF.
      if (bytesRead == 0) {
        _retval.Truncate();
        return NS_ERROR_FAILURE;
      }

    }
    return NS_OK;
}
Ejemplo n.º 24
0
bool
AppendUTF16toUTF8(const nsAString& aSource, nsACString& aDest,
                  const mozilla::fallible_t& aFallible)
{
  // At 16 characters analysis showed better performance of both the all ASCII
  // and non-ASCII cases, so we limit calling |FirstNonASCII| to strings of
  // that length.
  const nsAString::size_type kFastPathMinLength = 16;

  int32_t firstNonASCII = 0;
  if (aSource.Length() >= kFastPathMinLength) {
    firstNonASCII = FirstNonASCII(aSource.BeginReading(), aSource.EndReading());
  }

  if (firstNonASCII == -1) {
    // This is all ASCII, we can use the more efficient lossy append.
    mozilla::CheckedInt<nsACString::size_type> new_length(aSource.Length());
    new_length += aDest.Length();

    if (!new_length.isValid() ||
        !aDest.SetCapacity(new_length.value(), aFallible)) {
      return false;
    }

    LossyAppendUTF16toASCII(aSource, aDest);
    return true;
  }

  nsAString::const_iterator source_start, source_end;
  CalculateUTF8Size calculator;
  aSource.BeginReading(source_start);
  aSource.EndReading(source_end);

  // Skip the characters that we know are single byte.
  source_start.advance(firstNonASCII);

  copy_string(source_start,
              source_end, calculator);

  // Include the ASCII characters that were skipped in the count.
  size_t count = calculator.Size() + firstNonASCII;

  if (count) {
    auto old_dest_length = aDest.Length();
    // Grow the buffer if we need to.
    mozilla::CheckedInt<nsACString::size_type> new_length(count);
    new_length += old_dest_length;

    if (!new_length.isValid() ||
        !aDest.SetLength(new_length.value(), aFallible)) {
      return false;
    }

    // All ready? Time to convert

    nsAString::const_iterator ascii_end;
    aSource.BeginReading(ascii_end);

    if (firstNonASCII >= static_cast<int32_t>(kFastPathMinLength)) {
      // Use the more efficient lossy converter for the ASCII portion.
      LossyConvertEncoding16to8 lossy_converter(
          aDest.BeginWriting() + old_dest_length);
      nsAString::const_iterator ascii_start;
      aSource.BeginReading(ascii_start);
      ascii_end.advance(firstNonASCII);

      copy_string(ascii_start, ascii_end, lossy_converter);
    } else {
      // Not using the lossy shortcut, we need to include the leading ASCII
      // chars.
      firstNonASCII = 0;
    }

    ConvertUTF16toUTF8 converter(
        aDest.BeginWriting() + old_dest_length + firstNonASCII);
    copy_string(ascii_end,
                aSource.EndReading(source_end), converter);

    NS_ASSERTION(converter.Size() == count - firstNonASCII,
                 "Unexpected disparity between CalculateUTF8Size and "
                 "ConvertUTF16toUTF8");
  }

  return true;
}