static int32_t AddCustomHeader(const char* pHeader)
{
  nsresult rv;
  int32_t index = -1;
  nsCOMPtr<nsIPrefBranch> pref(do_GetService(NS_PREFSERVICE_CONTRACTID, &rv));
  NS_ENSURE_SUCCESS(rv, index);

  nsAutoCString headers;
  pref->GetCharPref(MAILNEWS_CUSTOM_HEADERS, getter_Copies(headers));
  index = 0;
  if (!headers.IsEmpty())
  {
    char *headersString = ToNewCString(headers);
    nsAutoCString hdrStr;
    hdrStr.Adopt(headersString);
    hdrStr.StripWhitespace();  //remove whitespace before parsing

    char *newStr = headersString;
    char *token = NS_strtok(":", &newStr);
    while (token)
    {
      if (!PL_strcasecmp(token, pHeader))
        return index;
      token = NS_strtok(":", &newStr);
      index++;
    }
    headers += ":";
  }
  headers += pHeader;
  pref->SetCharPref(MAILNEWS_CUSTOM_HEADERS, headers.get());

  return index;
}
Beispiel #2
0
/* str is the string which needs to be unserialized.
   If prefixes is NULL, simply returns the number of namespaces in str.  (len is ignored)
   If prefixes is not NULL, it should be an array of length len which is to be filled in
   with newly-allocated string.  Returns the number of strings filled in.
*/
int nsIMAPNamespaceList::UnserializeNamespaces(const char *str, char **prefixes, int len)
{
    if (!str)
        return 0;
    if (!prefixes)
    {
        if (str[0] != '"')
            return 1;
        else
        {
            int count = 0;
            char *ourstr = PL_strdup(str);
            char *origOurStr = ourstr;
            if (ourstr)
            {
                char *token = NS_strtok(SERIALIZER_SEPARATORS, &ourstr );
                while (token != nullptr)
                {
                    token = NS_strtok(SERIALIZER_SEPARATORS, &ourstr );
                    count++;
                }
                PR_Free(origOurStr);
            }
            return count;
        }
    }
    else
    {
        if ((str[0] != '"') && (len >= 1))
        {
            prefixes[0] = PL_strdup(str);
            return 1;
        }
        else
        {
            int count = 0;
            char *ourstr = PL_strdup(str);
            char *origOurStr = ourstr;
            if (ourstr)
            {
                char *token = NS_strtok(SERIALIZER_SEPARATORS, &ourstr );
                while ((count < len) && (token != nullptr))
                {

                    char *current = PL_strdup(token), *where = current;
                    if (where[0] == '"')
                        where++;
                    if (where[PL_strlen(where)-1] == '"')
                        where[PL_strlen(where)-1] = 0;
                    prefixes[count] = PL_strdup(where);
                    PR_FREEIF(current);
                    token = NS_strtok(SERIALIZER_SEPARATORS, &ourstr );
                    count++;
                }
                PR_Free(origOurStr);
            }
            return count;
        }
    }
}
Beispiel #3
0
/* void addIdentity (in nsIMsgIdentity identity); */
NS_IMETHODIMP
nsMsgAccount::AddIdentity(nsIMsgIdentity *identity)
{
  NS_ENSURE_ARG_POINTER(identity);

  // hack hack - need to add this to the list of identities.
  // for now just treat this as a Setxxx accessor
  // when this is actually implemented, don't refcount the default identity
  nsCString key;
  nsresult rv = identity->GetKey(key);

  if (NS_SUCCEEDED(rv)) {
    nsCString identityList;
    m_prefs->GetCharPref("identities", getter_Copies(identityList));

    nsCAutoString newIdentityList(identityList);

    nsCAutoString testKey;      // temporary to strip whitespace
    bool foundIdentity = false; // if the input identity is found

    if (!identityList.IsEmpty()) {
      char *newStr = identityList.BeginWriting();
      char *token = NS_strtok(",", &newStr);

      // look for the identity key that we're adding
      while (token) {
        testKey = token;
        testKey.StripWhitespace();

        if (testKey.Equals(key))
          foundIdentity = true;

        token = NS_strtok(",", &newStr);
      }
    }

    // if it didn't already exist, append it
    if (!foundIdentity) {
      if (newIdentityList.IsEmpty())
        newIdentityList = key;
      else {
        newIdentityList.Append(',');
        newIdentityList.Append(key);
      }
    }

    m_prefs->SetCharPref("identities", newIdentityList.get());
  }

  // now add it to the in-memory list
  rv = addIdentityInternal(identity);

  if (!m_defaultIdentity)
    SetDefaultIdentity(identity);

  return rv;
}
Beispiel #4
0
NS_METHOD
LocalSearchDataSource::parseResourceIntoFindTokens(nsIRDFResource *u, findTokenPtr tokens)
{
	const char		*uri = nsnull;
	char			*id, *token, *value, *newstr;
	int			loop;
	nsresult		rv;

	if (NS_FAILED(rv = u->GetValueConst(&uri)))	return(rv);

#ifdef	DEBUG
	printf("Find: %s\n", (const char*) uri);
#endif

	if (!(id = PL_strdup(uri + sizeof(kFindProtocol) - 1)))
		return(NS_ERROR_OUT_OF_MEMORY);

	/* parse ID, build up token list */
	newstr = id;
	if ((token = NS_strtok("&", &newstr)) != NULL)
	{
		while (token != NULL)
		{
			if ((value = strstr(token, "=")) != NULL)
			{
				*value++ = '\0';
			}
			for (loop=0; tokens[loop].token != NULL; loop++)
			{
				if (!strcmp(token, tokens[loop].token))
				{
				    if (!strcmp(token, "text"))
				    {
            			nsCOMPtr<nsITextToSubURI> textToSubURI = 
            			         do_GetService(kTextToSubURICID, &rv);
            			if (NS_SUCCEEDED(rv) && (textToSubURI))
            			{
            				PRUnichar	*uni = nsnull;
            				if (NS_SUCCEEDED(rv = textToSubURI->UnEscapeAndConvert("UTF-8", value, &uni)) && (uni))
            				{
    					        tokens[loop].value.Adopt(uni);
    					    }
    					}
				    }
				    else
				    {
				        CopyASCIItoUTF16(nsDependentCString(value), tokens[loop].value);
    			    }
					break;
				}
			}
			token = NS_strtok("&", &newstr);
		}
	}
	PL_strfree(id);
	return(NS_OK);
}
/*
 * set up the m_identities array
 * do not call this more than once or we'll leak.
 */
