Ejemplo n.º 1
0
void nsOutlookMail::MakeAddressBookNameUnique(nsString& name, nsString& list)
{
  nsString    newName;
  int        idx = 1;

  newName = name;
  while (!IsAddressBookNameUnique(newName, list)) {
    newName = name;
    newName.Append(PRUnichar(' '));
    newName.AppendInt((int32_t) idx);
    idx++;
  }

  name = newName;
  list.AppendLiteral("[");
  list.Append(name);
  list.AppendLiteral("],");
}
Ejemplo n.º 2
0
bool
mozTXTToHTMLConv::CheckURLAndCreateHTML(
     const nsString& txtURL, const nsString& desc, const modetype mode,
     nsString& outputHTML)
{
  // Create *uri from txtURL
  nsCOMPtr<nsIURI> uri;
  nsresult rv;
  // Lazily initialize mIOService
  if (!mIOService)
  {
    mIOService = do_GetIOService();

    if (!mIOService)
      return false;
  }

  // See if the url should be linkified.
  NS_ConvertUTF16toUTF8 utf8URL(txtURL);
  if (!ShouldLinkify(utf8URL))
    return false;

  // it would be faster if we could just check to see if there is a protocol
  // handler for the url and return instead of actually trying to create a url...
  rv = mIOService->NewURI(utf8URL, nsnull, nsnull, getter_AddRefs(uri));

  // Real work
  if (NS_SUCCEEDED(rv) && uri)
  {
    outputHTML.AssignLiteral("<a class=\"moz-txt-link-");
    switch(mode)
    {
    case RFC1738:
      outputHTML.AppendLiteral("rfc1738");
      break;
    case RFC2396E:
      outputHTML.AppendLiteral("rfc2396E");
      break;
    case freetext:
      outputHTML.AppendLiteral("freetext");
      break;
    case abbreviated:
      outputHTML.AppendLiteral("abbreviated");
      break;
    default: break;
    }
    nsAutoString escapedURL(txtURL);
    EscapeStr(escapedURL, true);

    outputHTML.AppendLiteral("\" href=\"");
    outputHTML += escapedURL;
    outputHTML.AppendLiteral("\">");
    outputHTML += desc;
    outputHTML.AppendLiteral("</a>");
    return true;
  }
  else
    return false;
}
Ejemplo n.º 3
0
void nsIndexedToHTML::FormatSizeString(PRInt64 inSize, nsString& outSizeString)
{
    outSizeString.Truncate();
    if (inSize > PRInt64(0)) {
        // round up to the nearest Kilobyte
        PRInt64  upperSize = (inSize + PRInt64(1023)) / PRInt64(1024);
        outSizeString.AppendInt(upperSize);
        outSizeString.AppendLiteral(" KB");
    }
}
Ejemplo n.º 4
0
void nsStyleSides::AppendToString(nsString& aBuffer) const
{
  nsStyleCoord  temp;

  GetLeft(temp);
  aBuffer.AppendLiteral("left: ");
  temp.AppendToString(aBuffer);

  GetTop(temp);
  aBuffer.AppendLiteral("top: ");
  temp.AppendToString(aBuffer);

  GetRight(temp);
  aBuffer.AppendLiteral("right: ");
  temp.AppendToString(aBuffer);

  GetBottom(temp);
  aBuffer.AppendLiteral("bottom: ");
  temp.AppendToString(aBuffer);
}
Ejemplo n.º 5
0
void CMapiFolderList::ChangeName( nsString& name)
{
  if (name.IsEmpty()) {
    name.AssignLiteral("1");
    return;
  }
  PRUnichar lastC = name.Last();
  if ((lastC >= '0') && (lastC <= '9')) {
    lastC++;
    if (lastC > '9') {
      lastC = '1';
      name.SetCharAt( lastC, name.Length() - 1);
      name.AppendLiteral("0");
    }
    else {
      name.SetCharAt( lastC, name.Length() - 1);
    }
  }
  else {
    name.AppendLiteral(" 2");
  }
}
Ejemplo n.º 6
0
/* Formats an error message for non-certificate-related SSL errors
 * and non-overridable certificate errors (both are of type
 * PlainErrormMessage). Use formatOverridableCertErrorMessage
 * for overridable cert errors.
 */
