예제 #1
0
nsresult nsEudoraEditor::GetEmbeddedObjects(nsISupportsArray ** aNodeList)
{
    NS_ENSURE_ARG_POINTER(aNodeList);

    // Check to see if we were already called
    if (m_EmbeddedObjectList != nsnull)
    {
        *aNodeList = m_EmbeddedObjectList;
        return NS_OK;
    }

    // Create array in m_EmbeddedObjectList
    nsresult rv = NS_NewISupportsArray( getter_AddRefs(m_EmbeddedObjectList) );
    NS_ENSURE_SUCCESS(rv, rv);

    // Return m_EmbeddedObjectList in aNodeList and increment ref count - caller
    // assumes that we incremented the ref count.
    NS_IF_ADDREF(*aNodeList = m_EmbeddedObjectList);

    // Create the embedded folder spec
    nsCOMPtr<nsIFile>   embeddedFolderSpec;
    // Create the embedded image spec
    nsCOMPtr<nsIFile>   embeddedImageSpec;

    // Fill in the details for the embedded folder spec - "Embedded" folder
    // inside of the mail folder. We don't bother to check to see if the embedded
    // folder exists, because it seems to me that would only save time in the
    // unexpected case where it doesn't exist. Keep in mind that we will be checking
    // for the existence of any embedded images anyway - if the folder doesn't
    // exist that check will fail.
    rv = m_pMailImportLocation->Clone(getter_AddRefs(embeddedFolderSpec));
    NS_ENSURE_SUCCESS(rv, rv);
    embeddedFolderSpec->AppendNative(NS_LITERAL_CSTRING("Embedded"));

    // Look for the start of the last closing tag so that we only search for
    // valid "Embedded Content" lines. (In practice this is not super important,
    // but there were some proof of concept exploits at one point where "Embedded
    // Content" lines were faked in the body of messages).
    PRInt32     startLastClosingTag = m_body.RFind("</");
    if (startLastClosingTag == kNotFound)
        startLastClosingTag = 0;
    bool        foundEmbeddedContentLines = false;

    // Search for various translations of "Embedded Content" - as of this writing only
    // one that I know of, but then again I didn't realize that Eudora translators had
    // ever translated "Attachment Converted" as suggested by other Eudora importing code.
    for (PRInt32 i = 0; *sEudoraEmbeddedContentLines[i] != '\0'; i++)
    {
        // Search for "Embedded Content: " lines starting after last closing tag (if any)
        PRInt32   startEmbeddedContentLine = startLastClosingTag;
        PRInt32   lenEmbeddedContentTag = strlen(sEudoraEmbeddedContentLines[i]);

        while ( (startEmbeddedContentLine = m_body.Find(sEudoraEmbeddedContentLines[i], true, startEmbeddedContentLine+1)) != kNotFound )
        {
            // Found this translation of "Embedded Content" - remember that so that we don't
            // bother looking for any other translations.
            foundEmbeddedContentLines = true;

            // Extract the file name from the embedded content line
            PRInt32   startFileName = startEmbeddedContentLine + lenEmbeddedContentTag;
            PRInt32   endFileName = m_body.Find(":", false, startFileName);

            // Create the file spec for the embedded image
            embeddedFolderSpec->Clone(getter_AddRefs(embeddedImageSpec));
            embeddedImageSpec->Append(Substring(m_body, startFileName, endFileName - startFileName));

            // Verify that the embedded image spec exists and is a file
            bool      isFile = false;
            bool      exists = false;
            if ( NS_FAILED(embeddedImageSpec->Exists( &exists)) || NS_FAILED(embeddedImageSpec->IsFile(&isFile)) )
                continue;
            if (!exists || !isFile)
                continue;

            // Extract CID hash from the embedded content line
            PRInt32     cidHashValue;
            PRInt32     startCIDHash = m_body.Find(",", false, endFileName);
            if (startCIDHash != kNotFound)
            {
                startCIDHash++;
                PRInt32   endCIDHash = m_body.Find(",", false, startCIDHash);

                if (endCIDHash != kNotFound)
                {
                    nsString    cidHash;
                    cidHash.Assign(Substring(m_body, startCIDHash, endCIDHash - startCIDHash));

                    if ( !cidHash.IsEmpty() )
                    {
                        // Convert CID hash string to numeric value
                        nsresult aErrorCode;
                        cidHashValue = cidHash.ToInteger(&aErrorCode, 16);
                    }
                }
            }

            // Get the URL for the embedded image
            nsCString     embeddedImageURL;
            rv = NS_GetURLSpecFromFile(embeddedImageSpec, embeddedImageURL);
            NS_ENSURE_SUCCESS(rv, rv);

            NS_ConvertASCIItoUTF16 srcUrl(embeddedImageURL);
            nsString cid;
            // We're going to remember the original cid in the image element,
            // which the send code will retrieve as the kMozCIDAttrName property.
            GetEmbeddedImageCID(cidHashValue, srcUrl, cid);
            // Create the embedded image node
            nsEudoraHTMLImageElement *image =
                new nsEudoraHTMLImageElement(srcUrl, cid);

            nsCOMPtr<nsIDOMHTMLImageElement>   imageNode;
            image->QueryInterface( NS_GET_IID(nsIDOMHTMLImageElement), getter_AddRefs(imageNode) );

            // Append the embedded image node to the list
            (*aNodeList)->AppendElement(imageNode);

            PRInt32   endEmbeddedContentLine = m_body.Find("\r\n", true, startEmbeddedContentLine+1);
            if (endEmbeddedContentLine != kNotFound)
            {
                // We recognized the "Embedded Content" line correctly and found the associated image.
                // Remove the Eudora specific line about it now.
                m_body.Cut(startEmbeddedContentLine, endEmbeddedContentLine - startEmbeddedContentLine + 2);

                // Backup by one to correct where we start looking for the next line
                startEmbeddedContentLine--;
            }
        }

        // Assume at most one translation for "Embedded Content: " in a given message
        if (foundEmbeddedContentLines)
            break;
    }

    return NS_OK;
}
예제 #2
0
nsresult nsSceneTracker::SplitHeading (const nsAString& aHeading,
                                       nsAString& aIntExt,
                                       nsAString& aSetting,
                                       nsAString& aDayNight) {
  NS_NAMED_LITERAL_STRING(kSeparatorChars, ". -");
  NS_NAMED_LITERAL_STRING(kPrefixChars, ". -0123456789");

  nsCOMPtr<nsIPrefService> ps = do_GetService(
    "@mozilla.org/preferences-service;1");
  nsCOMPtr<nsIPrefBranch> branch;

  nsresult rv = ps->GetBranch("celtx.scripteditor.", getter_AddRefs(branch));
  if (NS_FAILED(rv))
    return rv;
  nsXPIDLString strdata;

  // Get the int/ext values
  nsCOMPtr<nsISupportsString> intextstr;
  rv = branch->GetComplexValue("intexts",
    NS_GET_IID(nsISupportsString), getter_AddRefs(intextstr));
  if (NS_FAILED(rv))
    return rv;
  intextstr->ToString(getter_Copies(strdata));
  nsTArray<nsString> intexts;
  intexts.AppendElement(NS_LITERAL_STRING("INT"));
  intexts.AppendElement(NS_LITERAL_STRING("EXT"));
  nsXPIDLString::size_type startoffset = 0;
  nsXPIDLString::size_type endoffset = strdata.FindChar(PRUnichar(','));
  while (PRInt32(endoffset) > 0) {
    intexts.AppendElement(Substring(strdata, startoffset,
      endoffset - startoffset));
    startoffset = endoffset + 1;
    endoffset = strdata.FindChar(PRUnichar(','), startoffset);
  }
  if (startoffset < strdata.Length())
    intexts.AppendElement(Substring(strdata, startoffset,
      strdata.Length() - startoffset));

  // Get the day/night values
  nsCOMPtr<nsISupportsString> daynightstr;
  rv = branch->GetComplexValue("daynights",
    NS_GET_IID(nsISupportsString), getter_AddRefs(daynightstr));
  if (NS_FAILED(rv))
    return rv;
  daynightstr->ToString(getter_Copies(strdata));
  nsTArray<nsString> daynights;
  startoffset = 0;
  endoffset = strdata.FindChar(PRUnichar(','));
  while (PRInt32(endoffset) > 0) {
    daynights.AppendElement(Substring(strdata, startoffset,
      endoffset - startoffset));
    startoffset = endoffset + 1;
    endoffset = strdata.FindChar(PRUnichar(','), startoffset);
  }
  if (startoffset < strdata.Length())
    daynights.AppendElement(Substring(strdata, startoffset,
      strdata.Length() - startoffset));

  aIntExt.Truncate();
  aSetting.Truncate();
  aDayNight.Truncate();

  nsAString::const_iterator start, end;
  aHeading.BeginReading(start);
  aHeading.EndReading(end); // This is a one-past-the-end pointer!
  PRUint32 maxfindlen = 0;

  // Skip any prefix characters (e.g., scene numbers)
  while (kPrefixChars.FindChar(*start) >= 0)
    ++start;

  // Find the longest match for an int/ext string
  for (PRUint32 i = 0; i < intexts.Length(); ++i) {
    const nsAString& pattern = intexts[i];
    nsAString::const_iterator aStart = start;
    nsAString::const_iterator aEnd = end;
    if (pattern.Length() <= maxfindlen)
      continue;
    if (CaseInsensitiveFindInReadable(pattern, aStart, aEnd) &&
        aStart == start) {
      maxfindlen = pattern.Length();
      // The odds of assigning more than once should be zero for most locales
      aIntExt = pattern;
    }
  }
  start.advance(maxfindlen);

  // Skip any separator characters
  while (*start && kSeparatorChars.FindChar(*start) >= 0)
    ++start;

  // Find the longest match for a day/night string
  maxfindlen = 0;
  nsCaseInsensitiveStringComparator insensitive;
  for (PRUint32 i = 0; i < daynights.Length(); ++i) {
    const nsAString& pattern = daynights[i];
    nsAString::const_iterator aStart = start;
    nsAString::const_iterator aEnd = end;
    if (pattern.Length() <= maxfindlen)
      continue;
    if (RFindInReadable(pattern, aStart, aEnd, insensitive) && aEnd == end) {
      maxfindlen = pattern.Length();
      aDayNight = pattern;
    }
  }
  if (maxfindlen > 0)
    // Remember: End is one-past-the-end
    end.advance(- (PRInt32)(maxfindlen + 1));
  else if (end != start)
    --end;

  // Skip any separator characters
  while (*end && kSeparatorChars.FindChar(*end) >= 0)
    --end;

  aSetting = Substring(start, *end ? ++end : end);

  return NS_OK;
}
예제 #3
0
void
nsDOMTokenList::RemoveInternal(const nsAttrValue* aAttr,
                               const nsAString& aToken)
{
  NS_ABORT_IF_FALSE(aAttr, "Need an attribute");

  nsAutoString input;
  aAttr->ToString(input);

  nsAString::const_iterator copyStart, tokenStart, iter, end;
  input.BeginReading(iter);
  input.EndReading(end);
  copyStart = iter;

  nsAutoString output;
  bool lastTokenRemoved = false;

  while (iter != end) {
    // skip whitespace.
    while (iter != end && nsContentUtils::IsHTMLWhitespace(*iter)) {
      ++iter;
    }

    if (iter == end) {
      // At this point we're sure the last seen token (if any) wasn't to be
      // removed. So the trailing spaces will need to be kept.
      NS_ABORT_IF_FALSE(!lastTokenRemoved, "How did this happen?");

      output.Append(Substring(copyStart, end));
      break;
    }

    tokenStart = iter;
    do {
      ++iter;
    } while (iter != end && !nsContentUtils::IsHTMLWhitespace(*iter));

    if (Substring(tokenStart, iter).Equals(aToken)) {

      // Skip whitespace after the token, it will be collapsed.
      while (iter != end && nsContentUtils::IsHTMLWhitespace(*iter)) {
        ++iter;
      }
      copyStart = iter;
      lastTokenRemoved = true;

    } else {

      if (lastTokenRemoved && !output.IsEmpty()) {
        NS_ABORT_IF_FALSE(!nsContentUtils::IsHTMLWhitespace(
          output.CharAt(output.Length() - 1)), "Invalid last output token");
        output.Append(PRUnichar(' '));
      }
      lastTokenRemoved = false;
      output.Append(Substring(copyStart, iter));
      copyStart = iter;
    }
  }

  mElement->SetAttr(kNameSpaceID_None, mAttrAtom, output, true);
}
예제 #4
0
/* See https://bugzilla.gnome.org/show_bug.cgi?id=629608#c8
 *
 * GDK implements X11 error traps to ignore X11 errors.
 * Unfortunatelly We don't know which X11 events can be ignored
 * so we have to utilize the Gdk error handler to avoid
 * false alarms in Gtk3.
 */