nsresult
nsMsgAccount::createIdentities()
{
  NS_ENSURE_TRUE(!m_accountKey.IsEmpty(), NS_ERROR_NOT_INITIALIZED);
  if (m_identities)
    return NS_ERROR_FAILURE;

  NS_NewISupportsArray(getter_AddRefs(m_identities));

  // get the pref
  // ex) mail.account.myaccount.identities = "joe-home,joe-work"
  nsCAutoString identitiesKeyPref("mail.account.");
  identitiesKeyPref.Append(m_accountKey);
  identitiesKeyPref.Append(".identities");

  nsCString identityKey;
  nsresult rv;
  rv = getPrefService();
  NS_ENSURE_SUCCESS(rv, rv);

  m_prefs->GetCharPref(identitiesKeyPref.get(), getter_Copies(identityKey));
  if (identityKey.IsEmpty())    // not an error if no identities, but
    return NS_OK;               // strtok will be unhappy
  // get the server from the account manager
  nsCOMPtr<nsIMsgAccountManager> accountManager =
           do_GetService(NS_MSGACCOUNTMANAGER_CONTRACTID, &rv);
  NS_ENSURE_SUCCESS(rv, rv);

  char* newStr = identityKey.BeginWriting();
  char* token = NS_strtok(",", &newStr);

  // temporaries used inside the loop
  nsCOMPtr<nsIMsgIdentity> identity;
  nsCAutoString key;

  // iterate through id1,id2, etc
  while (token) {
    key = token;
    key.StripWhitespace();

    // create the account
    rv = accountManager->GetIdentity(key, getter_AddRefs(identity));
    if (NS_SUCCEEDED(rv)) {
      // ignore error from addIdentityInternal() - if it fails, it fails.
      rv = addIdentityInternal(identity);
      NS_ASSERTION(NS_SUCCEEDED(rv), "Couldn't create identity");
    }

    // advance to next key, if any
    token = NS_strtok(",", &newStr);
  }

  return rv;
}
nsresult
nsSubscribableServer::FindAndCreateNode(const nsACString &aPath,
                                        SubscribeTreeNode **aResult)
{
  nsresult rv = NS_OK;
  NS_ASSERTION(aResult, "no result");
  if (!aResult) return NS_ERROR_NULL_POINTER;

  if (!mTreeRoot) {
      nsCString serverUri;
      rv = mIncomingServer->GetServerURI(serverUri);
      NS_ENSURE_SUCCESS(rv,rv);
      // the root has no parent, and its name is server uri
      rv = CreateNode(nsnull, serverUri.get(), &mTreeRoot);
      NS_ENSURE_SUCCESS(rv,rv);
  }

  if (aPath.IsEmpty()) {
      *aResult = mTreeRoot;
      return NS_OK;
  }

  char *token = nsnull;
  nsCString pathStr(aPath);
  char *rest = pathStr.BeginWriting();

  // todo do this only once
  char delimstr[2];
  delimstr[0] = mDelimiter;
  delimstr[1] = '\0';

  *aResult = nsnull;

  SubscribeTreeNode *parent = mTreeRoot;
  SubscribeTreeNode *child = nsnull;

  token = NS_strtok(delimstr, &rest); 
  // special case paths that start with the hierarchy delimiter.
  // We want to include that delimiter in the first token name.
  if (token && pathStr[0] == mDelimiter)
    --token;
  while (token && *token) {
    rv = AddChildNode(parent, token, &child);
    if (NS_FAILED(rv))
      return rv;
    token = NS_strtok(delimstr, &rest);
    parent = child;
  }

  // the last child we add is the result
  *aResult = child;
  return rv;
}
Beispiel #7
0
void nsIMAPGenericParser::AdvanceToNextToken()
{
  if (!fCurrentLine || fAtEndOfLine)
    AdvanceToNextLine();
  if (Connected())
  {
    if (!fStartOfLineOfTokens)
    {
      // this is the first token of the line; setup tokenizer now
      fStartOfLineOfTokens = PL_strdup(fCurrentLine);
      if (!fStartOfLineOfTokens)
      {
        HandleMemoryFailure();
        return;
      }
      fLineOfTokens = fStartOfLineOfTokens;
      fCurrentTokenPlaceHolder = fStartOfLineOfTokens;
    }
    fNextToken = NS_strtok(WHITESPACE, &fCurrentTokenPlaceHolder);
    if (!fNextToken)
    {
      fAtEndOfLine = true;
      fNextToken = CRLF;
    }
  }
}
/*
 * set up the m_identities array
 * do not call this more than once or we'll leak.
 */
