Exemplo n.º 1
0
void
nsTextBoxFrame::UpdateAccessIndex()
{
    PRInt32 menuAccessKey;
    nsMenuBarListener::GetMenuAccessKey(&menuAccessKey);
    if (menuAccessKey) {
        if (mAccessKey.IsEmpty()) {
            if (mAccessKeyInfo) {
                delete mAccessKeyInfo;
                mAccessKeyInfo = nsnull;
            }
        } else {
            if (!mAccessKeyInfo) {
                mAccessKeyInfo = new nsAccessKeyInfo();
                if (!mAccessKeyInfo)
                    return;
            }

            nsAString::const_iterator start, end;
                
            mCroppedTitle.BeginReading(start);
            mCroppedTitle.EndReading(end);
            
            // remember the beginning of the string
            nsAString::const_iterator originalStart = start;

            PRBool found;
            if (!AlwaysAppendAccessKey()) {
                // not appending access key - do case-sensitive search
                // first
                found = FindInReadable(mAccessKey, start, end);
                if (!found) {
                    // didn't find it - perform a case-insensitive search
                    start = originalStart;
                    found = FindInReadable(mAccessKey, start, end,
                                           nsCaseInsensitiveStringComparator());
                }
            } else {
                found = RFindInReadable(mAccessKey, start, end,
                                        nsCaseInsensitiveStringComparator());
            }
            
            if (found)
                mAccessKeyInfo->mAccesskeyIndex = Distance(originalStart, start);
            else
                mAccessKeyInfo->mAccesskeyIndex = kNotFound;
        }
    }
}
Exemplo n.º 2
0
bool IsVideoContentType(const nsCString& aContentType) {
  NS_NAMED_LITERAL_CSTRING(video, "video");
  if (FindInReadable(video, aContentType)) {
    return true;
  }
  return false;
}
Exemplo n.º 3
0
// static
Modifiers
UIEvent::ComputeModifierState(const nsAString& aModifiersList)
{
  if (aModifiersList.IsEmpty()) {
    return 0;
  }

  // Be careful about the performance.  If aModifiersList is too long,
  // parsing it needs too long time.
  // XXX Should we abort if aModifiersList is too long?

  Modifiers modifiers = 0;

  nsAString::const_iterator listStart, listEnd;
  aModifiersList.BeginReading(listStart);
  aModifiersList.EndReading(listEnd);

  for (uint32_t i = 0; i < ArrayLength(kPairs); i++) {
    nsAString::const_iterator start(listStart), end(listEnd);
    if (!FindInReadable(NS_ConvertASCIItoUTF16(kPairs[i].name), start, end)) {
      continue;
    }

    if ((start != listStart && !NS_IsAsciiWhitespace(*(--start))) ||
        (end != listEnd && !NS_IsAsciiWhitespace(*(end)))) {
      continue;
    }
    modifiers |= kPairs[i].modifier;
  }

  return modifiers;
}
Exemplo n.º 4
0
nsresult
nsAboutCache::ParseURI(nsIURI * uri, nsCString &deviceID)
{
    //
    // about:cache[?device=string]
    //
    nsresult rv;

    deviceID.Truncate();

    nsCAutoString path;
    rv = uri->GetPath(path);
    if (NS_FAILED(rv)) return rv;

    nsACString::const_iterator start, valueStart, end;
    path.BeginReading(start);
    path.EndReading(end);

    valueStart = end;
    if (!FindInReadable(NS_LITERAL_CSTRING("?device="), start, valueStart))
        return NS_OK;

    deviceID.Assign(Substring(valueStart, end));
    return NS_OK;
}
Exemplo n.º 5
0
  // Reads over a boundary and sets start to the position after the end of the
  // boundary. Returns false if no boundary is found immediately.
  bool
  PushOverBoundary(const nsACString& aBoundaryString,
                   nsACString::const_iterator& aStart,
                   nsACString::const_iterator& aEnd)
  {
    // We copy the end iterator to keep the original pointing to the real end
    // of the string.
    nsACString::const_iterator end(aEnd);
    const char* beginning = aStart.get();
    if (FindInReadable(aBoundaryString, aStart, end)) {
      // We either should find the body immediately, or after 2 chars with the
      // 2 chars being '-', everything else is failure.
      if ((aStart.get() - beginning) == 0) {
        aStart.advance(aBoundaryString.Length());
        return true;
      }

      if ((aStart.get() - beginning) == 2) {
        if (*(--aStart) == '-' && *(--aStart) == '-') {
          aStart.advance(aBoundaryString.Length() + 2);
          return true;
        }
      }
    }

    return false;
  }
Exemplo n.º 6
0
 bool
 FindCRLF(nsACString::const_iterator& aStart,
          nsACString::const_iterator& aEnd)
 {
   nsACString::const_iterator end(aEnd);
   return FindInReadable(NS_LITERAL_CSTRING("\r\n"), aStart, end);
 }