static nsresult
formatPlainErrorMessage(const nsXPIDLCString &host, int32_t port,
                        PRErrorCode err,
                        bool suppressPort443,
                        nsString &returnedMessage)
{
    static NS_DEFINE_CID(kNSSComponentCID, NS_NSSCOMPONENT_CID);

    const char16_t *params[1];
    nsresult rv;

    nsCOMPtr<nsINSSComponent> component = do_GetService(kNSSComponentCID, &rv);
    NS_ENSURE_SUCCESS(rv, rv);

    if (host.Length())
    {
        nsString hostWithPort;

        // For now, hide port when it's 443 and we're reporting the error.
        // In the future a better mechanism should be used
        // to make a decision about showing the port number, possibly by requiring
        // the context object to implement a specific interface.
        // The motivation is that Mozilla browser would like to hide the port number
        // in error pages in the common case.

        hostWithPort.AssignASCII(host);
        if (!suppressPort443 || port != 443) {
            hostWithPort.Append(':');
            hostWithPort.AppendInt(port);
        }
        params[0] = hostWithPort.get();

        nsString formattedString;
        rv = component->PIPBundleFormatStringFromName("SSLConnectionErrorPrefix",
                params, 1,
                formattedString);
        if (NS_SUCCEEDED(rv))
        {
            returnedMessage.Append(formattedString);
            returnedMessage.AppendLiteral("\n\n");
        }
    }

    nsString explanation;
    rv = nsNSSErrors::getErrorMessageFromCode(err, component, explanation);
    if (NS_SUCCEEDED(rv))
        returnedMessage.Append(explanation);

    return NS_OK;
}
Ejemplo n.º 7
0
void
nsPerformanceSnapshot::GetGroupId(JSContext* cx,
                                  uint64_t uid,
                                  nsString& groupId)
{
  JSRuntime* rt = JS_GetRuntime(cx);
  uint64_t runtimeId = reinterpret_cast<uintptr_t>(rt);

  groupId.AssignLiteral("process: ");
  groupId.AppendInt(mProcessId);
  groupId.AssignLiteral(", thread: ");
  groupId.AppendInt(runtimeId);
  groupId.AppendLiteral(", group: ");
  groupId.AppendInt(uid);
}
Ejemplo n.º 8
0
// Returns NULL if there is no personal namespace on the given host
NS_IMETHODIMP nsIMAPHostSessionList::GetOnlineInboxPathForHost(const char *serverKey, nsString &result)
{
  PR_EnterMonitor(gCachedHostInfoMonitor);
  nsIMAPHostInfo *host = FindHost(serverKey);
  if (host)
  {
    nsIMAPNamespace *ns = NULL;
    ns = host->fNamespaceList->GetDefaultNamespaceOfType(kPersonalNamespace);
    if (ns)
    {
      CopyASCIItoUTF16(nsDependentCString(ns->GetPrefix()), result);
      result.AppendLiteral("INBOX");
    }
  }
  else
    result.Truncate();
  PR_ExitMonitor(gCachedHostInfoMonitor);
  return (host == NULL) ? NS_ERROR_ILLEGAL_VALUE : NS_OK;
}
ENameValueFlag
XULTreeGridRowAccessible::Name(nsString& aName)
{
  aName.Truncate();

  // XXX: the row name sholdn't be a concatenation of cell names (bug 664384).
  nsCOMPtr<nsITreeColumn> column = nsCoreUtils::GetFirstSensibleColumn(mTree);
  while (column) {
    if (!aName.IsEmpty())
      aName.AppendLiteral(" ");

    nsAutoString cellName;
    GetCellName(column, cellName);
    aName.Append(cellName);

    column = nsCoreUtils::GetNextSensibleColumn(column);
  }

  return eNameOK;
}
Ejemplo n.º 10
0
// Returns NULL if there is no personal namespace on the given host
NS_IMETHODIMP nsIMAPHostSessionList::GetOnlineInboxPathForHost(const char *serverKey, nsString &result)
{
  PR_EnterMonitor(gCachedHostInfoMonitor);
  nsIMAPHostInfo *host = FindHost(serverKey);
  if (host)
  {
    nsIMAPNamespace *ns = NULL;
    ns = host->fNamespaceList->GetDefaultNamespaceOfType(kPersonalNamespace);
    if (ns)
    {
      result.AssignWithConversion(ns->GetPrefix());
      result.AppendLiteral("INBOX");
    }
  }
  else
  {
    result.SetLength(0);
  }
  PR_ExitMonitor(gCachedHostInfoMonitor);
  return (host == NULL) ? NS_ERROR_ILLEGAL_VALUE : NS_OK;
}
void
ProgressMeterAccessible<Max>::Value(nsString& aValue)
{
  LeafAccessible::Value(aValue);
  if (!aValue.IsEmpty())
    return;

  double maxValue = MaxValue();
  if (IsNaN(maxValue) || maxValue == 0)
    return;

  double curValue = CurValue();
  if (IsNaN(curValue))
    return;

  // Treat the current value bigger than maximum as 100%.
  double percentValue = (curValue < maxValue) ?
    (curValue / maxValue) * 100 : 100;

  aValue.AppendFloat(percentValue);
  aValue.AppendLiteral("%");
}
Ejemplo n.º 12
0
// the glyph is appended to aOutputString instead of the original string...
bool
mozTXTToHTMLConv::GlyphHit(const PRUnichar * aInString, PRInt32 aInLength, bool col0,
         nsString& aOutputString, PRInt32& glyphTextLen)
{
  PRUnichar text0 = aInString[0]; 
  PRUnichar text1 = aInString[1];
  PRUnichar firstChar = (col0 ? text0 : text1);

  // temporary variable used to store the glyph html text
  nsAutoString outputHTML;
  bool bTestSmilie;
  bool bArg = false;
  int i;

  // refactor some of this mess to avoid code duplication and speed execution a bit
  // there are two cases that need to be tried one after another. To avoid a lot of
  // duplicate code, rolling into a loop

  i = 0;
  while ( i < 2 )
  {
    bTestSmilie = false;
    if ( !i && (firstChar == ':' || firstChar == ';' || firstChar == '=' || firstChar == '>' || firstChar == '8' || firstChar == 'O'))
    {
        // first test passed

        bTestSmilie = true;
        bArg = col0;
    }
    if ( i && col0 && ( text1 == ':' || text1 == ';' || text1 == '=' || text1 == '>' || text1 == '8' || text1 == 'O' ) )
    {
        // second test passed

        bTestSmilie = true;
        bArg = false;
    }
    if ( bTestSmilie && (
          SmilyHit(aInString, aInLength, bArg,
                   ":-)",
                   "moz-smiley-s1", // smile
                   outputHTML, glyphTextLen) ||
  
          SmilyHit(aInString, aInLength, bArg,
                   ":)",
                   "moz-smiley-s1", // smile
                   outputHTML, glyphTextLen) ||
          
          SmilyHit(aInString, aInLength, bArg,
                   ":-D",
                   "moz-smiley-s5", // laughing
                   outputHTML, glyphTextLen) ||
          
          SmilyHit(aInString, aInLength, bArg,
                   ":-(",
                   "moz-smiley-s2", // frown
                   outputHTML, glyphTextLen) ||
          
          SmilyHit(aInString, aInLength, bArg,
                   ":(",
                   "moz-smiley-s2", // frown
                   outputHTML, glyphTextLen) ||
          
          SmilyHit(aInString, aInLength, bArg,
                   ":-[",
                   "moz-smiley-s6", // embarassed
                   outputHTML, glyphTextLen) ||
          
          SmilyHit(aInString, aInLength, bArg,
                   ";-)",
                   "moz-smiley-s3", // wink
                   outputHTML, glyphTextLen) ||

          SmilyHit(aInString, aInLength, col0,
                   ";)",
                   "moz-smiley-s3", // wink
                   outputHTML, glyphTextLen) ||
          
          SmilyHit(aInString, aInLength, bArg,
                   ":-\\",
                   "moz-smiley-s7", // undecided
                   outputHTML, glyphTextLen) ||
          
          SmilyHit(aInString, aInLength, bArg,
                   ":-P",
                   "moz-smiley-s4", // tongue
                   outputHTML, glyphTextLen) ||
                   
          SmilyHit(aInString, aInLength, bArg,
                   ";-P",
                   "moz-smiley-s4", // tongue
                   outputHTML, glyphTextLen) ||  
         
          SmilyHit(aInString, aInLength, bArg,
                   "=-O",
                   "moz-smiley-s8", // surprise
                   outputHTML, glyphTextLen) ||
         
          SmilyHit(aInString, aInLength, bArg,
                   ":-*",
                   "moz-smiley-s9", // kiss
                   outputHTML, glyphTextLen) ||
         
          SmilyHit(aInString, aInLength, bArg,
                   ">:o",
                   "moz-smiley-s10", // yell
                   outputHTML, glyphTextLen) ||
          
          SmilyHit(aInString, aInLength, bArg,
                   ">:-o",
                   "moz-smiley-s10", // yell
                   outputHTML, glyphTextLen) ||
        
          SmilyHit(aInString, aInLength, bArg,
                   "8-)",
                   "moz-smiley-s11", // cool
                   outputHTML, glyphTextLen) ||
         
          SmilyHit(aInString, aInLength, bArg,
                   ":-$",
                   "moz-smiley-s12", // money
                   outputHTML, glyphTextLen) ||
         
          SmilyHit(aInString, aInLength, bArg,
                   ":-!",
                   "moz-smiley-s13", // foot
                   outputHTML, glyphTextLen) ||
         
          SmilyHit(aInString, aInLength, bArg,
                   "O:-)",
                   "moz-smiley-s14", // innocent
                   outputHTML, glyphTextLen) ||
         
          SmilyHit(aInString, aInLength, bArg,
                   ":'(",
                   "moz-smiley-s15", // cry
                   outputHTML, glyphTextLen) ||
         
          SmilyHit(aInString, aInLength, bArg,
                   ":-X",
                   "moz-smiley-s16", // sealed
                   outputHTML, glyphTextLen) 
        )
    )
    {
        aOutputString.Append(outputHTML);
        return true;
    }
    i++;
  }
  if (text0 == '\f')
  {
      aOutputString.AppendLiteral("<span class='moz-txt-formfeed'></span>");
      glyphTextLen = 1;
      return true;
  }
  if (text0 == '+' || text1 == '+')
  {
    if (ItMatchesDelimited(aInString, aInLength,
                           NS_LITERAL_STRING(" +/-").get(), 4,
                           LT_IGNORE, LT_IGNORE))
    {
      aOutputString.AppendLiteral(" &plusmn;");
      glyphTextLen = 4;
      return true;
    }
    if (col0 && ItMatchesDelimited(aInString, aInLength,
                                   NS_LITERAL_STRING("+/-").get(), 3,
                                   LT_IGNORE, LT_IGNORE))
    {
      aOutputString.AppendLiteral("&plusmn;");
      glyphTextLen = 3;
      return true;
    }
  }

  // x^2  =>  x<sup>2</sup>,   also handle powers x^-2,  x^0.5
  // implement regular expression /[\dA-Za-z\)\]}]\^-?\d+(\.\d+)*[^\dA-Za-z]/
  if    
    (
      text1 == '^'
      && 
      (
        nsCRT::IsAsciiDigit(text0) || nsCRT::IsAsciiAlpha(text0) || 
        text0 == ')' || text0 == ']' || text0 == '}'
      )
      &&
      (
        (2 < aInLength && nsCRT::IsAsciiDigit(aInString[2])) ||
        (3 < aInLength && aInString[2] == '-' && nsCRT::IsAsciiDigit(aInString[3]))
      )
    )
  {
    // Find first non-digit
    PRInt32 delimPos = 3;  // skip "^" and first digit (or '-')
    for (; delimPos < aInLength
           &&
           (
             nsCRT::IsAsciiDigit(aInString[delimPos]) || 
             (aInString[delimPos] == '.' && delimPos + 1 < aInLength &&
               nsCRT::IsAsciiDigit(aInString[delimPos + 1]))
           );
         delimPos++)
      ;

    if (delimPos < aInLength && nsCRT::IsAsciiAlpha(aInString[delimPos]))
    {
      return false;
    }

    outputHTML.Truncate();
    outputHTML += text0;
    outputHTML.AppendLiteral(
      "<sup class=\"moz-txt-sup\">"
      "<span style=\"display:inline-block;width:0;height:0;overflow:hidden\">"
      "^</span>");

    aOutputString.Append(outputHTML);
    aOutputString.Append(&aInString[2], delimPos - 2);
    aOutputString.AppendLiteral("</sup>");

    glyphTextLen = delimPos /* - 1 + 1 */ ;
    return true;
  }
  /*
   The following strings are not substituted:
   |TXT   |HTML     |Reason
   +------+---------+----------
    ->     &larr;    Bug #454
    =>     &lArr;    dito
    <-     &rarr;    dito
    <=     &rArr;    dito
    (tm)   &trade;   dito
    1/4    &frac14;  is triggered by 1/4 Part 1, 2/4 Part 2, ...
    3/4    &frac34;  dito
    1/2    &frac12;  similar
  */
  return false;
}
nsresult
FileSystemDataSource::getIEFavoriteURL(nsIRDFResource *source, nsString aFileURL, nsIRDFLiteral **urlLiteral)
{
    nsresult        rv = NS_OK;

    *urlLiteral = nullptr;

    nsCOMPtr<nsIFile> f;
    NS_GetFileFromURLSpec(NS_ConvertUTF16toUTF8(aFileURL), getter_AddRefs(f));

    bool value;

    if (NS_SUCCEEDED(f->IsDirectory(&value)) && value)
    {
        if (isValidFolder(source))
            return(NS_RDF_NO_VALUE);
        aFileURL.AppendLiteral("desktop.ini");
    }
    else if (aFileURL.Length() > 4)
    {
        nsAutoString    extension;

        aFileURL.Right(extension, 4);
        if (!extension.LowerCaseEqualsLiteral(".url"))
        {
            return(NS_RDF_NO_VALUE);
        }
    }

    nsCOMPtr<nsIInputStream> strm;
    NS_NewLocalFileInputStream(getter_AddRefs(strm),f);
    nsCOMPtr<nsILineInputStream> linereader = do_QueryInterface(strm, &rv);

    nsAutoString    line;
    nsAutoCString   cLine;
    while(NS_SUCCEEDED(rv))
    {
        bool    isEOF;
        rv = linereader->ReadLine(cLine, &isEOF);
        CopyASCIItoUTF16(cLine, line);

        if (isEOF)
        {
            if (line.Find("URL=", true) == 0)
            {
                line.Cut(0, 4);
                rv = mRDFService->GetLiteral(line.get(), urlLiteral);
                break;
            }
            else if (line.Find("CDFURL=", true) == 0)
            {
                line.Cut(0, 7);
                rv = mRDFService->GetLiteral(line.get(), urlLiteral);
                break;
            }
            line.Truncate();
        }
    }

    return(rv);
}
static void
ListInterestingFiles(nsString& aAnnotation, nsIFile* aFile,
                     const nsTArray<nsString>& aInterestingFilenames)
{
  nsString filename;
  aFile->GetLeafName(filename);
  for (const nsString& interestingFilename : aInterestingFilenames) {
    if (interestingFilename == filename) {
      nsString path;
      aFile->GetPath(path);
      aAnnotation.AppendLiteral("  ");
      aAnnotation.Append(path);
      aAnnotation.AppendLiteral(" (");
      int64_t size;
      if (NS_SUCCEEDED(aFile->GetFileSize(&size))) {
        aAnnotation.AppendPrintf("%ld", size);
      } else {
        aAnnotation.AppendLiteral("???");
      }
      aAnnotation.AppendLiteral(" bytes, crc32 = ");
      uint32_t crc;
      nsresult rv = ComputeCRC32(aFile, &crc);
      if (NS_SUCCEEDED(rv)) {
        aAnnotation.AppendPrintf("0x%08x)\n", crc);
      } else {
        aAnnotation.AppendPrintf("error 0x%08x)\n", uint32_t(rv));
      }
      return;
    }
  }

  bool isDir = false;
  aFile->IsDirectory(&isDir);

  if (!isDir) {
    return;
  }

  nsCOMPtr<nsISimpleEnumerator> entries;
  if (NS_FAILED(aFile->GetDirectoryEntries(getter_AddRefs(entries)))) {
    aAnnotation.AppendLiteral("  (failed to enumerated directory)\n");
    return;
  }

  for (;;) {
    bool hasMore = false;
    if (NS_FAILED(entries->HasMoreElements(&hasMore))) {
      aAnnotation.AppendLiteral("  (failed during directory enumeration)\n");
      return;
    }
    if (!hasMore) {
      break;
    }

    nsCOMPtr<nsISupports> entry;
    if (NS_FAILED(entries->GetNext(getter_AddRefs(entry)))) {
      aAnnotation.AppendLiteral("  (failed during directory enumeration)\n");
      return;
    }

    nsCOMPtr<nsIFile> file = do_QueryInterface(entry);
    if (file) {
      ListInterestingFiles(aAnnotation, file, aInterestingFilenames);
    }
  }
}
Ejemplo n.º 15
0
/**
 *  Parses the given input stream and returns a DOM Document.
 *  A NULL pointer will be returned if errors occurred
 */