nsresult
nsMsgAccount::createIdentities()
{
  NS_ENSURE_FALSE(m_identities, NS_ERROR_FAILURE);

  nsresult rv;
  m_identities = do_CreateInstance(NS_ARRAY_CONTRACTID, &rv);
  NS_ENSURE_SUCCESS(rv, rv);

  nsCString identityKey;
  rv = getPrefService();
  NS_ENSURE_SUCCESS(rv, rv);

  m_prefs->GetCharPref("identities", identityKey);
  if (identityKey.IsEmpty())    // not an error if no identities, but
    return NS_OK;               // strtok will be unhappy
  // get the server from the account manager
  nsCOMPtr<nsIMsgAccountManager> accountManager =
           do_GetService(NS_MSGACCOUNTMANAGER_CONTRACTID, &rv);
  NS_ENSURE_SUCCESS(rv, rv);

  char* newStr = identityKey.BeginWriting();
  char* token = NS_strtok(",", &newStr);

  // temporaries used inside the loop
  nsCOMPtr<nsIMsgIdentity> identity;
  nsAutoCString key;

  // iterate through id1,id2, etc
  while (token) {
    key = token;
    key.StripWhitespace();

    // create the account
    rv = accountManager->GetIdentity(key, getter_AddRefs(identity));
    if (NS_SUCCEEDED(rv)) {
      // ignore error from addIdentityInternal() - if it fails, it fails.
      rv = addIdentityInternal(identity);
      NS_ASSERTION(NS_SUCCEEDED(rv), "Couldn't create identity");
    }

    // advance to next key, if any
    token = NS_strtok(",", &newStr);
  }

  return rv;
}
nsresult nsMsgSearchValidityManager::SetOtherHeadersInTable(
    nsIMsgSearchValidityTable *aTable, const char *customHeaders) {
  uint32_t customHeadersLength = strlen(customHeaders);
  uint32_t numHeaders = 0;
  if (customHeadersLength) {
    nsAutoCString hdrStr(customHeaders);
    hdrStr.StripWhitespace();  // remove whitespace before parsing
    char *newStr = hdrStr.BeginWriting();
    char *token = NS_strtok(":", &newStr);
    while (token) {
      numHeaders++;
      token = NS_strtok(":", &newStr);
    }
  }

  NS_ASSERTION(nsMsgSearchAttrib::OtherHeader + numHeaders <
                   nsMsgSearchAttrib::kNumMsgSearchAttributes,
               "more headers than the table can hold");

  uint32_t maxHdrs =
      std::min(nsMsgSearchAttrib::OtherHeader + numHeaders + 1,
               (uint32_t)nsMsgSearchAttrib::kNumMsgSearchAttributes);
  for (uint32_t i = nsMsgSearchAttrib::OtherHeader + 1; i < maxHdrs; i++) {
    // clang-format off
    aTable->SetAvailable(i, nsMsgSearchOp::Contains, 1);  // added for arbitrary headers
    aTable->SetEnabled  (i, nsMsgSearchOp::Contains, 1);
    aTable->SetAvailable(i, nsMsgSearchOp::DoesntContain, 1);
    aTable->SetEnabled  (i, nsMsgSearchOp::DoesntContain, 1);
    aTable->SetAvailable(i, nsMsgSearchOp::Is, 1);
    aTable->SetEnabled  (i, nsMsgSearchOp::Is, 1);
    aTable->SetAvailable(i, nsMsgSearchOp::Isnt, 1);
    aTable->SetEnabled  (i, nsMsgSearchOp::Isnt, 1);
    // clang-format on
  }
  // because custom headers can change; so reset the table for those which are
  // no longer used.
  for (uint32_t j = maxHdrs; j < nsMsgSearchAttrib::kNumMsgSearchAttributes;
       j++) {
    for (uint32_t k = 0; k < nsMsgSearchOp::kNumMsgSearchOperators; k++) {
      aTable->SetAvailable(j, k, 0);
      aTable->SetEnabled(j, k, 0);
    }
  }
  return NS_OK;
}
NS_IMETHODIMP
nsSmtpService::DeleteSmtpServer(nsISmtpServer *aServer)
{
    if (!aServer) return NS_OK;

    PRInt32 idx = mSmtpServers.IndexOf(aServer);
    if (idx == -1)
      return NS_OK;

    nsCString serverKey;
    aServer->GetKey(getter_Copies(serverKey));
    
    nsresult rv = mSmtpServers.RemoveObjectAt(idx);

    if (mDefaultSmtpServer.get() == aServer)
        mDefaultSmtpServer = nsnull;
    if (mSessionDefaultServer.get() == aServer)
        mSessionDefaultServer = nsnull;
    
    nsCAutoString newServerList;
    nsCString tmpStr = mServerKeyList;
    char *newStr = tmpStr.BeginWriting();
    char *token = NS_strtok(",", &newStr);
    while (token) {
      // only re-add the string if it's not the key
      if (strcmp(token, serverKey.get()) != 0) {
          if (newServerList.IsEmpty())
              newServerList = token;
          else {
            newServerList += ',';
            newServerList += token;
          }
      }
      token = NS_strtok(",", &newStr);
    }

    // make sure the server clears out it's values....
    aServer->ClearAllValues();

    mServerKeyList = newServerList;
    saveKeyList();
    return rv;
}
Beispiel #11
0
void
SplitAt(const char* aDelims,
        const nsACString& aInput,
        nsTArray<nsCString>& aOutTokens)
{
  nsAutoCString str(aInput);
  char* end = str.BeginWriting();
  const char* start = nullptr;
  while (!!(start = NS_strtok(aDelims, &end))) {
    aOutTokens.AppendElement(nsCString(start));
  }
}
nsresult
nsXREDirProvider::AppendProfileString(nsIFile* aFile, const char* aPath)
{
  NS_ASSERTION(aFile, "Null file!");
  NS_ASSERTION(aPath, "Null path!");

  nsAutoCString pathDup(aPath);

  char* path = pathDup.BeginWriting();

  nsresult rv;
  char* subdir;
  while ((subdir = NS_strtok("/\\", &path))) {
    rv = aFile->AppendNative(nsDependentCString(subdir));
    NS_ENSURE_SUCCESS(rv, rv);
  }

  return NS_OK;
}
Beispiel #13
0
nsresult
nsINIParser::InitFromFILE(FILE *fd)
{
    /* get file size */
    if (fseek(fd, 0, SEEK_END) != 0)
        return NS_ERROR_FAILURE;

    long flen = ftell(fd);
    if (flen == 0)
        return NS_ERROR_FAILURE;

    /* malloc an internal buf the size of the file */
    mFileContents = new char[flen + 2];
    if (!mFileContents)
        return NS_ERROR_OUT_OF_MEMORY;

    /* read the file in one swoop */
    if (fseek(fd, 0, SEEK_SET) != 0)
        return NS_BASE_STREAM_OSERROR;

    int rd = fread(mFileContents, sizeof(char), flen, fd);
    if (rd != flen)
        return NS_BASE_STREAM_OSERROR;

    // We write a UTF16 null so that the file is easier to convert to UTF8
    mFileContents[flen] = mFileContents[flen + 1] = '\0';

    char *buffer = &mFileContents[0];

    if (flen >= 3
    && mFileContents[0] == static_cast<char>(0xEF)
    && mFileContents[1] == static_cast<char>(0xBB)
    && mFileContents[2] == static_cast<char>(0xBF)) {
      // Someone set us up the Utf-8 BOM
      // This case is easy, since we assume that BOM-less
      // files are Utf-8 anyway.  Just skip the BOM and process as usual.
      buffer = &mFileContents[3];
    }

#ifdef XP_WIN
    if (flen >= 2
     && mFileContents[0] == static_cast<char>(0xFF)
     && mFileContents[1] == static_cast<char>(0xFE)) {
        // Someone set us up the Utf-16LE BOM
        buffer = &mFileContents[2];
        // Get the size required for our Utf8 buffer
        flen = WideCharToMultiByte(CP_UTF8,
                                   0,
                                   reinterpret_cast<LPWSTR>(buffer),
                                   -1,
                                   NULL,
                                   0,
                                   NULL,
                                   NULL);
        if (0 == flen) {
            return NS_ERROR_FAILURE;
        }

        nsAutoArrayPtr<char> utf8Buffer(new char[flen]);
        if (0 == WideCharToMultiByte(CP_UTF8,
                                     0,
                                     reinterpret_cast<LPWSTR>(buffer),
                                     -1,
                                     utf8Buffer,
                                     flen,
                                     NULL,
                                     NULL)) {
            return NS_ERROR_FAILURE;
        }
        mFileContents = utf8Buffer.forget();
        buffer = mFileContents;
    }
#endif

    char *currSection = nullptr;

    // outer loop tokenizes into lines
    while (char *token = NS_strtok(kNL, &buffer)) {
        if (token[0] == '#' || token[0] == ';') // it's a comment
            continue;

        token = (char*) NS_strspnp(kWhitespace, token);
        if (!*token) // empty line
            continue;

        if (token[0] == '[') { // section header!
            ++token;
            currSection = token;

            char *rb = NS_strtok(kRBracket, &token);
            if (!rb || NS_strtok(kWhitespace, &token)) {
                // there's either an unclosed [Section or a [Section]Moretext!
                // we could frankly decide that this INI file is malformed right
                // here and stop, but we won't... keep going, looking for
                // a well-formed [section] to continue working with
                currSection = nullptr;
            }

            continue;
        }

        if (!currSection) {
            // If we haven't found a section header (or we found a malformed
            // section header), don't bother parsing this line.
            continue;
        }

        char *key = token;
        char *e = NS_strtok(kEquals, &token);
        if (!e || !token)
            continue;

        INIValue *v;
        if (!mSections.Get(currSection, &v)) {
            v = new INIValue(key, token);
            if (!v)
                return NS_ERROR_OUT_OF_MEMORY;

            mSections.Put(currSection, v);
            continue;
        }

        // Check whether this key has already been specified; overwrite
        // if so, or append if not.
        while (v) {
            if (!strcmp(key, v->key)) {
                v->value = token;
                break;
            }
            if (!v->next) {
                v->next = new INIValue(key, token);
                if (!v->next)
                    return NS_ERROR_OUT_OF_MEMORY;
                break;
            }
            v = v->next;
        }
        NS_ASSERTION(v, "v should never be null coming out of this loop");
    }

    return NS_OK;
}
Beispiel #14
0
nsresult
nsINIParser::InitFromFILE(FILE *fd)
{
    if (!mSections.Init())
        return NS_ERROR_OUT_OF_MEMORY;

    /* get file size */
    if (fseek(fd, 0, SEEK_END) != 0)
        return NS_ERROR_FAILURE;

    long flen = ftell(fd);
    if (flen == 0)
        return NS_ERROR_FAILURE;

    /* malloc an internal buf the size of the file */
    mFileContents = new char[flen + 1];
    if (!mFileContents)
        return NS_ERROR_OUT_OF_MEMORY;

    /* read the file in one swoop */
    if (fseek(fd, 0, SEEK_SET) != 0)
        return NS_BASE_STREAM_OSERROR;

    int rd = fread(mFileContents, sizeof(char), flen, fd);
    if (rd != flen)
        return NS_BASE_STREAM_OSERROR;

    mFileContents[flen] = '\0';

    char *buffer = mFileContents;
    char *currSection = nsnull;

    // outer loop tokenizes into lines
    while (char *token = NS_strtok(kNL, &buffer)) {
        if (token[0] == '#' || token[0] == ';') // it's a comment
            continue;

        token = (char*) NS_strspnp(kWhitespace, token);
        if (!*token) // empty line
            continue;

        if (token[0] == '[') { // section header!
            ++token;
            currSection = token;

            char *rb = NS_strtok(kRBracket, &token);
            if (!rb || NS_strtok(kWhitespace, &token)) {
                // there's either an unclosed [Section or a [Section]Moretext!
                // we could frankly decide that this INI file is malformed right
                // here and stop, but we won't... keep going, looking for
                // a well-formed [section] to continue working with
                currSection = nsnull;
            }

            continue;
        }

        if (!currSection) {
            // If we haven't found a section header (or we found a malformed
            // section header), don't bother parsing this line.
            continue;
        }

        char *key = token;
        char *e = NS_strtok(kEquals, &token);
        if (!e || !token)
            continue;

        INIValue *v;
        if (!mSections.Get(currSection, &v)) {
            v = new INIValue(key, token);
            if (!v)
                return NS_ERROR_OUT_OF_MEMORY;

            mSections.Put(currSection, v);
            continue;
        }

        // Check whether this key has already been specified; overwrite
        // if so, or append if not.
        while (v) {
            if (!strcmp(key, v->key)) {
                v->value = token;
                break;
            }
            if (!v->next) {
                v->next = new INIValue(key, token);
                if (!v->next)
                    return NS_ERROR_OUT_OF_MEMORY;
                break;
            }
            v = v->next;
        }
        NS_ASSERTION(v, "v should never be null coming out of this loop");
    }

    return NS_OK;
}
nsresult
nsStrictTransportSecurityService::ProcessStsHeaderMutating(nsIURI* aSourceURI,
                                                           char* aHeader,
                                                           uint64_t *aMaxAge,
                                                           bool *aIncludeSubdomains)
{
  STSLOG(("STS: ProcessStrictTransportHeader(%s)\n", aHeader));

  // "Strict-Transport-Security" ":" OWS
  //      STS-d  *( OWS ";" OWS STS-d  OWS)
  //
  //  ; STS directive
  //  STS-d      = maxAge / includeSubDomains
  //
  //  maxAge     = "max-age" "=" delta-seconds v-ext
  //
  //  includeSubDomains = [ "includeSubDomains" ]

  const char* directive;

  bool foundMaxAge = false;
  bool foundUnrecognizedTokens = false;
  bool includeSubdomains = false;
  int64_t maxAge = 0;

  NS_NAMED_LITERAL_CSTRING(max_age_var, "max-age");
  NS_NAMED_LITERAL_CSTRING(include_subd_var, "includesubdomains");

  while ((directive = NS_strtok(";", &aHeader))) {
    //skip leading whitespace
    directive = NS_strspnp(" \t", directive);
    STS_PARSER_FAIL_IF(!(*directive), ("error removing initial whitespace\n."));

    if (!PL_strncasecmp(directive, max_age_var.get(), max_age_var.Length())) {
      // skip directive name
      directive += max_age_var.Length();
      // skip leading whitespace
      directive = NS_strspnp(" \t", directive);
      STS_PARSER_FAIL_IF(*directive != '=',
                  ("No equal sign found in max-age directive\n"));

      // skip over the equal sign
      STS_PARSER_FAIL_IF(*(++directive) == '\0',
                  ("No delta-seconds present\n"));

      // obtain the delta-seconds value
      STS_PARSER_FAIL_IF(PR_sscanf(directive, "%lld", &maxAge) != 1,
                  ("Could not convert delta-seconds\n"));
      STSLOG(("STS: ProcessStrictTransportHeader() STS found maxage %lld\n", maxAge));
      foundMaxAge = true;

      // skip max-age value and trailing whitespace
      directive = NS_strspnp("0123456789 \t", directive);

      // log unknown tokens, but don't fail (for forwards compatibility)
      if (*directive != '\0') {
        foundUnrecognizedTokens = true;
        STSLOG(("Extra stuff in max-age after delta-seconds: %s \n", directive));
      }
    }
    else if (!PL_strncasecmp(directive, include_subd_var.get(), include_subd_var.Length())) {
      directive += include_subd_var.Length();

      // only record "includesubdomains" if it is a token by itself... for
      // example, don't set includeSubdomains = true if the directive is
      // "includesubdomainsFooBar".
      if (*directive == '\0' || *directive =='\t' || *directive == ' ') {
        includeSubdomains = true;
        STSLOG(("STS: ProcessStrictTransportHeader: obtained subdomains status\n"));

        // skip trailing whitespace
        directive = NS_strspnp(" \t", directive);

        if (*directive != '\0') {
          foundUnrecognizedTokens = true;
          STSLOG(("Extra stuff after includesubdomains: %s\n", directive));
        }
      } else {
        foundUnrecognizedTokens = true;
        STSLOG(("Unrecognized directive in header: %s\n", directive));
      }
    }
    else {
      // log unknown directives, but don't fail (for backwards compatibility)
      foundUnrecognizedTokens = true;
      STSLOG(("Unrecognized directive in header: %s\n", directive));
    }
  }

  // after processing all the directives, make sure we came across max-age
  // somewhere.
  STS_PARSER_FAIL_IF(!foundMaxAge,
              ("Parse ERROR: couldn't locate max-age token\n"));

  // record the successfully parsed header data.
  SetStsState(aSourceURI, maxAge, includeSubdomains);

  if (aMaxAge != nullptr) {
    *aMaxAge = (uint64_t)maxAge;
  }

  if (aIncludeSubdomains != nullptr) {
    *aIncludeSubdomains = includeSubdomains;
  }

  return foundUnrecognizedTokens ?
         NS_SUCCESS_LOSS_OF_INSIGNIFICANT_DATA :
         NS_OK;
}
const mozilla::Module*
nsNativeModuleLoader::LoadModule(nsILocalFile* aFile)
{
    nsresult rv;

    if (!NS_IsMainThread()) {
        // If this call is off the main thread, synchronously proxy it
        // to the main thread.
        nsRefPtr<LoadModuleMainThreadRunnable> r = new LoadModuleMainThreadRunnable(this, aFile);
        NS_DispatchToMainThread(r, NS_DISPATCH_SYNC);
        return r->mResult;
    }

    nsCOMPtr<nsIHashable> hashedFile(do_QueryInterface(aFile));
    if (!hashedFile) {
        NS_ERROR("nsIFile is not nsIHashable");
        return NULL;
    }

    nsCAutoString filePath;
    aFile->GetNativePath(filePath);

    NativeLoadData data;

    if (mLibraries.Get(hashedFile, &data)) {
        NS_ASSERTION(data.module, "Corrupt mLibraries hash");
        LOG(PR_LOG_DEBUG,
            ("nsNativeModuleLoader::LoadModule(\"%s\") - found in cache",
             filePath.get()));
        return data.module;
    }

    // We haven't loaded this module before

    rv = aFile->Load(&data.library);

    if (NS_FAILED(rv)) {
        char errorMsg[1024] = "<unknown; can't get error from NSPR>";

        if (PR_GetErrorTextLength() < (int) sizeof(errorMsg))
            PR_GetErrorText(errorMsg);

        LOG(PR_LOG_ERROR,
            ("nsNativeModuleLoader::LoadModule(\"%s\") - load FAILED, "
             "rv: %lx, error:\n\t%s\n",
             filePath.get(), rv, errorMsg));

#ifdef DEBUG
        fprintf(stderr,
                "nsNativeModuleLoader::LoadModule(\"%s\") - load FAILED, "
                "rv: %lx, error:\n\t%s\n",
                filePath.get(), (unsigned long)rv, errorMsg);
#endif

        return NULL;
    }

#ifdef IMPLEMENT_BREAK_AFTER_LOAD
    nsCAutoString leafName;
    aFile->GetNativeLeafName(leafName);

    char *env = getenv("XPCOM_BREAK_ON_LOAD");
    char *blist;
    if (env && *env && (blist = strdup(env))) {
        char *nextTok = blist;
        while (char *token = NS_strtok(":", &nextTok)) {
            if (leafName.Find(token, PR_TRUE) != kNotFound) {
                NS_BREAK();
            }
        }

        free(blist);
    }
#endif

    void *module = PR_FindSymbol(data.library, "NSModule");
    if (module) {
        data.module = *(mozilla::Module const *const *) module;
        if (mLibraries.Put(hashedFile, data))
            return data.module;
    }
    else {
        LOG(PR_LOG_ERROR,
            ("nsNativeModuleLoader::LoadModule(\"%s\") - "
             "Symbol NSModule not found", filePath.get()));
    }

    // at some point we failed, clean up
    data.module = nsnull;
    PR_UnloadLibrary(data.library);

    return NULL;
}
Beispiel #17
0
void
GfxInfo::GetData()
{
    // to understand this function, see bug 639842. We retrieve the OpenGL driver information in a
    // separate process to protect against bad drivers.

    // if glxtest_pipe == 0, that means that we already read the information
    if (!glxtest_pipe)
        return;

    enum { buf_size = 1024 };
    char buf[buf_size];
    ssize_t bytesread = read(glxtest_pipe,
                             &buf,
                             buf_size-1); // -1 because we'll append a zero
    close(glxtest_pipe);
    glxtest_pipe = 0;

    // bytesread < 0 would mean that the above read() call failed. This should never happen.
    if (bytesread < 0)
        bytesread = 0;

    // let buf be a zero-terminated string
    buf[bytesread] = 0;

    // Wait for the glxtest process to finish. This serves 2 purposes:
    // * avoid having a zombie glxtest process laying around
    // * get the glxtest process status info.
    int glxtest_status = 0;
    bool wait_for_glxtest_process = true;
    bool waiting_for_glxtest_process_failed = false;
    while(wait_for_glxtest_process) {
        wait_for_glxtest_process = false;
        if (waitpid(glxtest_pid, &glxtest_status, 0) == -1) {
            if (errno == EINTR)
                wait_for_glxtest_process = true;
            else
                waiting_for_glxtest_process_failed = true;
        }
    }

    bool exited_with_error_code = !waiting_for_glxtest_process_failed &&
                                  WIFEXITED(glxtest_status) && 
                                  WEXITSTATUS(glxtest_status) != EXIT_SUCCESS;
    bool received_signal = !waiting_for_glxtest_process_failed &&
                           WIFSIGNALED(glxtest_status);

    bool error = waiting_for_glxtest_process_failed || exited_with_error_code || received_signal;

    nsCString *stringToFill = nsnull;
    char *bufptr = buf;
    if (!error) {
        while(true) {
            char *line = NS_strtok("\n", &bufptr);
            if (!line)
                break;
            if (stringToFill) {
                stringToFill->Assign(line);
                stringToFill = nsnull;
            }
            else if(!strcmp(line, "VENDOR"))
                stringToFill = &mVendor;
            else if(!strcmp(line, "RENDERER"))
                stringToFill = &mRenderer;
            else if(!strcmp(line, "VERSION"))
                stringToFill = &mVersion;
        }
    }

    const char *spoofedVendor = PR_GetEnv("MOZ_GFX_SPOOF_GL_VENDOR");
    if (spoofedVendor)
        mVendor.Assign(spoofedVendor);
    const char *spoofedRenderer = PR_GetEnv("MOZ_GFX_SPOOF_GL_RENDERER");
    if (spoofedRenderer)
        mRenderer.Assign(spoofedRenderer);
    const char *spoofedVersion = PR_GetEnv("MOZ_GFX_SPOOF_GL_VERSION");
    if (spoofedVersion)
        mVersion.Assign(spoofedVersion);

    if (error ||
        mVendor.IsEmpty() ||
        mRenderer.IsEmpty() ||
        mVersion.IsEmpty())
    {
        mAdapterDescription.AppendLiteral("GLXtest process failed");
        if (waiting_for_glxtest_process_failed)
            mAdapterDescription.AppendLiteral(" (waitpid failed)");
        if (exited_with_error_code)
            mAdapterDescription.AppendPrintf(" (exited with status %d)", WEXITSTATUS(glxtest_status));
        if (received_signal)
            mAdapterDescription.AppendPrintf(" (received signal %d)", WTERMSIG(glxtest_status));
        if (bytesread) {
            mAdapterDescription.AppendLiteral(": ");
            mAdapterDescription.Append(nsDependentCString(buf));
            mAdapterDescription.AppendLiteral("\n");
        }
#ifdef MOZ_CRASHREPORTER
        CrashReporter::AppendAppNotesToCrashReport(mAdapterDescription);
#endif
        return;
    }

    mAdapterDescription.Append(mVendor);
    mAdapterDescription.AppendLiteral(" -- ");
    mAdapterDescription.Append(mRenderer);

    nsCAutoString note;
    note.Append("OpenGL: ");
    note.Append(mAdapterDescription);
    note.Append(" -- ");
    note.Append(mVersion);
    note.Append("\n");
#ifdef MOZ_CRASHREPORTER
    CrashReporter::AppendAppNotesToCrashReport(note);
#endif

    // determine driver type (vendor) and where in the version string
    // the actual driver version numbers should be expected to be found (whereToReadVersionNumbers)
    const char *whereToReadVersionNumbers = nsnull;
    const char *Mesa_in_version_string = strstr(mVersion.get(), "Mesa");
    if (Mesa_in_version_string) {
        mIsMesa = true;
        // with Mesa, the version string contains "Mesa major.minor" and that's all the version information we get:
        // there is no actual driver version info.
        whereToReadVersionNumbers = Mesa_in_version_string + strlen("Mesa");
    } else if (strstr(mVendor.get(), "NVIDIA Corporation")) {
        mIsNVIDIA = true;
        // with the NVIDIA driver, the version string contains "NVIDIA major.minor"
        // note that here the vendor and version strings behave differently, that's why we don't put this above
        // alongside Mesa_in_version_string.
        const char *NVIDIA_in_version_string = strstr(mVersion.get(), "NVIDIA");
        if (NVIDIA_in_version_string)
            whereToReadVersionNumbers = NVIDIA_in_version_string + strlen("NVIDIA");
    } else if (strstr(mVendor.get(), "ATI Technologies Inc")) {
        mIsFGLRX = true;
        // with the FGLRX driver, the version string only gives a OpenGL version :/ so let's return that.
        // that can at least give a rough idea of how old the driver is.
        whereToReadVersionNumbers = mVersion.get();
    }

    // read major.minor version numbers
    if (whereToReadVersionNumbers) {
        // copy into writable buffer, for tokenization
        strncpy(buf, whereToReadVersionNumbers, buf_size);
        bufptr = buf;

        // now try to read major.minor version numbers. In case of failure, gracefully exit: these numbers have
        // been initialized as 0 anyways
        char *token = NS_strtok(".", &bufptr);
        if (token) {
            mMajorVersion = strtol(token, 0, 10);
            token = NS_strtok(".", &bufptr);
            if (token)
                mMinorVersion = strtol(token, 0, 10);
        }
    }
}
nsresult
nsSmtpService::loadSmtpServers()
{
    if (mSmtpServersLoaded)
      return NS_OK;
    
    nsresult rv;
    nsCOMPtr<nsIPrefService> prefService(do_GetService(NS_PREFSERVICE_CONTRACTID, &rv));
    if (NS_FAILED(rv)) return rv;
    nsCOMPtr<nsIPrefBranch> prefRootBranch;
    prefService->GetBranch(nsnull, getter_AddRefs(prefRootBranch));
    if (NS_FAILED(rv)) return rv;

    nsCString tempServerList;
    nsCString serverList;
    rv = prefRootBranch->GetCharPref(PREF_MAIL_SMTPSERVERS, getter_Copies(tempServerList));

    //Get the pref in a tempServerList and then parse it to see if it has dupes.
    //if so remove the dupes and then create the serverList.
    if (!tempServerList.IsEmpty()) {

      // Tokenize the data and add each smtp server if it is not already there 
      // in the user's current smtp server list
      nsCStringArray servers;
      servers.ParseString(tempServerList.get(), SERVER_DELIMITER);
      nsCAutoString tempSmtpServer;
      for (PRInt32 i = 0; i < servers.Count(); i++)
      {
          if (servers.IndexOf(* (servers[i])) == i) {
            tempSmtpServer.Assign(* (servers[i]));
            tempSmtpServer.StripWhitespace();
            if (!serverList.IsEmpty())
              serverList += SERVER_DELIMITER;
            serverList += tempSmtpServer;
          }
      }
    }
    else {
      serverList = tempServerList;
    }

    // We need to check if we have any pre-configured smtp servers so that
    // those servers can be appended to the list. 
    nsCString appendServerList;
    rv = prefRootBranch->GetCharPref(PREF_MAIL_SMTPSERVERS_APPEND_SERVERS, getter_Copies(appendServerList));

    // Get the list of smtp servers (either from regular pref i.e, mail.smtpservers or
    // from preconfigured pref mail.smtpservers.appendsmtpservers) and create a keyed 
    // server list.
    if (!serverList.IsEmpty() || !appendServerList.IsEmpty()) {
    /** 
             * Check to see if we need to add pre-configured smtp servers.
             * Following prefs are important to note in understanding the procedure here.
             *
             * 1. pref("mailnews.append_preconfig_smtpservers.version", version number);
             * This pref registers the current version in the user prefs file. A default value 
             * is stored in mailnews.js file. If a given vendor needs to add more preconfigured 
             * smtp servers, the default version number can be increased. Comparing version 
             * number from user's prefs file and the default one from mailnews.js, we
             * can add new smtp servers and any other version level changes that need to be done.
             *
             * 2. pref("mail.smtpservers.appendsmtpservers", <comma separated servers list>);
             * This pref contains the list of pre-configured smp servers that ISP/Vendor wants to
             * to add to the existing servers list. 
             */
      nsCOMPtr<nsIPrefBranch> defaultsPrefBranch;
      rv = prefService->GetDefaultBranch(MAIL_ROOT_PREF, getter_AddRefs(defaultsPrefBranch));
      NS_ENSURE_SUCCESS(rv,rv);

      nsCOMPtr<nsIPrefBranch> prefBranch;
      rv = prefService->GetBranch(MAIL_ROOT_PREF, getter_AddRefs(prefBranch));
      NS_ENSURE_SUCCESS(rv,rv);

      PRInt32 appendSmtpServersCurrentVersion = 0;
      PRInt32 appendSmtpServersDefaultVersion = 0;
      rv = prefBranch->GetIntPref(APPEND_SERVERS_VERSION_PREF_NAME, &appendSmtpServersCurrentVersion);
      NS_ENSURE_SUCCESS(rv,rv);

      rv = defaultsPrefBranch->GetIntPref(APPEND_SERVERS_VERSION_PREF_NAME, &appendSmtpServersDefaultVersion);
      NS_ENSURE_SUCCESS(rv,rv);

      // Update the smtp server list if needed
      if ((appendSmtpServersCurrentVersion <= appendSmtpServersDefaultVersion)) {
        // If there are pre-configured servers, add them to the existing server list
        if (!appendServerList.IsEmpty()) {
          if (!serverList.IsEmpty()) {
            nsCStringArray existingSmtpServersArray;
            existingSmtpServersArray.ParseString(serverList.get(), SERVER_DELIMITER);

            // Tokenize the data and add each smtp server if it is not already there 
            // in the user's current smtp server list
            char *newSmtpServerStr = appendServerList.BeginWriting(); 
            char *token = NS_strtok(SERVER_DELIMITER, &newSmtpServerStr);

            nsCAutoString newSmtpServer;
            while (token) {
              if (token && *token) {
                newSmtpServer.Assign(token);
                newSmtpServer.StripWhitespace();
                if (existingSmtpServersArray.IndexOf(newSmtpServer) == -1) {
                  serverList += ",";
                  serverList += newSmtpServer;
                }
              }
              token = NS_strtok(SERVER_DELIMITER, &newSmtpServerStr);
            }
          }
          else {
            serverList = appendServerList;
          }
          // Increase the version number so that updates will happen as and when needed
          rv = prefBranch->SetIntPref(APPEND_SERVERS_VERSION_PREF_NAME, appendSmtpServersCurrentVersion + 1);
        }
      }

      char *newStr = serverList.BeginWriting();
      char *pref = NS_strtok(", ", &newStr);

      while (pref) {
        // fix for bug #96207
        // code above makes sure that no duplicate entries in mail.smtpservers find
        // their way to the mSmtpServers list.  But it doesn't check, if a server to be
        // added already is in mSmtpServers.  That can happen in mail has been sent before 
        // opening the settings (loading the list).
        // use GetServerByKey to check if the key (pref) is already in
        // in the list. If not it calls createKeyedServer directly.
        nsCOMPtr<nsISmtpServer> server;
        rv = GetServerByKey(pref, getter_AddRefs(server));
        NS_ASSERTION(NS_SUCCEEDED(rv), "GetServerByKey failed");
        pref = NS_strtok(", ", &newStr);
      }
    }

    saveKeyList();

    mSmtpServersLoaded = PR_TRUE;
    return NS_OK;
}
const mozilla::Module*
nsNativeModuleLoader::LoadModule(nsILocalFile* aFile)
{
    nsresult rv;

    if (!NS_IsMainThread()) {
        // If this call is off the main thread, synchronously proxy it
        // to the main thread.
        nsRefPtr<LoadModuleMainThreadRunnable> r = new LoadModuleMainThreadRunnable(this, aFile);
        NS_DispatchToMainThread(r, NS_DISPATCH_SYNC);
        return r->mResult;
    }

    nsCOMPtr<nsIHashable> hashedFile(do_QueryInterface(aFile));
    if (!hashedFile) {
        NS_ERROR("nsIFile is not nsIHashable");
        return NULL;
    }

    nsCAutoString filePath;
    aFile->GetNativePath(filePath);

    NativeLoadData data;

    if (mLibraries.Get(hashedFile, &data)) {
        NS_ASSERTION(data.module, "Corrupt mLibraries hash");
        LOG(PR_LOG_DEBUG,
            ("nsNativeModuleLoader::LoadModule(\"%s\") - found in cache",
             filePath.get()));
        return data.module;
    }

    // We haven't loaded this module before

    rv = aFile->Load(&data.library);

    if (NS_FAILED(rv)) {
        char errorMsg[1024] = "<unknown; can't get error from NSPR>";

        if (PR_GetErrorTextLength() < (int) sizeof(errorMsg))
            PR_GetErrorText(errorMsg);

        LogMessage("Failed to load native module at path '%s': (%lx) %s",
                   filePath.get(), rv, errorMsg);

        return NULL;
    }

#ifdef IMPLEMENT_BREAK_AFTER_LOAD
    nsCAutoString leafName;
    aFile->GetNativeLeafName(leafName);

    char *env = getenv("XPCOM_BREAK_ON_LOAD");
    char *blist;
    if (env && *env && (blist = strdup(env))) {
        char *nextTok = blist;
        while (char *token = NS_strtok(":", &nextTok)) {
            if (leafName.Find(token, true) != kNotFound) {
                NS_BREAK();
            }
        }

        free(blist);
    }
#endif

    void *module = PR_FindSymbol(data.library, "NSModule");
    if (!module) {
        LogMessage("Native module at path '%s' doesn't export symbol `NSModule`.",
                   filePath.get());
        PR_UnloadLibrary(data.library);
        return NULL;
    }

    data.module = *(mozilla::Module const *const *) module;
    if (mozilla::Module::kVersion != data.module->mVersion) {
        LogMessage("Native module at path '%s' is incompatible with this version of Firefox, has version %i, expected %i.",
                   filePath.get(), data.module->mVersion,
                   mozilla::Module::kVersion);
        PR_UnloadLibrary(data.library);
        return NULL;
    }
        
    mLibraries.Put(hashedFile, data); // infallible
    return data.module;
}
Beispiel #20
0
nsresult nsMailtoUrl::ParseMailtoUrl(char * searchPart)
{
    char *rest = searchPart;
    nsCString escapedInReplyToPart;
    nsCString escapedToPart;
    nsCString escapedCcPart;
    nsCString escapedSubjectPart;
    nsCString escapedNewsgroupPart;
    nsCString escapedNewsHostPart;
    nsCString escapedReferencePart;
    nsCString escapedBodyPart;
    nsCString escapedBccPart;
    nsCString escapedFollowUpToPart;
    nsCString escapedFromPart;
    nsCString escapedHtmlPart;
    nsCString escapedOrganizationPart;
    nsCString escapedReplyToPart;
    nsCString escapedPriorityPart;

    // okay, first, free up all of our old search part state.....
    CleanupMailtoState();
    // m_toPart has the escaped address from before the query string, copy it
    // over so we can add on any additional to= addresses and unescape them all.
    escapedToPart = m_toPart;

    if (rest && *rest == '?')
    {
        /* start past the '?' */
        rest++;
    }

    if (rest)
    {
        char *token = NS_strtok("&", &rest);
        while (token && *token)
        {
            char *value = 0;
            char *eq = PL_strchr(token, '=');
            if (eq)
            {
                value = eq+1;
                *eq = 0;
            }

            nsCString decodedName;
            MsgUnescapeString(nsDependentCString(token), 0, decodedName);

            switch (NS_ToUpper(decodedName.First()))
            {
            /* DO NOT support attachment= in mailto urls. This poses a security fire hole!!!
                              case 'A':
                              if (!PL_strcasecmp (token, "attachment"))
                              m_attachmentPart = value;
                              break;
                         */
            case 'B':
                if (decodedName.LowerCaseEqualsLiteral("bcc"))
                {
                    if (!escapedBccPart.IsEmpty())
                    {
                        escapedBccPart += ", ";
                        escapedBccPart += value;
                    }
                    else
                        escapedBccPart = value;
                }
                else if (decodedName.LowerCaseEqualsLiteral("body"))
                {
                    if (!escapedBodyPart.IsEmpty())
                    {
                        escapedBodyPart +="\n";
                        escapedBodyPart += value;
                    }
                    else
                        escapedBodyPart = value;
                }
                break;
            case 'C':
                if (decodedName.LowerCaseEqualsLiteral("cc"))
                {
                    if (!escapedCcPart.IsEmpty())
                    {
                        escapedCcPart += ", ";
                        escapedCcPart += value;
                    }
                    else
                        escapedCcPart = value;
                }
                break;
            case 'F':
                if (decodedName.LowerCaseEqualsLiteral("followup-to"))
                    escapedFollowUpToPart = value;
                else if (decodedName.LowerCaseEqualsLiteral("from"))
                    escapedFromPart = value;
                break;
            case 'H':
                if (decodedName.LowerCaseEqualsLiteral("html-part") ||
                        decodedName.LowerCaseEqualsLiteral("html-body"))
                {
                    // escapedHtmlPart holds the body for both html-part and html-body.
                    escapedHtmlPart = value;
                    mFormat = nsIMsgCompFormat::HTML;
                }
                break;
            case 'I':
                if (decodedName.LowerCaseEqualsLiteral("in-reply-to"))
                    escapedInReplyToPart = value;
                break;

            case 'N':
                if (decodedName.LowerCaseEqualsLiteral("newsgroups"))
                    escapedNewsgroupPart = value;
                else if (decodedName.LowerCaseEqualsLiteral("newshost"))
                    escapedNewsHostPart = value;
                break;
            case 'O':
                if (decodedName.LowerCaseEqualsLiteral("organization"))
                    escapedOrganizationPart = value;
                break;
            case 'R':
                if (decodedName.LowerCaseEqualsLiteral("references"))
                    escapedReferencePart = value;
                else if (decodedName.LowerCaseEqualsLiteral("reply-to"))
                    escapedReplyToPart = value;
                break;
            case 'S':
                if(decodedName.LowerCaseEqualsLiteral("subject"))
                    escapedSubjectPart = value;
                break;
            case 'P':
                if (decodedName.LowerCaseEqualsLiteral("priority"))
                    escapedPriorityPart = PL_strdup(value);
                break;
            case 'T':
                if (decodedName.LowerCaseEqualsLiteral("to"))
                {
                    if (!escapedToPart.IsEmpty())
                    {
                        escapedToPart += ", ";
                        escapedToPart += value;
                    }
                    else
                        escapedToPart = value;
                }
                break;
            default:
                break;
            } // end of switch statement...

            if (eq)
                *eq = '='; /* put it back */
            token = NS_strtok("&", &rest);
        } // while we still have part of the url to parse...
    } // if rest && *rest

    // Get a global converter
    nsCOMPtr<nsIMimeConverter> mimeConverter =
        do_GetService(NS_MIME_CONVERTER_CONTRACTID);

    // Now unescape everything, and mime-decode the things that can be encoded.
    UnescapeAndConvert(mimeConverter, escapedToPart, m_toPart);
    UnescapeAndConvert(mimeConverter, escapedCcPart, m_ccPart);
    UnescapeAndConvert(mimeConverter, escapedBccPart, m_bccPart);
    UnescapeAndConvert(mimeConverter, escapedSubjectPart, m_subjectPart);
    UnescapeAndConvert(mimeConverter, escapedNewsgroupPart, m_newsgroupPart);
    UnescapeAndConvert(mimeConverter, escapedReferencePart, m_referencePart);
    if (!escapedBodyPart.IsEmpty())
        MsgUnescapeString(escapedBodyPart, 0, m_bodyPart);
    if (!escapedHtmlPart.IsEmpty())
        MsgUnescapeString(escapedHtmlPart, 0, m_htmlPart);
    UnescapeAndConvert(mimeConverter, escapedNewsHostPart, m_newsHostPart);
    UnescapeAndConvert(mimeConverter, escapedFollowUpToPart, m_followUpToPart);
    UnescapeAndConvert(mimeConverter, escapedFromPart, m_fromPart);
    UnescapeAndConvert(mimeConverter, escapedOrganizationPart, m_organizationPart);
    UnescapeAndConvert(mimeConverter, escapedReplyToPart, m_replyToPart);
    UnescapeAndConvert(mimeConverter, escapedPriorityPart, m_priorityPart);

    nsCString inReplyToPart; // Not a member like the others...
    UnescapeAndConvert(mimeConverter, escapedInReplyToPart, inReplyToPart);

    if (!inReplyToPart.IsEmpty())
    {
        // Ensure that References and In-Reply-To are consistent... The last
        // reference will be used as In-Reply-To header.
        if (m_referencePart.IsEmpty())
        {
            // If References is not set, set it to be the In-Reply-To.
            m_referencePart = inReplyToPart;
        }
        else
        {
            // References is set. Add the In-Reply-To as last header unless it's
            // set as last reference already.
            int32_t lastRefStart = m_referencePart.RFindChar('<');
            nsAutoCString lastReference;
            if (lastRefStart != -1)
                lastReference = StringTail(m_referencePart, lastRefStart);
            else
                lastReference = m_referencePart;

            if (lastReference != inReplyToPart)
            {
                m_referencePart += " ";
                m_referencePart += inReplyToPart;
            }
        }
    }

    return NS_OK;
}
nsresult purpleCoreService::InitProxies()
{
  /* Get the list of proxies */
  nsCString proxyList;
  nsresult rv = mPrefService->GetCharPref(PREF_MESSENGER_PROXIES,
                                          getter_Copies(proxyList));

  LOG(("InitProxies list = %s", proxyList.get()));

  nsCOMPtr<purpleProxy> proxy;
  char *newStr = proxyList.BeginWriting();
  nsAutoCString key;
  for (char *token = NS_strtok(",", &newStr);
       token;
       token = NS_strtok(",", &newStr)) {
    key = token;
    key.StripWhitespace();

    if (key.IsEmpty()) {
      continue;
    }

    LOG(("Creating proxy %s", key.get()));

    /* create the purpleProxy object */
    proxy = do_CreateInstance(PURPLE_PROXY_CONTRACTID);
    NS_ENSURE_TRUE(proxy, NS_ERROR_OUT_OF_MEMORY);

    LOG(("Creating proxy %s", key.get()));

    rv = proxy->Init(key);
    if (NS_FAILED(rv)) {
      NS_WARNING("Failed to init proxy!");
      continue;
    }

    /* Keep it in the local proxy list */
    mProxies.AppendObject(proxy);
    LOG(("Adding proxy %s in the list", key.get()));
  }

  /* Read the pref indicating the global proxy settings */
  rv = mPrefService->GetCharPref(PREF_MESSENGER_GLOBAL_PROXY,
                                 getter_Copies(key));
  NS_ENSURE_SUCCESS(rv, rv);

  /* Init mGlobalProxy */
  if (StringBeginsWith(key, NS_LITERAL_CSTRING(PROXY_KEY))) {
    for (PRInt32 i = mProxies.Count() - 1; i >= 0; --i) {
      if (mProxies[i]->GetKey().Equals(key)) {
        mGlobalProxy = mProxies[i];
        break;
      }
    }
  }

  if (!mGlobalProxy) {
    mGlobalProxy = do_CreateInstance(PURPLE_PROXY_INFO_CONTRACTID);
    NS_ENSURE_TRUE(mGlobalProxy, NS_ERROR_OUT_OF_MEMORY);

    if (key.Equals(PROXY_KEY_ENVVAR))
      mGlobalProxy->SetType(purpleIProxyInfo::useEnvVar);
    else
      mGlobalProxy->SetType(purpleIProxyInfo::noProxy);
  }

  /* Give the information to libpurple */
  PurpleProxyInfo *info;
  rv = mGlobalProxy->GetPurpleProxy(&info);
  NS_ENSURE_SUCCESS(rv, rv);
  purple_global_proxy_set_info(info);

  return NS_OK;
}
Beispiel #22
0
// Simple parser to parse META charset. 
// It only supports the case when the description is within one line. 
const char * 
nsMsgI18NParseMetaCharset(nsIFile* file) 
{ 
  static char charset[nsIMimeConverter::MAX_CHARSET_NAME_LENGTH+1];

  *charset = '\0'; 

  bool isDirectory = false;
  file->IsDirectory(&isDirectory);
  if (isDirectory) {
    NS_ERROR("file is a directory");
    return charset; 
  }

  nsresult rv;
  nsCOMPtr <nsIFileInputStream> fileStream = do_CreateInstance(NS_LOCALFILEINPUTSTREAM_CONTRACTID, &rv);
  NS_ENSURE_SUCCESS(rv, charset);
  
  rv = fileStream->Init(file, PR_RDONLY, 0664, false);
  nsCOMPtr <nsILineInputStream> lineStream = do_QueryInterface(fileStream, &rv);

  nsCString curLine;
  bool more = true;
  while (NS_SUCCEEDED(rv) && more) { 
    rv = lineStream->ReadLine(curLine, &more); 
    if (curLine.IsEmpty()) 
      continue; 

    ToUpperCase(curLine);

    if (curLine.Find("/HEAD") != -1) 
      break; 

    if (curLine.Find("META") != -1 && 
       curLine.Find("HTTP-EQUIV") != -1 && 
        curLine.Find("CONTENT-TYPE") != -1 && 
       curLine.Find("CHARSET") != -1) { 
      char *cp = (char *) PL_strchr(PL_strstr(curLine.get(), "CHARSET"), '=');
      char *token = nullptr;
      if (cp)
      {
        char *newStr = cp + 1;
        token = NS_strtok(" \"\'", &newStr);
      }
      if (token) { 
        PL_strncpy(charset, token, sizeof(charset));
        charset[sizeof(charset)-1] = '\0';

        // this function cannot parse a file if it is really
        // encoded by one of the following charsets
        // so we can say that the charset label must be incorrect for
        // the .html if we actually see those charsets parsed
        // and we should ignore them
        if (!PL_strncasecmp("UTF-16", charset, sizeof("UTF-16")-1) || 
            !PL_strncasecmp("UTF-32", charset, sizeof("UTF-32")-1))
          charset[0] = '\0';

        break;
      } 
    } 
  } 

  return charset; 
} 
Beispiel #23
0
/**
 * A very basic parser for updater.ini taken mostly from nsINIParser.cpp
 * that can be used by standalone apps.
 *
 * @param path       Path to the .ini file to read
 * @param keyList    List of zero-delimited keys ending with two zero characters
 * @param numStrings Number of strings to read into results buffer - must be equal to the number of keys
 * @param results    Two-dimensional array of strings to be filled in the same order as the keys provided
 * @param section    Optional name of the section to read; defaults to "Strings"
 */