Exemplo n.º 7
0
static PRBool DoFindInReadable(const nsACString& str, const nsACString& value)
{
  nsACString::const_iterator start, end;
  str.BeginReading(start);
  str.EndReading(end);

  return FindInReadable(value, start, end);
}
nsresult
nsAboutCacheEntry::ParseURI(nsIURI *uri, nsCString &clientID,
                            bool &streamBased, nsCString &key)
{
    //
    // about:cache-entry?client=[string]&sb=[boolean]&key=[string]
    //
    nsresult rv;

    nsAutoCString path;
    rv = uri->GetPath(path);
    if (NS_FAILED(rv)) return rv;

    nsACString::const_iterator i1, i2, i3, end;
    path.BeginReading(i1);
    path.EndReading(end);

    i2 = end;
    if (!FindInReadable(NS_LITERAL_CSTRING("?client="), i1, i2))
        return NS_ERROR_FAILURE;
    // i2 points to the start of clientID

    i1 = i2;
    i3 = end;
    if (!FindInReadable(NS_LITERAL_CSTRING("&sb="), i1, i3))
        return NS_ERROR_FAILURE;
    // i1 points to the end of clientID
    // i3 points to the start of isStreamBased

    clientID.Assign(Substring(i2, i1));

    i1 = i3;
    i2 = end;
    if (!FindInReadable(NS_LITERAL_CSTRING("&key="), i1, i2))
        return NS_ERROR_FAILURE;
    // i1 points to the end of isStreamBased
    // i2 points to the start of key

    streamBased = FindCharInReadable('1', i3, i1);
    key.Assign(Substring(i2, end));

    return NS_OK;
}
Exemplo n.º 9
0
static bool
AttrHasSubstring(Implementor* aElement, nsIAtom* aNS, nsIAtom* aName,
                 nsIAtom* aStr_)
{
  FakeRef<nsIAtom> aStr(aStr_);
  auto match = [aStr](const nsAttrValue* aValue) {
    nsAutoString str;
    aValue->ToString(str);
    return FindInReadable(str, nsDependentAtomString(aStr));
  };
  return DoMatch(aElement, aNS, aName, match);
}
Exemplo n.º 10
0
// the following block is to append the accesskey to mTitle if there is an accesskey
// but the mTitle doesn't have the character
void
nsTextBoxFrame::UpdateAccessTitle()
{
    /*
     * Note that if you change appending access key label spec,
     * you need to maintain same logic in following methods. See bug 324159.
     * toolkit/content/commonDialog.js (setLabelForNode)
     * toolkit/content/widgets/text.xml (formatAccessKey)
     */
    PRInt32 menuAccessKey;
    nsMenuBarListener::GetMenuAccessKey(&menuAccessKey);
    if (!menuAccessKey || mAccessKey.IsEmpty())
        return;

    if (!AlwaysAppendAccessKey() &&
        FindInReadable(mAccessKey, mTitle, nsCaseInsensitiveStringComparator()))
        return;

    nsAutoString accessKeyLabel;
    accessKeyLabel += '(';
    accessKeyLabel += mAccessKey;
    ToUpperCase(accessKeyLabel);
    accessKeyLabel += ')';

    if (mTitle.IsEmpty()) {
        mTitle = accessKeyLabel;
        return;
    }

    const nsDependentString& kEllipsis = nsContentUtils::GetLocalizedEllipsis();
    PRUint32 offset = mTitle.Length();
    if (StringEndsWith(mTitle, kEllipsis)) {
        offset -= kEllipsis.Length();
    } else if (StringEndsWith(mTitle, OLD_ELLIPSIS)) {
        // Try to check with our old ellipsis (for old addons)
        offset -= OLD_ELLIPSIS.Length();
    } else {
        // Try to check with
        // our default ellipsis (for non-localized addons) or ':'
        const PRUnichar kLastChar = mTitle.Last();
        if (kLastChar == PRUnichar(0x2026) || kLastChar == PRUnichar(':'))
            offset--;
    }

    if (InsertSeparatorBeforeAccessKey() &&
        offset > 0 && !NS_IS_SPACE(mTitle[offset - 1])) {
        mTitle.Insert(' ', offset);
        offset++;
    }

    mTitle.Insert(accessKeyLabel, offset);
}
Exemplo n.º 11
0
NS_IMETHODIMP nsMailboxService::NewURI(const nsACString &aSpec,
                                       const char *aOriginCharset,
                                       nsIURI *aBaseURI,
                                       nsIURI **_retval)
{
    nsresult rv = NS_OK;
    nsACString::const_iterator b, e;
    if (FindInReadable(NS_LITERAL_CSTRING("?uidl="), aSpec.BeginReading(b), aSpec.EndReading(e)) ||
        FindInReadable(NS_LITERAL_CSTRING("&uidl="), aSpec.BeginReading(b), aSpec.EndReading(e)))
  {
    nsCOMPtr<nsIProtocolHandler> handler = 
             do_GetService(kCPop3ServiceCID, &rv);
    if (NS_SUCCEEDED(rv))
        rv = handler->NewURI(aSpec, aOriginCharset, aBaseURI, _retval);
  }
  else
  {
    nsCOMPtr<nsIURI> aMsgUri = do_CreateInstance(kCMailboxUrl, &rv);
        
    if (NS_SUCCEEDED(rv))
    {
      if (aBaseURI) 
      {
        nsCAutoString newSpec;
        rv = aBaseURI->Resolve(aSpec, newSpec);
        if (NS_FAILED(rv))
          return rv;
        aMsgUri->SetSpec(newSpec);
      } 
      else 
      {
        aMsgUri->SetSpec(aSpec);
      }
      NS_ADDREF(*_retval = aMsgUri);
    }
  }

  return rv;
}
Exemplo n.º 12
0
NS_IMETHODIMP
nsLocalFile::SetRelativeDescriptor(nsIFile* aFromFile,
                                   const nsACString& aRelativeDesc)
{
  NS_NAMED_LITERAL_CSTRING(kParentDirStr, "../");

  nsCOMPtr<nsIFile> targetFile;
  nsresult rv = aFromFile->Clone(getter_AddRefs(targetFile));
  if (NS_FAILED(rv)) {
    return rv;
  }

  //
  // aRelativeDesc is UTF-8 encoded
  //

  nsCString::const_iterator strBegin, strEnd;
  aRelativeDesc.BeginReading(strBegin);
  aRelativeDesc.EndReading(strEnd);

  nsCString::const_iterator nodeBegin(strBegin), nodeEnd(strEnd);
  nsCString::const_iterator pos(strBegin);

  nsCOMPtr<nsIFile> parentDir;
  while (FindInReadable(kParentDirStr, nodeBegin, nodeEnd)) {
    rv = targetFile->GetParent(getter_AddRefs(parentDir));
    if (NS_FAILED(rv)) {
      return rv;
    }
    if (!parentDir) {
      return NS_ERROR_FILE_UNRECOGNIZED_PATH;
    }
    targetFile = parentDir;

    nodeBegin = nodeEnd;
    pos = nodeEnd;
    nodeEnd = strEnd;
  }

  nodeBegin = nodeEnd = pos;
  while (nodeEnd != strEnd) {
    FindCharInReadable('/', nodeEnd, strEnd);
    targetFile->Append(NS_ConvertUTF8toUTF16(Substring(nodeBegin, nodeEnd)));
    if (nodeEnd != strEnd) { // If there's more left in the string, inc over the '/' nodeEnd is on.
      ++nodeEnd;
    }
    nodeBegin = nodeEnd;
  }

  return InitWithFile(targetFile);
}
nsresult
nsDASHWebMODParser::GetTime(nsAString& aTimeStr, double& aTime)
{
  NS_ENSURE_FALSE(aTimeStr.IsEmpty(), NS_ERROR_NOT_INITIALIZED);
  // Fail if time string is not of the format "PT<time>S".
  NS_NAMED_LITERAL_STRING(prefix, "PT");
  NS_NAMED_LITERAL_STRING(suffix, "S");
  nsAString::const_iterator start, end, prefixStart, prefixEnd,
                            suffixStart, suffixEnd;

  // Search for "PT" at the start.
  aTimeStr.BeginReading(start);
  aTimeStr.EndReading(end);
  prefixStart = start;
  prefixEnd = end;
  NS_ENSURE_TRUE(FindInReadable(prefix, prefixStart, prefixEnd),
                 NS_ERROR_ILLEGAL_VALUE);
  NS_ENSURE_TRUE(prefixStart == start, NS_ERROR_ILLEGAL_VALUE);

  // Search for "S" after "PT".
  suffixStart = prefixEnd;
  suffixEnd = end;
  NS_ENSURE_TRUE(FindInReadable(suffix, suffixStart, suffixEnd),
                 NS_ERROR_ILLEGAL_VALUE);
  NS_ENSURE_TRUE(suffixStart != prefixEnd, NS_ERROR_ILLEGAL_VALUE);
  NS_ENSURE_TRUE(suffixEnd == end, NS_ERROR_ILLEGAL_VALUE);

  // Parse inner substring for time.
  const nsAutoString timeSubString(Substring(prefixEnd, suffixStart));
  LOG("Parsing substring \"%s\" in \"%s\"",
      NS_ConvertUTF16toUTF8(timeSubString).get(),
      NS_ConvertUTF16toUTF8(aTimeStr).get());
  NS_ENSURE_FALSE(timeSubString.IsEmpty(), NS_ERROR_ILLEGAL_VALUE);
  nsresult rv;
  aTime = timeSubString.ToDouble(&rv);
  NS_ENSURE_SUCCESS(rv, rv);
  return NS_OK;
}
Exemplo n.º 14
0
static void ReplaceChar(nsCString& str, const nsACString& character,
                        const nsACString& replacement)
{
  nsCString::const_iterator start, end;

  str.BeginReading(start);
  str.EndReading(end);

  while (FindInReadable(character, start, end)) {
    PRInt32 pos = end.size_backward();
    str.Replace(pos - 1, 1, replacement);

    str.BeginReading(start);
    start.advance(pos + replacement.Length() - 1);
    str.EndReading(end);
  }
}
Exemplo n.º 15
0
/**
 * Determines whether or not a string exists as the root element in an XML data
 * string buffer.
 * @param   dataString
 *          The data being sniffed
 * @param   substring
 *          The substring being tested for existence and root-ness.
 * @returns true if the substring exists and is the documentElement, false
 *          otherwise.
 */
