/** ---------------------------------------------------
 *  Helper function - Creates the "prefix" for the pref
 *  It is either "print."
 *  or "print.printer_<print name>."
 */
const char*
nsPrintOptions::GetPrefName(const char * aPrefName,
                            const nsAString& aPrinterName)
{
  if (!aPrefName || !*aPrefName) {
    NS_ERROR("Must have a valid pref name!");
    return aPrefName;
  }

  mPrefName.Truncate(); /* mPrefName = ""; */

  if (aPrinterName.Length()) {
    mPrefName.Append("printer_");
    AppendUTF16toUTF8(aPrinterName, mPrefName);
    mPrefName.Append(".");
  }
  mPrefName += aPrefName;

  return mPrefName.get();
}
Beispiel #2
0
TEST(UTF, Valid)
{
  for (unsigned int i = 0; i < ArrayLength(ValidStrings); ++i) {
    nsDependentCString str8(ValidStrings[i].m8);
    nsDependentString str16(ValidStrings[i].m16);

    EXPECT_TRUE(NS_ConvertUTF16toUTF8(str16).Equals(str8));

    EXPECT_TRUE(NS_ConvertUTF8toUTF16(str8).Equals(str16));

    nsCString tmp8("string ");
    AppendUTF16toUTF8(str16, tmp8);
    EXPECT_TRUE(tmp8.Equals(NS_LITERAL_CSTRING("string ") + str8));

    nsString tmp16(NS_LITERAL_STRING("string "));
    AppendUTF8toUTF16(str8, tmp16);
    EXPECT_TRUE(tmp16.Equals(NS_LITERAL_STRING("string ") + str16));

    EXPECT_EQ(CompareUTF8toUTF16(str8, str16), 0);
  }
}
Beispiel #3
0
bool
test_invalid16()
{
  for (unsigned int i = 0; i < ArrayLength(Invalid16Strings); ++i) {
    nsDependentString str16(Invalid16Strings[i].m16);
    nsDependentCString str8(Invalid16Strings[i].m8);

    if (!NS_ConvertUTF16toUTF8(str16).Equals(str8))
      return false;

    nsCString tmp8("string ");
    AppendUTF16toUTF8(str16, tmp8);
    if (!tmp8.Equals(NS_LITERAL_CSTRING("string ") + str8))
      return false;

    if (CompareUTF8toUTF16(str8, str16) != 0)
      return false;
  }
  
  return true;
}
Beispiel #4
0
PRBool
test_invalid16()
{
  for (unsigned int i = 0; i < NS_ARRAY_LENGTH(Invalid16Strings); ++i) {
    nsDependentString str16(Invalid16Strings[i].m16);
    nsDependentCString str8(Invalid16Strings[i].m8);

    if (!NS_ConvertUTF16toUTF8(str16).Equals(str8))
      return PR_FALSE;

    nsCString tmp8("string ");
    AppendUTF16toUTF8(str16, tmp8);
    if (!tmp8.Equals(NS_LITERAL_CSTRING("string ") + str8))
      return PR_FALSE;

    if (CompareUTF8toUTF16(str8, str16) != 0)
      return PR_FALSE;
  }
  
  return PR_TRUE;
}
NS_IMETHODIMP
nsDOMScriptObjectFactory::GetScriptRuntime(const nsAString &aLanguageName,
                                           nsIScriptRuntime **aLanguage)
{
  // Note that many callers have optimized detection for JS (along with
  // supporting various alternate names for JS), so don't call this.
  // One exception is for the new "script-type" attribute on a node - and
  // there is no need to support backwards compatible names.
  // As JS is the default language, this is still rarely called for JS -
  // only when a node explicitly sets JS - so that is done last.
  nsCAutoString contractid(NS_LITERAL_CSTRING(
                          "@mozilla.org/script-language;1?script-type="));
  // Arbitrarily use utf8 encoding should the name have extended chars
  AppendUTF16toUTF8(aLanguageName, contractid);
  nsresult rv;
  nsCOMPtr<nsIScriptRuntime> lang =
        do_GetService(contractid.get(), &rv);

  if (NS_FAILED(rv)) {
    if (aLanguageName.Equals(NS_LITERAL_STRING("application/javascript")))
      return GetScriptRuntimeByID(nsIProgrammingLanguage::JAVASCRIPT, aLanguage);
    // Not JS and nothing else we know about.
    NS_WARNING("No script language registered for this mime-type");
    return NS_ERROR_FACTORY_NOT_REGISTERED;
  }
  // And stash it away in our array for fast lookup by ID.
  PRUint32 lang_ndx = NS_STID_INDEX(lang->GetScriptTypeID());
  if (mLanguageArray[lang_ndx] == nsnull) {
    mLanguageArray[lang_ndx] = lang;
  } else {
    // All languages are services - we should have an identical object!
    NS_ASSERTION(mLanguageArray[lang_ndx] == lang,
                 "Got a different language for this ID???");
  }
  *aLanguage = lang;
  NS_IF_ADDREF(*aLanguage);
  return NS_OK;
}
nsresult
nsXTFService::CreateElement(nsIContent** aResult, nsINodeInfo* aNodeInfo)
{
  nsCOMPtr<nsIXTFElementFactory> factory;

  // Check if we have an xtf factory for the given namespaceid in our cache:
  if (!mFactoryHash.Get(aNodeInfo->NamespaceID(), getter_AddRefs(factory))) {
    // No. See if there is one registered with the component manager:
    nsCAutoString xtf_contract_id(NS_XTF_ELEMENT_FACTORY_CONTRACTID_PREFIX);
    nsAutoString uri;
    aNodeInfo->GetNamespaceURI(uri);
    AppendUTF16toUTF8(uri, xtf_contract_id);
#ifdef DEBUG_xtf_verbose
    printf("Testing for XTF factory at %s\n", xtf_contract_id.get());
#endif
    factory = do_GetService(xtf_contract_id.get());
    if (factory) {
#ifdef DEBUG
      printf("We've got an XTF factory: %s \n", xtf_contract_id.get());
#endif
      // Put into hash:
      mFactoryHash.Put(aNodeInfo->NamespaceID(), factory);
    }
  }
  if (!factory) return NS_ERROR_FAILURE;

  // We have an xtf factory. Now try to create an element for the given tag name:
  nsCOMPtr<nsIXTFElement> elem;
  nsAutoString tagName;
  aNodeInfo->GetName(tagName);
  factory->CreateElement(tagName, getter_AddRefs(elem));
  if (!elem) return NS_ERROR_FAILURE;
  
  // We've got an xtf element. Create a wrapper for it:
  return NS_NewXTFElementWrapper(elem, aNodeInfo, aResult);
}
Beispiel #7
0
static int
MimeInlineTextPlain_parse_line (char *line, PRInt32 length, MimeObject *obj)
{
  int status;
  PRBool quoting = ( obj->options
    && ( obj->options->format_out == nsMimeOutput::nsMimeMessageQuoting ||
         obj->options->format_out == nsMimeOutput::nsMimeMessageBodyQuoting
       )           );  // see above
  PRBool plainHTML = quoting || (obj->options &&
       obj->options->format_out == nsMimeOutput::nsMimeMessageSaveAs);
       // see above

  PRBool rawPlainText = obj->options &&
       (obj->options->format_out == nsMimeOutput::nsMimeMessageFilterSniffer
       || obj->options->format_out == nsMimeOutput::nsMimeMessageAttach);

  // this routine gets called for every line of data that comes through the
  // mime converter. It's important to make sure we are efficient with 
  // how we allocate memory in this routine. be careful if you go to add
  // more to this routine.

  NS_ASSERTION(length > 0, "zero length");
  if (length <= 0) return 0;

  mozITXTToHTMLConv *conv = GetTextConverter(obj->options);
  MimeInlineTextPlain *text = (MimeInlineTextPlain *) obj;

  PRBool skipConversion = !conv || rawPlainText ||
                          (obj->options && obj->options->force_user_charset);

  char *mailCharset = NULL;
  nsresult rv;

  // if this part has a name and it's not a message/rfc822, don't quote
  if (quoting && obj->headers && MimeHeaders_get_name(obj->headers, obj->options) 
      && PL_strcasecmp(obj->content_type, MESSAGE_RFC822))
    return 0;

  if (!skipConversion)
  {
    nsDependentCString inputStr(line, length);
    nsAutoString lineSourceStr;

    // For 'SaveAs', |line| is in |mailCharset|.
    // convert |line| to UTF-16 before 'html'izing (calling ScanTXT())
    if (obj->options->format_out == nsMimeOutput::nsMimeMessageSaveAs)
    { // Get the mail charset of this message.
      MimeInlineText  *inlinetext = (MimeInlineText *) obj;
      if (!inlinetext->initializeCharset)
         ((MimeInlineTextClass*)&mimeInlineTextClass)->initialize_charset(obj);
      mailCharset = inlinetext->charset;
      if (mailCharset && *mailCharset) {
        rv = nsMsgI18NConvertToUnicode(mailCharset, inputStr, lineSourceStr);
        NS_ENSURE_SUCCESS(rv, -1);
      }
      else // this probably never happens ...
        CopyUTF8toUTF16(inputStr, lineSourceStr);
    }
    else  // line is in UTF-8
      CopyUTF8toUTF16(inputStr, lineSourceStr);

    nsCAutoString prefaceResultStr;  // Quoting stuff before the real text

    // Recognize quotes
    PRUint32 oldCiteLevel = text->mCiteLevel;
    PRUint32 logicalLineStart = 0;
    rv = conv->CiteLevelTXT(lineSourceStr.get(),
                            &logicalLineStart, &(text->mCiteLevel));
    NS_ENSURE_SUCCESS(rv, -1);

    // Find out, which recognitions to do
    PRBool whattodo = obj->options->whattodo;
    if (plainHTML)
    {
      if (quoting)
        whattodo = 0;  // This is done on Send. Don't do it twice.
      else
        whattodo = whattodo & ~mozITXTToHTMLConv::kGlyphSubstitution;
                   /* Do recognition for the case, the result is viewed in
                      Mozilla, but not GlyphSubstitution, because other UAs
                      might not be able to display the glyphs. */
      if (!text->mBlockquoting)
        text->mCiteLevel = 0;
    }

    // Write blockquote
    if (text->mCiteLevel > oldCiteLevel)
    {
      prefaceResultStr += "</pre>";
      for (PRUint32 i = 0; i < text->mCiteLevel - oldCiteLevel; i++)
      {
        nsCAutoString style;
        MimeTextBuildPrefixCSS(text->mQuotedSizeSetting, text->mQuotedStyleSetting,
                               text->mCitationColor, style);
        if (!plainHTML && !style.IsEmpty())
        {
          prefaceResultStr += "<blockquote type=cite style=\"";
          prefaceResultStr += style;
          prefaceResultStr += "\">";
        }
        else
          prefaceResultStr += "<blockquote type=cite>";
      }
      prefaceResultStr += "<pre wrap>";
    }
    else if (text->mCiteLevel < oldCiteLevel)
    {
      prefaceResultStr += "</pre>";
      for (PRUint32 i = 0; i < oldCiteLevel - text->mCiteLevel; i++)
        prefaceResultStr += "</blockquote>";
      prefaceResultStr += "<pre wrap>";
      if (text->mCiteLevel == 0)
        prefaceResultStr += "<!---->";   /* Make sure, NGLayout puts out
                                            a linebreak */
    }

    // Write plain text quoting tags
    if (logicalLineStart != 0 && !(plainHTML && text->mBlockquoting))
    {
      if (!plainHTML)
        prefaceResultStr += "<span class=\"moz-txt-citetags\">";

      nsAutoString citeTagsSource;
      lineSourceStr.Mid(citeTagsSource, 0, logicalLineStart);

      // Convert to HTML
      nsXPIDLString citeTagsResultUnichar;
      rv = conv->ScanTXT(citeTagsSource.get(), 0 /* no recognition */,
                         getter_Copies(citeTagsResultUnichar));
      if (NS_FAILED(rv)) return -1;

      AppendUTF16toUTF8(citeTagsResultUnichar, prefaceResultStr);
      if (!plainHTML)
        prefaceResultStr += "</span>";
    }


    // recognize signature
    if ((lineSourceStr.Length() >= 4)
        && lineSourceStr.First() == '-'
        && Substring(lineSourceStr, 0, 3).EqualsLiteral("-- ")
        && (lineSourceStr[3] == '\r' || lineSourceStr[3] == '\n') )
    {
      text->mIsSig = PR_TRUE;
      if (!quoting)
        prefaceResultStr += "<div class=\"moz-txt-sig\">";
    }


    /* This is the main TXT to HTML conversion:
       escaping (very important), eventually recognizing etc. */
    nsXPIDLString lineResultUnichar;

    rv = conv->ScanTXT(lineSourceStr.get() + logicalLineStart,
                       whattodo, getter_Copies(lineResultUnichar));
    NS_ENSURE_SUCCESS(rv, -1);

    if (!(text->mIsSig && quoting))
    {
      status = MimeObject_write(obj, prefaceResultStr.get(), prefaceResultStr.Length(), PR_TRUE);
      if (status < 0) return status;
      nsCAutoString outString;
      if (obj->options->format_out != nsMimeOutput::nsMimeMessageSaveAs ||
          !mailCharset || !*mailCharset)
        CopyUTF16toUTF8(lineResultUnichar, outString);
      else
      { // convert back to mailCharset before writing.       
        rv = nsMsgI18NConvertFromUnicode(mailCharset, 
                                         lineResultUnichar, outString);
        NS_ENSURE_SUCCESS(rv, -1);
      }

      status = MimeObject_write(obj, outString.get(), outString.Length(), PR_TRUE);
    }
    else
    {
      status = NS_OK;
    }
  }
  else
  {
    status = MimeObject_write(obj, line, length, PR_TRUE);
  }

  return status;
}
/*---------------------------------------------------------------------------

  SetupEditorOnWindow

  nsIEditor setupEditorOnWindow (in nsIDOMWindow aWindow);
----------------------------------------------------------------------------*/
NS_IMETHODIMP
nsEditingSession::SetupEditorOnWindow(nsIDOMWindow *aWindow)
{
  mDoneSetup = true;

  nsresult rv;

  //MIME CHECKING
  //must get the content type
  // Note: the doc gets this from the network channel during StartPageLoad,
  //    so we don't have to get it from there ourselves
  nsCOMPtr<nsIDOMDocument> doc;
  nsCAutoString mimeCType;

  //then lets check the mime type
  if (NS_SUCCEEDED(aWindow->GetDocument(getter_AddRefs(doc))) && doc)
  {
    nsAutoString mimeType;
    if (NS_SUCCEEDED(doc->GetContentType(mimeType)))
      AppendUTF16toUTF8(mimeType, mimeCType);

    if (IsSupportedTextType(mimeCType.get()))
    {
      mEditorType.AssignLiteral("text");
      mimeCType = "text/plain";
    }
    else if (!mimeCType.EqualsLiteral("text/html") &&
             !mimeCType.EqualsLiteral("application/xhtml+xml"))
    {
      // Neither an acceptable text or html type.
      mEditorStatus = eEditorErrorCantEditMimeType;

      // Turn editor into HTML -- we will load blank page later
      mEditorType.AssignLiteral("html");
      mimeCType.AssignLiteral("text/html");
    }

    // Flush out frame construction to make sure that the subframe's
    // presshell is set up if it needs to be.
    nsCOMPtr<nsIDocument> document = do_QueryInterface(doc);
    if (document) {
      document->FlushPendingNotifications(Flush_Frames);
      if (mMakeWholeDocumentEditable) {
        document->SetEditableFlag(true);
        nsCOMPtr<nsIHTMLDocument> htmlDocument = do_QueryInterface(document);
        if (htmlDocument) {
          // Enable usage of the execCommand API
          htmlDocument->SetEditingState(nsIHTMLDocument::eDesignMode);
        }
      }
    }
  }
  bool needHTMLController = false;

  const char *classString = "@mozilla.org/editor/htmleditor;1";
  if (mEditorType.EqualsLiteral("textmail"))
  {
    mEditorFlags = nsIPlaintextEditor::eEditorPlaintextMask | 
                   nsIPlaintextEditor::eEditorEnableWrapHackMask | 
                   nsIPlaintextEditor::eEditorMailMask;
  }
  else if (mEditorType.EqualsLiteral("text"))
  {
    mEditorFlags = nsIPlaintextEditor::eEditorPlaintextMask | 
                   nsIPlaintextEditor::eEditorEnableWrapHackMask;
  }
  else if (mEditorType.EqualsLiteral("htmlmail"))
  {
    if (mimeCType.EqualsLiteral("text/html"))
    {
      needHTMLController = true;
      mEditorFlags = nsIPlaintextEditor::eEditorMailMask;
    }
    else //set the flags back to textplain.
      mEditorFlags = nsIPlaintextEditor::eEditorPlaintextMask | 
                     nsIPlaintextEditor::eEditorEnableWrapHackMask;
  }
  else // Defaulted to html
  {
    needHTMLController = true;
  }

  if (mInteractive) {
    mEditorFlags |= nsIPlaintextEditor::eEditorAllowInteraction;
  }

  // make the UI state maintainer
  mStateMaintainer = new nsComposerCommandsUpdater();

  // now init the state maintainer
  // This allows notification of error state
  //  even if we don't create an editor
  rv = mStateMaintainer->Init(aWindow);
  NS_ENSURE_SUCCESS(rv, rv);

  if (mEditorStatus != eEditorCreationInProgress)
  {
    mStateMaintainer->NotifyDocumentCreated();
    return NS_ERROR_FAILURE;
  }

  // Create editor and do other things 
  //  only if we haven't found some error above,
  nsIDocShell *docShell = GetDocShellFromWindow(aWindow);
  NS_ENSURE_TRUE(docShell, NS_ERROR_FAILURE);  

  if (!mInteractive) {
    // Disable animation of images in this document:
    nsCOMPtr<nsIDOMWindowUtils> utils(do_GetInterface(aWindow));
    NS_ENSURE_TRUE(utils, NS_ERROR_FAILURE);

    rv = utils->GetImageAnimationMode(&mImageAnimationMode);
    NS_ENSURE_SUCCESS(rv, rv);
    utils->SetImageAnimationMode(imgIContainer::kDontAnimMode);
  }

  // create and set editor
  nsCOMPtr<nsIEditorDocShell> editorDocShell = do_QueryInterface(docShell, &rv);
  NS_ENSURE_SUCCESS(rv, rv);

  // Try to reuse an existing editor
  nsCOMPtr<nsIEditor> editor = do_QueryReferent(mExistingEditor);
  if (editor) {
    editor->PreDestroy(false);
  } else {
    editor = do_CreateInstance(classString, &rv);
    NS_ENSURE_SUCCESS(rv, rv);
    mExistingEditor = do_GetWeakReference(editor);
  }
  // set the editor on the docShell. The docShell now owns it.
  rv = editorDocShell->SetEditor(editor);
  NS_ENSURE_SUCCESS(rv, rv);

  // setup the HTML editor command controller
  if (needHTMLController)
  {
    // The third controller takes an nsIEditor as the context
    rv = SetupEditorCommandController("@mozilla.org/editor/htmleditorcontroller;1",
                                      aWindow, editor,
                                      &mHTMLCommandControllerId);
    NS_ENSURE_SUCCESS(rv, rv);
  }

  // Set mimetype on editor
  rv = editor->SetContentsMIMEType(mimeCType.get());
  NS_ENSURE_SUCCESS(rv, rv);

  nsCOMPtr<nsIContentViewer> contentViewer;
  rv = docShell->GetContentViewer(getter_AddRefs(contentViewer));
  NS_ENSURE_SUCCESS(rv, rv);
  NS_ENSURE_TRUE(contentViewer, NS_ERROR_FAILURE);

  nsCOMPtr<nsIDOMDocument> domDoc;  
  rv = contentViewer->GetDOMDocument(getter_AddRefs(domDoc));
  NS_ENSURE_SUCCESS(rv, rv);
  NS_ENSURE_TRUE(domDoc, NS_ERROR_FAILURE);

  // Set up as a doc state listener
  // Important! We must have this to broadcast the "obs_documentCreated" message
  rv = editor->AddDocumentStateListener(mStateMaintainer);
  NS_ENSURE_SUCCESS(rv, rv);

  rv = editor->Init(domDoc, nullptr /* root content */,
                    nullptr, mEditorFlags);
  NS_ENSURE_SUCCESS(rv, rv);

  nsCOMPtr<nsISelection> selection;
  editor->GetSelection(getter_AddRefs(selection));
  nsCOMPtr<nsISelectionPrivate> selPriv = do_QueryInterface(selection);
  NS_ENSURE_TRUE(selPriv, NS_ERROR_FAILURE);

  rv = selPriv->AddSelectionListener(mStateMaintainer);
  NS_ENSURE_SUCCESS(rv, rv);

  // and as a transaction listener
  nsCOMPtr<nsITransactionManager> txnMgr;
  editor->GetTransactionManager(getter_AddRefs(txnMgr));
  if (txnMgr)
    txnMgr->AddListener(mStateMaintainer);

  // Set context on all controllers to be the editor
  rv = SetEditorOnControllers(aWindow, editor);
  NS_ENSURE_SUCCESS(rv, rv);

  // Everything went fine!
  mEditorStatus = eEditorOK;

  // This will trigger documentCreation notification
  return editor->PostCreate();
}
Beispiel #9
0
nsresult
nsGopherChannel::SendRequest()
{
    nsresult rv = NS_OK;

    // Note - you have to keep this as a class member, because the char input
    // stream doesn't copy its buffer
    mRequest.Assign(mSelector);

    // So, we use the selector as is unless it is a search url
    if (mType=='7') {
        // Note that we don't use the "standard" nsIURL parsing stuff here
        // because the only special character is ?, and its possible to search
        // for a string containing a #, and so on
        
        // XXX - should this find the last or first entry?
        // '?' is valid in both the search string and the url
        // so no matter what this does, it may be incorrect
        // This only affects people codeing the query directly into the URL
        PRInt32 pos = mRequest.RFindChar('?');
        if (pos == -1) {
            // We require a query string here - if we don't have one,
            // then we need to ask the user
            nsCOMPtr<nsIPrompt> prompter;
            NS_QueryNotificationCallbacks(mCallbacks, mLoadGroup, prompter);
            if (!prompter) {
                NS_ERROR("We need a prompter!");
                return NS_ERROR_FAILURE;
            }

            if (!mStringBundle) {

                nsCOMPtr<nsIStringBundleService> bundleSvc =
                        do_GetService(NS_STRINGBUNDLE_CONTRACTID, &rv);
                if (NS_FAILED(rv)) return rv;

                rv = bundleSvc->CreateBundle(NECKO_MSGS_URL, getter_AddRefs(mStringBundle));
                if (NS_FAILED(rv)) return rv;

            }

            nsXPIDLString  promptTitle;
            nsXPIDLString  promptText;

            if (mStringBundle)
                rv = mStringBundle->GetStringFromName(NS_LITERAL_STRING("GopherPromptTitle").get(),
                                                      getter_Copies(promptTitle));

            if (NS_FAILED(rv) || !mStringBundle)
                promptTitle.AssignLiteral("Search");


            if (mStringBundle)
                rv = mStringBundle->GetStringFromName(NS_LITERAL_STRING("GopherPromptText").get(),
                                                      getter_Copies(promptText));

            if (NS_FAILED(rv) || !mStringBundle)
                promptText.AssignLiteral("Enter a search term:");


            nsXPIDLString search;
            PRBool res;
            prompter->Prompt(promptTitle.get(),
                              promptText.get(),
                              getter_Copies(search),
                              NULL,
                              NULL,
                              &res);
            if (!res || !(*search.get()))
                return NS_ERROR_FAILURE;
    
            mRequest.Append('\t');
            AppendUTF16toUTF8(search, mRequest); // XXX Is UTF-8 the right thing?

            // and update our uri
            nsCAutoString spec;
            rv = mUrl->GetAsciiSpec(spec);
            if (NS_FAILED(rv))
                return rv;

            spec.Append('?');
            AppendUTF16toUTF8(search, spec);
            rv = mUrl->SetSpec(spec);
            if (NS_FAILED(rv))
                return rv;
        } else {
            // Just replace it with a tab
            mRequest.SetCharAt('\t',pos);
        }
    }

    mRequest.Append(CRLF);
    
    PR_LOG(gGopherLog,PR_LOG_DEBUG,
           ("Sending: %s\n", mRequest.get()));

    // open a buffered, blocking output stream.  (it should never block because
    // the buffer is big enough for our entire request.)
    nsCOMPtr<nsIOutputStream> output;
    rv = mTransport->OpenOutputStream(nsITransport::OPEN_BLOCKING,
                                      mRequest.Length(), 1,
                                      getter_AddRefs(output));
    if (NS_FAILED(rv)) return rv;

    PRUint32 n;
    rv = output->Write(mRequest.get(), mRequest.Length(), &n);
    if (NS_FAILED(rv)) return rv;

    if (n != mRequest.Length())
        return NS_ERROR_UNEXPECTED;

    return NS_OK;
}
Beispiel #10
0
int
nsExpatDriver::HandleExternalEntityRef(const char16_t *openEntityNames,
                                       const char16_t *base,
                                       const char16_t *systemId,
                                       const char16_t *publicId)
{
  if (mInInternalSubset && !mInExternalDTD && openEntityNames) {
    mInternalSubset.Append(char16_t('%'));
    mInternalSubset.Append(nsDependentString(openEntityNames));
    mInternalSubset.Append(char16_t(';'));
  }

  // Load the external entity into a buffer.
  nsCOMPtr<nsIInputStream> in;
  nsAutoString absURL;
  nsresult rv = OpenInputStreamFromExternalDTD(publicId, systemId, base,
                                               getter_AddRefs(in), absURL);
  if (NS_FAILED(rv)) {
#ifdef DEBUG
    nsCString message("Failed to open external DTD: publicId \"");
    AppendUTF16toUTF8(publicId, message);
    message += "\" systemId \"";
    AppendUTF16toUTF8(systemId, message);
    message += "\" base \"";
    AppendUTF16toUTF8(base, message);
    message += "\" URL \"";
    AppendUTF16toUTF8(absURL, message);
    message += "\"";
    NS_WARNING(message.get());
#endif
    return 1;
  }

  nsCOMPtr<nsIUnicharInputStream> uniIn;
  rv = nsSimpleUnicharStreamFactory::GetInstance()->
    CreateInstanceFromUTF8Stream(in, getter_AddRefs(uniIn));
  NS_ENSURE_SUCCESS(rv, 1);

  int result = 1;
  if (uniIn) {
    XML_Parser entParser = XML_ExternalEntityParserCreate(mExpatParser, 0,
                                                          kUTF16);
    if (entParser) {
      XML_SetBase(entParser, absURL.get());

      mInExternalDTD = true;

      uint32_t totalRead;
      do {
        rv = uniIn->ReadSegments(ExternalDTDStreamReaderFunc, entParser,
                                 uint32_t(-1), &totalRead);
      } while (NS_SUCCEEDED(rv) && totalRead > 0);

      result = XML_Parse(entParser, nullptr, 0, 1);

      mInExternalDTD = false;

      XML_ParserFree(entParser);
    }
  }

  return result;
}
// void OnLDAPSearchEntry (in nsILDAPMessage aMessage);
//
// XXXdmose most of this function should live in nsILDAPMessage::toString()
//
nsresult
nsLDAPChannel::OnLDAPSearchEntry(nsILDAPMessage *aMessage)
{
    nsresult rv;
    nsCAutoString dn;
    nsCString entry;

    PR_LOG(gLDAPLogModule, PR_LOG_DEBUG, ("entry returned!\n"));

    // get the DN
    // XXX better err handling
    //
    rv = aMessage->GetDn(dn);
    NS_ENSURE_SUCCESS(rv, rv);

    entry.SetCapacity(256);
    entry = NS_LITERAL_CSTRING("dn: ") + dn + NS_LITERAL_CSTRING("\n");

    char **attrs;
    PRUint32 attrCount;

    // get an array of all the attribute names
    // XXX better error-handling
    //
    rv = aMessage->GetAttributes(&attrCount, &attrs);
    NS_ENSURE_SUCCESS(rv, rv);

    // XXX is this an error?  should log in non-debug console too?
    //
    if (!attrCount) {
        NS_WARNING("Warning: entry received with no attributes");
    }

    // iterate through the attributes
    //
    for ( PRUint32 i=0 ; i < attrCount ; i++ ) {

        PRUnichar **vals;
        PRUint32 valueCount;

        // get the values of this attribute
        // XXX better failure handling
        //
        rv = aMessage->GetValues(attrs[i], &valueCount, &vals);
        if (NS_FAILED(rv)) {
            NS_WARNING("nsLDAPChannel:OnLDAPSearchEntry(): "
                       "aMessage->GetValues() failed\n");
            NS_FREE_XPCOM_ALLOCATED_POINTER_ARRAY(attrCount, attrs);
            return rv;;
        }

        // print all values of this attribute
        //
        for ( PRUint32 j=0 ; j < valueCount; j++ ) {
            entry.Append(attrs[i]);
            entry.Append(": ");
            AppendUTF16toUTF8(vals[j], entry);
            entry.Append('\n');
        }
        NS_FREE_XPCOM_ALLOCATED_POINTER_ARRAY(valueCount, vals);

    }
    NS_FREE_XPCOM_ALLOCATED_POINTER_ARRAY(attrCount, attrs);

    // XXXdmose better error handling
    //
    if (NS_FAILED(rv)) {
        PR_LOG(gLDAPLogModule, PR_LOG_ERROR, 
               ("aMessage: error getting attribute\n"));
        return rv;
    }

    // separate this entry from the next
    //
    entry.Append('\n');

    // do the write
    // XXX better err handling
    //
    PRUint32 bytesWritten = 0;
    PRUint32 entryLength = entry.Length();

    rv = mReadPipeOut->Write(entry.get(), entryLength, &bytesWritten);
    NS_ENSURE_SUCCESS(rv, rv);

    // short writes shouldn't happen on blocking pipes!
    // XXX runtime error handling too
    //
    NS_ASSERTION(bytesWritten == entryLength, 
                 "nsLDAPChannel::OnLDAPSearchEntry(): "
                 "internal error: blocking pipe returned a short write");

    // XXXdmose deal more gracefully with an error here
    //
    rv = mListener->OnDataAvailable(this, mResponseContext, mReadPipeIn, 
                                    mReadPipeOffset, entryLength);
    NS_ENSURE_SUCCESS(rv, rv);

    mReadPipeOffset += entryLength;

    return NS_OK;
}
Beispiel #12
0
NS_IMETHODIMP
LSPAnnotationGatherer::Run()
{
  PR_SetCurrentThreadName("LSP Annotator");

  mThread = NS_GetCurrentThread();

  DWORD size = 0;
  int err;
  // Get the size of the buffer we need
  if (SOCKET_ERROR != WSCEnumProtocols(nullptr, nullptr, &size, &err) ||
      err != WSAENOBUFS) {
    // Er, what?
    NS_NOTREACHED("WSCEnumProtocols suceeded when it should have failed ...");
    return NS_ERROR_FAILURE;
  }

  auto byteArray = MakeUnique<char[]>(size);
  WSAPROTOCOL_INFOW* providers =
    reinterpret_cast<WSAPROTOCOL_INFOW*>(byteArray.get());

  int n = WSCEnumProtocols(nullptr, providers, &size, &err);
  if (n == SOCKET_ERROR) {
    // Lame. We provided the right size buffer; we'll just give up now.
    NS_WARNING("Could not get LSP list");
    return NS_ERROR_FAILURE;
  }

  nsCString str;
  for (int i = 0; i < n; i++) {
    AppendUTF16toUTF8(nsDependentString(providers[i].szProtocol), str);
    str.AppendLiteral(" : ");
    str.AppendInt(providers[i].iVersion);
    str.AppendLiteral(" : ");
    str.AppendInt(providers[i].iAddressFamily);
    str.AppendLiteral(" : ");
    str.AppendInt(providers[i].iSocketType);
    str.AppendLiteral(" : ");
    str.AppendInt(providers[i].iProtocol);
    str.AppendLiteral(" : ");
    str.AppendPrintf("0x%x", providers[i].dwServiceFlags1);
    str.AppendLiteral(" : ");
    str.AppendPrintf("0x%x", providers[i].dwProviderFlags);
    str.AppendLiteral(" : ");

    wchar_t path[MAX_PATH];
    int pathLen = MAX_PATH;
    if (!WSCGetProviderPath(&providers[i].ProviderId, path, &pathLen, &err)) {
      AppendUTF16toUTF8(nsDependentString(path), str);
    }

    str.AppendLiteral(" : ");
    // If WSCGetProviderInfo is available, we should call it to obtain the
    // category flags for this provider. When present, these flags inform
    // Windows as to which order to chain the providers.
    nsModuleHandle ws2_32(LoadLibraryW(L"ws2_32.dll"));
    if (ws2_32) {
      decltype(WSCGetProviderInfo)* pWSCGetProviderInfo =
        reinterpret_cast<decltype(WSCGetProviderInfo)*>(
            GetProcAddress(ws2_32, "WSCGetProviderInfo"));
      if (pWSCGetProviderInfo) {
        DWORD categoryInfo;
        size_t categoryInfoSize = sizeof(categoryInfo);
        if (!pWSCGetProviderInfo(&providers[i].ProviderId,
                                 ProviderInfoLspCategories,
                                 (PBYTE)&categoryInfo, &categoryInfoSize, 0,
                                 &err)) {
          str.AppendPrintf("0x%x", categoryInfo);
        }
      }
    }

    str.AppendLiteral(" : ");
    if (providers[i].ProtocolChain.ChainLen <= BASE_PROTOCOL) {
      // If we're dealing with a catalog entry that identifies an individual
      // base or layer provider, log its provider GUID.
      RPC_CSTR provIdStr = nullptr;
      if (UuidToStringA(&providers[i].ProviderId, &provIdStr) == RPC_S_OK) {
        str.Append(reinterpret_cast<char*>(provIdStr));
        RpcStringFreeA(&provIdStr);
      }
    }

    if (i + 1 != n) {
      str.AppendLiteral(" \n ");
    }
  }

  mString = str;
  NS_DispatchToMainThread(NewRunnableMethod(this, &LSPAnnotationGatherer::Annotate));
  return NS_OK;
}
Beispiel #13
0
void
CopyUTF16toUTF8( const char16_t* aSource, nsACString& aDest )
  {
    aDest.Truncate();
    AppendUTF16toUTF8(aSource, aDest);
  }