nsresult
txXMLParser::parse(istream& aInputStream, const nsAString& aUri,
                   txXPathNode** aResultDoc)
{
    mErrorString.Truncate();
    *aResultDoc = nsnull;
    if (!aInputStream) {
        mErrorString.AppendLiteral("unable to parse xml: invalid or unopen stream encountered.");
        return NS_ERROR_FAILURE;
    }

    static const XML_Memory_Handling_Suite memsuite = {
        (void *(*)(size_t))PR_Malloc,
        (void *(*)(void *, size_t))PR_Realloc,
        PR_Free
    };
    static const PRUnichar expatSeparator = kExpatSeparatorChar;
    mExpatParser = XML_ParserCreate_MM(nsnull, &memsuite, &expatSeparator);
    if (!mExpatParser) {
        return NS_ERROR_OUT_OF_MEMORY;
    }
    mDocument = new Document();
    if (!mDocument) {
        XML_ParserFree(mExpatParser);
        return NS_ERROR_OUT_OF_MEMORY;
    }
    mDocument->documentBaseURI = aUri;
    mCurrentNode = mDocument;

    XML_SetReturnNSTriplet(mExpatParser, XML_TRUE);
    XML_SetUserData(mExpatParser, this);
    XML_SetElementHandler(mExpatParser, startElement, endElement);
    XML_SetCharacterDataHandler(mExpatParser, charData);
    XML_SetProcessingInstructionHandler(mExpatParser, piHandler);
    XML_SetCommentHandler(mExpatParser, commentHandler);
#ifdef XML_DTD
    XML_SetParamEntityParsing(mExpatParser, XML_PARAM_ENTITY_PARSING_ALWAYS);
#endif
    XML_SetExternalEntityRefHandler(mExpatParser, externalEntityRefHandler);
    XML_SetExternalEntityRefHandlerArg(mExpatParser, this);
    XML_SetBase(mExpatParser,
                (const XML_Char*)(PromiseFlatString(aUri).get()));

    const int bufferSize = 1024;
    char buf[bufferSize];
    PRBool done;
    do {
        aInputStream.read(buf, bufferSize);
        done = aInputStream.eof();

        if (!XML_Parse(mExpatParser, buf, aInputStream.gcount(), done)) {
            createErrorString();
            done = MB_TRUE;
            delete mDocument;
            mDocument = nsnull;
        }
    } while (!done);
    aInputStream.clear();

    // clean up
    XML_ParserFree(mExpatParser);
    // ownership to the caller
    *aResultDoc = txXPathNativeNode::createXPathNode(mDocument);
    mDocument = nsnull;
    return *aResultDoc ? NS_OK : NS_ERROR_OUT_OF_MEMORY;
}
Ejemplo n.º 16
0
/* Formats an error message for overridable certificate errors (of type
 * OverridableCertErrorMessage). Use formatPlainErrorMessage to format
 * non-overridable cert errors and non-cert-related errors.
 */