static bool
ContainsTopLevelSubstring(nsACString& dataString, const char *substring) 
{
  nsACString::const_iterator start, end;
  dataString.BeginReading(start);
  dataString.EndReading(end);

  if (!FindInReadable(nsCString(substring), start, end)){
    return false;
  }

  auto offset = start.get() - dataString.Data();

  const char *begin = dataString.BeginReading();

  // Only do the validation when we find the substring.
  return IsDocumentElement(begin, begin + offset);
}
Exemplo n.º 16
0
bool
nsPicoService::GetVoiceFileLanguage(const nsACString& aFileName, nsAString& aLang)
{
  nsACString::const_iterator start, end;
  aFileName.BeginReading(start);
  aFileName.EndReading(end);

  // The lingware filename syntax is language_(ta/sg).bin,
  // we extract the language prefix here.
  if (FindInReadable(NS_LITERAL_CSTRING("_"), start, end)) {
    end = start;
    aFileName.BeginReading(start);
    aLang.Assign(NS_ConvertUTF8toUTF16(Substring(start, end)));
    return true;
  }

  return false;
}
Exemplo n.º 17
0
PRBool
nsCoreUtils::IsErrorPage(nsIDocument *aDocument)
{
  nsIURI *uri = aDocument->GetDocumentURI();
  PRBool isAboutScheme = PR_FALSE;
  uri->SchemeIs("about", &isAboutScheme);
  if (!isAboutScheme)
    return PR_FALSE;

  nsCAutoString path;
  uri->GetPath(path);

  nsCAutoString::const_iterator start, end;
  path.BeginReading(start);
  path.EndReading(end);

  NS_NAMED_LITERAL_CSTRING(neterror, "neterror");
  return FindInReadable(neterror, start, end);
}
Exemplo n.º 18
0
/* static */ eMATHVARIANT
nsMathMLOperators::LookupInvariantChar(const nsAString& aChar)
{
  if (!gInitialized) {
    InitGlobals();
  }
  if (gInvariantCharArray) {
    for (PRInt32 i = gInvariantCharArray->Length()-1; i >= 0; --i) {
      const nsString& list = gInvariantCharArray->ElementAt(i);
      nsString::const_iterator start, end;
      list.BeginReading(start);
      list.EndReading(end);
      // Style-invariant characters are at offset 3*j + 1.
      if (FindInReadable(aChar, start, end) &&
          start.size_backward() % 3 == 1) {
        return eMATHVARIANT(i);
      }
    }
  }
  return eMATHVARIANT_NONE;
}
Exemplo n.º 19
0
/* static */
already_AddRefed<MediaEncoder>
MediaEncoder::CreateEncoder(const nsAString& aMIMEType)
{
  nsAutoPtr<ContainerWriter> writer;
  nsAutoPtr<AudioTrackEncoder> audioEncoder;
  nsAutoPtr<VideoTrackEncoder> videoEncoder;
  nsRefPtr<MediaEncoder> encoder;

  if (aMIMEType.IsEmpty()) {
    // TODO: Should pick out a default container+codec base on the track
    //       coming from MediaStreamGraph. For now, just default to Ogg+Opus.
    const_cast<nsAString&>(aMIMEType) = NS_LITERAL_STRING("audio/ogg");
  }

  bool isAudioOnly = FindInReadable(NS_LITERAL_STRING("audio/"), aMIMEType);
#ifdef MOZ_OGG
  if (IsOggType(aMIMEType)) {
    writer = new OggWriter();
    if (!isAudioOnly) {
      // Initialize the videoEncoder.
    }
#ifdef MOZ_OPUS
    audioEncoder = new OpusTrackEncoder();
#endif
  }
#endif
  // If the given mime-type is video but fail to create the video encoder.
  if (!isAudioOnly) {
    NS_ENSURE_TRUE(videoEncoder, nullptr);
  }

  // Return null if we fail to create the audio encoder.
  NS_ENSURE_TRUE(audioEncoder, nullptr);

  encoder = new MediaEncoder(writer.forget(), audioEncoder.forget(),
                             videoEncoder.forget(), aMIMEType);


  return encoder.forget();
}
Exemplo n.º 20
0
bool
FileSystemSecurity::ContentProcessHasAccessTo(ContentParentId aId,
                                              const nsAString& aPath)
{
  MOZ_ASSERT(NS_IsMainThread());
  AssertIsInMainProcess();

  if (FindInReadable(NS_LITERAL_STRING(".."), aPath)) {
    return false;
  }

  nsTArray<nsString>* paths;
  if (!mPaths.Get(aId, &paths)) {
    return false;
  }

  for (uint32_t i = 0, len = paths->Length(); i < len; ++i) {
    if (FileSystemUtils::IsDescendantPath(paths->ElementAt(i), aPath)) {
      return true;
    }
  }

  return false;
}
Exemplo n.º 21
0
  // The end of a body is marked by a CRLF followed by the boundary. So the
  // CRLF is part of the boundary and not the body, but any prior CRLFs are
  // part of the body. This will position the iterator at the beginning of the
  // boundary (after the CRLF).
  bool
  ParseBody(const nsACString& aBoundaryString,
            nsACString::const_iterator& aStart,
            nsACString::const_iterator& aEnd)
  {
    const char* beginning = aStart.get();

    // Find the boundary marking the end of the body.
    nsACString::const_iterator end(aEnd);
    if (!FindInReadable(aBoundaryString, aStart, end)) {
      return false;
    }

    // We found a boundary, strip the just prior CRLF, and consider
    // everything else the body section.
    if (aStart.get() - beginning < 2) {
      // Only the first entry can have a boundary right at the beginning. Even
      // an empty body will have a CRLF before the boundary. So this is
      // a failure.
      return false;
    }

    // Check that there is a CRLF right before the boundary.
    aStart.advance(-2);

    // Skip optional hyphens.
    if (*aStart == '-' && *(aStart.get()+1) == '-') {
      if (aStart.get() - beginning < 2) {
        return false;
      }

      aStart.advance(-2);
    }

    if (*aStart != nsCRT::CR || *(aStart.get()+1) != nsCRT::LF) {
      return false;
    }

    nsAutoCString body(beginning, aStart.get() - beginning);

    // Restore iterator to after the \r\n as we promised.
    // We do not need to handle the extra hyphens case since our boundary
    // parser in PushOverBoundary()
    aStart.advance(2);

    if (!mFormData) {
      mFormData = new nsFormData();
    }

    NS_ConvertUTF8toUTF16 name(mName);

    if (mFilename.IsVoid()) {
      mFormData->Append(name, NS_ConvertUTF8toUTF16(body));
    } else {
      // Unfortunately we've to copy the data first since all our strings are
      // going to free it. We also need fallible alloc, so we can't just use
      // ToNewCString().
      char* copy = static_cast<char*>(moz_xmalloc(body.Length()));
      if (!copy) {
        NS_WARNING("Failed to copy File entry body.");
        return false;
      }
      nsCString::const_iterator bodyIter, bodyEnd;
      body.BeginReading(bodyIter);
      body.EndReading(bodyEnd);
      char *p = copy;
      while (bodyIter != bodyEnd) {
        *p++ = *bodyIter++;
      }
      p = nullptr;

      nsRefPtr<Blob> file =
        File::CreateMemoryFile(mParentObject,
                               reinterpret_cast<void *>(copy), body.Length(),
                               NS_ConvertUTF8toUTF16(mFilename),
                               NS_ConvertUTF8toUTF16(mContentType), /* aLastModifiedDate */ 0);
      Optional<nsAString> dummy;
      mFormData->Append(name, *file, dummy);
    }

    return true;
  }
Exemplo n.º 22
0
PRBool
LocalSearchDataSource::doMatch(nsIRDFLiteral *literal,
                               const nsAString &matchMethod,
                               const nsString &matchText)
{
	PRBool		found = PR_FALSE;

	if ((nsnull == literal) ||
            matchMethod.IsEmpty() ||
            matchText.IsEmpty())
		return(found);

	const	PRUnichar	*str = nsnull;
	literal->GetValueConst( &str );
	if (! str)	return(found);
	nsAutoString	value(str);

        if (matchMethod.EqualsLiteral("contains"))
	{
            if (FindInReadable(matchText, value,
                               nsCaseInsensitiveStringComparator()))
                found = PR_TRUE;
	}
        else if (matchMethod.EqualsLiteral("startswith"))
	{
            nsAString::const_iterator start, realstart, end;
            value.BeginReading(start);
            value.EndReading(end);
            realstart = start;
            
            if (FindInReadable(matchText, start, end,
                               nsCaseInsensitiveStringComparator()) &&
                start == realstart)
                
                found = PR_TRUE;
	}
        else if (matchMethod.EqualsLiteral("endswith"))
	{
            nsAString::const_iterator start, end, realend;
            value.BeginReading(start);
            value.EndReading(end);
            realend = end;

            if (RFindInReadable(matchText, start, end,
                                nsCaseInsensitiveStringComparator()) &&
                end == realend)
                
                found = PR_TRUE;
	}
        else if (matchMethod.EqualsLiteral("is"))
	{
            if (value.Equals(matchText, nsCaseInsensitiveStringComparator()))
                found = PR_TRUE;
	}
        else if (matchMethod.EqualsLiteral("isnot"))
	{
            if (!value.Equals(matchText, nsCaseInsensitiveStringComparator()))
                found = PR_TRUE;
	}
        else if (matchMethod.EqualsLiteral("doesntcontain"))
	{
            if (!FindInReadable(matchText, value,
                                nsCaseInsensitiveStringComparator()))
                found = PR_TRUE;
	}
        return(found);
}
Exemplo n.º 23
0
/*
 * Evaluates this Expr based on the given context node and processor state
 * @param context the context node for evaluation of this Expr
 * @param ps the ContextState containing the stack information needed
 * for evaluation
 * @return the result of the evaluation
 */