static void
GdkErrorHandler(const gchar *log_domain, GLogLevelFlags log_level,
                const gchar *message,  gpointer user_data)
{
  if (strstr(message, "X Window System error")) {
    XErrorEvent event;
    nsDependentCString buffer(message);
    char *endptr;

    /* Parse Gdk X Window error message which has this format:
     * (Details: serial XXXX error_code XXXX request_code XXXX (XXXX) minor_code XXXX)
     */
    NS_NAMED_LITERAL_CSTRING(serialString, "(Details: serial ");
    int32_t start = buffer.Find(serialString);
    if (start == kNotFound)
      NS_RUNTIMEABORT(message);

    start += serialString.Length();
    errno = 0;
    event.serial = strtol(buffer.BeginReading() + start, &endptr, 10);
    if (errno)
      NS_RUNTIMEABORT(message);

    NS_NAMED_LITERAL_CSTRING(errorCodeString, " error_code ");    
    if (!StringBeginsWith(Substring(endptr, buffer.EndReading()), errorCodeString))
      NS_RUNTIMEABORT(message);

    errno = 0;
    event.error_code = strtol(endptr + errorCodeString.Length(), &endptr, 10);
    if (errno)
      NS_RUNTIMEABORT(message);

    NS_NAMED_LITERAL_CSTRING(requestCodeString, " request_code ");
    if (!StringBeginsWith(Substring(endptr, buffer.EndReading()), requestCodeString))
      NS_RUNTIMEABORT(message);

    errno = 0;
    event.request_code = strtol(endptr + requestCodeString.Length(), &endptr, 10);
    if (errno)
      NS_RUNTIMEABORT(message);

    NS_NAMED_LITERAL_CSTRING(minorCodeString, " minor_code ");
    start = buffer.Find(minorCodeString, endptr - buffer.BeginReading());
    if (!start)
      NS_RUNTIMEABORT(message);

    errno = 0;
    event.minor_code = strtol(buffer.BeginReading() + start + minorCodeString.Length(), nullptr, 10);
    if (errno)
      NS_RUNTIMEABORT(message);

    event.display = GDK_DISPLAY_XDISPLAY(gdk_display_get_default());
    // Gdk does not provide resource ID
    event.resourceid = 0;

    X11Error(event.display, &event);
  } else {
    g_log_default_handler(log_domain, log_level, message, user_data);
    NS_RUNTIMEABORT(message);
  }
}
bool nsPropertiesParser::ParseValueCharacter(
    PRUnichar c, const PRUnichar* cur, const PRUnichar* &tokenStart,
    nsAString& oldValue)
{
  switch (mSpecialState) {

    // the normal state - look for special characters
  case eParserSpecial_None:
    switch (c) {
    case '\\':
      if (mHaveMultiLine)
        // there is nothing to append to mValue yet
        mHaveMultiLine = false;
      else
        mValue += Substring(tokenStart, cur);

      mSpecialState = eParserSpecial_Escaped;
      break;

    case '\n':
      // if we detected multiline and got only "\\\r" ignore next "\n" if any
      if (mHaveMultiLine && mMultiLineCanSkipN) {
        // but don't allow another '\n' to be skipped
        mMultiLineCanSkipN = false;
        // Now there is nothing to append to the mValue since we are skipping
        // whitespaces at the beginning of the new line of the multiline
        // property. Set tokenStart properly to ensure that nothing is appended
        // if we find regular line-end or the end of the buffer.
        tokenStart = cur+1;
        break;
      }
      // no break

    case '\r':
      // we're done! We have a key and value
      mValue += Substring(tokenStart, cur);
      FinishValueState(oldValue);
      mHaveMultiLine = false;
      break;

    default:
      // there is nothing to do with normal characters,
      // but handle multilines correctly
      if (mHaveMultiLine) {
        if (c == ' ' || c == '\t') {
          // don't allow another '\n' to be skipped
          mMultiLineCanSkipN = false;
          // Now there is nothing to append to the mValue since we are skipping
          // whitespaces at the beginning of the new line of the multiline
          // property. Set tokenStart properly to ensure that nothing is appended
          // if we find regular line-end or the end of the buffer.
          tokenStart = cur+1;
          break;
        }
        mHaveMultiLine = false;
        tokenStart = cur;
      }
      break; // from switch on (c)
    }
    break; // from switch on (mSpecialState)

    // saw a \ character, so parse the character after that
  case eParserSpecial_Escaped:
    // probably want to start parsing at the next token
    // other characters, like 'u' might override this
    tokenStart = cur+1;
    mSpecialState = eParserSpecial_None;

    switch (c) {

      // the easy characters - \t, \n, and so forth
    case 't':
      mValue += PRUnichar('\t');
      mMinLength = mValue.Length();
      break;
    case 'n':
      mValue += PRUnichar('\n');
      mMinLength = mValue.Length();
      break;
    case 'r':
      mValue += PRUnichar('\r');
      mMinLength = mValue.Length();
      break;
    case '\\':
      mValue += PRUnichar('\\');
      break;

      // switch to unicode mode!
    case 'u':
    case 'U':
      mSpecialState = eParserSpecial_Unicode;
      mUnicodeValuesRead = 0;
      mUnicodeValue = 0;
      break;

      // a \ immediately followed by a newline means we're going multiline
    case '\r':
    case '\n':
      mHaveMultiLine = true;
      mMultiLineCanSkipN = (c == '\r');
      mSpecialState = eParserSpecial_None;
      break;

    default:
      // don't recognize the character, so just append it
      mValue += c;
      break;
    }
    break;

    // we're in the middle of parsing a 4-character unicode value
    // like \u5f39
  case eParserSpecial_Unicode:

    if(('0' <= c) && (c <= '9'))
      mUnicodeValue =
        (mUnicodeValue << 4) | (c - '0');
    else if(('a' <= c) && (c <= 'f'))
      mUnicodeValue =
        (mUnicodeValue << 4) | (c - 'a' + 0x0a);
    else if(('A' <= c) && (c <= 'F'))
      mUnicodeValue =
        (mUnicodeValue << 4) | (c - 'A' + 0x0a);
    else {
      // non-hex character. Append what we have, and move on.
      mValue += mUnicodeValue;
      mMinLength = mValue.Length();
      mSpecialState = eParserSpecial_None;

      // leave tokenStart at this unknown character, so it gets appended
      tokenStart = cur;

      // ensure parsing this non-hex character again
      return false;
    }

    if (++mUnicodeValuesRead >= 4) {
      tokenStart = cur+1;
      mSpecialState = eParserSpecial_None;
      mValue += mUnicodeValue;
      mMinLength = mValue.Length();
    }

    break;
  }

  return true;
}
예제 #6
0
파일: mac.c 프로젝트: moyuanming/NWeight
EXPORT char *   MAC8(char * data,int dataLength, char * ran, char * key8)
{
	char result[17] ;
	char d3[17] ;
	char d4[17];
	unsigned char Ran9[9];
	unsigned char Prtwmp[17];
	unsigned char key8aaa[strlen(key8)/2];Hex2Bin(key8,key8aaa);
	if (dataLength >= 16)
	{
		
		Substring(data,0, 16,d3);
		Prtwmp[16] = 0x00;
		XOR(PadRight( Substring(ran,0,8,Ran9),16,'0',Prtwmp),d3,dataLength,result);
		result[16]=0;
		if (dataLength % 16 == 0)
		{
			unsigned char temp777[8];
			int i;
			for (  i = 1; i < dataLength / 16; i++)
			{
				Hex2Bin(result,temp777);//temp777=Hex2Bin(result);
				enc(key8aaa, temp777);
				Bin2Hex(temp777,8,result);
				Substring(data,i * 16, 16,d3);
				XOR(result, d3,16,result);
				memcpy(d4,(char *)"8000000000000000",16);
				d4[16] = 0x00;
			}
			if (dataLength == 16) 
			{
				memcpy(d4,(char*)"8000000000000000",16);
				d4[16] = 0x00;
			}
			Hex2Bin(result,temp777);
			enc(key8aaa, temp777);
			Bin2Hex(temp777,8,result);
			XOR(result, d4,16,result);
			Hex2Bin(result,temp777);
			enc(key8aaa, temp777);
			Bin2Hex(temp777,8,result);

		}
		else
		{
			int i;
			unsigned char tmp999[8];
			char *tmpx99x;
			unsigned char tmp999keya[strlen(key8)/2];Hex2Bin(key8,tmp999keya);
			for ( i= 1; i < dataLength / 16; i++)
			{
				unsigned char tmp888[8];Hex2Bin(result,tmp888);
				enc(key8aaa, tmp888);
				Substring(data,i * 16, 16,d3);
				Bin2Hex(tmp888,8,result);
				XOR(result, d3,16,result);

			}

			Substring(data,dataLength - dataLength % 16, dataLength % 16,d4);			
			strcat(d4,"8");
			PadRight(d4,16, '0',d4);
			Hex2Bin(result,tmp999);
			enc(tmp999keya, tmp999);
			Bin2Hex(tmp999,8,result);
			XOR(result, d4,16,result);
			Hex2Bin(result,tmp999);
			enc(tmp999keya, tmp999);
			Bin2Hex(tmp999,8,result);
		}
	}
	else
	{
		unsigned char tmp888111[8];
		unsigned char PdTemp[17];
		sprintf(d3,"%s%s", data, "8");
		PadRight(d3,16, '0',d3);
		PdTemp[16] = 0;
		XOR(PadRight( Substring(ran,0, 8,Ran9),16, '0',PdTemp), d3,16,result);
		Hex2Bin(result,tmp888111);
		enc(key8aaa, tmp888111);
		Bin2Hex(tmp888111,8,result);
	}
	memset(___MAC8,0x00,9);
	memcpy(___MAC8,result,8);
	return ___MAC8;
}
예제 #7
0
already_AddRefed<Promise>
DataTransfer::GetFilesAndDirectories(ErrorResult& aRv)
{
  nsCOMPtr<nsINode> parentNode = do_QueryInterface(mParent);
  if (!parentNode) {
    aRv.Throw(NS_ERROR_FAILURE);
    return nullptr;
  }

  nsCOMPtr<nsIGlobalObject> global = parentNode->OwnerDoc()->GetScopeObject();
  MOZ_ASSERT(global);
  if (!global) {
    aRv.Throw(NS_ERROR_FAILURE);
    return nullptr;
  }

  RefPtr<Promise> p = Promise::Create(global, aRv);
  if (aRv.Failed()) {
    return nullptr;
  }

  if (!mFiles) {
    GetFiles(aRv);
    if (NS_WARN_IF(aRv.Failed())) {
      return nullptr;
    }
  }

  Sequence<OwningFileOrDirectory> filesAndDirsSeq;

  if (mFiles && mFiles->Length()) {
    if (!filesAndDirsSeq.SetLength(mFiles->Length(), mozilla::fallible_t())) {
      p->MaybeReject(NS_ERROR_OUT_OF_MEMORY);
      return p.forget();
    }

    nsPIDOMWindow* window = parentNode->OwnerDoc()->GetInnerWindow();

    RefPtr<OSFileSystem> fs;
    for (uint32_t i = 0; i < mFiles->Length(); ++i) {
      if (mFiles->Item(i)->Impl()->IsDirectory()) {
#if defined(ANDROID) || defined(MOZ_B2G)
        MOZ_ASSERT(false,
                   "Directory picking should have been redirected to normal "
                   "file picking for platforms that don't have a directory "
                   "picker");
#endif
        nsAutoString path;
        mFiles->Item(i)->GetMozFullPathInternal(path, aRv);
        if (aRv.Failed()) {
          return nullptr;
        }
        int32_t leafSeparatorIndex = path.RFind(FILE_PATH_SEPARATOR);
        nsDependentSubstring dirname = Substring(path, 0, leafSeparatorIndex);
        nsDependentSubstring basename = Substring(path, leafSeparatorIndex);
        fs = MakeOrReuseFileSystem(dirname, fs, window);
        filesAndDirsSeq[i].SetAsDirectory() = new Directory(fs, basename);
      } else {
        filesAndDirsSeq[i].SetAsFile() = mFiles->Item(i);
      }
    }
  }

  p->MaybeResolve(filesAndDirsSeq);

  return p.forget();
}
nsresult
nsXREDirProvider::GetUpdateRootDir(nsIFile* *aResult)
{
  nsCOMPtr<nsIFile> updRoot;
#if defined(MOZ_WIDGET_GONK)

  nsresult rv = NS_NewNativeLocalFile(nsDependentCString("/data/local"),
                                      true,
                                      getter_AddRefs(updRoot));
  NS_ENSURE_SUCCESS(rv, rv);

#else
  nsCOMPtr<nsIFile> appFile;
  bool per = false;
  nsresult rv = GetFile(XRE_EXECUTABLE_FILE, &per, getter_AddRefs(appFile));
  NS_ENSURE_SUCCESS(rv, rv);
  rv = appFile->GetParent(getter_AddRefs(updRoot));
  NS_ENSURE_SUCCESS(rv, rv);

#ifdef XP_WIN

  nsAutoString pathHash;
  bool pathHashResult = false;

  nsAutoString appDirPath;
  if (gAppData->vendor && !getenv("MOZ_UPDATE_NO_HASH_DIR") &&
      SUCCEEDED(updRoot->GetPath(appDirPath))) {

    // Figure out where we should check for a cached hash value
    wchar_t regPath[1024] = { L'\0' };
    swprintf_s(regPath, mozilla::ArrayLength(regPath), L"SOFTWARE\\%S\\%S\\TaskBarIDs",
               gAppData->vendor, MOZ_APP_NAME);

    // If we pre-computed the hash, grab it from the registry.
    pathHashResult = GetCachedHash(HKEY_LOCAL_MACHINE,
                                   nsDependentString(regPath), appDirPath,
                                   pathHash);
    if (!pathHashResult) {
      pathHashResult = GetCachedHash(HKEY_CURRENT_USER,
                                     nsDependentString(regPath), appDirPath,
                                     pathHash);
    }
  }

  // Get the local app data directory and if a vendor name exists append it.
  // If only a product name exists, append it.  If neither exist fallback to
  // old handling.  We don't use the product name on purpose because we want a
  // shared update directory for different apps run from the same path (like
  // Metro & Desktop).
  nsCOMPtr<nsIFile> localDir;
  if (pathHashResult && (gAppData->vendor || gAppData->name) &&
      NS_SUCCEEDED(GetUserDataDirectoryHome(getter_AddRefs(localDir), true)) &&
      NS_SUCCEEDED(localDir->AppendNative(nsDependentCString(gAppData->vendor ?
                                          gAppData->vendor : gAppData->name))) &&
      NS_SUCCEEDED(localDir->Append(NS_LITERAL_STRING("updates"))) &&
      NS_SUCCEEDED(localDir->Append(pathHash))) {
    NS_ADDREF(*aResult = localDir);
    return NS_OK;
  }

  nsAutoString appPath;
  rv = updRoot->GetPath(appPath);
  NS_ENSURE_SUCCESS(rv, rv);

  // AppDir may be a short path. Convert to long path to make sure
  // the consistency of the update folder location
  nsString longPath;
  PRUnichar* buf;

  uint32_t bufLength = longPath.GetMutableData(&buf, MAXPATHLEN);
  NS_ENSURE_TRUE(bufLength >= MAXPATHLEN, NS_ERROR_OUT_OF_MEMORY);

  DWORD len = GetLongPathNameW(appPath.get(), buf, bufLength);

  // Failing GetLongPathName() is not fatal.
  if (len <= 0 || len >= bufLength)
    longPath.Assign(appPath);
  else
    longPath.SetLength(len);

  // Use <UserLocalDataDir>\updates\<relative path to app dir from
  // Program Files> if app dir is under Program Files to avoid the
  // folder virtualization mess on Windows Vista
  nsAutoString programFiles;
  rv = GetShellFolderPath(CSIDL_PROGRAM_FILES, programFiles);
  NS_ENSURE_SUCCESS(rv, rv);

  programFiles.AppendLiteral("\\");
  uint32_t programFilesLen = programFiles.Length();

  nsAutoString programName;
  if (_wcsnicmp(programFiles.get(), longPath.get(), programFilesLen) == 0) {
    programName = Substring(longPath, programFilesLen);
  } else {
    // We need the update root directory to live outside of the installation
    // directory, because otherwise the updater writing the log file can cause
    // the directory to be locked, which prevents it from being replaced after
    // background updates.
    programName.AssignASCII(MOZ_APP_NAME);
  }

  rv = GetUserLocalDataDirectory(getter_AddRefs(updRoot));
  NS_ENSURE_SUCCESS(rv, rv);

  rv = updRoot->AppendRelativePath(programName);
  NS_ENSURE_SUCCESS(rv, rv);

#endif
#endif
  NS_ADDREF(*aResult = updRoot);
  return NS_OK;
}
static void
loadTestEVInfos()
{
  if (!testEVInfos)
    return;

  testEVInfos->Clear();

  char *env_val = getenv("ENABLE_TEST_EV_ROOTS_FILE");
  if (!env_val)
    return;
    
  int enabled_val = atoi(env_val);
  if (!enabled_val)
    return;

  nsCOMPtr<nsIFile> aFile;
  NS_GetSpecialDirectory(NS_APP_USER_PROFILE_50_DIR, getter_AddRefs(aFile));
  if (!aFile)
    return;

  aFile->AppendNative(NS_LITERAL_CSTRING(kTestEVRootsFileName));

  nsresult rv;
  nsCOMPtr<nsIInputStream> fileInputStream;
  rv = NS_NewLocalFileInputStream(getter_AddRefs(fileInputStream), aFile);
  if (NS_FAILED(rv))
    return;

  nsCOMPtr<nsILineInputStream> lineInputStream = do_QueryInterface(fileInputStream, &rv);
  if (NS_FAILED(rv))
    return;

  nsCAutoString buffer;
  bool isMore = true;

  /* file format
   *
   * file format must be strictly followed
   * strings in file must be UTF-8
   * each record consists of multiple lines
   * each line consists of a descriptor, a single space, and the data
   * the descriptors are:
   *   1_fingerprint (in format XX:XX:XX:...)
   *   2_readable_oid (treated as a comment)
   * the input file must strictly follow this order
   * the input file may contain 0, 1 or many records
   * completely empty lines are ignored
   * lines that start with the # char are ignored
   */

  int line_counter = 0;
  bool found_error = false;

  enum { 
    pos_fingerprint, pos_readable_oid, pos_issuer, pos_serial
  } reader_position = pos_fingerprint;

  nsCString fingerprint, readable_oid, issuer, serial;

  while (isMore && NS_SUCCEEDED(lineInputStream->ReadLine(buffer, &isMore))) {
    ++line_counter;
    if (buffer.IsEmpty() || buffer.First() == '#') {
      continue;
    }

    int32_t seperatorIndex = buffer.FindChar(' ', 0);
    if (seperatorIndex == 0) {
      found_error = true;
      break;
    }

    const nsASingleFragmentCString &descriptor = Substring(buffer, 0, seperatorIndex);
    const nsASingleFragmentCString &data = 
            Substring(buffer, seperatorIndex + 1, 
                      buffer.Length() - seperatorIndex + 1);

    if (reader_position == pos_fingerprint &&
        descriptor.EqualsLiteral(("1_fingerprint"))) {
      fingerprint = data;
      reader_position = pos_readable_oid;
      continue;
    }
    else if (reader_position == pos_readable_oid &&
        descriptor.EqualsLiteral(("2_readable_oid"))) {
      readable_oid = data;
      reader_position = pos_issuer;
      continue;
    }
    else if (reader_position == pos_issuer &&
        descriptor.EqualsLiteral(("3_issuer"))) {
      issuer = data;
      reader_position = pos_serial;
      continue;
    }
    else if (reader_position == pos_serial &&
        descriptor.EqualsLiteral(("4_serial"))) {
      serial = data;
      reader_position = pos_fingerprint;
    }
    else {
      found_error = true;
      break;
    }

    nsMyTrustedEVInfoClass *temp_ev = new nsMyTrustedEVInfoClass;
    if (!temp_ev)
      return;

    temp_ev->ev_root_sha1_fingerprint = strdup(fingerprint.get());
    temp_ev->oid_name = strdup(readable_oid.get());
    temp_ev->dotted_oid = strdup(readable_oid.get());
    temp_ev->issuer_base64 = strdup(issuer.get());
    temp_ev->serial_base64 = strdup(serial.get());

    SECStatus rv;
    CERTIssuerAndSN ias;

    rv = ATOB_ConvertAsciiToItem(&ias.derIssuer, const_cast<char*>(temp_ev->issuer_base64));
    NS_ASSERTION(rv==SECSuccess, "error converting ascii to binary.");
    rv = ATOB_ConvertAsciiToItem(&ias.serialNumber, const_cast<char*>(temp_ev->serial_base64));
    NS_ASSERTION(rv==SECSuccess, "error converting ascii to binary.");

    temp_ev->cert = CERT_FindCertByIssuerAndSN(nullptr, &ias);
    NS_ASSERTION(temp_ev->cert, "Could not find EV root in NSS storage");

    SECITEM_FreeItem(&ias.derIssuer, false);
    SECITEM_FreeItem(&ias.serialNumber, false);

    if (!temp_ev->cert)
      return;

    nsNSSCertificate c(temp_ev->cert);
    nsAutoString fingerprint;
    c.GetSha1Fingerprint(fingerprint);

    NS_ConvertASCIItoUTF16 sha1(temp_ev->ev_root_sha1_fingerprint);

    if (sha1 != fingerprint) {
      NS_ASSERTION(sha1 == fingerprint, "found EV root with unexpected SHA1 mismatch");
      CERT_DestroyCertificate(temp_ev->cert);
      temp_ev->cert = nullptr;
      return;
    }

    SECItem ev_oid_item;
    ev_oid_item.data = nullptr;
    ev_oid_item.len = 0;
    SECStatus srv = SEC_StringToOID(nullptr, &ev_oid_item,
                                    readable_oid.get(), readable_oid.Length());
    if (srv != SECSuccess) {
      delete temp_ev;
      found_error = true;
      break;
    }

    temp_ev->oid_tag = register_oid(&ev_oid_item, temp_ev->oid_name);
    SECITEM_FreeItem(&ev_oid_item, false);

    testEVInfos->AppendElement(temp_ev);
  }

  if (found_error) {
    fprintf(stderr, "invalid line %d in test_ev_roots file\n", line_counter);
  }
}
예제 #10
0
PRBool gfxPlatform::ForEachPrefFont(eFontPrefLang aLangArray[], PRUint32 aLangArrayLen, PrefFontCallback aCallback,
                                    void *aClosure)
{
    nsresult rv;

    nsCOMPtr<nsIPrefBranch> prefs(do_GetService(NS_PREFSERVICE_CONTRACTID));
    if (!prefs)
        return PR_FALSE;

    PRUint32    i;
    
    for (i = 0; i < aLangArrayLen; i++) {
        eFontPrefLang prefLang = aLangArray[i];
        const char *langGroup = GetPrefLangName(prefLang);
        
        nsCAutoString prefName;
        nsXPIDLCString nameValue, nameListValue;
    
        nsCAutoString genericDotLang;
        prefName.AssignLiteral("font.default.");
        prefName.Append(langGroup);
        prefs->GetCharPref(prefName.get(), getter_Copies(genericDotLang));
    
        genericDotLang.AppendLiteral(".");
        genericDotLang.Append(langGroup);
    
        // fetch font.name.xxx value                   
        prefName.AssignLiteral("font.name.");
        prefName.Append(genericDotLang);
        rv = prefs->GetCharPref(prefName.get(), getter_Copies(nameValue));
        if (NS_SUCCEEDED(rv)) {
            if (!aCallback(prefLang, NS_ConvertUTF8toUTF16(nameValue), aClosure))
                return PR_FALSE;
        }
    
        // fetch font.name-list.xxx value                   
        prefName.AssignLiteral("font.name-list.");
        prefName.Append(genericDotLang);
        rv = prefs->GetCharPref(prefName.get(), getter_Copies(nameListValue));
        if (NS_SUCCEEDED(rv) && !nameListValue.Equals(nameValue)) {
            const char kComma = ',';
            const char *p, *p_end;
            nsCAutoString list(nameListValue);
            list.BeginReading(p);
            list.EndReading(p_end);
            while (p < p_end) {
                while (nsCRT::IsAsciiSpace(*p)) {
                    if (++p == p_end)
                        break;
                }
                if (p == p_end)
                    break;
                const char *start = p;
                while (++p != p_end && *p != kComma)
                    /* nothing */ ;
                nsCAutoString fontName(Substring(start, p));
                fontName.CompressWhitespace(PR_FALSE, PR_TRUE);
                if (!aCallback(prefLang, NS_ConvertUTF8toUTF16(fontName), aClosure))
                    return PR_FALSE;
                p++;
            }
        }
    }

    return PR_TRUE;
}
예제 #11
0
void
gfxPlatform::AppendCJKPrefLangs(eFontPrefLang aPrefLangs[], PRUint32 &aLen, eFontPrefLang aCharLang, eFontPrefLang aPageLang)
{
    nsCOMPtr<nsIPrefBranch> prefs(do_GetService(NS_PREFSERVICE_CONTRACTID));

    // prefer the lang specified by the page *if* CJK
    if (IsLangCJK(aPageLang)) {
        AppendPrefLang(aPrefLangs, aLen, aPageLang);
    }
    
    // if not set up, set up the default CJK order, based on accept lang settings and locale
    if (mCJKPrefLangs.Length() == 0) {
    
        // temp array
        eFontPrefLang tempPrefLangs[kMaxLenPrefLangList];
        PRUint32 tempLen = 0;
        
        // Add the CJK pref fonts from accept languages, the order should be same order
        nsCAutoString list;
        if (prefs) {
            nsCOMPtr<nsIPrefLocalizedString> prefString;
            nsresult rv =
                prefs->GetComplexValue("intl.accept_languages",
                                       NS_GET_IID(nsIPrefLocalizedString),
                                       getter_AddRefs(prefString));
            if (NS_SUCCEEDED(rv) && prefString) {
                nsAutoString temp;
                prefString->ToString(getter_Copies(temp));
                LossyCopyUTF16toASCII(temp, list);
            }
        }
        
        if (!list.IsEmpty()) {
            const char kComma = ',';
            const char *p, *p_end;
            list.BeginReading(p);
            list.EndReading(p_end);
            while (p < p_end) {
                while (nsCRT::IsAsciiSpace(*p)) {
                    if (++p == p_end)
                        break;
                }
                if (p == p_end)
                    break;
                const char *start = p;
                while (++p != p_end && *p != kComma)
                    /* nothing */ ;
                nsCAutoString lang(Substring(start, p));
                lang.CompressWhitespace(PR_FALSE, PR_TRUE);
                eFontPrefLang fpl = gfxPlatform::GetFontPrefLangFor(lang.get());
                switch (fpl) {
                    case eFontPrefLang_Japanese:
                    case eFontPrefLang_Korean:
                    case eFontPrefLang_ChineseCN:
                    case eFontPrefLang_ChineseHK:
                    case eFontPrefLang_ChineseTW:
                        AppendPrefLang(tempPrefLangs, tempLen, fpl);
                        break;
                    default:
                        break;
                }
                p++;
            }
        }

        do { // to allow 'break' to abort this block if a call fails
            nsresult rv;
            nsCOMPtr<nsILocaleService> ls =
                do_GetService(NS_LOCALESERVICE_CONTRACTID, &rv);
            if (NS_FAILED(rv))
                break;

            nsCOMPtr<nsILocale> appLocale;
            rv = ls->GetApplicationLocale(getter_AddRefs(appLocale));
            if (NS_FAILED(rv))
                break;

            nsString localeStr;
            rv = appLocale->
                GetCategory(NS_LITERAL_STRING(NSILOCALE_MESSAGE), localeStr);
            if (NS_FAILED(rv))
                break;

            const nsAString& lang = Substring(localeStr, 0, 2);
            if (lang.EqualsLiteral("ja")) {
                AppendPrefLang(tempPrefLangs, tempLen, eFontPrefLang_Japanese);
            } else if (lang.EqualsLiteral("zh")) {
                const nsAString& region = Substring(localeStr, 3, 2);
                if (region.EqualsLiteral("CN")) {
                    AppendPrefLang(tempPrefLangs, tempLen, eFontPrefLang_ChineseCN);
                } else if (region.EqualsLiteral("TW")) {
                    AppendPrefLang(tempPrefLangs, tempLen, eFontPrefLang_ChineseTW);
                } else if (region.EqualsLiteral("HK")) {
                    AppendPrefLang(tempPrefLangs, tempLen, eFontPrefLang_ChineseHK);
                }
            } else if (lang.EqualsLiteral("ko")) {
                AppendPrefLang(tempPrefLangs, tempLen, eFontPrefLang_Korean);
            }
        } while (0);

        // last resort... (the order is same as old gfx.)
        AppendPrefLang(tempPrefLangs, tempLen, eFontPrefLang_Japanese);
        AppendPrefLang(tempPrefLangs, tempLen, eFontPrefLang_Korean);
        AppendPrefLang(tempPrefLangs, tempLen, eFontPrefLang_ChineseCN);
        AppendPrefLang(tempPrefLangs, tempLen, eFontPrefLang_ChineseHK);
        AppendPrefLang(tempPrefLangs, tempLen, eFontPrefLang_ChineseTW);
        
        // copy into the cached array
        PRUint32 j;
        for (j = 0; j < tempLen; j++) {
            mCJKPrefLangs.AppendElement(tempPrefLangs[j]);
        }
    }
    
    // append in cached CJK langs
    PRUint32  i, numCJKlangs = mCJKPrefLangs.Length();
    
    for (i = 0; i < numCJKlangs; i++) {
        AppendPrefLang(aPrefLangs, aLen, (eFontPrefLang) (mCJKPrefLangs[i]));
    }
        
}
nsresult
nsIndexedToHTML::FormatInputStream(nsIRequest* aRequest, nsISupports *aContext, const nsAString &aBuffer) 
{
    nsresult rv = NS_OK;

    // set up unicode encoder
    if (!mUnicodeEncoder) {
      nsXPIDLCString encoding;
      rv = mParser->GetEncoding(getter_Copies(encoding));
      if (NS_SUCCEEDED(rv)) {
        nsCOMPtr<nsICharsetConverterManager> charsetConverterManager;
        charsetConverterManager = do_GetService(NS_CHARSETCONVERTERMANAGER_CONTRACTID, &rv);
        rv = charsetConverterManager->GetUnicodeEncoder(encoding.get(), 
                                                          getter_AddRefs(mUnicodeEncoder));
        if (NS_SUCCEEDED(rv))
            rv = mUnicodeEncoder->SetOutputErrorBehavior(nsIUnicodeEncoder::kOnError_Replace, 
                                                       nullptr, (PRUnichar)'?');
      }
    }

    // convert the data with unicode encoder
    char *buffer = nullptr;
    int32_t dstLength;
    if (NS_SUCCEEDED(rv)) {
      int32_t unicharLength = aBuffer.Length();
      rv = mUnicodeEncoder->GetMaxLength(PromiseFlatString(aBuffer).get(), 
                                         unicharLength, &dstLength);
      if (NS_SUCCEEDED(rv)) {
        buffer = (char *) nsMemory::Alloc(dstLength);
        NS_ENSURE_TRUE(buffer, NS_ERROR_OUT_OF_MEMORY);

        rv = mUnicodeEncoder->Convert(PromiseFlatString(aBuffer).get(), &unicharLength, 
                                      buffer, &dstLength);
        if (NS_SUCCEEDED(rv)) {
          int32_t finLen = 0;
          rv = mUnicodeEncoder->Finish(buffer + dstLength, &finLen);
          if (NS_SUCCEEDED(rv))
            dstLength += finLen;
        }
      }
    }

    // if conversion error then fallback to UTF-8
    if (NS_FAILED(rv)) {
      rv = NS_OK;
      if (buffer) {
        nsMemory::Free(buffer);
        buffer = nullptr;
      }
    }

    nsCOMPtr<nsIInputStream> inputData;
    if (buffer) {
      rv = NS_NewCStringInputStream(getter_AddRefs(inputData), Substring(buffer, dstLength));
      nsMemory::Free(buffer);
      NS_ENSURE_SUCCESS(rv, rv);
      rv = mListener->OnDataAvailable(aRequest, aContext,
                                      inputData, 0, dstLength);
    }
    else {
      NS_ConvertUTF16toUTF8 utf8Buffer(aBuffer);
      rv = NS_NewCStringInputStream(getter_AddRefs(inputData), utf8Buffer);
      NS_ENSURE_SUCCESS(rv, rv);
      rv = mListener->OnDataAvailable(aRequest, aContext,
                                      inputData, 0, utf8Buffer.Length());
    }
    return (rv);
}
예제 #13
0
NS_IMETHODIMP
nsExpatDriver::ConsumeToken(nsScanner& aScanner, bool& aFlushTokens)
{
  // We keep the scanner pointing to the position where Expat will start
  // parsing.
  nsScannerIterator currentExpatPosition;
  aScanner.CurrentPosition(currentExpatPosition);

  // This is the start of the first buffer that we need to pass to Expat.
  nsScannerIterator start = currentExpatPosition;
  start.advance(mExpatBuffered);

  // This is the end of the last buffer (at this point, more data could come in
  // later).
  nsScannerIterator end;
  aScanner.EndReading(end);

  PR_LOG(gExpatDriverLog, PR_LOG_DEBUG,
         ("Remaining in expat's buffer: %i, remaining in scanner: %i.",
          mExpatBuffered, Distance(start, end)));

  // We want to call Expat if we have more buffers, or if we know there won't
  // be more buffers (and so we want to flush the remaining data), or if we're
  // currently blocked and there's data in Expat's buffer.
  while (start != end || (mIsFinalChunk && !mMadeFinalCallToExpat) ||
         (BlockedOrInterrupted() && mExpatBuffered > 0)) {
    bool noMoreBuffers = start == end && mIsFinalChunk;
    bool blocked = BlockedOrInterrupted();

    const PRUnichar *buffer;
    uint32_t length;
    if (blocked || noMoreBuffers) {
      // If we're blocked we just resume Expat so we don't need a buffer, if
      // there aren't any more buffers we pass a null buffer to Expat.
      buffer = nullptr;
      length = 0;

#if defined(PR_LOGGING) || defined (DEBUG)
      if (blocked) {
        PR_LOG(gExpatDriverLog, PR_LOG_DEBUG,
               ("Resuming Expat, will parse data remaining in Expat's "
                "buffer.\nContent of Expat's buffer:\n-----\n%s\n-----\n",
                NS_ConvertUTF16toUTF8(currentExpatPosition.get(),
                                      mExpatBuffered).get()));
      }
      else {
        NS_ASSERTION(mExpatBuffered == Distance(currentExpatPosition, end),
                     "Didn't pass all the data to Expat?");
        PR_LOG(gExpatDriverLog, PR_LOG_DEBUG,
               ("Last call to Expat, will parse data remaining in Expat's "
                "buffer.\nContent of Expat's buffer:\n-----\n%s\n-----\n",
                NS_ConvertUTF16toUTF8(currentExpatPosition.get(),
                                      mExpatBuffered).get()));
      }
#endif
    }
    else {
      buffer = start.get();
      length = uint32_t(start.size_forward());

      PR_LOG(gExpatDriverLog, PR_LOG_DEBUG,
             ("Calling Expat, will parse data remaining in Expat's buffer and "
              "new data.\nContent of Expat's buffer:\n-----\n%s\n-----\nNew "
              "data:\n-----\n%s\n-----\n",
              NS_ConvertUTF16toUTF8(currentExpatPosition.get(),
                                    mExpatBuffered).get(),
              NS_ConvertUTF16toUTF8(start.get(), length).get()));
    }

    uint32_t consumed;
    ParseBuffer(buffer, length, noMoreBuffers, &consumed);
    if (consumed > 0) {
      nsScannerIterator oldExpatPosition = currentExpatPosition;
      currentExpatPosition.advance(consumed);

      // We consumed some data, we want to store the last line of data that
      // was consumed in case we run into an error (to show the line in which
      // the error occurred).

      // The length of the last line that Expat has parsed.
      XML_Size lastLineLength = XML_GetCurrentColumnNumber(mExpatParser);

      if (lastLineLength <= consumed) {
        // The length of the last line was less than what expat consumed, so
        // there was at least one line break in the consumed data. Store the
        // last line until the point where we stopped parsing.
        nsScannerIterator startLastLine = currentExpatPosition;
        startLastLine.advance(-((ptrdiff_t)lastLineLength));
        CopyUnicodeTo(startLastLine, currentExpatPosition, mLastLine);
      }
      else {
        // There was no line break in the consumed data, append the consumed
        // data.
        AppendUnicodeTo(oldExpatPosition, currentExpatPosition, mLastLine);
      }
    }

    mExpatBuffered += length - consumed;

    if (BlockedOrInterrupted()) {
      PR_LOG(gExpatDriverLog, PR_LOG_DEBUG,
             ("Blocked or interrupted parser (probably for loading linked "
              "stylesheets or scripts)."));

      aScanner.SetPosition(currentExpatPosition, true);
      aScanner.Mark();

      return mInternalState;
    }

    if (noMoreBuffers && mExpatBuffered == 0) {
      mMadeFinalCallToExpat = true;
    }

    if (NS_FAILED(mInternalState)) {
      if (XML_GetErrorCode(mExpatParser) != XML_ERROR_NONE) {
        NS_ASSERTION(mInternalState == NS_ERROR_HTMLPARSER_STOPPARSING,
                     "Unexpected error");

        // Look for the next newline after the last one we consumed
        nsScannerIterator lastLine = currentExpatPosition;
        while (lastLine != end) {
          length = uint32_t(lastLine.size_forward());
          uint32_t endOffset = 0;
          const PRUnichar *buffer = lastLine.get();
          while (endOffset < length && buffer[endOffset] != '\n' &&
                 buffer[endOffset] != '\r') {
            ++endOffset;
          }
          mLastLine.Append(Substring(buffer, buffer + endOffset));
          if (endOffset < length) {
            // We found a newline.
            break;
          }

          lastLine.advance(length);
        }

        HandleError();
      }

      return mInternalState;
    }

    // Either we have more buffers, or we were blocked (and we'll flush in the
    // next iteration), or we should have emptied Expat's buffer.
    NS_ASSERTION(!noMoreBuffers || blocked ||
                 (mExpatBuffered == 0 && currentExpatPosition == end),
                 "Unreachable data left in Expat's buffer");

    start.advance(length);

    // It's possible for start to have passed end if we received more data
    // (e.g. if we spun the event loop in an inline script). Reload end now
    // to compensate.
    aScanner.EndReading(end);
  }

  aScanner.SetPosition(currentExpatPosition, true);
  aScanner.Mark();

  PR_LOG(gExpatDriverLog, PR_LOG_DEBUG,
         ("Remaining in expat's buffer: %i, remaining in scanner: %i.",
          mExpatBuffered, Distance(currentExpatPosition, end)));

  return NS_SUCCEEDED(mInternalState) ? kEOF : NS_OK;
}
예제 #14
0
nsresult
nsDogbertProfileMigrator::FixDogbertCookies()
{
  nsCOMPtr<nsIFile> dogbertCookiesFile;
  mSourceProfile->Clone(getter_AddRefs(dogbertCookiesFile));
  dogbertCookiesFile->Append(COOKIES_FILE_NAME_IN_4x);

  nsCOMPtr<nsIInputStream> fileInputStream;
  NS_NewLocalFileInputStream(getter_AddRefs(fileInputStream), dogbertCookiesFile);
  if (!fileInputStream) return NS_ERROR_OUT_OF_MEMORY;

  nsCOMPtr<nsIFile> firebirdCookiesFile;
  mTargetProfile->Clone(getter_AddRefs(firebirdCookiesFile));
  firebirdCookiesFile->Append(COOKIES_FILE_NAME_IN_5x);

  nsCOMPtr<nsIOutputStream> fileOutputStream;
  NS_NewLocalFileOutputStream(getter_AddRefs(fileOutputStream), firebirdCookiesFile);
  if (!fileOutputStream) return NS_ERROR_OUT_OF_MEMORY;

  nsCOMPtr<nsILineInputStream> lineInputStream(do_QueryInterface(fileInputStream));
  nsCAutoString buffer, outBuffer;
  PRBool moreData = PR_FALSE;
  PRUint32 written = 0;
  do {
    nsresult rv = lineInputStream->ReadLine(buffer, &moreData);
    if (NS_FAILED(rv)) return rv;
    
    if (!moreData)
      break;

    // skip line if it is a comment or null line
    if (buffer.IsEmpty() || buffer.CharAt(0) == '#' ||
        buffer.CharAt(0) == '\r' || buffer.CharAt(0) == '\n') {
      fileOutputStream->Write(buffer.get(), buffer.Length(), &written);
      continue;
    }

    // locate expire field, skip line if it does not contain all its fields
    int hostIndex, isDomainIndex, pathIndex, xxxIndex, expiresIndex, nameIndex, cookieIndex;
    hostIndex = 0;
    if ((isDomainIndex = buffer.FindChar('\t', hostIndex)+1) == 0 ||
        (pathIndex = buffer.FindChar('\t', isDomainIndex)+1) == 0 ||
        (xxxIndex = buffer.FindChar('\t', pathIndex)+1) == 0 ||
        (expiresIndex = buffer.FindChar('\t', xxxIndex)+1) == 0 ||
        (nameIndex = buffer.FindChar('\t', expiresIndex)+1) == 0 ||
        (cookieIndex = buffer.FindChar('\t', nameIndex)+1) == 0 )
      continue;

    // separate the expires field from the rest of the cookie line
    const nsDependentCSubstring prefix = 
      Substring(buffer, hostIndex, expiresIndex-hostIndex-1);
    const nsDependentCSubstring expiresString =
      Substring(buffer, expiresIndex, nameIndex-expiresIndex-1);
    const nsDependentCSubstring suffix =
      Substring(buffer, nameIndex, buffer.Length()-nameIndex);

    // correct the expires field
    char* expiresCString = ToNewCString(expiresString);
    unsigned long expires = strtoul(expiresCString, nsnull, 10);
    NS_Free(expiresCString);

    // if the cookie is supposed to expire at the end of the session
    // expires == 0.  don't adjust those cookies.
    if (expires)
    	expires -= SECONDS_BETWEEN_1900_AND_1970;
    char dateString[36];
    PR_snprintf(dateString, sizeof(dateString), "%lu", expires);

    // generate the output buffer and write it to file
    outBuffer = prefix;
    outBuffer.Append('\t');
    outBuffer.Append(dateString);
    outBuffer.Append('\t');
    outBuffer.Append(suffix);

    fileOutputStream->Write(outBuffer.get(), outBuffer.Length(), &written);
  }
  while (1);
  
  return NS_OK;
}
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 PRUnichar* formatString[1] = { ratioStr.get() };
    mStringBundle->FormatStringFromName(NS_LITERAL_STRING("ScaledImage").get(),
                                        formatString, 1,
                                        getter_Copies(status));
  }

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

  MediaDocument::UpdateTitleAndCharset(typeStr, formatNames,
                                       mImageWidth, mImageHeight, status);
}
예제 #16
0
nsresult
nsContentBlocker::TestPermission(nsIURI *aCurrentURI,
                                 nsIURI *aFirstURI,
                                 int32_t aContentType,
                                 bool *aPermission,
                                 bool *aFromPrefs)
{
  *aFromPrefs = false;
  // This default will also get used if there is an unknown value in the
  // permission list, or if the permission manager returns unknown values.
  *aPermission = true;

  // check the permission list first; if we find an entry, it overrides
  // default prefs.
  // Don't forget the aContentType ranges from 1..8, while the
  // array is indexed 0..7
  uint32_t permission;
  nsresult rv = mPermissionManager->TestPermission(aCurrentURI, 
                                                   kTypeString[aContentType - 1],
                                                   &permission);
  NS_ENSURE_SUCCESS(rv, rv);

  // If there is nothing on the list, use the default.
  if (!permission) {
    permission = mBehaviorPref[aContentType - 1];
    *aFromPrefs = true;
  }

  // Use the fact that the nsIPermissionManager values map to 
  // the BEHAVIOR_* values above.
  switch (permission) {
  case BEHAVIOR_ACCEPT:
    *aPermission = true;
    break;
  case BEHAVIOR_REJECT:
    *aPermission = false;
    break;

  case BEHAVIOR_NOFOREIGN:
    // Third party checking

    // Need a requesting uri for third party checks to work.
    if (!aFirstURI)
      return NS_OK;

    bool trustedSource = false;
    rv = aFirstURI->SchemeIs("chrome", &trustedSource);
    NS_ENSURE_SUCCESS(rv,rv);
    if (!trustedSource) {
      rv = aFirstURI->SchemeIs("resource", &trustedSource);
      NS_ENSURE_SUCCESS(rv,rv);
    }
    if (trustedSource)
      return NS_OK;

    // compare tails of names checking to see if they have a common domain
    // we do this by comparing the tails of both names where each tail 
    // includes at least one dot
    
    // A more generic method somewhere would be nice

    nsAutoCString currentHost;
    rv = aCurrentURI->GetAsciiHost(currentHost);
    NS_ENSURE_SUCCESS(rv, rv);

    // Search for two dots, starting at the end.
    // If there are no two dots found, ++dot will turn to zero,
    // that will return the entire string.
    int32_t dot = currentHost.RFindChar('.');
    dot = currentHost.RFindChar('.', dot-1);
    ++dot;

    // Get the domain, ie the last part of the host (www.domain.com -> domain.com)
    // This will break on co.uk
    const nsCSubstring &tail =
      Substring(currentHost, dot, currentHost.Length() - dot);

    nsAutoCString firstHost;
    rv = aFirstURI->GetAsciiHost(firstHost);
    NS_ENSURE_SUCCESS(rv, rv);

    // If the tail is longer then the whole firstHost, it will never match
    if (firstHost.Length() < tail.Length()) {
      *aPermission = false;
      return NS_OK;
    }
    
    // Get the last part of the firstUri with the same length as |tail|
    const nsCSubstring &firstTail = 
      Substring(firstHost, firstHost.Length() - tail.Length(), tail.Length());

    // Check that both tails are the same, and that just before the tail in
    // |firstUri| there is a dot. That means both url are in the same domain
    if ((firstHost.Length() > tail.Length() && 
         firstHost.CharAt(firstHost.Length() - tail.Length() - 1) != '.') || 
        !tail.Equals(firstTail)) {
      *aPermission = false;
    }
    break;
  }
  
  return NS_OK;
}
예제 #17
0
파일: mac.c 프로젝트: moyuanming/NWeight
char * MAC(char* data,int dataLength, char * ran, char * key16)
{
	int key16Length =32 ;
	char keya[17];
	char keyb[17];
	char d3[17];
	char d4[17];
	char result[17];
	memcpy( keya ,key16, key16Length / 2);
	memcpy( keyb  , (char*)&key16[key16Length / 2],key16Length / 2);
	keya[16]=0;
	keyb[16]=0;
	memset( d3 ,0x00,sizeof(d3));
	memset( d4 ,0x00,sizeof(d3));
	memset( result,0x00,sizeof(16));
	echomac("bb");
	if (dataLength >= 16)
	{
		unsigned char Ran9[9];
		unsigned char PrTemp[17];
		memcpy(d3, data, 16);
		PrTemp[16] = 0x00;
		d3[16]=0;
		XOR(PadRight(Substring(ran,0,8,Ran9), 16, '0',PrTemp),  d3,16,result);
		echomac("bb");
		if (dataLength % 16 == 0)
		{
			int i ;
			for ( i = 1; i <dataLength / 16; i++)
			{
				unsigned char resultBin[8],keyaBin[8] ;				;
				enc(Hex2Bin(keya,keyaBin), Hex2Bin(result,resultBin));
				Bin2Hex(resultBin,8,result);
				printf( result);
				Substring(data,i * 16, 16,d3);
				XOR(result, d3,16,result);
				memcpy(d4 , (char*)&"8000000000000000",16);
				echomac("bb");
			}
			if (dataLength == 16) 
			{
				memcpy(d4 ,"8000000000000000",16);
			}
			echomac("bb");
			unsigned char temp222[8];Hex2Bin(result,temp222);
			unsigned char keyaXXX[8];Hex2Bin(keya,keyaXXX);
			unsigned char keybXXX[8];Hex2Bin(keyb,keybXXX);
			enc(keyaXXX, temp222);
			Bin2Hex(temp222,8,result);			
			XOR(result, d4,16,result);			
			Hex2Bin(result,temp222);
			enc(keyaXXX, temp222);
			Bin2Hex(temp222,8,result);			
			dec(keybXXX, temp222);
			Bin2Hex(temp222,8,result);			
			enc(keyaXXX, temp222);
			Bin2Hex(temp222,8,result);	
			echomac("bb");
		}
		else
		{
			
			int i ;
			unsigned char keyaXXX1[8];Hex2Bin(keya,keyaXXX1);
			unsigned char keybXXX1[8];Hex2Bin(keyb,keybXXX1);
			echomac("bb");
			for ( i = 1; i < dataLength / 16; i++)
			{
				unsigned char temp4441[8];Hex2Bin(result,temp4441);
				unsigned char temp4442keya[8];Hex2Bin(keya,temp4442keya);
				enc(temp4442keya, temp4441);
				Bin2Hex(temp4441,8,result);
				Substring(data, i * 16, 16,d3);
				XOR(result, d3,16,result);
			}
			Substring(data,dataLength - dataLength % 16, dataLength % 16,d4);
			strcat(d4,"8");//可能有问题
			PadRight(d4,16, '0',d4);
			unsigned char temp555[8];Hex2Bin(result,temp555);
			enc(keyaXXX1, temp555);
			Bin2Hex(temp555,8,result);
			XOR(result,  d4,16,result);
			Hex2Bin(result,temp555);//temp555=Hex2Bin(result);
			enc(keyaXXX1, temp555);
			dec(keybXXX1, temp555);
			enc(keyaXXX1, temp555);
			Bin2Hex(temp555,8,result);
			echomac("bb");
		}
	}
	else
	{
		echomac("bb");
		unsigned char Ran9[9];
		unsigned char temp4442keya[8];Hex2Bin(keya,temp4442keya);
		unsigned char temp4442keyb[8];Hex2Bin(keyb,temp4442keyb);
		sprintf(d3,"%s%s",data,"8");
		PadRight(d3,16, '0',d3);
		PadRight(Substring(ran,0,8,Ran9),16,'0',result);
		XOR( result, d3,16,result);
		unsigned char temp777[8];Hex2Bin(result,temp777);
		enc(temp4442keya, temp777);
		Bin2Hex(temp777,8,result);;
		dec(temp4442keyb, temp777);
		Bin2Hex(temp777,8,result);
		enc(temp4442keya, temp777);
		Bin2Hex(temp777,8,result);
		echomac("bb");
	}
	memset(___MAC,0x00,9);
	memcpy(___MAC,result,8);
	return ___MAC;

}
예제 #18
0
// Return a fully populated command string based on
// passing information. Used in launchWithFile to trace
// back to the full handler path based on the dll.
// (dll, targetfile, return args, open/edit)
bool nsMIMEInfoWin::GetDllLaunchInfo(nsIFile * aDll,
                                       nsIFile * aFile,
                                       nsAString& args,
                                       bool edit)
{
  if (!aDll || !aFile) 
    return false;

  nsString appExeName;
  aDll->GetLeafName(appExeName);

  nsCOMPtr<nsIWindowsRegKey> appKey = 
    do_CreateInstance("@mozilla.org/windows-registry-key;1");
  if (!appKey) 
    return false; 

  // HKEY_CLASSES_ROOT\Applications\iexplore.exe
  nsAutoString applicationsPath;
  applicationsPath.AppendLiteral("Applications\\");
  applicationsPath.Append(appExeName);

  nsresult rv = appKey->Open(nsIWindowsRegKey::ROOT_KEY_CLASSES_ROOT,
                             applicationsPath,
                             nsIWindowsRegKey::ACCESS_QUERY_VALUE);
  if (NS_FAILED(rv))
    return false;

  // Check for the NoOpenWith flag, if it exists
  uint32_t value;
  rv = appKey->ReadIntValue(NS_LITERAL_STRING("NoOpenWith"), &value);
  if (NS_SUCCEEDED(rv) && value == 1)
    return false;

  nsAutoString dummy;
  if (NS_SUCCEEDED(appKey->ReadStringValue(NS_LITERAL_STRING("NoOpenWith"), 
                                           dummy)))
    return false;

  appKey->Close();

  // HKEY_CLASSES_ROOT\Applications\iexplore.exe\shell\open\command
  applicationsPath.AssignLiteral("Applications\\");
  applicationsPath.Append(appExeName);
  if (!edit)
    applicationsPath.AppendLiteral("\\shell\\open\\command");
  else
    applicationsPath.AppendLiteral("\\shell\\edit\\command");

  rv = appKey->Open(nsIWindowsRegKey::ROOT_KEY_CLASSES_ROOT,
                    applicationsPath,
                    nsIWindowsRegKey::ACCESS_QUERY_VALUE);
  if (NS_FAILED(rv))
    return false;

  nsAutoString appFilesystemCommand;
  if (NS_SUCCEEDED(appKey->ReadStringValue(EmptyString(),
                                           appFilesystemCommand))) {
    // Replace embedded environment variables.
    uint32_t bufLength = 
      ::ExpandEnvironmentStringsW(appFilesystemCommand.get(),
                                  L"", 0);
    if (bufLength == 0) // Error
      return false;

    nsAutoArrayPtr<wchar_t> destination(new wchar_t[bufLength]);
    if (!destination)
      return false;
    if (!::ExpandEnvironmentStringsW(appFilesystemCommand.get(),
                                     destination,
                                     bufLength))
      return false;

    appFilesystemCommand = static_cast<const wchar_t*>(destination);

    // C:\Windows\System32\rundll32.exe "C:\Program Files\Windows 
    // Photo Gallery\PhotoViewer.dll", ImageView_Fullscreen %1
    nsAutoString params;
    NS_NAMED_LITERAL_STRING(rundllSegment, "rundll32.exe ");
    int32_t index = appFilesystemCommand.Find(rundllSegment);
    if (index > kNotFound) {
      params.Append(Substring(appFilesystemCommand,
                    index + rundllSegment.Length()));
    } else {
      params.Append(appFilesystemCommand);
    }

    // check to make sure we have a %1 and fill it
    NS_NAMED_LITERAL_STRING(percentOneParam, "%1");
    index = params.Find(percentOneParam);
    if (index == kNotFound) // no parameter
      return false;

    nsString target;
    aFile->GetTarget(target);
    params.Replace(index, 2, target);

    args = params;

    return true;
  }
  return false;
}
예제 #19
0
void
DOMEventTargetHelper::EventListenerRemoved(nsIAtom* aType)
{
  ErrorResult rv;
  EventListenerWasRemoved(Substring(nsDependentAtomString(aType), 2), rv);
}
예제 #20
0
NS_IMETHODIMP
nsMIMEInfoWin::LaunchWithFile(nsIFile* aFile)
{
  nsresult rv;

  // it doesn't make any sense to call this on protocol handlers
  NS_ASSERTION(mClass == eMIMEInfo,
               "nsMIMEInfoBase should have mClass == eMIMEInfo");

  if (mPreferredAction == useSystemDefault) {
    return LaunchDefaultWithFile(aFile);
  }

  if (mPreferredAction == useHelperApp) {
    if (!mPreferredApplication)
      return NS_ERROR_FILE_NOT_FOUND;

    // at the moment, we only know how to hand files off to local handlers
    nsCOMPtr<nsILocalHandlerApp> localHandler = 
      do_QueryInterface(mPreferredApplication, &rv);
    NS_ENSURE_SUCCESS(rv, rv);

    nsCOMPtr<nsIFile> executable;
    rv = localHandler->GetExecutable(getter_AddRefs(executable));
    NS_ENSURE_SUCCESS(rv, rv);

    nsAutoString path;
    aFile->GetPath(path);

    // Deal with local dll based handlers
    nsCString filename;
    executable->GetNativeLeafName(filename);
    if (filename.Length() > 4) {
      nsCString extension(Substring(filename, filename.Length() - 4, 4));

      if (extension.LowerCaseEqualsLiteral(".dll")) {
        nsAutoString args;

        // executable is rundll32, everything else is a list of parameters, 
        // including the dll handler.
        if (!GetDllLaunchInfo(executable, aFile, args, false))
          return NS_ERROR_INVALID_ARG;

        WCHAR rundll32Path[MAX_PATH + sizeof(RUNDLL32_EXE) / sizeof(WCHAR) + 1] = {L'\0'};
        if (!GetSystemDirectoryW(rundll32Path, MAX_PATH)) {
          return NS_ERROR_FILE_NOT_FOUND;
        }
        lstrcatW(rundll32Path, RUNDLL32_EXE);

        SHELLEXECUTEINFOW seinfo;
        memset(&seinfo, 0, sizeof(seinfo));
        seinfo.cbSize = sizeof(SHELLEXECUTEINFOW);
        seinfo.fMask  = 0;
        seinfo.hwnd   = nullptr;
        seinfo.lpVerb = nullptr;
        seinfo.lpFile = rundll32Path;
        seinfo.lpParameters =  args.get();
        seinfo.lpDirectory  = nullptr;
        seinfo.nShow  = SW_SHOWNORMAL;
        if (ShellExecuteExW(&seinfo))
          return NS_OK;

        switch ((LONG_PTR)seinfo.hInstApp) {
          case 0:
          case SE_ERR_OOM:
            return NS_ERROR_OUT_OF_MEMORY;
          case SE_ERR_ACCESSDENIED:
            return NS_ERROR_FILE_ACCESS_DENIED;
          case SE_ERR_ASSOCINCOMPLETE:
          case SE_ERR_NOASSOC:
            return NS_ERROR_UNEXPECTED;
          case SE_ERR_DDEBUSY:
          case SE_ERR_DDEFAIL:
          case SE_ERR_DDETIMEOUT:
            return NS_ERROR_NOT_AVAILABLE;
          case SE_ERR_DLLNOTFOUND:
            return NS_ERROR_FAILURE;
          case SE_ERR_SHARE:
            return NS_ERROR_FILE_IS_LOCKED;
          default:
            switch(GetLastError()) {
              case ERROR_FILE_NOT_FOUND:
                return NS_ERROR_FILE_NOT_FOUND;
              case ERROR_PATH_NOT_FOUND:
                return NS_ERROR_FILE_UNRECOGNIZED_PATH;
              case ERROR_BAD_FORMAT:
                return NS_ERROR_FILE_CORRUPTED;
            }

        }
        return NS_ERROR_FILE_EXECUTION_FAILED;
      }
    }
    return LaunchWithIProcess(executable, path);
  }

  return NS_ERROR_INVALID_ARG;
}
예제 #21
0
int
mozilla_decoders_init(void)
{
    static PRBool initialized = PR_FALSE;
    if (initialized)
        return 0;

    PangoContext* context = gdk_pango_context_get ();
    PangoFontMap* fontmap = pango_context_get_font_map (context);
    g_object_unref (context);
    
    if (!PANGO_IS_FC_FONT_MAP (fontmap))
        return -1;

    encoder_hash = g_hash_table_new(g_str_hash, g_str_equal);
    cmap_hash = g_hash_table_new(g_str_hash, g_str_equal);
    wide_hash = g_hash_table_new(g_str_hash, g_str_equal);

    PRBool dumb = PR_FALSE;
    nsCOMPtr<nsIPersistentProperties> props;
    nsCOMPtr<nsISimpleEnumerator> encodeEnum;

    NS_LoadPersistentPropertiesFromURISpec(getter_AddRefs(props),
        NS_LITERAL_CSTRING("resource://gre/res/fonts/pangoFontEncoding.properties"));

    if (!props)
        goto loser;

    // Enumerate the properties in this file and figure out all of the
    // fonts for which we have custom encodings.
    props->Enumerate(getter_AddRefs(encodeEnum));
    if (!encodeEnum)
        goto loser;

    while (encodeEnum->HasMoreElements(&dumb), dumb) {
        nsCOMPtr<nsIPropertyElement> prop;
        encodeEnum->GetNext(getter_AddRefs(prop));
        if (!prop)
            goto loser;

        nsCAutoString name;
        prop->GetKey(name);
        nsAutoString value;
        prop->GetValue(value);

        if (!StringBeginsWith(name, NS_LITERAL_CSTRING("encoding."))) {
            printf("string doesn't begin with encoding?\n");
            continue;
        }

        name = Substring(name, 9);

        if (StringEndsWith(name, NS_LITERAL_CSTRING(".ttf"))) {
            name = Substring(name, 0, name.Length() - 4);

            // Strip off a .wide if it's there.
            if (StringEndsWith(value, NS_LITERAL_STRING(".wide"))) {
                g_hash_table_insert(wide_hash, g_strdup(name.get()),
                                    g_strdup("wide"));
                value = Substring(value, 0, name.Length() - 5);
            }

            g_hash_table_insert(encoder_hash,
                                g_strdup(name.get()),
                                g_strdup(NS_ConvertUTF16toUTF8(value).get()));
        }
        else if (StringEndsWith(name, NS_LITERAL_CSTRING(".ftcmap"))) {
            name = Substring(name, 0, name.Length() - 7);
            g_hash_table_insert(cmap_hash,
                                g_strdup(name.get()),
                                g_strdup(NS_ConvertUTF16toUTF8(value).get()));
        }
        else {
            printf("unknown suffix used for mapping\n");
        }
    }

    pango_fc_font_map_add_decoder_find_func(PANGO_FC_FONT_MAP(fontmap),
                                            mozilla_find_decoder,
                                            NULL,
                                            NULL);

    initialized = PR_TRUE;

#ifdef DEBUG_CUSTOM_ENCODER
    printf("*** encoders\n");
    g_hash_table_foreach(encoder_hash, (GHFunc)dump_hash, NULL);

    printf("*** cmaps\n");
    g_hash_table_foreach(cmap_hash, (GHFunc)dump_hash, NULL);
#endif

    return 0;

 loser:
    return -1;
}
nsresult
XULSortServiceImpl::InitializeSortState(nsIContent* aRootElement,
                                        nsIContent* aContainer,
                                        const nsAString& aSortKey,
                                        const nsAString& aSortDirection,
                                        nsSortState* aSortState)
{
  // used as an optimization for the content builder
  if (aContainer != aSortState->lastContainer.get()) {
    aSortState->lastContainer = aContainer;
    aSortState->lastWasFirst = PR_FALSE;
    aSortState->lastWasLast = PR_FALSE;
  }

  // The attributes allowed are either:
  //    sort="key1 key2 ..."
  // or sortResource="key1" sortResource2="key2"
  // The latter is for backwards compatibility, and is equivalent to concatenating
  // both values in the sort attribute
  nsAutoString sort(aSortKey);
  aSortState->sortKeys.Clear();
  if (sort.IsEmpty()) {
    nsAutoString sortResource, sortResource2;
    aRootElement->GetAttr(kNameSpaceID_None, nsGkAtoms::sortResource, sortResource);
    if (!sortResource.IsEmpty()) {
      nsCOMPtr<nsIAtom> sortkeyatom = do_GetAtom(sortResource);
      aSortState->sortKeys.AppendObject(sortkeyatom);
      sort.Append(sortResource);

      aRootElement->GetAttr(kNameSpaceID_None, nsGkAtoms::sortResource2, sortResource2);
      if (!sortResource2.IsEmpty()) {
        nsCOMPtr<nsIAtom> sortkeyatom2 = do_GetAtom(sortResource2);
        aSortState->sortKeys.AppendObject(sortkeyatom2);
        sort.AppendLiteral(" ");
        sort.Append(sortResource2);
    }
  }
    }
    else {
    PRInt32 start = 0, end = 0;
    while ((end = sort.FindChar(' ',start)) >= 0) {
      if (end > start) {
        nsCOMPtr<nsIAtom> keyatom = do_GetAtom(Substring(sort, start, end - start));
        if (!keyatom)
          return NS_ERROR_OUT_OF_MEMORY;

        aSortState->sortKeys.AppendObject(keyatom);
      }
      start = end + 1;
    }
    if (start < (PRInt32)sort.Length()) {
      nsCOMPtr<nsIAtom> keyatom = do_GetAtom(Substring(sort, start));
      if (!keyatom)
        return NS_ERROR_OUT_OF_MEMORY;

      aSortState->sortKeys.AppendObject(keyatom);
    }
  }

  aSortState->sort.Assign(sort);

  // set up sort order info
  if (aSortDirection.EqualsLiteral("descending"))
    aSortState->direction = nsSortState_descending;
  else if (aSortDirection.EqualsLiteral("ascending"))
    aSortState->direction = nsSortState_ascending;
        else
    aSortState->direction = nsSortState_natural;

  aSortState->invertSort = PR_FALSE;
          
  nsAutoString existingsort;
  aRootElement->GetAttr(kNameSpaceID_None, nsGkAtoms::sort, existingsort);
  nsAutoString existingsortDirection;
  aRootElement->GetAttr(kNameSpaceID_None, nsGkAtoms::sortDirection, existingsortDirection);
          
  // if just switching direction, set the invertSort flag
  if (sort.Equals(existingsort)) {
    if (aSortState->direction == nsSortState_descending) {
      if (existingsortDirection.EqualsLiteral("ascending"))
        aSortState->invertSort = PR_TRUE;
      }
    else if (aSortState->direction == nsSortState_ascending &&
              existingsortDirection.EqualsLiteral("descending")) {
      aSortState->invertSort = PR_TRUE;
    }
  }

  // sort items between separatore independently
  aSortState->inbetweenSeparatorSort =
    aRootElement->AttrValueIs(kNameSpaceID_None, nsGkAtoms::sortSeparators,
                              nsGkAtoms::_true, eCaseMatters);

  // sort static content (non template generated nodes) after generated content
  aSortState->sortStaticsLast = aRootElement->AttrValueIs(kNameSpaceID_None,
                                  nsGkAtoms::sortStaticsLast,
                                  nsGkAtoms::_true, eCaseMatters);

  aSortState->initialized = PR_TRUE;

  return NS_OK;
}
예제 #23
0
static int
MimeInlineTextPlainFlowed_parse_line (const char *aLine, int32_t length, MimeObject *obj)
{
  int status;
  bool quoting = ( obj->options
    && ( obj->options->format_out == nsMimeOutput::nsMimeMessageQuoting ||
         obj->options->format_out == nsMimeOutput::nsMimeMessageBodyQuoting
       )           );  // see above
  bool plainHTML = quoting || (obj->options &&
       obj->options->format_out == nsMimeOutput::nsMimeMessageSaveAs);
       // see above

  struct MimeInlineTextPlainFlowedExData *exdata;
  exdata = MimeInlineTextPlainFlowedExDataList;
  while(exdata && (exdata->ownerobj != obj)) {
    exdata = exdata->next;
  }

  NS_ASSERTION(exdata, "The extra data has disappeared!");

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

  uint32_t linequotelevel = 0;
  nsAutoCString real_line(aLine, length);
  char *line = real_line.BeginWriting();
  const char *linep = real_line.BeginReading();
  // Space stuffed?
  if(' ' == *linep) {
    linep++;
  } else {
    // count '>':s before the first non-'>'
    while('>' == *linep) {
      linep++;
      linequotelevel++;
    }
    // Space stuffed?
    if(' ' == *linep) {
      linep++;
    }
  }

  // Look if the last character (after stripping ending end
  // of lines and quoting stuff) is a SPACE. If it is, we are looking at a
  // flowed line. Normally we assume that the last two chars
  // are CR and LF as said in RFC822, but that doesn't seem to
  // be the case always.
  bool flowed = false;
  bool sigSeparator = false;
  int32_t index = length-1;
  while(index >= 0 && ('\r' == line[index] || '\n' == line[index])) {
    index--;
  }
  if (index > linep - line && ' ' == line[index])
       /* Ignore space stuffing, i.e. lines with just
          (quote marks and) a space count as empty */
  {
    flowed = true;
    sigSeparator = (index - (linep - line) + 1 == 3) && !strncmp(linep, "-- ", 3);
    if (((MimeInlineTextPlainFlowed *) obj)->delSp && !sigSeparator)
       /* If line is flowed and DelSp=yes, logically
          delete trailing space. Line consisting of
          dash dash space ("-- "), commonly used as
          signature separator, gets special handling
          (RFC 3676) */
    {
      length--;
      line[index] = '\0';
    }
  }

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

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

  nsAutoString lineSource;
  nsString lineResult;

  char *mailCharset = NULL;
  nsresult rv;

  if (!skipConversion)
  {
    // Convert only if the source string is not empty
    if (length - (linep - line) > 0)
    {
      uint32_t whattodo = obj->options->whattodo;
      if (plainHTML)
      {
        if (quoting)
          whattodo = 0;
        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. */
      }

      const nsDependentCSubstring& inputStr = Substring(linep, linep + (length - (linep - line)));

      // 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, PromiseFlatCString(inputStr), lineSource);
          NS_ENSURE_SUCCESS(rv, -1);
        }
        else // this probably never happens...
          CopyUTF8toUTF16(inputStr, lineSource);
      }
      else   // line is in UTF-8
        CopyUTF8toUTF16(inputStr, lineSource);

      // This is the main TXT to HTML conversion:
      // escaping (very important), eventually recognizing etc.
      rv = conv->ScanTXT(lineSource.get(), whattodo, getter_Copies(lineResult));
      NS_ENSURE_SUCCESS(rv, -1);
    }
  }
  else
  {
    CopyUTF8toUTF16(nsDependentCString(line, length), lineResult);
    status = 0;
  }

  nsAutoCString preface;

  /* Correct number of blockquotes */
  int32_t quoteleveldiff=linequotelevel - exdata->quotelevel;
  if((quoteleveldiff != 0) && flowed && exdata->inflow) {
    // From RFC 2646 4.5
    // The receiver SHOULD handle this error by using the 'quote-depth-wins' rule,
    // which is to ignore the flowed indicator and treat the line as fixed.  That
    // is, the change in quote depth ends the paragraph.

    // We get that behaviour by just going on.
  }

  // Cast so we have access to the prefs we need.
  MimeInlineTextPlainFlowed *tObj = (MimeInlineTextPlainFlowed *) obj;
  while(quoteleveldiff>0) {
    quoteleveldiff--;
    preface += "<blockquote type=cite";

    nsAutoCString style;
    MimeTextBuildPrefixCSS(tObj->mQuotedSizeSetting, tObj->mQuotedStyleSetting,
                           tObj->mCitationColor, style);
    if (!plainHTML && !style.IsEmpty())
    {
      preface += " style=\"";
      preface += style;
      preface += '"';
    }
    preface += '>';
  }
  while(quoteleveldiff<0) {
    quoteleveldiff++;
    preface += "</blockquote>";
  }
  exdata->quotelevel = linequotelevel;

  nsAutoString lineResult2;

  if(flowed) {
    // Check RFC 2646 "4.3. Usenet Signature Convention": "-- "+CRLF is
    // not a flowed line
    if (sigSeparator)
    {
      if (linequotelevel > 0 || exdata->isSig)
      {
        preface += "--&nbsp;<br>";
      } else {
        exdata->isSig = true;
        preface += "<div class=\"moz-txt-sig\"><span class=\"moz-txt-tag\">"
                   "--&nbsp;<br></span>";
      }
    } else {
      Line_convert_whitespace(lineResult, false /* Allow wraps */,
                              lineResult2);
    }

    exdata->inflow=true;
  } else {
    // Fixed paragraph.
    Line_convert_whitespace(lineResult,
                            !plainHTML && !obj->options->wrap_long_lines_p
                              /* If wrap, convert all spaces but the last in
                                 a row into nbsp, otherwise all. */,
                            lineResult2);
    lineResult2.AppendLiteral("<br>");
    exdata->inflow = false;
  } // End Fixed line

  if (!(exdata->isSig && quoting && tObj->mStripSig))
  {
    status = MimeObject_write(obj, preface.get(), preface.Length(), true);
    if (status < 0) return status;
    nsAutoCString outString;
    if (obj->options->format_out != nsMimeOutput::nsMimeMessageSaveAs ||
        !mailCharset || !*mailCharset)
      CopyUTF16toUTF8(lineResult2, outString);
    else
    { // convert back to mailCharset before writing.
      rv = nsMsgI18NConvertFromUnicode(mailCharset, lineResult2, outString);
      NS_ENSURE_SUCCESS(rv, -1);
    }
    status = MimeObject_write(obj, outString.get(), outString.Length(), true);
    return status;
  }
  return 0;
}
예제 #24
0
void
nsAttrValue::ParseAtomArray(const nsAString& aValue)
{
  nsAString::const_iterator iter, end;
  aValue.BeginReading(iter);
  aValue.EndReading(end);
  PRBool hasSpace = PR_FALSE;
  
  // skip initial whitespace
  while (iter != end && nsContentUtils::IsHTMLWhitespace(*iter)) {
    hasSpace = PR_TRUE;
    ++iter;
  }

  if (iter == end) {
    SetTo(aValue);
    return;
  }

  nsAString::const_iterator start(iter);

  // get first - and often only - atom
  do {
    ++iter;
  } while (iter != end && !nsContentUtils::IsHTMLWhitespace(*iter));

  nsCOMPtr<nsIAtom> classAtom = do_GetAtom(Substring(start, iter));
  if (!classAtom) {
    Reset();
    return;
  }

  // skip whitespace
  while (iter != end && nsContentUtils::IsHTMLWhitespace(*iter)) {
    hasSpace = PR_TRUE;
    ++iter;
  }

  if (iter == end && !hasSpace) {
    // we only found one classname and there was no whitespace so
    // don't bother storing a list
    ResetIfSet();
    nsIAtom* atom = nsnull;
    classAtom.swap(atom);
    SetPtrValueAndType(atom, eAtomBase);
    return;
  }

  if (!EnsureEmptyAtomArray()) {
    return;
  }

  AtomArray* array = GetAtomArrayValue();
  
  if (!array->AppendElement(classAtom)) {
    Reset();
    return;
  }

  // parse the rest of the classnames
  while (iter != end) {
    start = iter;

    do {
      ++iter;
    } while (iter != end && !nsContentUtils::IsHTMLWhitespace(*iter));

    classAtom = do_GetAtom(Substring(start, iter));

    if (!array->AppendElement(classAtom)) {
      Reset();
      return;
    }

    // skip whitespace
    while (iter != end && nsContentUtils::IsHTMLWhitespace(*iter)) {
      ++iter;
    }
  }

  SetMiscAtomOrString(&aValue);
  return;
}
nsresult nsPropertiesParser::ParseBuffer(const PRUnichar* aBuffer,
                                         uint32_t aBufferLength)
{
  const PRUnichar* cur = aBuffer;
  const PRUnichar* end = aBuffer + aBufferLength;

  // points to the start/end of the current key or value
  const PRUnichar* tokenStart = nullptr;

  // if we're in the middle of parsing a key or value, make sure
  // the current token points to the beginning of the current buffer
  if (mState == eParserState_Key ||
      mState == eParserState_Value) {
    tokenStart = aBuffer;
  }

  nsAutoString oldValue;

  while (cur != end) {

    PRUnichar c = *cur;

    switch (mState) {
    case eParserState_AwaitingKey:
      if (c == '#' || c == '!')
        EnterCommentState();

      else if (!IsWhiteSpace(c)) {
        // not a comment, not whitespace, we must have found a key!
        EnterKeyState();
        tokenStart = cur;
      }
      break;

    case eParserState_Key:
      if (c == '=' || c == ':') {
        mKey += Substring(tokenStart, cur);
        WaitForValue();
      }
      break;

    case eParserState_AwaitingValue:
      if (IsEOL(c)) {
        // no value at all! mimic the normal value-ending
        EnterValueState();
        FinishValueState(oldValue);
      }

      // ignore white space leading up to the value
      else if (!IsWhiteSpace(c)) {
        tokenStart = cur;
        EnterValueState();

        // make sure to handle this first character
        if (ParseValueCharacter(c, cur, tokenStart, oldValue))
          cur++;
        // If the character isn't consumed, don't do cur++ and parse
        // the character again. This can happen f.e. for char 'X' in sequence
        // "\u00X". This character can be control character and must be
        // processed again.
        continue;
      }
      break;

    case eParserState_Value:
      if (ParseValueCharacter(c, cur, tokenStart, oldValue))
        cur++;
      // See few lines above for reason of doing this
      continue;

    case eParserState_Comment:
      // stay in this state till we hit EOL
      if (c == '\r' || c== '\n')
        WaitForKey();
      break;
    }

    // finally, advance to the next character
    cur++;
  }

  // if we're still parsing the value and are in eParserSpecial_None, then
  // append whatever we have..
  if (mState == eParserState_Value && tokenStart &&
      mSpecialState == eParserSpecial_None) {
    mValue += Substring(tokenStart, cur);
  }
  // if we're still parsing the key, then append whatever we have..
  else if (mState == eParserState_Key && tokenStart) {
    mKey += Substring(tokenStart, cur);
  }

  return NS_OK;
}
예제 #26
0
bool CAliasData::Process(const char *pLine, PRInt32 len)
{
  // Extract any comments first!
  nsCString  str;

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

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

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

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

  str.Trim(kWhitespace);

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

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

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

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

  return !m_email.IsEmpty();
}
예제 #27
0
nsresult nsMapiHook::HandleAttachments (nsIMsgCompFields * aCompFields, int32_t aFileCount,
                                        lpnsMapiFileDesc aFiles, BOOL aIsUnicode)
{
    nsresult rv = NS_OK ;

    nsAutoCString Attachments ;
    nsAutoCString TempFiles ;

    nsCOMPtr <nsIFile> pFile = do_CreateInstance (NS_LOCAL_FILE_CONTRACTID, &rv) ;
    if (NS_FAILED(rv) || (!pFile) ) return rv ;
    nsCOMPtr <nsIFile> pTempDir = do_CreateInstance (NS_LOCAL_FILE_CONTRACTID, &rv) ;
    if (NS_FAILED(rv) || (!pTempDir) ) return rv ;

    for (int i=0 ; i < aFileCount ; i++)
    {
        bool bTempFile = false ;
        if (aFiles[i].lpszPathName)
        {
            // check if attachment exists
            if (aIsUnicode)
                pFile->InitWithPath (nsDependentString(aFiles[i].lpszPathName));
            else
                pFile->InitWithNativePath (nsDependentCString((const char*)aFiles[i].lpszPathName));

            bool bExist ;
            rv = pFile->Exists(&bExist) ;
            PR_LOG(MAPI, PR_LOG_DEBUG, ("nsMapiHook::HandleAttachments: filename: %s path: %s exists = %s \n", (const char*)aFiles[i].lpszFileName, (const char*)aFiles[i].lpszPathName, bExist ? "true" : "false"));
            if (NS_FAILED(rv) || (!bExist) ) return NS_ERROR_FILE_TARGET_DOES_NOT_EXIST ;

            //Temp Directory
            nsCOMPtr <nsIFile> pTempDir;
            NS_GetSpecialDirectory(NS_OS_TEMP_DIR, getter_AddRefs(pTempDir));

            // create a new sub directory called moz_mapi underneath the temp directory
            pTempDir->AppendRelativePath(NS_LITERAL_STRING("moz_mapi"));
            pTempDir->Exists (&bExist) ;
            if (!bExist)
            {
                rv = pTempDir->Create(nsIFile::DIRECTORY_TYPE, 777) ;
                if (NS_FAILED(rv)) return rv ;
            }

            // rename or copy the existing temp file with the real file name

            nsAutoString leafName ;
            // convert to Unicode using Platform charset
            // leafName already contains a unicode leafName from lpszPathName. If we were given
            // a value for lpszFileName, use it. Otherwise stick with leafName
            if (aFiles[i].lpszFileName)
            {
              nsAutoString wholeFileName;
                if (aIsUnicode)
                    wholeFileName.Assign(aFiles[i].lpszFileName);
                else
                    ConvertToUnicode(nsMsgI18NFileSystemCharset(), (char *) aFiles[i].lpszFileName, wholeFileName);
                // need to find the last '\' and find the leafname from that.
                int32_t lastSlash = wholeFileName.RFindChar(PRUnichar('\\'));
                if (lastSlash != kNotFound)
                  leafName.Assign(Substring(wholeFileName, lastSlash + 1));
                else
                  leafName.Assign(wholeFileName);
            }
            else
              pFile->GetLeafName (leafName);

            nsCOMPtr<nsIMsgAttachment> attachment = do_CreateInstance(NS_MSGATTACHMENT_CONTRACTID, &rv);
            NS_ENSURE_SUCCESS(rv, rv);
            attachment->SetName(leafName);

            nsCOMPtr<nsIFile> pTempFile;
            rv = pTempDir->Clone(getter_AddRefs(pTempFile));
            if (NS_FAILED(rv) || !pTempFile)
              return rv;

            pTempFile->Append(leafName);
            pTempFile->Exists(&bExist);
            if (bExist)
            {
              rv = pTempFile->CreateUnique(nsIFile::NORMAL_FILE_TYPE, 0777);
              NS_ENSURE_SUCCESS(rv, rv);
              pTempFile->Remove(false); // remove so we can copy over it.
              pTempFile->GetLeafName(leafName);
            }
            // copy the file to its new location and file name
            pFile->CopyTo(pTempDir, leafName);
            // point pFile to the new location of the attachment
            pFile->InitWithFile(pTempDir);
            pFile->Append(leafName);

            // create MsgCompose attachment object
            attachment->SetTemporary(true); // this one is a temp file so set the flag for MsgCompose

            // now set the attachment object
            nsAutoCString pURL ;
            NS_GetURLSpecFromFile(pFile, pURL);
            attachment->SetUrl(pURL);

            // set the file size
            int64_t fileSize;
            pFile->GetFileSize(&fileSize);
            attachment->SetSize(fileSize);

            // add the attachment
            rv = aCompFields->AddAttachment (attachment);
            if (NS_FAILED(rv))
              PR_LOG(MAPI, PR_LOG_DEBUG, ("nsMapiHook::HandleAttachments: AddAttachment rv =  %lx\n", rv));
        }
    }
    return rv ;
}
예제 #28
0
void nsEudoraAddress::AddSingleCard(CAliasEntry *pEntry, nsVoidArray &emailList, nsIAddrDatabase *pDb)
{
  // We always have a nickname and everything else is optional.
  // Map both home and work related fields to our address card. Eudora
  // fields that can't be mapped will be left in the 'note' field!
  nsIMdbRow* newRow = nsnull;
  pDb->GetNewRow(&newRow);
  if (!newRow)
    return;

  nsCString                   displayName, name, firstName, lastName;
  nsCString                   fax, secondaryFax, phone, mobile, secondaryMobile, webLink;
  nsCString                   address, address2, city, state, zip, country;
  nsCString                   phoneWK, webLinkWK, title, company;
  nsCString                   addressWK, address2WK, cityWK, stateWK, zipWK, countryWK;
  nsCString                   primaryLocation, otherPhone, otherWeb;
  nsCString                   additionalEmail, stillMoreEmail;
  nsCString                   note(pEntry->m_notes);
  nsString                    noteUTF16;
  bool                        isSecondaryMobileWorkNumber = true;
  bool                        isSecondaryFaxWorkNumber = true;

  if (!note.IsEmpty())
  {
    ExtractNoteField(note, fax, "fax");
    ExtractNoteField(note, secondaryFax, "fax2");
    ExtractNoteField(note, phone, "phone");
    ExtractNoteField(note, mobile, "mobile");
    ExtractNoteField(note, secondaryMobile, "mobile2");
    ExtractNoteField(note, address, "address");
    ExtractNoteField(note, city, "city");
    ExtractNoteField(note, state, "state");
    ExtractNoteField(note, zip, "zip");
    ExtractNoteField(note, country, "country");
    ExtractNoteField(note, name, "name");
    ExtractNoteField(note, firstName, "first");
    ExtractNoteField(note, lastName, "last");
    ExtractNoteField(note, webLink, "web");

    ExtractNoteField(note, addressWK, "address2");
    ExtractNoteField(note, cityWK, "city2");
    ExtractNoteField(note, stateWK, "state2");
    ExtractNoteField(note, zipWK, "zip2");
    ExtractNoteField(note, countryWK, "country2");
    ExtractNoteField(note, phoneWK, "phone2");
    ExtractNoteField(note, title, "title");
    ExtractNoteField(note, company, "company");
    ExtractNoteField(note, webLinkWK, "web2");

    ExtractNoteField(note, primaryLocation, "primary");
    ExtractNoteField(note, additionalEmail, "otheremail");
    ExtractNoteField(note, otherPhone, "otherphone");
    ExtractNoteField(note, otherWeb, "otherweb");

    // Is there any "extra" data that we may want to format nicely and place
    // in the notes field?
    if (!additionalEmail.IsEmpty() || !otherPhone.IsEmpty() || !otherWeb.IsEmpty())
    {
      nsCString     otherNotes(note);

      if (!additionalEmail.IsEmpty())
      {
        // Reconstitute line breaks for additional email
        MsgReplaceSubstring(additionalEmail, "\x03", "\n");

        // Try to figure out if there are multiple email addresses in additionalEmail
        PRInt32     idx = MsgFindCharInSet(additionalEmail, "\t\r\n,; ");

        if (idx != -1)
        {
          // We found a character that indicates that there's more than one email address here.
          // Separate out the addresses after the first one.
          stillMoreEmail = Substring(additionalEmail, idx + 1);
          stillMoreEmail.Trim(kWhitespace);

          // Separate out the first address.
          additionalEmail.SetLength(idx);
        }

        // If there were more than one additional email addresses store all the extra
        // ones in the notes field, labeled nicely.
        if (!stillMoreEmail.IsEmpty())
          FormatExtraDataInNoteField(EUDORAIMPORT_ADDRESS_LABEL_OTHEREMAIL, stillMoreEmail, noteUTF16);
      }

      if (!otherPhone.IsEmpty())
      {
        // Reconstitute line breaks for other phone numbers
        MsgReplaceSubstring(otherPhone, "\x03", "\n");

        // Store other phone numbers in the notes field, labeled nicely
        FormatExtraDataInNoteField(EUDORAIMPORT_ADDRESS_LABEL_OTHERPHONE, otherPhone, noteUTF16);
      }

      if (!otherWeb.IsEmpty())
      {
        // Reconstitute line breaks for other web sites
        MsgReplaceSubstring(otherWeb, "\x03", "\n");

        // Store other web sites in the notes field, labeled nicely
        FormatExtraDataInNoteField(EUDORAIMPORT_ADDRESS_LABEL_OTHERWEB, otherWeb, noteUTF16);
      }

      noteUTF16.Append(NS_ConvertASCIItoUTF16(note));
    }
  }

  CAliasData *pData = emailList.Count() ? (CAliasData *)emailList.ElementAt(0) : nsnull;

  if (pData && !pData->m_realName.IsEmpty())
    displayName = pData->m_realName;
  else if (!name.IsEmpty())
    displayName = name;
  else
    displayName = pEntry->m_name;

  MsgReplaceSubstring(address, "\x03", "\n");
  SplitString(address, address2);
  MsgReplaceSubstring(note, "\x03", "\n");
  MsgReplaceSubstring(fax, "\x03", " ");
  MsgReplaceSubstring(secondaryFax, "\x03", " ");
  MsgReplaceSubstring(phone, "\x03", " ");
  MsgReplaceSubstring(name, "\x03", " ");
  MsgReplaceSubstring(city, "\x03", " ");
  MsgReplaceSubstring(state, "\x03", " ");
  MsgReplaceSubstring(zip, "\x03", " ");
  MsgReplaceSubstring(country, "\x03", " ");

  MsgReplaceSubstring(addressWK, "\x03", "\n");
  SplitString(addressWK, address2WK);
  MsgReplaceSubstring(phoneWK, "\x03", " ");
  MsgReplaceSubstring(cityWK, "\x03", " ");
  MsgReplaceSubstring(stateWK, "\x03", " ");
  MsgReplaceSubstring(zipWK, "\x03", " ");
  MsgReplaceSubstring(countryWK, "\x03", " ");
  MsgReplaceSubstring(title, "\x03", " ");
  MsgReplaceSubstring(company, "\x03", " ");

  if (newRow)
  {
    nsAutoString uniStr;

    // Home related fields.
    ADD_FIELD_TO_DB_ROW(pDb, AddDisplayName, newRow, displayName, uniStr);
    ADD_FIELD_TO_DB_ROW(pDb, AddNickName, newRow, pEntry->m_name, uniStr);
    if (pData)
      ADD_FIELD_TO_DB_ROW(pDb, AddPrimaryEmail, newRow, pData->m_email, uniStr);
    ADD_FIELD_TO_DB_ROW(pDb, AddFirstName, newRow, firstName, uniStr);
    ADD_FIELD_TO_DB_ROW(pDb, AddLastName, newRow, lastName, uniStr);
    ADD_FIELD_TO_DB_ROW(pDb, AddWebPage2, newRow, webLink, uniStr);
    ADD_FIELD_TO_DB_ROW(pDb, AddHomePhone, newRow, phone, uniStr);
    ADD_FIELD_TO_DB_ROW(pDb, AddHomeAddress, newRow, address, uniStr);
    ADD_FIELD_TO_DB_ROW(pDb, AddHomeAddress2, newRow, address2, uniStr);
    ADD_FIELD_TO_DB_ROW(pDb, AddHomeCity, newRow, city, uniStr);
    ADD_FIELD_TO_DB_ROW(pDb, AddHomeZipCode, newRow, zip, uniStr);
    ADD_FIELD_TO_DB_ROW(pDb, AddHomeState, newRow, state, uniStr);
    ADD_FIELD_TO_DB_ROW(pDb, AddHomeCountry, newRow, country, uniStr);

    // Work related fields.
    ADD_FIELD_TO_DB_ROW(pDb, AddJobTitle, newRow, title, uniStr);
    ADD_FIELD_TO_DB_ROW(pDb, AddCompany, newRow, company, uniStr);
    ADD_FIELD_TO_DB_ROW(pDb, AddWebPage1, newRow, webLinkWK, uniStr);
    ADD_FIELD_TO_DB_ROW(pDb, AddWorkPhone, newRow, phoneWK, uniStr);
    ADD_FIELD_TO_DB_ROW(pDb, AddWorkAddress, newRow, addressWK, uniStr);
    ADD_FIELD_TO_DB_ROW(pDb, AddWorkAddress2, newRow, address2WK, uniStr);
    ADD_FIELD_TO_DB_ROW(pDb, AddWorkCity, newRow, cityWK, uniStr);
    ADD_FIELD_TO_DB_ROW(pDb, AddWorkZipCode, newRow, zipWK, uniStr);
    ADD_FIELD_TO_DB_ROW(pDb, AddWorkState, newRow, stateWK, uniStr);
    ADD_FIELD_TO_DB_ROW(pDb, AddWorkCountry, newRow, countryWK, uniStr);

    if ((primaryLocation.IsEmpty() || primaryLocation.LowerCaseEqualsLiteral("home")) &&
         !mobile.IsEmpty())
    {
      // Primary location field is either specified to be "home" or is not
      // specified and there is a home mobile number, so use that as the mobile number.
      ADD_FIELD_TO_DB_ROW(pDb, AddCellularNumber, newRow, mobile, uniStr);

      isSecondaryMobileWorkNumber = true;
    }
    else
    {
      // Primary location field is either specified to be "work" or there is no
      // home mobile number, so use work mobile number.
      ADD_FIELD_TO_DB_ROW(pDb, AddCellularNumber, newRow, secondaryMobile, uniStr);

      // Home mobile number (if any) is the secondary mobile number
      secondaryMobile = mobile;
      isSecondaryMobileWorkNumber = false;
    }

    if ((primaryLocation.IsEmpty() || primaryLocation.LowerCaseEqualsLiteral("home")) &&
         !fax.IsEmpty())
    {
      // Primary location field is either specified to be "home" or is not
      // specified and there is a home fax number, so use that as the fax number.
      ADD_FIELD_TO_DB_ROW(pDb, AddFaxNumber, newRow, fax, uniStr);

      isSecondaryFaxWorkNumber = true;
    }
    else
    {
      // Primary location field is either specified to be "work" or there is no
      // home fax number, so use work fax number.
      ADD_FIELD_TO_DB_ROW(pDb, AddFaxNumber, newRow, secondaryFax, uniStr);

      // Home fax number (if any) is the secondary fax number
      secondaryFax = fax;
      isSecondaryFaxWorkNumber = false;
    }

    ADD_FIELD_TO_DB_ROW(pDb, Add2ndEmail, newRow, additionalEmail, uniStr);

    // Extra info fields
    PRInt32         stringID;
    nsString        pFormat;
    nsString        pCustomData;

    // Add second mobile number, if any, to the Custom 1 field
    if (!secondaryMobile.IsEmpty())
    {
      stringID = isSecondaryMobileWorkNumber ?
                 EUDORAIMPORT_ADDRESS_LABEL_WORKMOBILE : EUDORAIMPORT_ADDRESS_LABEL_HOMEMOBILE;
      pFormat.Adopt(nsEudoraStringBundle::GetStringByID(stringID));
      pCustomData.Adopt(nsTextFormatter::smprintf(pFormat.get(), NS_ConvertASCIItoUTF16(secondaryMobile).get()));
      pDb->AddCustom1(newRow, NS_ConvertUTF16toUTF8(pCustomData).get());
    }

    // Add second fax number, if any, to the Custom 2 field
    if (!secondaryFax.IsEmpty())
    {
      stringID = isSecondaryFaxWorkNumber ?
                 EUDORAIMPORT_ADDRESS_LABEL_WORKFAX : EUDORAIMPORT_ADDRESS_LABEL_HOMEFAX;
      pFormat.Adopt(nsEudoraStringBundle::GetStringByID(stringID));
      pCustomData.Adopt(nsTextFormatter::smprintf(pFormat.get(), NS_ConvertASCIItoUTF16(secondaryFax).get()));
      pDb->AddCustom2(newRow, NS_ConvertUTF16toUTF8(pCustomData).get());
    }

    // Lastly, note field.
    pDb->AddNotes(newRow, NS_ConvertUTF16toUTF8(noteUTF16).get());

    pDb->AddCardRowToDB(newRow);

    IMPORT_LOG1("Added card to db: %s\n", displayName.get());
  }
}
예제 #29
0
/**
 * Run a category of Xalan tests
 */