Beispiel #14
0
nsresult
nsXTFService::CreateElement(nsIContent** aResult, nsINodeInfo* aNodeInfo)
{
  nsCOMPtr<nsIXTFElementFactory> factory;

  // Check if we have an xtf factory for the given namespaceid in our cache:
  if (!mFactoryHash.Get(aNodeInfo->NamespaceID(), getter_AddRefs(factory))) {
    // No. See if there is one registered with the component manager:
    nsCAutoString xtf_contract_id(NS_XTF_ELEMENT_FACTORY_CONTRACTID_PREFIX);
    nsAutoString uri;
    aNodeInfo->GetNamespaceURI(uri);
    AppendUTF16toUTF8(uri, xtf_contract_id);
#ifdef DEBUG_xtf_verbose
    printf("Testing for XTF factory at %s\n", xtf_contract_id.get());
#endif
    factory = do_GetService(xtf_contract_id.get());
    if (factory) {
#ifdef DEBUG
      printf("We've got an XTF factory.\n");
#endif
      // Put into hash:
      mFactoryHash.Put(aNodeInfo->NamespaceID(), factory);
    }
  }
  if (!factory) return NS_ERROR_FAILURE;

  // We have an xtf factory. Now try to create an element for the given tag name:
  nsCOMPtr<nsIXTFElement> elem;
  nsAutoString tagName;
  aNodeInfo->GetName(tagName);
  factory->CreateElement(tagName, getter_AddRefs(elem));
  if (!elem) return NS_ERROR_FAILURE;
  
  // We've got an xtf element. Create an appropriate wrapper for it:
  PRUint32 elementType;
  elem->GetElementType(&elementType);
  switch (elementType) {
    case nsIXTFElement::ELEMENT_TYPE_GENERIC_ELEMENT:
    {
      nsCOMPtr<nsIXTFGenericElement> elem2 = do_QueryInterface(elem);
      return NS_NewXTFGenericElementWrapper(elem2, aNodeInfo, aResult);
    }
    case nsIXTFElement::ELEMENT_TYPE_BINDABLE:
    {
      nsCOMPtr<nsIXTFBindableElement> elem2 = do_QueryInterface(elem);
      return NS_NewXTFBindableElementWrapper(elem2, aNodeInfo, aResult);
    }
    case nsIXTFElement::ELEMENT_TYPE_SVG_VISUAL:
    {
#ifdef MOZ_SVG
      nsCOMPtr<nsIXTFSVGVisual> elem2 = do_QueryInterface(elem);
      return NS_NewXTFSVGVisualWrapper(elem2, aNodeInfo, aResult);
#else
      NS_ERROR("xtf svg visuals are only supported in mozilla builds with native svg support");
      break;
#endif
    }
    case nsIXTFElement::ELEMENT_TYPE_XML_VISUAL:
    {
      nsCOMPtr<nsIXTFXMLVisual> elem2 = do_QueryInterface(elem);
      return NS_NewXTFXMLVisualWrapper(elem2, aNodeInfo, aResult);
    }
    case nsIXTFElement::ELEMENT_TYPE_XUL_VISUAL:
    {
      nsCOMPtr<nsIXTFXULVisual> elem2 = do_QueryInterface(elem);
      return NS_NewXTFXULVisualWrapper(elem2, aNodeInfo, aResult);
    }
    default:
      NS_ERROR("unknown xtf element type");
      break;
  }
  return NS_ERROR_FAILURE;
}
nsresult
RDFContentSinkImpl::GetIdAboutAttribute(const PRUnichar** aAttributes,
                                        nsIRDFResource** aResource,
                                        PRBool* aIsAnonymous)
{
    // This corresponds to the dirty work of production [6.5]
    nsresult rv = NS_OK;

    nsAutoString nodeID;

    nsCOMPtr<nsIAtom> localName;
    for (; *aAttributes; aAttributes += 2) {
        const nsDependentSubstring& nameSpaceURI =
            SplitExpatName(aAttributes[0], getter_AddRefs(localName));

        // We'll accept either `ID' or `rdf:ID' (ibid with `about' or
        // `rdf:about') in the spirit of being liberal towards the
        // input that we receive.
        if (!nameSpaceURI.IsEmpty() &&
            !nameSpaceURI.EqualsLiteral(RDF_NAMESPACE_URI)) {
          continue;
        }

        // XXX you can't specify both, but we'll just pick up the
        // first thing that was specified and ignore the other.
      
        if (localName == kAboutAtom) {
            if (aIsAnonymous)
                *aIsAnonymous = PR_FALSE;

            nsAutoString relURI(aAttributes[1]);
            if (rdf_RequiresAbsoluteURI(relURI)) {
                nsCAutoString uri;
                rv = mDocumentURL->Resolve(NS_ConvertUTF16toUTF8(aAttributes[1]), uri);
                if (NS_FAILED(rv)) return rv;
                
                return gRDFService->GetResource(uri, 
                                                aResource);
            } 
            return gRDFService->GetResource(NS_ConvertUTF16toUTF8(aAttributes[1]), 
                                            aResource);
        }
        else if (localName == kIdAtom) {
            if (aIsAnonymous)
                *aIsAnonymous = PR_FALSE;
            // In the spirit of leniency, we do not bother trying to
            // enforce that this be a valid "XML Name" (see
            // http://www.w3.org/TR/REC-xml#NT-Nmtoken), as per
            // 6.21. If we wanted to, this would be where to do it.

            // Construct an in-line resource whose URI is the
            // document's URI plus the XML name specified in the ID
            // attribute.
            nsCAutoString name;
            nsCAutoString ref('#');
            AppendUTF16toUTF8(aAttributes[1], ref);

            rv = mDocumentURL->Resolve(ref, name);
            if (NS_FAILED(rv)) return rv;

            return gRDFService->GetResource(name, aResource);
        }
        else if (localName == kNodeIdAtom) {
            nodeID.Assign(aAttributes[1]);
        }
        else if (localName == kAboutEachAtom) {
            // XXX we don't deal with aboutEach...
            //PR_LOG(gLog, PR_LOG_WARNING,
            //       ("rdfxml: ignoring aboutEach at line %d",
            //        aNode.GetSourceLineNumber()));
        }
    }

    // Otherwise, we couldn't find anything, so just gensym one...
    if (aIsAnonymous)
        *aIsAnonymous = PR_TRUE;

    // If nodeID is present, check if we already know about it. If we've seen
    // the nodeID before, use the same resource, otherwise generate a new one.
    if (!nodeID.IsEmpty()) {
        mNodeIDMap.Get(nodeID,aResource);

        if (!*aResource) {
            rv = gRDFService->GetAnonymousResource(aResource);
            mNodeIDMap.Put(nodeID,*aResource);
        }
    }
    else {
        rv = gRDFService->GetAnonymousResource(aResource);
    }

    return rv;
}
// Annotate the crash report with a Unique User ID and time
// since install.  Also do some prep work for recording
// time since last crash, which must be calculated at
// crash time.
// If any piece of data doesn't exist, initialize it first.
nsresult SetupExtraData(nsILocalFile* aAppDataDirectory,
                        const nsACString& aBuildID)
{
  nsCOMPtr<nsIFile> dataDirectory;
  nsresult rv = aAppDataDirectory->Clone(getter_AddRefs(dataDirectory));
  NS_ENSURE_SUCCESS(rv, rv);

  rv = dataDirectory->AppendNative(NS_LITERAL_CSTRING("Crash Reports"));
  NS_ENSURE_SUCCESS(rv, rv);

  PRBool exists;
  rv = dataDirectory->Exists(&exists);
  NS_ENSURE_SUCCESS(rv, rv);

  if (!exists) {
    rv = dataDirectory->Create(nsIFile::DIRECTORY_TYPE, 0700);
    NS_ENSURE_SUCCESS(rv, rv);
  }

  // Save this path in the environment for the crash reporter application.
  nsCAutoString dataDirEnv("MOZ_CRASHREPORTER_DATA_DIRECTORY=");

#if defined(XP_WIN32)
  nsAutoString dataDirectoryPath;
  rv = dataDirectory->GetPath(dataDirectoryPath);
  NS_ENSURE_SUCCESS(rv, rv);

  AppendUTF16toUTF8(dataDirectoryPath, dataDirEnv);
#else
  nsCAutoString dataDirectoryPath;
  rv = dataDirectory->GetNativePath(dataDirectoryPath);
  NS_ENSURE_SUCCESS(rv, rv);

  dataDirEnv.Append(dataDirectoryPath);
#endif

  char* env = ToNewCString(dataDirEnv);
  NS_ENSURE_TRUE(env, NS_ERROR_OUT_OF_MEMORY);

  PR_SetEnv(env);

  nsCAutoString data;
  if(NS_SUCCEEDED(GetOrInit(dataDirectory, NS_LITERAL_CSTRING("UserID"),
                            data, InitUserID)))
    AnnotateCrashReport(NS_LITERAL_CSTRING("UserID"), data);

  if(NS_SUCCEEDED(GetOrInit(dataDirectory,
                            NS_LITERAL_CSTRING("InstallTime") + aBuildID,
                            data, InitInstallTime)))
    AnnotateCrashReport(NS_LITERAL_CSTRING("InstallTime"), data);

  // this is a little different, since we can't init it with anything,
  // since it's stored at crash time, and we can't annotate the
  // crash report with the stored value, since we really want
  // (now - LastCrash), so we just get a value if it exists,
  // and store it in a time_t value.
  if(NS_SUCCEEDED(GetOrInit(dataDirectory, NS_LITERAL_CSTRING("LastCrash"),
                            data, NULL))) {
    lastCrashTime = (time_t)atol(data.get());
  }

  // not really the best place to init this, but I have the path I need here
  nsCOMPtr<nsIFile> lastCrashFile;
  rv = dataDirectory->Clone(getter_AddRefs(lastCrashFile));
  NS_ENSURE_SUCCESS(rv, rv);

  rv = lastCrashFile->AppendNative(NS_LITERAL_CSTRING("LastCrash"));
  NS_ENSURE_SUCCESS(rv, rv);
  memset(lastCrashTimeFilename, 0, sizeof(lastCrashTimeFilename));

#if defined(XP_WIN32)
  nsAutoString filename;
  rv = lastCrashFile->GetPath(filename);
  NS_ENSURE_SUCCESS(rv, rv);

  if (filename.Length() < XP_PATH_MAX)
    wcsncpy(lastCrashTimeFilename, filename.get(), filename.Length());
#else
  nsCAutoString filename;
  rv = lastCrashFile->GetNativePath(filename);
  NS_ENSURE_SUCCESS(rv, rv);

  if (filename.Length() < XP_PATH_MAX)
    strncpy(lastCrashTimeFilename, filename.get(), filename.Length());
#endif

  return NS_OK;
}