static nsresult
formatOverridableCertErrorMessage(nsISSLStatus & sslStatus,
                                  PRErrorCode errorCodeToReport,
                                  const nsXPIDLCString & host, int32_t port,
                                  bool suppressPort443,
                                  bool wantsHtml,
                                  nsString & returnedMessage)
{
    static NS_DEFINE_CID(kNSSComponentCID, NS_NSSCOMPONENT_CID);

    const char16_t *params[1];
    nsresult rv;
    nsAutoString hostWithPort;
    nsAutoString hostWithoutPort;

    // For now, hide port when it's 443 and we're reporting the error.
    // In the future a better mechanism should be used
    // to make a decision about showing the port number, possibly by requiring
    // the context object to implement a specific interface.
    // The motivation is that Mozilla browser would like to hide the port number
    // in error pages in the common case.

    hostWithoutPort.AppendASCII(host);
    if (suppressPort443 && port == 443) {
        params[0] = hostWithoutPort.get();
    } else {
        hostWithPort.AppendASCII(host);
        hostWithPort.Append(':');
        hostWithPort.AppendInt(port);
        params[0] = hostWithPort.get();
    }

    nsCOMPtr<nsINSSComponent> component = do_GetService(kNSSComponentCID, &rv);
    NS_ENSURE_SUCCESS(rv, rv);

    returnedMessage.Truncate();
    rv = component->PIPBundleFormatStringFromName("certErrorIntro", params, 1,
            returnedMessage);
    NS_ENSURE_SUCCESS(rv, rv);

    returnedMessage.AppendLiteral("\n\n");

    RefPtr<nsIX509Cert> ix509;
    rv = sslStatus.GetServerCert(byRef(ix509));
    NS_ENSURE_SUCCESS(rv, rv);

    bool isUntrusted;
    rv = sslStatus.GetIsUntrusted(&isUntrusted);
    NS_ENSURE_SUCCESS(rv, rv);
    if (isUntrusted) {
        AppendErrorTextUntrusted(errorCodeToReport, hostWithoutPort, ix509,
                                 component, returnedMessage);
    }

    bool isDomainMismatch;
    rv = sslStatus.GetIsDomainMismatch(&isDomainMismatch);
    NS_ENSURE_SUCCESS(rv, rv);
    if (isDomainMismatch) {
        AppendErrorTextMismatch(hostWithoutPort, ix509, component, wantsHtml, returnedMessage);
    }

    bool isNotValidAtThisTime;
    rv = sslStatus.GetIsNotValidAtThisTime(&isNotValidAtThisTime);
    NS_ENSURE_SUCCESS(rv, rv);
    if (isNotValidAtThisTime) {
        AppendErrorTextTime(ix509, component, returnedMessage);
    }

    AppendErrorTextCode(errorCodeToReport, component, returnedMessage);

    return NS_OK;
}
Ejemplo n.º 17
0
// returns TRUE if SAN was used to produce names
// return FALSE if nothing was produced
// names => a single name or a list of names
// multipleNames => whether multiple names were delivered
static bool
GetSubjectAltNames(CERTCertificate *nssCert,
                   nsINSSComponent *component,
                   nsString &allNames,
                   uint32_t &nameCount)
{
    allNames.Truncate();
    nameCount = 0;

    SECItem altNameExtension = {siBuffer, nullptr, 0 };
    CERTGeneralName *sanNameList = nullptr;

    SECStatus rv = CERT_FindCertExtension(nssCert, SEC_OID_X509_SUBJECT_ALT_NAME,
                                          &altNameExtension);
    if (rv != SECSuccess) {
        return false;
    }

    ScopedPLArenaPool arena(PORT_NewArena(DER_DEFAULT_CHUNKSIZE));
    if (!arena) {
        return false;
    }

    sanNameList = CERT_DecodeAltNameExtension(arena.get(), &altNameExtension);
    if (!sanNameList) {
        return false;
    }

    SECITEM_FreeItem(&altNameExtension, false);

    CERTGeneralName *current = sanNameList;
    do {
        nsAutoString name;
        switch (current->type) {
        case certDNSName:
        {
            nsDependentCSubstring nameFromCert(reinterpret_cast<char*>
                                               (current->name.other.data),
                                               current->name.other.len);
            // dNSName fields are defined as type IA5String and thus should
            // be limited to ASCII characters.
            if (IsASCII(nameFromCert)) {
                name.Assign(NS_ConvertASCIItoUTF16(nameFromCert));
                if (!allNames.IsEmpty()) {
                    allNames.AppendLiteral(", ");
                }
                ++nameCount;
                allNames.Append(name);
            }
        }
        break;

        case certIPAddress:
        {
            char buf[INET6_ADDRSTRLEN];
            PRNetAddr addr;
            if (current->name.other.len == 4) {
                addr.inet.family = PR_AF_INET;
                memcpy(&addr.inet.ip, current->name.other.data, current->name.other.len);
                PR_NetAddrToString(&addr, buf, sizeof(buf));
                name.AssignASCII(buf);
            } else if (current->name.other.len == 16) {
                addr.ipv6.family = PR_AF_INET6;
                memcpy(&addr.ipv6.ip, current->name.other.data, current->name.other.len);
                PR_NetAddrToString(&addr, buf, sizeof(buf));
                name.AssignASCII(buf);
            } else {
                /* invalid IP address */
            }
            if (!name.IsEmpty()) {
                if (!allNames.IsEmpty()) {
                    allNames.AppendLiteral(", ");
                }
                ++nameCount;
                allNames.Append(name);
            }
            break;
        }

        default: // all other types of names are ignored
            break;
        }
        current = CERT_GetNextGeneralName(current);
    } while (current != sanNameList); // double linked

    return true;
}
Ejemplo n.º 18
0
void 
nsCSSToken::AppendToString(nsString& aBuffer)
{
  switch (mType) {
    case eCSSToken_AtKeyword:
      aBuffer.Append(PRUnichar('@')); // fall through intentional
    case eCSSToken_Ident:
    case eCSSToken_WhiteSpace:
    case eCSSToken_Function:
    case eCSSToken_URL:
    case eCSSToken_InvalidURL:
    case eCSSToken_HTMLComment:
      aBuffer.Append(mIdent);
      break;
    case eCSSToken_Number:
      if (mIntegerValid) {
        aBuffer.AppendInt(mInteger, 10);
      }
      else {
        aBuffer.AppendFloat(mNumber);
      }
      break;
    case eCSSToken_Percentage:
      NS_ASSERTION(!mIntegerValid, "How did a percentage token get this set?");
      aBuffer.AppendFloat(mNumber * 100.0f);
      aBuffer.Append(PRUnichar('%')); // STRING USE WARNING: technically, this should be |AppendWithConversion|
      break;
    case eCSSToken_Dimension:
      if (mIntegerValid) {
        aBuffer.AppendInt(mInteger, 10);
      }
      else {
        aBuffer.AppendFloat(mNumber);
      }
      aBuffer.Append(mIdent);
      break;
    case eCSSToken_String:
      aBuffer.Append(mSymbol);
      aBuffer.Append(mIdent); // fall through intentional
    case eCSSToken_Symbol:
      aBuffer.Append(mSymbol);
      break;
    case eCSSToken_ID:
    case eCSSToken_Ref:
      aBuffer.Append(PRUnichar('#'));
      aBuffer.Append(mIdent);
      break;
    case eCSSToken_Includes:
      aBuffer.AppendLiteral("~=");
      break;
    case eCSSToken_Dashmatch:
      aBuffer.AppendLiteral("|=");
      break;
    case eCSSToken_Error:
      aBuffer.Append(mSymbol);
      aBuffer.Append(mIdent);
      break;
    default:
      NS_ERROR("invalid token type");
      break;
  }
}
Ejemplo n.º 19
0
static void
AppendErrorTextMismatch(const nsString &host,
                        nsIX509Cert* ix509,
                        nsINSSComponent *component,
                        bool wantsHtml,
                        nsString &returnedMessage)
{
    const char16_t *params[1];
    nsresult rv;

    ScopedCERTCertificate nssCert(ix509->GetCert());

    if (!nssCert) {
        // We are unable to extract the valid names, say "not valid for name".
        params[0] = host.get();
        nsString formattedString;
        rv = component->PIPBundleFormatStringFromName("certErrorMismatch",
                params, 1,
                formattedString);
        if (NS_SUCCEEDED(rv)) {
            returnedMessage.Append(formattedString);
            returnedMessage.Append('\n');
        }
        return;
    }

    nsString allNames;
    uint32_t nameCount = 0;
    bool useSAN = false;

    if (nssCert)
        useSAN = GetSubjectAltNames(nssCert.get(), component, allNames, nameCount);

    if (!useSAN) {
        char *certName = CERT_GetCommonName(&nssCert->subject);
        if (certName) {
            nsDependentCSubstring commonName(certName, strlen(certName));
            if (IsUTF8(commonName)) {
                // Bug 1024781
                // We should actually check that the common name is a valid dns name or
                // ip address and not any string value before adding it to the display
                // list.
                ++nameCount;
                allNames.Assign(NS_ConvertUTF8toUTF16(commonName));
            }
            PORT_Free(certName);
        }
    }

    if (nameCount > 1) {
        nsString message;
        rv = component->GetPIPNSSBundleString("certErrorMismatchMultiple",
                                              message);
        if (NS_SUCCEEDED(rv)) {
            returnedMessage.Append(message);
            returnedMessage.AppendLiteral("\n  ");
            returnedMessage.Append(allNames);
            returnedMessage.AppendLiteral("  \n");
        }
    }
    else if (nameCount == 1) {
        const char16_t *params[1];
        params[0] = allNames.get();

        const char *stringID;
        if (wantsHtml)
            stringID = "certErrorMismatchSingle2";
        else
            stringID = "certErrorMismatchSinglePlain";

        nsString formattedString;
        rv = component->PIPBundleFormatStringFromName(stringID,
                params, 1,
                formattedString);
        if (NS_SUCCEEDED(rv)) {
            returnedMessage.Append(formattedString);
            returnedMessage.Append('\n');
        }
    }
    else { // nameCount == 0
        nsString message;
        nsresult rv = component->GetPIPNSSBundleString("certErrorMismatchNoNames",
                      message);
        if (NS_SUCCEEDED(rv)) {
            returnedMessage.Append(message);
            returnedMessage.Append('\n');
        }
    }
}
Ejemplo n.º 20
0
/**
 * Append the textual representation of |this| to |aBuffer|.
 */