void runCategory(nsIFile* aConfCat, nsIFile* aGoldCat, nsIFile* aRefTmp,
                 txRDFOut* aOut)
{
    nsresult rv;
    //clone the nsIFiles, so that we can return easily
    nsCOMPtr<nsIFile> conf, gold;
    aConfCat->Clone(getter_AddRefs(conf));
    aGoldCat->Clone(getter_AddRefs(gold));
    nsCAutoString catName, refTmp;
    conf->GetNativeLeafName(catName);
    aRefTmp->GetNativePath(refTmp);
    txRDFOut results(catName, aOut);
    nsCOMPtr<nsISimpleEnumerator> tests;
    rv = conf->GetDirectoryEntries(getter_AddRefs(tests));
    if (NS_FAILED(rv))
        return;
    PRBool hasMore, isFile;
    nsCAutoString leaf;
    NS_NAMED_LITERAL_CSTRING(xsl, ".xsl");
    while (NS_SUCCEEDED(tests->HasMoreElements(&hasMore)) && hasMore) {
        nsCOMPtr<nsILocalFile> test;
        tests->GetNext(getter_AddRefs(test));
        test->GetNativeLeafName(leaf);
        if (xsl.Equals(Substring(leaf, leaf.Length()-4, 4))) {
            // we have a stylesheet, let's look for source and reference
            nsAFlatCString::char_iterator start, ext;
            leaf.BeginWriting(start);
            leaf.EndWriting(ext);
            ext -= 2;
            // overwrite extension with .xml
            *ext = 'm'; // this one was easy
            nsCOMPtr<nsIFile> source;
            conf->Clone(getter_AddRefs(source));
            rv = source->AppendNative(leaf);
            if (NS_SUCCEEDED(rv) && NS_SUCCEEDED(source->IsFile(&isFile)) &&
                isFile) {
                nsCOMPtr<nsIFile> reference;
                gold->Clone(getter_AddRefs(reference));
                // overwrite extension with .out
                --ext;
                nsCharTraits<char>::copy(ext, "out", 3);
                rv = reference->AppendNative(leaf);
                if (NS_SUCCEEDED(rv) &&
                    NS_SUCCEEDED(reference->IsFile(&isFile)) &&
                    isFile) {
                    nsCAutoString src, style, refPath;
                    test->GetNativePath(style);
                    source->GetNativePath(src);
                    reference->GetNativePath(refPath);
                    if (PR_GetDirectorySeparator() =='\\') {
                        src.ReplaceChar('\\','/');
                        style.ReplaceChar('\\','/');
                        refPath.ReplaceChar('\\','/');
                    }
                    SimpleErrorObserver obs;
                    txStandaloneXSLTProcessor proc;
                    fstream result(refTmp.get(),
                                   ios::in | ios::out | ios::trunc);
                    rv = proc.transform(src, style, result, obs);
                    PRBool success = PR_FALSE;
                    if (NS_SUCCEEDED(rv)) {
                        result.flush();
                        PRInt64 resultSize, refSize;
                        aRefTmp->GetFileSize(&resultSize);
                        reference->GetFileSize(&refSize);
                        result.seekg(0);
                        int toread = (int)resultSize;
                        nsCString resContent, refContent;
                        resContent.SetCapacity(toread);
                        readToString(result, resContent);
                        result.close();
                        ifstream refStream(refPath.get());
                        toread = (int)refSize;
                        refContent.SetCapacity(toread);
                        readToString(refStream, refContent);
                        refStream.close();
                        success = resContent.Equals(refContent);
                    }
                    ext--;
                    results.feed(Substring(start, ext), success);
                }
            }
        }
    }
}
예제 #30
0
bool nsEudoraEditor::GetEmbeddedImageCID(PRUint32 aCIDHash, const nsAString & aOldRef, nsString &aCID)
{
    bool      foundMatch = false;
    PRInt32   startImageTag = 0;
    PRInt32   closeImageTag = 0;

    while ( (startImageTag = m_body.Find("<img", true, closeImageTag)) != kNotFound )
    {
        closeImageTag = m_body.Find(">", false, startImageTag);

        // We should always find a close tag, bail if we don't
        if (closeImageTag == kNotFound)
            break;

        // Find the source attribute and make sure it's for our image tag
        PRInt32   startSrcValue = m_body.Find("src", true, startImageTag);
        if ( (startSrcValue == kNotFound) || (startSrcValue > closeImageTag) )
            continue;

        // Move past the src
        startSrcValue += 3;

        // Move past any whitespace
        while ( isspace(m_body.CharAt(startSrcValue)) )
            ++startSrcValue;

        // We should find an = now
        if (m_body.CharAt(startSrcValue) != '=')
            continue;

        // Move past =
        ++startSrcValue;

        // Move past any whitespace
        while ( isspace(m_body.CharAt(startSrcValue)) )
            ++startSrcValue;

        // Get the quote char and verify that it's valid
        char    quoteChar = static_cast <char> (m_body.CharAt(startSrcValue));
        if ( (quoteChar != '"') && (quoteChar != '\'') )
            continue;

        // Move past the quote
        ++startSrcValue;

        PRInt32   endSrcValue = m_body.FindChar(quoteChar, startSrcValue);
        PRInt32   srcLength = endSrcValue - startSrcValue;

        nsString  srcValue;
        aCID.Assign(Substring(m_body, startSrcValue, srcLength));

        if (aCIDHash != 0)
        {
            // Verify source value starts with "cid:"
            if (!StringBeginsWith(aCID, NS_LITERAL_STRING("cid:"), nsCaseInsensitiveStringComparator()))
                continue;

            // Remove "cid:" from the start
            aCID.Cut(0, 4);

            PRUint32  hashValue = EudoraHashString( NS_LossyConvertUTF16toASCII(aCID).get() );
            foundMatch = (hashValue == aCIDHash);
        }
        else
        {
            foundMatch = aCID.Equals(aOldRef);
        }
    }

    return foundMatch;
}