nsresult
txCoreFunctionCall::evaluate(txIEvalContext* aContext, txAExprResult** aResult)
{
    *aResult = nsnull;

    if (!requireParams(descriptTable[mType].mMinParams,
                       descriptTable[mType].mMaxParams,
                       aContext)) {
        return NS_ERROR_XPATH_BAD_ARGUMENT_COUNT;
    }

    nsresult rv = NS_OK;
    switch (mType) {
        case COUNT:
        {
            nsRefPtr<txNodeSet> nodes;
            rv = evaluateToNodeSet(mParams[0], aContext,
                                   getter_AddRefs(nodes));
            NS_ENSURE_SUCCESS(rv, rv);

            return aContext->recycler()->getNumberResult(nodes->size(),
                                                         aResult);
        }
        case ID:
        {
            nsRefPtr<txAExprResult> exprResult;
            rv = mParams[0]->evaluate(aContext, getter_AddRefs(exprResult));
            NS_ENSURE_SUCCESS(rv, rv);

            nsRefPtr<txNodeSet> resultSet;
            rv = aContext->recycler()->getNodeSet(getter_AddRefs(resultSet));
            NS_ENSURE_SUCCESS(rv, rv);

            txXPathTreeWalker walker(aContext->getContextNode());
            
            if (exprResult->getResultType() == txAExprResult::NODESET) {
                txNodeSet* nodes = static_cast<txNodeSet*>
                                              (static_cast<txAExprResult*>
                                                          (exprResult));
                PRInt32 i;
                for (i = 0; i < nodes->size(); ++i) {
                    nsAutoString idList;
                    txXPathNodeUtils::appendNodeValue(nodes->get(i), idList);
                    nsWhitespaceTokenizer tokenizer(idList);
                    while (tokenizer.hasMoreTokens()) {
                        if (walker.moveToElementById(tokenizer.nextToken())) {
                            resultSet->add(walker.getCurrentPosition());
                        }
                    }
                }
            }
            else {
                nsAutoString idList;
                exprResult->stringValue(idList);
                nsWhitespaceTokenizer tokenizer(idList);
                while (tokenizer.hasMoreTokens()) {
                    if (walker.moveToElementById(tokenizer.nextToken())) {
                        resultSet->add(walker.getCurrentPosition());
                    }
                }
            }

            *aResult = resultSet;
            NS_ADDREF(*aResult);

            return NS_OK;
        }
        case LAST:
        {
            return aContext->recycler()->getNumberResult(aContext->size(),
                                                         aResult);
        }
        case LOCAL_NAME:
        case NAME:
        case NAMESPACE_URI:
        {
            // Check for optional arg
            nsRefPtr<txNodeSet> nodes;
            if (!mParams.IsEmpty()) {
                rv = evaluateToNodeSet(mParams[0], aContext,
                                       getter_AddRefs(nodes));
                NS_ENSURE_SUCCESS(rv, rv);

                if (nodes->isEmpty()) {
                    aContext->recycler()->getEmptyStringResult(aResult);

                    return NS_OK;
                }
            }

            const txXPathNode& node = nodes ? nodes->get(0) :
                                              aContext->getContextNode();
            switch (mType) {
                case LOCAL_NAME:
                {
                    StringResult* strRes = nsnull;
                    rv = aContext->recycler()->getStringResult(&strRes);
                    NS_ENSURE_SUCCESS(rv, rv);

                    *aResult = strRes;
                    txXPathNodeUtils::getLocalName(node, strRes->mValue);

                    return NS_OK;
                }
                case NAMESPACE_URI:
                {
                    StringResult* strRes = nsnull;
                    rv = aContext->recycler()->getStringResult(&strRes);
                    NS_ENSURE_SUCCESS(rv, rv);

                    *aResult = strRes;
                    txXPathNodeUtils::getNamespaceURI(node, strRes->mValue);

                    return NS_OK;
                }
                case NAME:
                {
                    // XXX Namespace: namespaces have a name
                    if (txXPathNodeUtils::isAttribute(node) ||
                        txXPathNodeUtils::isElement(node) ||
                        txXPathNodeUtils::isProcessingInstruction(node)) {
                        StringResult* strRes = nsnull;
                        rv = aContext->recycler()->getStringResult(&strRes);
                        NS_ENSURE_SUCCESS(rv, rv);

                        *aResult = strRes;
                        txXPathNodeUtils::getNodeName(node, strRes->mValue);
                    }
                    else {
                        aContext->recycler()->getEmptyStringResult(aResult);
                    }

                    return NS_OK;
                }
                default:
                {
                    break;
                }
            }
        }
        case POSITION:
        {
            return aContext->recycler()->getNumberResult(aContext->position(),
                                                         aResult);
        }

        // String functions

        case CONCAT:
        {
            nsRefPtr<StringResult> strRes;
            rv = aContext->recycler()->getStringResult(getter_AddRefs(strRes));
            NS_ENSURE_SUCCESS(rv, rv);

            PRUint32 i, len = mParams.Length();
            for (i = 0; i < len; ++i) {
                rv = mParams[i]->evaluateToString(aContext, strRes->mValue);
                NS_ENSURE_SUCCESS(rv, rv);
            }

            NS_ADDREF(*aResult = strRes);

            return NS_OK;
        }
        case CONTAINS:
        {
            nsAutoString arg2;
            rv = mParams[1]->evaluateToString(aContext, arg2);
            NS_ENSURE_SUCCESS(rv, rv);

            if (arg2.IsEmpty()) {
                aContext->recycler()->getBoolResult(PR_TRUE, aResult);
            }
            else {
                nsAutoString arg1;
                rv = mParams[0]->evaluateToString(aContext, arg1);
                NS_ENSURE_SUCCESS(rv, rv);

                aContext->recycler()->getBoolResult(FindInReadable(arg2, arg1),
                                                    aResult);
            }

            return NS_OK;
        }
        case NORMALIZE_SPACE:
        {
            nsAutoString resultStr;
            if (!mParams.IsEmpty()) {
                rv = mParams[0]->evaluateToString(aContext, resultStr);
                NS_ENSURE_SUCCESS(rv, rv);
            }
            else {
                txXPathNodeUtils::appendNodeValue(aContext->getContextNode(),
                                                  resultStr);
            }

            nsRefPtr<StringResult> strRes;
            rv = aContext->recycler()->getStringResult(getter_AddRefs(strRes));
            NS_ENSURE_SUCCESS(rv, rv);

            MBool addSpace = MB_FALSE;
            MBool first = MB_TRUE;
            strRes->mValue.SetCapacity(resultStr.Length());
            PRUnichar c;
            PRUint32 src;
            for (src = 0; src < resultStr.Length(); src++) {
                c = resultStr.CharAt(src);
                if (XMLUtils::isWhitespace(c)) {
                    addSpace = MB_TRUE;
                }
                else {
                    if (addSpace && !first)
                        strRes->mValue.Append(PRUnichar(' '));

                    strRes->mValue.Append(c);
                    addSpace = MB_FALSE;
                    first = MB_FALSE;
                }
            }
            *aResult = strRes;
            NS_ADDREF(*aResult);

            return NS_OK;
        }
        case STARTS_WITH:
        {
            nsAutoString arg2;
            rv = mParams[1]->evaluateToString(aContext, arg2);
            NS_ENSURE_SUCCESS(rv, rv);

            PRBool result = PR_FALSE;
            if (arg2.IsEmpty()) {
                result = PR_TRUE;
            }
            else {
                nsAutoString arg1;
                rv = mParams[0]->evaluateToString(aContext, arg1);
                NS_ENSURE_SUCCESS(rv, rv);

                result = StringBeginsWith(arg1, arg2);
            }

            aContext->recycler()->getBoolResult(result, aResult);

            return NS_OK;
        }
        case STRING:
        {
            nsRefPtr<StringResult> strRes;
            rv = aContext->recycler()->getStringResult(getter_AddRefs(strRes));
            NS_ENSURE_SUCCESS(rv, rv);

            if (!mParams.IsEmpty()) {
                rv = mParams[0]->evaluateToString(aContext, strRes->mValue);
                NS_ENSURE_SUCCESS(rv, rv);
            }
            else {
                txXPathNodeUtils::appendNodeValue(aContext->getContextNode(),
                                                  strRes->mValue);
            }

            NS_ADDREF(*aResult = strRes);

            return NS_OK;
        }
        case STRING_LENGTH:
        {
            nsAutoString resultStr;
            if (!mParams.IsEmpty()) {
                rv = mParams[0]->evaluateToString(aContext, resultStr);
                NS_ENSURE_SUCCESS(rv, rv);
            }
            else {
                txXPathNodeUtils::appendNodeValue(aContext->getContextNode(),
                                                  resultStr);
            }
            rv = aContext->recycler()->getNumberResult(resultStr.Length(),
                                                       aResult);
            NS_ENSURE_SUCCESS(rv, rv);

            return NS_OK;
        }
        case SUBSTRING:
        {
            nsAutoString src;
            rv = mParams[0]->evaluateToString(aContext, src);
            NS_ENSURE_SUCCESS(rv, rv);

            double start;
            rv = evaluateToNumber(mParams[1], aContext, &start);
            NS_ENSURE_SUCCESS(rv, rv);

            // check for NaN or +/-Inf
            if (Double::isNaN(start) ||
                Double::isInfinite(start) ||
                start >= src.Length() + 0.5) {
                aContext->recycler()->getEmptyStringResult(aResult);

                return NS_OK;
            }

            start = floor(start + 0.5) - 1;

            double end;
            if (mParams.Length() == 3) {
                rv = evaluateToNumber(mParams[2], aContext, &end);
                NS_ENSURE_SUCCESS(rv, rv);

                end += start;
                if (Double::isNaN(end) || end < 0) {
                    aContext->recycler()->getEmptyStringResult(aResult);

                    return NS_OK;
                }
                
                if (end > src.Length())
                    end = src.Length();
                else
                    end = floor(end + 0.5);
            }
            else {
                end = src.Length();
            }

            if (start < 0)
                start = 0;
 
            if (start > end) {
                aContext->recycler()->getEmptyStringResult(aResult);
                
                return NS_OK;
            }

            return aContext->recycler()->getStringResult(
                  Substring(src, (PRUint32)start, (PRUint32)(end - start)),
                  aResult);
        }
        case SUBSTRING_AFTER:
        {
            nsAutoString arg1;
            rv = mParams[0]->evaluateToString(aContext, arg1);
            NS_ENSURE_SUCCESS(rv, rv);

            nsAutoString arg2;
            rv = mParams[1]->evaluateToString(aContext, arg2);
            NS_ENSURE_SUCCESS(rv, rv);

            if (arg2.IsEmpty()) {
                return aContext->recycler()->getStringResult(arg1, aResult);
            }

            PRInt32 idx = arg1.Find(arg2);
            if (idx == kNotFound) {
                aContext->recycler()->getEmptyStringResult(aResult);
                
                return NS_OK;
            }

            const nsSubstring& result = Substring(arg1, idx + arg2.Length());
            return aContext->recycler()->getStringResult(result, aResult);
        }
        case SUBSTRING_BEFORE:
        {
            nsAutoString arg2;
            rv = mParams[1]->evaluateToString(aContext, arg2);
            NS_ENSURE_SUCCESS(rv, rv);

            if (arg2.IsEmpty()) {
                aContext->recycler()->getEmptyStringResult(aResult);

                return NS_OK;
            }

            nsAutoString arg1;
            rv = mParams[0]->evaluateToString(aContext, arg1);
            NS_ENSURE_SUCCESS(rv, rv);

            PRInt32 idx = arg1.Find(arg2);
            if (idx == kNotFound) {
                aContext->recycler()->getEmptyStringResult(aResult);
                
                return NS_OK;
            }

            return aContext->recycler()->getStringResult(StringHead(arg1, idx),
                                                         aResult);
        }
        case TRANSLATE:
        {
            nsAutoString src;
            rv = mParams[0]->evaluateToString(aContext, src);
            NS_ENSURE_SUCCESS(rv, rv);

            if (src.IsEmpty()) {
                aContext->recycler()->getEmptyStringResult(aResult);

                return NS_OK;
            }
            
            nsRefPtr<StringResult> strRes;
            rv = aContext->recycler()->getStringResult(getter_AddRefs(strRes));
            NS_ENSURE_SUCCESS(rv, rv);

            strRes->mValue.SetCapacity(src.Length());

            nsAutoString oldChars, newChars;
            rv = mParams[1]->evaluateToString(aContext, oldChars);
            NS_ENSURE_SUCCESS(rv, rv);

            rv = mParams[2]->evaluateToString(aContext, newChars);
            NS_ENSURE_SUCCESS(rv, rv);

            PRUint32 i;
            PRInt32 newCharsLength = (PRInt32)newChars.Length();
            for (i = 0; i < src.Length(); i++) {
                PRInt32 idx = oldChars.FindChar(src.CharAt(i));
                if (idx != kNotFound) {
                    if (idx < newCharsLength)
                        strRes->mValue.Append(newChars.CharAt((PRUint32)idx));
                }
                else {
                    strRes->mValue.Append(src.CharAt(i));
                }
            }

            NS_ADDREF(*aResult = strRes);

            return NS_OK;
        }
        
        // Number functions

        case NUMBER:
        {
            double res;
            if (!mParams.IsEmpty()) {
                rv = evaluateToNumber(mParams[0], aContext, &res);
                NS_ENSURE_SUCCESS(rv, rv);
            }
            else {
                nsAutoString resultStr;
                txXPathNodeUtils::appendNodeValue(aContext->getContextNode(),
                                                  resultStr);
                res = Double::toDouble(resultStr);
            }
            return aContext->recycler()->getNumberResult(res, aResult);
        }
        case ROUND:
        {
            double dbl;
            rv = evaluateToNumber(mParams[0], aContext, &dbl);
            NS_ENSURE_SUCCESS(rv, rv);

            if (!Double::isNaN(dbl) && !Double::isInfinite(dbl)) {
                if (Double::isNeg(dbl) && dbl >= -0.5) {
                    dbl *= 0;
                }
                else {
                    dbl = floor(dbl + 0.5);
                }
            }

            return aContext->recycler()->getNumberResult(dbl, aResult);
        }
        case FLOOR:
        {
            double dbl;
            rv = evaluateToNumber(mParams[0], aContext, &dbl);
            NS_ENSURE_SUCCESS(rv, rv);

            if (!Double::isNaN(dbl) &&
                !Double::isInfinite(dbl) &&
                !(dbl == 0 && Double::isNeg(dbl))) {
                dbl = floor(dbl);
            }

            return aContext->recycler()->getNumberResult(dbl, aResult);
        }
        case CEILING:
        {
            double dbl;
            rv = evaluateToNumber(mParams[0], aContext, &dbl);
            NS_ENSURE_SUCCESS(rv, rv);

            if (!Double::isNaN(dbl) && !Double::isInfinite(dbl)) {
                if (Double::isNeg(dbl) && dbl > -1) {
                    dbl *= 0;
                }
                else {
                    dbl = ceil(dbl);
                }
            }

            return aContext->recycler()->getNumberResult(dbl, aResult);
        }
        case SUM:
        {
            nsRefPtr<txNodeSet> nodes;
            nsresult rv = evaluateToNodeSet(mParams[0], aContext,
                                            getter_AddRefs(nodes));
            NS_ENSURE_SUCCESS(rv, rv);

            double res = 0;
            PRInt32 i;
            for (i = 0; i < nodes->size(); ++i) {
                nsAutoString resultStr;
                txXPathNodeUtils::appendNodeValue(nodes->get(i), resultStr);
                res += Double::toDouble(resultStr);
            }
            return aContext->recycler()->getNumberResult(res, aResult);
        }
        
        // Boolean functions
        
        case BOOLEAN:
        {
            PRBool result;
            nsresult rv = mParams[0]->evaluateToBool(aContext, result);
            NS_ENSURE_SUCCESS(rv, rv);

            aContext->recycler()->getBoolResult(result, aResult);

            return NS_OK;
        }
        case _FALSE:
        {
            aContext->recycler()->getBoolResult(PR_FALSE, aResult);

            return NS_OK;
        }
        case LANG:
        {
            txXPathTreeWalker walker(aContext->getContextNode());

            nsAutoString lang;
            PRBool found;
            do {
                found = walker.getAttr(txXMLAtoms::lang, kNameSpaceID_XML,
                                       lang);
            } while (!found && walker.moveToParent());

            if (!found) {
                aContext->recycler()->getBoolResult(PR_FALSE, aResult);

                return NS_OK;
            }

            nsAutoString arg;
            rv = mParams[0]->evaluateToString(aContext, arg);
            NS_ENSURE_SUCCESS(rv, rv);

            PRBool result =
                StringBeginsWith(lang, arg,
                                 txCaseInsensitiveStringComparator()) &&
                (lang.Length() == arg.Length() ||
                 lang.CharAt(arg.Length()) == '-');

            aContext->recycler()->getBoolResult(result, aResult);

            return NS_OK;
        }
        case _NOT:
        {
            PRBool result;
            rv = mParams[0]->evaluateToBool(aContext, result);
            NS_ENSURE_SUCCESS(rv, rv);

            aContext->recycler()->getBoolResult(!result, aResult);

            return NS_OK;
        }
        case _TRUE:
        {
            aContext->recycler()->getBoolResult(PR_TRUE, aResult);

            return NS_OK;
        }
    }

    aContext->receiveError(NS_LITERAL_STRING("Internal error"),
                           NS_ERROR_UNEXPECTED);
    return NS_ERROR_UNEXPECTED;
}
Exemplo n.º 24
0
void 
ImageDocument::UpdateTitleAndCharset()
{
  nsAutoCString typeStr;
  nsCOMPtr<imgIRequest> imageRequest;
  nsCOMPtr<nsIImageLoadingContent> imageLoader = do_QueryInterface(mImageContent);
  if (imageLoader) {
    imageLoader->GetRequest(nsIImageLoadingContent::CURRENT_REQUEST,
                            getter_AddRefs(imageRequest));
  }
    
  if (imageRequest) {
    nsXPIDLCString mimeType;
    imageRequest->GetMimeType(getter_Copies(mimeType));
    ToUpperCase(mimeType);
    nsXPIDLCString::const_iterator start, end;
    mimeType.BeginReading(start);
    mimeType.EndReading(end);
    nsXPIDLCString::const_iterator iter = end;
    if (FindInReadable(NS_LITERAL_CSTRING("IMAGE/"), start, iter) && 
        iter != end) {
      // strip out "X-" if any
      if (*iter == 'X') {
        ++iter;
        if (iter != end && *iter == '-') {
          ++iter;
          if (iter == end) {
            // looks like "IMAGE/X-" is the type??  Bail out of here.
            mimeType.BeginReading(iter);
          }
        } else {
          --iter;
        }
      }
      typeStr = Substring(iter, end);
    } else {
      typeStr = mimeType;
    }
  }

  nsXPIDLString status;
  if (mImageIsResized) {
    nsAutoString ratioStr;
    ratioStr.AppendInt(NSToCoordFloor(GetRatio() * 100));

    const char16_t* formatString[1] = { ratioStr.get() };
    mStringBundle->FormatStringFromName(MOZ_UTF16("ScaledImage"),
                                        formatString, 1,
                                        getter_Copies(status));
  }

  static const char* const formatNames[4] = 
  {
    "ImageTitleWithNeitherDimensionsNorFile",
    "ImageTitleWithoutDimensions",
    "ImageTitleWithDimensions2",
    "ImageTitleWithDimensions2AndFile",
  };

  MediaDocument::UpdateTitleAndCharset(typeStr, formatNames,
                                       mImageWidth, mImageHeight, status);
}
Exemplo n.º 25
0
/* Astring getCellText (in long row, in nsITreeColumn col); */
NS_IMETHODIMP 
nsCertTree::GetCellText(PRInt32 row, nsITreeColumn* col, 
                        nsAString& _retval)
{
  if (!mTreeArray)
    return NS_ERROR_NOT_INITIALIZED;

  nsresult rv;
  _retval.Truncate();

  const PRUnichar* colID;
  col->GetIdConst(&colID);

  treeArrayEl *el = GetThreadDescAtIndex(row);
  if (el != nsnull) {
    if (NS_LITERAL_STRING("certcol").Equals(colID))
      _retval.Assign(el->orgName);
    else
      _retval.Truncate();
    return NS_OK;
  }

  PRInt32 absoluteCertOffset;
  nsRefPtr<nsCertTreeDispInfo> certdi = 
    GetDispInfoAtIndex(row, &absoluteCertOffset);
  if (!certdi)
    return NS_ERROR_FAILURE;

  nsCOMPtr<nsIX509Cert> cert = certdi->mCert;
  if (!cert && certdi->mAddonInfo) {
    cert = certdi->mAddonInfo->mCert;
  }

  PRInt32 colIndex;
  col->GetIndex(&colIndex);
  PRUint32 arrayIndex=absoluteCertOffset+colIndex*(mNumRows-mNumOrgs);
  PRUint32 arrayLength=0;
  if (mCellText) {
    mCellText->GetLength(&arrayLength);
  }
  if (arrayIndex < arrayLength) {
    nsCOMPtr<nsISupportsString> myString(do_QueryElementAt(mCellText, arrayIndex));
    if (myString) {
      myString->GetData(_retval);
      return NS_OK;
    }
  }

  if (NS_LITERAL_STRING("certcol").Equals(colID)) {
    if (!cert) {
      mNSSComponent->GetPIPNSSBundleString("CertNotStored", _retval);
    }
    else {
      rv = cert->GetCommonName(_retval);
      if (NS_FAILED(rv) || _retval.IsEmpty()) {
        // kaie: I didn't invent the idea to cut off anything before 
        //       the first colon. :-)
        nsAutoString nick;
        rv = cert->GetNickname(nick);
        
        nsAString::const_iterator start, end, end2;
        nick.BeginReading(start);
        nick.EndReading(end);
        end2 = end;
  
        if (FindInReadable(NS_LITERAL_STRING(":"), start, end)) {
          // found. end points to the first char after the colon,
          // that's what we want.
          _retval = Substring(end, end2);
        }
        else {
          _retval = nick;
        }
      }
    }
  } else if (NS_LITERAL_STRING("tokencol").Equals(colID) && cert) {
    rv = cert->GetTokenName(_retval);
  } else if (NS_LITERAL_STRING("emailcol").Equals(colID) && cert) {
    rv = cert->GetEmailAddress(_retval);
  } else if (NS_LITERAL_STRING("purposecol").Equals(colID) && mNSSComponent && cert) {
    PRUint32 verified;

    nsAutoString theUsages;
    rv = cert->GetUsagesString(false, &verified, theUsages); // allow OCSP
    if (NS_FAILED(rv)) {
      verified = nsIX509Cert::NOT_VERIFIED_UNKNOWN;
    }

    switch (verified) {
      case nsIX509Cert::VERIFIED_OK:
        _retval = theUsages;
        break;

      case nsIX509Cert::CERT_REVOKED:
        rv = mNSSComponent->GetPIPNSSBundleString("VerifyRevoked", _retval);
        break;
      case nsIX509Cert::CERT_EXPIRED:
        rv = mNSSComponent->GetPIPNSSBundleString("VerifyExpired", _retval);
        break;
      case nsIX509Cert::CERT_NOT_TRUSTED:
        rv = mNSSComponent->GetPIPNSSBundleString("VerifyNotTrusted", _retval);
        break;
      case nsIX509Cert::ISSUER_NOT_TRUSTED:
        rv = mNSSComponent->GetPIPNSSBundleString("VerifyIssuerNotTrusted", _retval);
        break;
      case nsIX509Cert::ISSUER_UNKNOWN:
        rv = mNSSComponent->GetPIPNSSBundleString("VerifyIssuerUnknown", _retval);
        break;
      case nsIX509Cert::INVALID_CA:
        rv = mNSSComponent->GetPIPNSSBundleString("VerifyInvalidCA", _retval);
        break;
      case nsIX509Cert::NOT_VERIFIED_UNKNOWN:
      case nsIX509Cert::USAGE_NOT_ALLOWED:
      default:
        rv = mNSSComponent->GetPIPNSSBundleString("VerifyUnknown", _retval);
        break;
    }
  } else if (NS_LITERAL_STRING("issuedcol").Equals(colID) && cert) {
    nsCOMPtr<nsIX509CertValidity> validity;

    rv = cert->GetValidity(getter_AddRefs(validity));
    if (NS_SUCCEEDED(rv)) {
      validity->GetNotBeforeLocalDay(_retval);
    }
  } else if (NS_LITERAL_STRING("expiredcol").Equals(colID) && cert) {
    nsCOMPtr<nsIX509CertValidity> validity;

    rv = cert->GetValidity(getter_AddRefs(validity));
    if (NS_SUCCEEDED(rv)) {
      validity->GetNotAfterLocalDay(_retval);
    }
  } else if (NS_LITERAL_STRING("serialnumcol").Equals(colID) && cert) {
    rv = cert->GetSerialNumber(_retval);


  } else if (NS_LITERAL_STRING("overridetypecol").Equals(colID)) {
    // default to classic permanent-trust
    nsCertOverride::OverrideBits ob = nsCertOverride::ob_Untrusted;
    if (certdi->mTypeOfEntry == nsCertTreeDispInfo::host_port_override) {
      ob = certdi->mOverrideBits;
    }
    nsCAutoString temp;
    nsCertOverride::convertBitsToString(ob, temp);
    _retval = NS_ConvertUTF8toUTF16(temp);
  } else if (NS_LITERAL_STRING("sitecol").Equals(colID)) {
    if (certdi->mTypeOfEntry == nsCertTreeDispInfo::host_port_override) {
      nsCAutoString hostPort;
      nsCertOverrideService::GetHostWithPort(certdi->mAsciiHost, certdi->mPort, hostPort);
      _retval = NS_ConvertUTF8toUTF16(hostPort);
    }
    else {
      _retval = NS_LITERAL_STRING("*");
    }
  } else if (NS_LITERAL_STRING("lifetimecol").Equals(colID)) {
    const char *stringID = 
      (certdi->mIsTemporary) ? "CertExceptionTemporary" : "CertExceptionPermanent";
    rv = mNSSComponent->GetPIPNSSBundleString(stringID, _retval);
  } else if (NS_LITERAL_STRING("typecol").Equals(colID) && cert) {
    nsCOMPtr<nsIX509Cert2> pipCert = do_QueryInterface(cert);
    PRUint32 type = nsIX509Cert::UNKNOWN_CERT;

    if (pipCert) {
	rv = pipCert->GetCertType(&type);
    }

    switch (type) {
    case nsIX509Cert::USER_CERT:
        rv = mNSSComponent->GetPIPNSSBundleString("CertUser", _retval);
	break;
    case nsIX509Cert::CA_CERT:
        rv = mNSSComponent->GetPIPNSSBundleString("CertCA", _retval);
	break;
    case nsIX509Cert::SERVER_CERT:
        rv = mNSSComponent->GetPIPNSSBundleString("CertSSL", _retval);
	break;
    case nsIX509Cert::EMAIL_CERT:
        rv = mNSSComponent->GetPIPNSSBundleString("CertEmail", _retval);
	break;
    default:
        rv = mNSSComponent->GetPIPNSSBundleString("CertUnknown", _retval);
	break;
    }

  } else {
    return NS_ERROR_FAILURE;
  }
  if (mCellText) {
    nsCOMPtr<nsISupportsString> text(do_CreateInstance(NS_SUPPORTS_STRING_CONTRACTID, &rv));
    NS_ENSURE_SUCCESS(rv, rv);
    text->SetData(_retval);
    mCellText->ReplaceElementAt(text, arrayIndex, false);
  }
  return rv;
}
Exemplo n.º 26
0
bool
nsTemplateCondition::CheckMatchStrings(const nsAString& aLeftString,
                                       const nsAString& aRightString)
{
    bool match = false;

    if (aRightString.IsEmpty()) {
        if ((mRelation == eEquals) && aLeftString.IsEmpty())
            match = true;
    }
    else {
        switch (mRelation) {
            case eEquals:
                if (mIgnoreCase)
                    match = aLeftString.Equals(aRightString,
                                               nsCaseInsensitiveStringComparator());
                else
                    match = aLeftString.Equals(aRightString);
                break;

            case eLess:
            case eGreater:
            {
                // non-numbers always compare false
                nsresult err;
                PRInt32 leftint = PromiseFlatString(aLeftString).ToInteger(&err);
                if (NS_SUCCEEDED(err)) {
                    PRInt32 rightint = PromiseFlatString(aRightString).ToInteger(&err);
                    if (NS_SUCCEEDED(err)) {
                        match = (mRelation == eLess) ? (leftint < rightint) :
                                                       (leftint > rightint);
                    }
                }

                break;
            }

            case eBefore:
            {
                nsICollation* collation = nsXULContentUtils::GetCollation();
                if (collation) {
                    PRInt32 sortOrder;
                    collation->CompareString((mIgnoreCase ?
                                              static_cast<PRInt32>(nsICollation::kCollationCaseInSensitive) :
                                              static_cast<PRInt32>(nsICollation::kCollationCaseSensitive)),
                                              aLeftString,
                                              aRightString,
                                              &sortOrder);
                    match = (sortOrder < 0);
                }
                else if (mIgnoreCase) {
                    match = (Compare(aLeftString, aRightString,
                                     nsCaseInsensitiveStringComparator()) < 0);
                }
                else {
                    match = (Compare(aLeftString, aRightString) < 0);
                }
                break;
            }

            case eAfter:
            {
                nsICollation* collation = nsXULContentUtils::GetCollation();
                if (collation) {
                    PRInt32 sortOrder;
                    collation->CompareString((mIgnoreCase ?
                                              static_cast<PRInt32>(nsICollation::kCollationCaseInSensitive) :
                                              static_cast<PRInt32>(nsICollation::kCollationCaseSensitive)),
                                              aLeftString,
                                              aRightString,
                                              &sortOrder);
                    match = (sortOrder > 0);
                }
                else if (mIgnoreCase) {
                    match = (Compare(aLeftString, aRightString,
                                     nsCaseInsensitiveStringComparator()) > 0);
                }
                else {
                    match = (Compare(aLeftString, aRightString) > 0);
                }
                break;
            }

            case eStartswith:
                if (mIgnoreCase)
                    match = (StringBeginsWith(aLeftString, aRightString,
                                              nsCaseInsensitiveStringComparator()));
                else
                    match = (StringBeginsWith(aLeftString, aRightString));
                break;

            case eEndswith:
                if (mIgnoreCase)
                    match = (StringEndsWith(aLeftString, aRightString,
                                            nsCaseInsensitiveStringComparator()));
                else
                    match = (StringEndsWith(aLeftString, aRightString));
                break;

            case eContains:
            {
                nsAString::const_iterator start, end;
                aLeftString.BeginReading(start);
                aLeftString.EndReading(end);
                if (mIgnoreCase)
                    match = CaseInsensitiveFindInReadable(aRightString, start, end);
                else
                    match = FindInReadable(aRightString, start, end);
                break;
            }

            default:
                break;
        }
    }

    if (mNegate) match = !match;

    return match;
}
Exemplo n.º 27
0
Maybe<bool>
Compatibility::OnUIAMessage(WPARAM aWParam, LPARAM aLParam)
{
  auto clearUiaRemotePid = MakeScopeExit([]() {
    sUiaRemotePid = Nothing();
  });

  Telemetry::AutoTimer<Telemetry::A11Y_UIA_DETECTION_TIMING_MS> timer;

  // UIA creates a section containing the substring "HOOK_SHMEM_"
  NS_NAMED_LITERAL_STRING(kStrHookShmem, "HOOK_SHMEM_");

  // The section name always ends with this suffix, which is derived from the
  // current thread id and the UIA message's WPARAM and LPARAM.
  nsAutoString partialSectionSuffix;
  partialSectionSuffix.AppendPrintf("_%08x_%08x_%08x", ::GetCurrentThreadId(),
                                    static_cast<DWORD>(aLParam), aWParam);

  // Find any named Section that matches the naming convention of the UIA shared
  // memory.
  nsAutoHandle section;
  auto comparator = [&](const nsDependentSubstring& aName,
                        const nsDependentSubstring& aType) -> bool {
    if (aType.Equals(NS_LITERAL_STRING("Section")) &&
        FindInReadable(kStrHookShmem, aName) &&
        StringEndsWith(aName, partialSectionSuffix)) {
      section.own(::OpenFileMapping(GENERIC_READ, FALSE,
                                    PromiseFlatString(aName).get()));
      return false;
    }

    return true;
  };

  if (!FindNamedObject(comparator) || !section) {
    return Nothing();
  }

  NTSTATUS ntStatus;

  // First we must query for a list of all the open handles in the system.
  UniquePtr<char[]> handleInfoBuf;
  ULONG handleInfoBufLen = sizeof(SYSTEM_HANDLE_INFORMATION_EX) +
                           1024 * sizeof(SYSTEM_HANDLE_TABLE_ENTRY_INFO_EX);

  // We must query for handle information in a loop, since we are effectively
  // asking the kernel to take a snapshot of all the handles on the system;
  // the size of the required buffer may fluctuate between successive calls.
  while (true) {
    // These allocations can be hundreds of megabytes on some computers, so
    // we should use fallible new here.
    handleInfoBuf = MakeUniqueFallible<char[]>(handleInfoBufLen);
    if (!handleInfoBuf) {
      return Nothing();
    }

    ntStatus = ::NtQuerySystemInformation(
                 (SYSTEM_INFORMATION_CLASS) SystemExtendedHandleInformation,
                 handleInfoBuf.get(), handleInfoBufLen, &handleInfoBufLen);
    if (ntStatus == STATUS_INFO_LENGTH_MISMATCH) {
      continue;
    }

    if (!NT_SUCCESS(ntStatus)) {
      return Nothing();
    }

    break;
  }

  const DWORD ourPid = ::GetCurrentProcessId();
  Maybe<PVOID> kernelObject;
  static Maybe<USHORT> sectionObjTypeIndex;
  nsTHashtable<nsUint32HashKey> nonSectionObjTypes;
  nsDataHashtable<nsVoidPtrHashKey, DWORD> objMap;

  auto handleInfo = reinterpret_cast<SYSTEM_HANDLE_INFORMATION_EX*>(handleInfoBuf.get());

  for (ULONG index = 0; index < handleInfo->mHandleCount; ++index) {
    SYSTEM_HANDLE_TABLE_ENTRY_INFO_EX& curHandle = handleInfo->mHandles[index];

    HANDLE handle = reinterpret_cast<HANDLE>(curHandle.mHandle);

    // The mapping of the curHandle.mObjectTypeIndex field depends on the
    // underlying OS kernel. As we scan through the handle list, we record the
    // type indices such that we may use those values to skip over handles that
    // refer to non-section objects.
    if (sectionObjTypeIndex) {
      // If we know the type index for Sections, that's the fastest check...
      if (sectionObjTypeIndex.value() != curHandle.mObjectTypeIndex) {
        // Not a section
        continue;
      }
    } else if (nonSectionObjTypes.Contains(static_cast<uint32_t>(
                                             curHandle.mObjectTypeIndex))) {
      // Otherwise we check whether or not the object type is definitely _not_
      // a Section...
      continue;
    } else if (ourPid == curHandle.mPid) {
      // Otherwise we need to issue some system calls to find out the object
      // type corresponding to the current handle's type index.
      ULONG objTypeBufLen;
      ntStatus = ::NtQueryObject(handle, ObjectTypeInformation,
                                 nullptr, 0, &objTypeBufLen);
      if (ntStatus != STATUS_INFO_LENGTH_MISMATCH) {
        continue;
      }

      auto objTypeBuf = MakeUnique<char[]>(objTypeBufLen);
      ntStatus = ::NtQueryObject(handle, ObjectTypeInformation, objTypeBuf.get(),
                                 objTypeBufLen, &objTypeBufLen);
      if (!NT_SUCCESS(ntStatus)) {
        continue;
      }

      auto objType =
        reinterpret_cast<PUBLIC_OBJECT_TYPE_INFORMATION*>(objTypeBuf.get());

      // Now we check whether the object's type name matches "Section"
      nsDependentSubstring objTypeName(objType->TypeName.Buffer,
                                       objType->TypeName.Length / sizeof(wchar_t));
      if (!objTypeName.Equals(NS_LITERAL_STRING("Section"))) {
        nonSectionObjTypes.PutEntry(static_cast<uint32_t>(curHandle.mObjectTypeIndex));
        continue;
      }

      sectionObjTypeIndex = Some(curHandle.mObjectTypeIndex);
    }

    // At this point we know that curHandle references a Section object.
    // Now we can do some actual tests on it.

    if (ourPid != curHandle.mPid) {
      if (kernelObject && kernelObject.value() == curHandle.mObject) {
        // The kernel objects match -- we have found the remote pid!
        sUiaRemotePid = Some(curHandle.mPid);
        break;
      }

      // An object that is not ours. Since we do not yet know which kernel
      // object we're interested in, we'll save the current object for later.
      objMap.Put(curHandle.mObject, curHandle.mPid);
    } else if (handle == section.get()) {
      // This is the file mapping that we opened above. We save this mObject
      // in order to compare to Section objects opened by other processes.
      kernelObject = Some(curHandle.mObject);
    }
  }

  if (!kernelObject) {
    return Nothing();
  }

  if (!sUiaRemotePid) {
    // We found kernelObject *after* we saw the remote process's copy. Now we
    // must look it up in objMap.
    DWORD pid;
    if (objMap.Get(kernelObject.value(), &pid)) {
      sUiaRemotePid = Some(pid);
    }
  }

  if (!sUiaRemotePid) {
    return Nothing();
  }

  a11y::SetInstantiator(sUiaRemotePid.value());

  // Block if necessary
  nsCOMPtr<nsIFile> instantiator;
  if (a11y::GetInstantiator(getter_AddRefs(instantiator)) &&
      ShouldBlockUIAClient(instantiator)) {
    return Some(false);
  }

  return Some(true);
}
Exemplo n.º 28
0
PRBool test_findinreadable()
  {
    const char text[] = "jar:jar:file:///c:/software/mozilla/mozilla_2006_02_21.jar!/browser/chrome/classic.jar!/";
    nsCAutoString value(text);

    nsACString::const_iterator begin, end;
    value.BeginReading(begin);
    value.EndReading(end);
    nsACString::const_iterator delim_begin (begin),
                               delim_end   (end);

    // Search for last !/ at the end of the string
    if (!FindInReadable(NS_LITERAL_CSTRING("!/"), delim_begin, delim_end))
        return PR_FALSE;
    char *r = ToNewCString(Substring(delim_begin, delim_end));
    // Should match the first "!/" but not the last
    if ((delim_end == end) || (strcmp(r, "!/")!=0))
      {
        printf("r = %s\n", r);
        nsMemory::Free(r);
        return PR_FALSE;
      }
    nsMemory::Free(r);

    delim_begin = begin;
    delim_end = end;

    // Search for first jar:
    if (!FindInReadable(NS_LITERAL_CSTRING("jar:"), delim_begin, delim_end))
        return PR_FALSE;

    r = ToNewCString(Substring(delim_begin, delim_end));
    // Should not match the first jar:, but the second one
    if ((delim_begin != begin) || (strcmp(r, "jar:")!=0))
      {
        printf("r = %s\n", r);
        nsMemory::Free(r);
        return PR_FALSE;
      }
    nsMemory::Free(r);

    // Search for jar: in a Substring
    delim_begin = begin; delim_begin++;
    delim_end = end;
    if (!FindInReadable(NS_LITERAL_CSTRING("jar:"), delim_begin, delim_end))
        return PR_FALSE;

    r = ToNewCString(Substring(delim_begin, delim_end));
    // Should not match the first jar:, but the second one
    if ((delim_begin == begin) || (strcmp(r, "jar:")!=0))
      {
        printf("r = %s\n", r);
        nsMemory::Free(r);
        return PR_FALSE;
      }
    nsMemory::Free(r);

    // Should not find a match
    if (FindInReadable(NS_LITERAL_CSTRING("gecko"), delim_begin, delim_end))
        return PR_FALSE;

    // When no match is found, range should be empty
    if (delim_begin != delim_end) 
        return PR_FALSE;

    // Should not find a match (search not beyond Substring)
    delim_begin = begin; for (int i=0;i<6;i++) delim_begin++;
    delim_end = end;
    if (FindInReadable(NS_LITERAL_CSTRING("jar:"), delim_begin, delim_end))
        return PR_FALSE;

    // When no match is found, range should be empty
    if (delim_begin != delim_end) 
        return PR_FALSE;

    // Should not find a match (search not beyond Substring)
    delim_begin = begin;
    delim_end = end; for (int i=0;i<7;i++) delim_end--;
    if (FindInReadable(NS_LITERAL_CSTRING("classic"), delim_begin, delim_end))
        return PR_FALSE;

    // When no match is found, range should be empty
    if (delim_begin != delim_end) 
        return PR_FALSE;

    return PR_TRUE;
  }