int
ReadStrings(const NS_tchar *path,
            const char *keyList,
            unsigned int numStrings,
            char results[][MAX_TEXT_LEN],
            const char *section)
{
  AutoFILE fp(NS_tfopen(path, OPEN_MODE));

  if (!fp)
    return READ_ERROR;

  /* get file size */
  if (fseek(fp, 0, SEEK_END) != 0)
    return READ_ERROR;

  long len = ftell(fp);
  if (len <= 0)
    return READ_ERROR;

  size_t flen = size_t(len);
  AutoCharArray fileContents(flen + 1);
  if (!fileContents)
    return READ_STRINGS_MEM_ERROR;

  /* read the file in one swoop */
  if (fseek(fp, 0, SEEK_SET) != 0)
    return READ_ERROR;

  size_t rd = fread(fileContents, sizeof(char), flen, fp);
  if (rd != flen)
    return READ_ERROR;

  fileContents[flen] = '\0';

  char *buffer = fileContents;
  bool inStringsSection = false;

  unsigned int read = 0;

  while (char *token = NS_strtok(kNL, &buffer)) {
    if (token[0] == '#' || token[0] == ';') // it's a comment
      continue;

    token = (char*) NS_strspnp(kWhitespace, token);
    if (!*token) // empty line
      continue;

    if (token[0] == '[') { // section header!
      ++token;
      char const * currSection = token;

      char *rb = NS_strtok(kRBracket, &token);
      if (!rb || NS_strtok(kWhitespace, &token)) {
        // there's either an unclosed [Section or a [Section]Moretext!
        // we could frankly decide that this INI file is malformed right
        // here and stop, but we won't... keep going, looking for
        // a well-formed [section] to continue working with
        inStringsSection = false;
      }
      else {
        if (section)
          inStringsSection = strcmp(currSection, section) == 0;
        else
          inStringsSection = strcmp(currSection, "Strings") == 0;
      }

      continue;
    }

    if (!inStringsSection) {
      // If we haven't found a section header (or we found a malformed
      // section header), or this isn't the [Strings] section don't bother
      // parsing this line.
      continue;
    }

    char *key = token;
    char *e = NS_strtok(kEquals, &token);
    if (!e)
      continue;

    int keyIndex = find_key(keyList, key);
    if (keyIndex >= 0 && (unsigned int)keyIndex < numStrings)
    {
      strncpy(results[keyIndex], token, MAX_TEXT_LEN - 1);
      results[keyIndex][MAX_TEXT_LEN - 1] = '\0';
      read++;
    }
  }

  return (read == numStrings) ? OK : PARSE_ERROR;
}