void
nsCSSToken::AppendToString(nsString& aBuffer) const
{
  switch (mType) {
    case eCSSToken_Ident:
      nsStyleUtil::AppendEscapedCSSIdent(mIdent, aBuffer);
      break;

    case eCSSToken_AtKeyword:
      aBuffer.Append('@');
      nsStyleUtil::AppendEscapedCSSIdent(mIdent, aBuffer);
      break;

    case eCSSToken_ID:
    case eCSSToken_Hash:
      aBuffer.Append('#');
      nsStyleUtil::AppendEscapedCSSIdent(mIdent, aBuffer);
      break;

    case eCSSToken_Function:
      nsStyleUtil::AppendEscapedCSSIdent(mIdent, aBuffer);
      aBuffer.Append('(');
      break;

    case eCSSToken_URL:
    case eCSSToken_Bad_URL:
      aBuffer.AppendLiteral("url(");
      if (mSymbol != PRUnichar(0)) {
        nsStyleUtil::AppendEscapedCSSString(mIdent, aBuffer, mSymbol);
      } else {
        aBuffer.Append(mIdent);
      }
      if (mType == eCSSToken_URL) {
        aBuffer.Append(PRUnichar(')'));
      }
      break;

    case eCSSToken_Number:
      if (mIntegerValid) {
        aBuffer.AppendInt(mInteger, 10);
      } else {
        aBuffer.AppendFloat(mNumber);
      }
      break;

    case eCSSToken_Percentage:
      aBuffer.AppendFloat(mNumber * 100.0f);
      aBuffer.Append(PRUnichar('%'));
      break;

    case eCSSToken_Dimension:
      if (mIntegerValid) {
        aBuffer.AppendInt(mInteger, 10);
      } else {
        aBuffer.AppendFloat(mNumber);
      }
      nsStyleUtil::AppendEscapedCSSIdent(mIdent, aBuffer);
      break;

    case eCSSToken_Bad_String:
      nsStyleUtil::AppendEscapedCSSString(mIdent, aBuffer, mSymbol);
      // remove the trailing quote character
      aBuffer.Truncate(aBuffer.Length() - 1);
      break;

    case eCSSToken_String:
      nsStyleUtil::AppendEscapedCSSString(mIdent, aBuffer, mSymbol);
      break;

    case eCSSToken_Symbol:
      aBuffer.Append(mSymbol);
      break;

    case eCSSToken_Whitespace:
      aBuffer.Append(' ');
      break;

    case eCSSToken_HTMLComment:
    case eCSSToken_URange:
      aBuffer.Append(mIdent);
      break;

    case eCSSToken_Includes:
      aBuffer.AppendLiteral("~=");
      break;
    case eCSSToken_Dashmatch:
      aBuffer.AppendLiteral("|=");
      break;
    case eCSSToken_Beginsmatch:
      aBuffer.AppendLiteral("^=");
      break;
    case eCSSToken_Endsmatch:
      aBuffer.AppendLiteral("$=");
      break;
    case eCSSToken_Containsmatch:
      aBuffer.AppendLiteral("*=");
      break;

    default:
      NS_ERROR("invalid token type");
      break;
  }
}
nsresult nsAddbookProtocolHandler::BuildDirectoryXML(nsIAbDirectory *aDirectory,
                                                     nsString &aOutput) {
  NS_ENSURE_ARG_POINTER(aDirectory);

  nsresult rv;
  nsCOMPtr<nsISimpleEnumerator> cardsEnumerator;
  nsCOMPtr<nsIAbCard> card;

  aOutput.AppendLiteral(
      "<?xml version=\"1.0\"?>\n"
      "<?xml-stylesheet type=\"text/css\" "
      "href=\"chrome://messagebody/content/addressbook/print.css\"?>\n"
      "<directory>\n");

  // Get Address Book string and set it as title of XML document
  nsCOMPtr<nsIStringBundle> bundle;
  nsCOMPtr<nsIStringBundleService> stringBundleService =
      mozilla::services::GetStringBundleService();
  if (stringBundleService) {
    rv = stringBundleService->CreateBundle(
        "chrome://messenger/locale/addressbook/addressBook.properties",
        getter_AddRefs(bundle));
    if (NS_SUCCEEDED(rv)) {
      nsString addrBook;
      rv = bundle->GetStringFromName("addressBook", addrBook);
      if (NS_SUCCEEDED(rv)) {
        aOutput.AppendLiteral("<title xmlns=\"http://www.w3.org/1999/xhtml\">");
        aOutput.Append(addrBook);
        aOutput.AppendLiteral("</title>\n");
      }
    }
  }

  // create a view and init it with the generated name sort order. Then, iterate
  // over the view, getting the card for each row, and printing them.
  nsString sortColumn;
  nsCOMPtr<nsIAbView> view =
      do_CreateInstance("@mozilla.org/addressbook/abview;1", &rv);

  view->SetView(aDirectory, nullptr, NS_LITERAL_STRING("GeneratedName"),
                NS_LITERAL_STRING("ascending"), sortColumn);

  int32_t numRows;
  nsCOMPtr<nsITreeView> treeView = do_QueryInterface(view, &rv);
  NS_ENSURE_SUCCESS(rv, rv);
  treeView->GetRowCount(&numRows);

  for (int32_t row = 0; row < numRows; row++) {
    nsCOMPtr<nsIAbCard> card;
    view->GetCardFromRow(row, getter_AddRefs(card));
    nsCString xmlSubstr;

    rv = card->TranslateTo(NS_LITERAL_CSTRING("xml"), xmlSubstr);
    NS_ENSURE_SUCCESS(rv, rv);

    aOutput.AppendLiteral("<separator/>");
    aOutput.Append(NS_ConvertUTF8toUTF16(xmlSubstr));
    aOutput.AppendLiteral("<separator/>");
  }

  aOutput.AppendLiteral("</directory>\n");

  return NS_OK;
}
Ejemplo n.º 22
0
void
nsCSSToken::AppendToString(nsString& aBuffer)
{
  switch (mType) {
    case eCSSToken_AtKeyword:
      aBuffer.Append(PRUnichar('@')); // fall through intentional
    case eCSSToken_Ident:
    case eCSSToken_WhiteSpace:
    case eCSSToken_Function:
    case eCSSToken_HTMLComment:
    case eCSSToken_URange:
      aBuffer.Append(mIdent);
      if (mType == eCSSToken_Function)
        aBuffer.Append(PRUnichar('('));
      break;
    case eCSSToken_URL:
    case eCSSToken_Bad_URL:
      aBuffer.AppendLiteral("url(");
      if (mSymbol != PRUnichar(0)) {
        aBuffer.Append(mSymbol);
      }
      aBuffer.Append(mIdent);
      if (mSymbol != PRUnichar(0)) {
        aBuffer.Append(mSymbol);
      }
      if (mType == eCSSToken_URL) {
        aBuffer.Append(PRUnichar(')'));
      }
      break;
    case eCSSToken_Number:
      if (mIntegerValid) {
        aBuffer.AppendInt(mInteger, 10);
      }
      else {
        aBuffer.AppendFloat(mNumber);
      }
      break;
    case eCSSToken_Percentage:
      NS_ASSERTION(!mIntegerValid, "How did a percentage token get this set?");
      aBuffer.AppendFloat(mNumber * 100.0f);
      aBuffer.Append(PRUnichar('%'));
      break;
    case eCSSToken_Dimension:
      if (mIntegerValid) {
        aBuffer.AppendInt(mInteger, 10);
      }
      else {
        aBuffer.AppendFloat(mNumber);
      }
      aBuffer.Append(mIdent);
      break;
    case eCSSToken_String:
      aBuffer.Append(mSymbol);
      aBuffer.Append(mIdent); // fall through intentional
    case eCSSToken_Symbol:
      aBuffer.Append(mSymbol);
      break;
    case eCSSToken_ID:
    case eCSSToken_Ref:
      aBuffer.Append(PRUnichar('#'));
      aBuffer.Append(mIdent);
      break;
    case eCSSToken_Includes:
      aBuffer.AppendLiteral("~=");
      break;
    case eCSSToken_Dashmatch:
      aBuffer.AppendLiteral("|=");
      break;
    case eCSSToken_Beginsmatch:
      aBuffer.AppendLiteral("^=");
      break;
    case eCSSToken_Endsmatch:
      aBuffer.AppendLiteral("$=");
      break;
    case eCSSToken_Containsmatch:
      aBuffer.AppendLiteral("*=");
      break;
    case eCSSToken_Bad_String:
      aBuffer.Append(mSymbol);
      aBuffer.Append(mIdent);
      break;
    default:
      NS_ERROR("invalid token type");
      break;
  }
}