Exemplo n.º 29
0
NS_IMETHODIMP
nsFeedSniffer::GetMIMETypeFromContent(nsIRequest* request, 
                                      const uint8_t* data, 
                                      uint32_t length, 
                                      nsACString& sniffedType)
{
  nsCOMPtr<nsIHttpChannel> channel(do_QueryInterface(request));
  if (!channel)
    return NS_ERROR_NO_INTERFACE;

  // Check that this is a GET request, since you can't subscribe to a POST...
  nsAutoCString method;
  channel->GetRequestMethod(method);
  if (!method.EqualsLiteral("GET")) {
    sniffedType.Truncate();
    return NS_OK;
  }

  // We need to find out if this is a load of a view-source document. In this
  // case we do not want to override the content type, since the source display
  // does not need to be converted from feed format to XUL. More importantly, 
  // we don't want to change the content type from something 
  // nsContentDLF::CreateInstance knows about (e.g. application/xml, text/html 
  // etc) to something that only the application fe knows about (maybe.feed) 
  // thus deactivating syntax highlighting.
  nsCOMPtr<nsIURI> originalURI;
  channel->GetOriginalURI(getter_AddRefs(originalURI));

  nsAutoCString scheme;
  originalURI->GetScheme(scheme);
  if (scheme.EqualsLiteral("view-source")) {
    sniffedType.Truncate();
    return NS_OK;
  }

  // Check the Content-Type to see if it is set correctly. If it is set to 
  // something specific that we think is a reliable indication of a feed, don't
  // bother sniffing since we assume the site maintainer knows what they're 
  // doing. 
  nsAutoCString contentType;
  channel->GetContentType(contentType);
  bool noSniff = contentType.EqualsLiteral(TYPE_RSS) ||
                   contentType.EqualsLiteral(TYPE_ATOM);

  // Check to see if this was a feed request from the location bar or from
  // the feed: protocol. This is also a reliable indication.
  // The value of the header doesn't matter.  
  if (!noSniff) {
    nsAutoCString sniffHeader;
    nsresult foundHeader =
      channel->GetRequestHeader(NS_LITERAL_CSTRING("X-Moz-Is-Feed"),
                                sniffHeader);
    noSniff = NS_SUCCEEDED(foundHeader);
  }

  if (noSniff) {
    // check for an attachment after we have a likely feed.
    if(HasAttachmentDisposition(channel)) {
      sniffedType.Truncate();
      return NS_OK;
    }

    // set the feed header as a response header, since we have good metadata
    // telling us that the feed is supposed to be RSS or Atom
    channel->SetResponseHeader(NS_LITERAL_CSTRING("X-Moz-Is-Feed"),
                               NS_LITERAL_CSTRING("1"), false);
    sniffedType.AssignLiteral(TYPE_MAYBE_FEED);
    return NS_OK;
  }

  // Don't sniff arbitrary types.  Limit sniffing to situations that
  // we think can reasonably arise.
  if (!contentType.EqualsLiteral(TEXT_HTML) &&
      !contentType.EqualsLiteral(APPLICATION_OCTET_STREAM) &&
      // Same criterion as XMLHttpRequest.  Should we be checking for "+xml"
      // and check for text/xml and application/xml by hand instead?
      contentType.Find("xml") == -1) {
    sniffedType.Truncate();
    return NS_OK;
  }

  // Now we need to potentially decompress data served with 
  // Content-Encoding: gzip
  nsresult rv = ConvertEncodedData(request, data, length);
  if (NS_FAILED(rv))
    return rv;

  // We cap the number of bytes to scan at MAX_BYTES to prevent picking up 
  // false positives by accidentally reading document content, e.g. a "how to
  // make a feed" page.
  const char* testData;
  if (mDecodedData.IsEmpty()) {
    testData = (const char*)data;
    length = std::min(length, MAX_BYTES);
  } else {
    testData = mDecodedData.get();
    length = std::min(mDecodedData.Length(), MAX_BYTES);
  }

  // The strategy here is based on that described in:
  // http://blogs.msdn.com/rssteam/articles/PublishersGuide.aspx
  // for interoperarbility purposes.

  // Thus begins the actual sniffing.
  nsDependentCSubstring dataString((const char*)testData, length);

  bool isFeed = false;

  // RSS 0.91/0.92/2.0
  isFeed = ContainsTopLevelSubstring(dataString, "<rss");

  // Atom 1.0
  if (!isFeed)
    isFeed = ContainsTopLevelSubstring(dataString, "<feed");

  // RSS 1.0
  if (!isFeed) {
    bool foundNS_RDF = FindInReadable(NS_LITERAL_CSTRING(NS_RDF), dataString);
    bool foundNS_RSS = FindInReadable(NS_LITERAL_CSTRING(NS_RSS), dataString);
    isFeed = ContainsTopLevelSubstring(dataString, "<rdf:RDF") &&
      foundNS_RDF && foundNS_RSS;
  }

  // If we sniffed a feed, coerce our internal type
  if (isFeed && !HasAttachmentDisposition(channel))
    sniffedType.AssignLiteral(TYPE_MAYBE_FEED);
  else
    sniffedType.Truncate();
  return NS_OK;
}