Ejemplo n.º 1
0
bool WMSettings::getOEacctFiles(nsILocalFile* file,
                                  nsCOMArray<nsILocalFile>& fileArray)
{
  nsresult rv;
  nsCOMPtr<nsISimpleEnumerator> entries;
  rv = file->GetDirectoryEntries(getter_AddRefs(entries));
  if (NS_FAILED(rv) || !entries)
    return false;

  bool hasMore;
  while (NS_SUCCEEDED(entries->HasMoreElements(&hasMore)) && hasMore) {
    nsCOMPtr<nsISupports> sup;
    entries->GetNext(getter_AddRefs(sup));
    if (!sup)
      return false;
    nsCOMPtr<nsILocalFile> fileX = do_QueryInterface(sup);
    if (!fileX)
      return false;
    nsString name;
    if (NS_FAILED(fileX->GetLeafName(name)))
      return false;
    bool isDir;
    if (NS_FAILED(fileX->IsDirectory(&isDir)))
      return false;
    if (isDir) {
      getOEacctFiles(fileX, fileArray);
    }
    else {
      if (StringEndsWith(name, NS_LITERAL_STRING(".oeaccount")))
        fileArray.AppendObject(fileX);
    }
  }
  return true;
}
Ejemplo n.º 2
0
void LuaMatUniforms::Parse(lua_State* L, const int tableIdx)
{
	auto uniformAndNames = GetUniformsAndPossibleNames();
	decltype(uniformAndNames) uniformAndNamesLower;
	for (auto& p: uniformAndNames) {
		uniformAndNamesLower[StringToLower(p.first)] = p.second;
	}

	for (lua_pushnil(L); lua_next(L, tableIdx) != 0; lua_pop(L, 1)) {
		if (!lua_israwstring(L, -2) || !lua_isnumber(L, -1))
			continue;

		// get the lua table key
		// and remove the "loc" at the end (cameraPosLoc -> camerapos)
		std::string uniformLocStr = luaL_tosstring(L, -2);
		StringToLowerInPlace(uniformLocStr);
		if (StringEndsWith(uniformLocStr, "loc")) {
			uniformLocStr.resize(uniformLocStr.size() - 3);
		}

		const auto uniformLocIt = uniformAndNamesLower.find(uniformLocStr);
		if (uniformLocIt == uniformAndNamesLower.end()) {
			LOG_L(L_WARNING, "LuaMaterial: unknown uniform \"%s\"", lua_tostring(L, -2));
			continue;
		}

		uniformLocIt->second->loc = static_cast<GLint>(lua_tonumber(L, -1));
	}
}
nsresult
nsNetscapeProfileMigratorBase::CopyAddressBookDirectories(PBStructArray &aLdapServers,
                                                          nsIPrefService* aPrefService)
{
  // each server has a pref ending with .filename. The value of that pref
  // points to a profile which we need to migrate.
  nsAutoString index;
  index.AppendInt(nsISuiteProfileMigrator::ADDRESSBOOK_DATA);
  NOTIFY_OBSERVERS(MIGRATION_ITEMBEFOREMIGRATE, index.get());

  uint32_t count = aLdapServers.Length();
  for (uint32_t i = 0; i < count; ++i) {
    PrefBranchStruct* pref = aLdapServers.ElementAt(i);
    nsDependentCString prefName(pref->prefName);

    if (StringEndsWith(prefName, NS_LITERAL_CSTRING(".filename"))) {
      CopyFile(pref->stringValue, pref->stringValue);
    }

    // we don't need to do anything to the fileName pref itself
  }

  NOTIFY_OBSERVERS(MIGRATION_ITEMAFTERMIGRATE, index.get());

  return NS_OK;
}
Ejemplo n.º 4
0
NS_IMETHODIMP
nsPrintSettingsGTK::SetToFileName(const char16_t * aToFileName)
{
  if (aToFileName[0] == 0) {
    mToFileName.SetLength(0);
    gtk_print_settings_set(mPrintSettings, GTK_PRINT_SETTINGS_OUTPUT_URI,
                           nullptr);
    return NS_OK;
  }

  if (StringEndsWith(nsDependentString(aToFileName), NS_LITERAL_STRING(".ps"))) {
    gtk_print_settings_set(mPrintSettings, GTK_PRINT_SETTINGS_OUTPUT_FILE_FORMAT, "ps");
  } else {
    gtk_print_settings_set(mPrintSettings, GTK_PRINT_SETTINGS_OUTPUT_FILE_FORMAT, "pdf");
  }

  nsCOMPtr<nsIFile> file;
  nsresult rv = NS_NewLocalFile(nsDependentString(aToFileName), true,
                                getter_AddRefs(file));
  NS_ENSURE_SUCCESS(rv, rv);

  // Convert the nsIFile to a URL
  nsAutoCString url;
  rv = NS_GetURLSpecFromFile(file, url);
  NS_ENSURE_SUCCESS(rv, rv);

  gtk_print_settings_set(mPrintSettings, GTK_PRINT_SETTINGS_OUTPUT_URI, url.get());
  mToFileName = aToFileName;

  return NS_OK;
}
Ejemplo n.º 5
0
int HashDirectoryTreeCallback(const char *filename, ARG_UNUSED const struct stat *sb, void *user_data)
{
    HashDirectoryTreeState *state = user_data;
    bool ignore = true;
    for (size_t i = 0; state->extensions_filter[i]; i++)
    {
        if (StringEndsWith(filename, state->extensions_filter[i]))
        {
            ignore = false;
            break;
        }
    }

    if (ignore)
    {
        return 0;
    }

    FILE *file = fopen(filename, "rb");
    if (!file)
    {
        Log(LOG_LEVEL_ERR, "Cannot open file for hashing '%s'. (fopen: %s)", filename, GetErrorStr());
        return -1;
    }

    size_t len = 0;
    char buffer[1024];
    while ((len = fread(buffer, 1, 1024, file)))
    {
        EVP_DigestUpdate(state->crypto_context, state->buffer, len);
    }

    fclose(file);
    return 0;
}
NS_IMETHODIMP
nsFileProtocolHandler::ReadURLFile(nsIFile* aFile, nsIURI** aURI)
{
    // We only support desktop files that end in ".desktop" like the spec says:
    // http://standards.freedesktop.org/desktop-entry-spec/latest/ar01s02.html
    nsAutoCString leafName;
    nsresult rv = aFile->GetNativeLeafName(leafName);
    if (NS_FAILED(rv) ||
	!StringEndsWith(leafName, NS_LITERAL_CSTRING(".desktop")))
        return NS_ERROR_NOT_AVAILABLE;

    nsINIParser parser;
    rv = parser.Init(aFile);
    if (NS_FAILED(rv))
        return rv;

    nsAutoCString type;
    parser.GetString(DESKTOP_ENTRY_SECTION, "Type", type);
    if (!type.EqualsLiteral("Link"))
        return NS_ERROR_NOT_AVAILABLE;

    nsAutoCString url;
    rv = parser.GetString(DESKTOP_ENTRY_SECTION, "URL", url);
    if (NS_FAILED(rv) || url.IsEmpty())
        return NS_ERROR_NOT_AVAILABLE;

    return NS_NewURI(aURI, url);
}
Ejemplo n.º 7
0
static const TCHAR *
SelectLuaFile(TCHAR *buffer, const TCHAR *path)
{
  if (StringIsEmpty(path)) {
    /* no parameter: let user select a *.lua file */
    LuaFileVisitor visitor;

    Directory::VisitSpecificFiles(LocalPath(buffer, _T("lua")), _T("*.lua"),
                                  visitor, true);
    if (visitor.combo_list.empty()) {
      ShowMessageBox(_("Not found"), _T("RunLuaFile"),
                     MB_OK|MB_ICONINFORMATION);
      return nullptr;
    }

    int i = ComboPicker(_("Select a file"), visitor.combo_list);
    if (i < 0)
      return nullptr;

    UnsafeCopyString(buffer, visitor.combo_list[i].string_value);
    return buffer;
  } else if (StringEndsWith(path, _T(".lua"))) {
    /* *.lua file specified: run this file */
    return IsAbsolutePath(path)
      ? path
      : LocalPath(buffer, _T("lua"), path);
  } else {
    ShowMessageBox(_T("RunLuaFile expects *.lua parameter"),
                   _T("RunLuaFile"), MB_OK|MB_ICONINFORMATION);
    return nullptr;
  }
}
NS_IMETHODIMP MsgMailNewsUrlBase::GetIsMessageUri(bool *aIsMessageUri)
{
  NS_ENSURE_ARG(aIsMessageUri);
  nsAutoCString scheme;
  m_baseURL->GetScheme(scheme);
  *aIsMessageUri = StringEndsWith(scheme, NS_LITERAL_CSTRING("-message"));
  return NS_OK;
}
Ejemplo n.º 9
0
PRBool nsOEScanBoxes::Scan50MailboxDir( nsIFile * srcDir)
{
  Reset();

  MailboxEntry *  pEntry;
  PRInt32      index = 1;
  char *      pLeaf;

  PRBool hasMore;
  nsCOMPtr<nsISimpleEnumerator> directoryEnumerator;
  nsresult rv = srcDir->GetDirectoryEntries(getter_AddRefs(directoryEnumerator));
  NS_ENSURE_SUCCESS(rv, rv);

  directoryEnumerator->HasMoreElements(&hasMore);
  PRBool            isFile;
  nsCOMPtr<nsIFile> entry;
  nsCString         fName;

  while (hasMore && NS_SUCCEEDED(rv))
  {
    nsCOMPtr<nsISupports> aSupport;
    rv = directoryEnumerator->GetNext(getter_AddRefs(aSupport));
    nsCOMPtr<nsILocalFile> entry(do_QueryInterface(aSupport, &rv));
    directoryEnumerator->HasMoreElements(&hasMore);

    isFile = PR_FALSE;
    rv = entry->IsFile( &isFile);
    if (NS_SUCCEEDED( rv) && isFile) {
      pLeaf = nsnull;
      rv = entry->GetNativeLeafName( fName);
      if (NS_SUCCEEDED( rv)  &&
        (StringEndsWith(fName, NS_LITERAL_CSTRING(".dbx")))) {
          // This is a *.dbx file in the mail directory
          if (nsOE5File::IsLocalMailFile(entry)) {
            pEntry = new MailboxEntry;
            pEntry->index = index;
            index++;
            pEntry->parent = 0;
            pEntry->child = 0;
            pEntry->sibling = index;
            pEntry->type = -1;
            fName.SetLength(fName.Length() - 4);
            pEntry->fileName = fName.get();
            NS_CopyNativeToUnicode(fName, pEntry->mailName);
            m_entryArray.AppendElement( pEntry);
          }
      }
    }
  }

  if (m_entryArray.Count() > 0) {
    pEntry = (MailboxEntry *)m_entryArray.ElementAt( m_entryArray.Count() - 1);
    pEntry->sibling = -1;
    return( PR_TRUE);
  }

  return( PR_FALSE);
}
Ejemplo n.º 10
0
/* code borrow from kde-workspace/kcontrol/keyboard/xkb_rules.cpp */
void RulesHandlerStartElement(void *ctx, const xmlChar *name,
                              const xmlChar **atts)
{
    FcitxXkbRulesHandler* ruleshandler = (FcitxXkbRulesHandler*) ctx;
    FcitxXkbRules* rules = ruleshandler->rules;
    utarray_push_back(ruleshandler->path, &name);

    char* strPath = fcitx_utils_join_string_list(ruleshandler->path, '/');
    if ( StringEndsWith(strPath, "layoutList/layout/configItem") ) {
        utarray_extend_back(rules->layoutInfos);
    }
    else if ( StringEndsWith(strPath, "layoutList/layout/variantList/variant") ) {
        FcitxXkbLayoutInfo* layoutInfo = (FcitxXkbLayoutInfo*) utarray_back(rules->layoutInfos);
        utarray_extend_back(layoutInfo->variantInfos);
    }
    else if ( StringEndsWith(strPath, "modelList/model") ) {
        utarray_extend_back(rules->modelInfos);
    }
    else if ( StringEndsWith(strPath, "optionList/group") ) {
        utarray_extend_back(rules->optionGroupInfos);
        FcitxXkbOptionGroupInfo* optionGroupInfo = (FcitxXkbOptionGroupInfo*) utarray_back(rules->optionGroupInfos);
        int i = 0;
        while(atts && atts[i*2] != 0) {
            if (strcmp(XMLCHAR_CAST atts[i*2], "allowMultipleSelection") == 0) {
                optionGroupInfo->exclusive = (strcmp(XMLCHAR_CAST atts[i*2 + 1], "true") != 0);
            }
            i++;
        }
    }
    else if ( StringEndsWith(strPath, "optionList/group/option") ) {
        FcitxXkbOptionGroupInfo* optionGroupInfo = (FcitxXkbOptionGroupInfo*) utarray_back(rules->optionGroupInfos);
        utarray_extend_back(optionGroupInfo->optionInfos);
    }
    else if ( strcmp(strPath, "xkbConfigRegistry") == 0 ) {
        int i = 0;
        while(atts && atts[i*2] != 0) {
            if (strcmp(XMLCHAR_CAST atts[i*2], "version") == 0 && strlen(XMLCHAR_CAST atts[i*2 + 1]) != 0) {
                rules->version = strdup(XMLCHAR_CAST atts[i*2 + 1]);
            }
            i++;
        }
    }
    free(strPath);
}
Ejemplo n.º 11
0
PRBool nsPluginsDir::IsPluginFile(nsIFile* file)
{
    nsCAutoString filename;
    if (NS_FAILED(file->GetNativeLeafName(filename)))
        return PR_FALSE;

    NS_NAMED_LITERAL_CSTRING(dllSuffix, LOCAL_PLUGIN_DLL_SUFFIX);
    if (filename.Length() > dllSuffix.Length() &&
        StringEndsWith(filename, dllSuffix))
        return PR_TRUE;
    
#ifdef LOCAL_PLUGIN_DLL_ALT_SUFFIX
    NS_NAMED_LITERAL_CSTRING(dllAltSuffix, LOCAL_PLUGIN_DLL_ALT_SUFFIX);
    if (filename.Length() > dllAltSuffix.Length() &&
        StringEndsWith(filename, dllAltSuffix))
        return PR_TRUE;
#endif
    return PR_FALSE;
}
static PRBool
IsInNoProxyList(const nsACString& aHost, PRInt32 aPort, const char* noProxyVal)
{
  NS_ASSERTION(aPort >= 0, "Negative port?");
  
  nsCAutoString noProxy(noProxyVal);
  if (noProxy.EqualsLiteral("*"))
    return PR_TRUE;
    
  noProxy.StripWhitespace();
  
  nsReadingIterator<char> pos;
  nsReadingIterator<char> end;
  noProxy.BeginReading(pos);
  noProxy.EndReading(end);
  while (pos != end) {
    nsReadingIterator<char> last = pos;
    nsReadingIterator<char> nextPos;
    if (FindCharInReadable(',', last, end)) {
      nextPos = last;
      ++nextPos;
    } else {
      last = end;
      nextPos = end;
    }
    
    nsReadingIterator<char> colon = pos;
    PRInt32 port = -1;
    if (FindCharInReadable(':', colon, last)) {
      ++colon;
      nsDependentCSubstring portStr(colon, last);
      nsCAutoString portStr2(portStr); // We need this for ToInteger. String API's suck.
      PRInt32 err;
      port = portStr2.ToInteger(&err);
      if (NS_FAILED(err)) {
        port = -2; // don't match any port, so we ignore this pattern
      }
      --colon;
    } else {
      colon = last;
    }
    
    if (port == -1 || port == aPort) {
      nsDependentCSubstring hostStr(pos, colon);
      // By using StringEndsWith instead of an equality comparator, we can include sub-domains
      if (StringEndsWith(aHost, hostStr, nsCaseInsensitiveCStringComparator()))
        return PR_TRUE;
    }
    
    pos = nextPos;
  }
  
  return PR_FALSE;
}
Ejemplo n.º 13
0
//==============================================================================
bool
CheckFileExtension(
const char* extension,  ///< file extension
const char* FileName )  ///< file name
{
  // first check extension
  if ( ! StringEndsWith(extension, FileName) ) return false;
  
  // then check separator
  return FileName[ strlen(FileName) - strlen(extension) - 1 ] == '.';
}
Ejemplo n.º 14
0
// caller passes in upgrading==true if they want back a db even if the db is out of date.
// If so, they'll extract out the interesting info from the db, close it, delete it, and
// then try to open the db again, prior to reparsing.
nsresult nsMailDatabase::Open(nsIFile *aSummaryFile, bool aCreate,
                              bool aUpgrading)
{
#ifdef DEBUG
  nsString leafName;
  aSummaryFile->GetLeafName(leafName);
  if (!StringEndsWith(leafName, NS_LITERAL_STRING(".msf"),
                     nsCaseInsensitiveStringComparator()))
    NS_ERROR("non summary file passed into open\n");
#endif
  return nsMsgDatabase::Open(aSummaryFile, aCreate, aUpgrading);
}
Ejemplo n.º 15
0
void
nsHyphenationManager::LoadPatternListFromDir(nsIFile *aDir)
{
  nsresult rv;
  
  PRBool check = PR_FALSE;
  rv = aDir->Exists(&check);
  if (NS_FAILED(rv) || !check) {
    return;
  }
  
  rv = aDir->IsDirectory(&check);
  if (NS_FAILED(rv) || !check) {
    return;
  }

  nsCOMPtr<nsISimpleEnumerator> e;
  rv = aDir->GetDirectoryEntries(getter_AddRefs(e));
  if (NS_FAILED(rv)) {
    return;
  }
  
  nsCOMPtr<nsIDirectoryEnumerator> files(do_QueryInterface(e));
  if (!files) {
    return;
  }
  
  nsCOMPtr<nsIFile> file;
  while (NS_SUCCEEDED(files->GetNextFile(getter_AddRefs(file))) && file){
    nsAutoString dictName;
    file->GetLeafName(dictName);
    NS_ConvertUTF16toUTF8 locale(dictName);
    ToLowerCase(locale);
    if (!StringEndsWith(locale, NS_LITERAL_CSTRING(".dic"))) {
      continue;
    }
    if (StringBeginsWith(locale, NS_LITERAL_CSTRING("hyph_"))) {
      locale.Cut(0, 5);
    }
    locale.SetLength(locale.Length() - 4); // strip ".dic"
    for (PRUint32 i = 0; i < locale.Length(); ++i) {
      if (locale[i] == '_') {
        locale.Replace(i, 1, '-');
      }
    }
#ifdef DEBUG
    printf("adding hyphenation patterns for %s: %s\n", locale.get(),
           NS_ConvertUTF16toUTF8(dictName).get());
#endif
    nsCOMPtr<nsIAtom> localeAtom = do_GetAtom(locale);
    mPatternFiles.Put(localeAtom, file);
  }
}
Ejemplo n.º 16
0
already_AddRefed<nsHyphenator>
nsHyphenationManager::GetHyphenator(nsIAtom *aLocale)
{
  nsRefPtr<nsHyphenator> hyph;
  mHyphenators.Get(aLocale, getter_AddRefs(hyph));
  if (hyph) {
    return hyph.forget();
  }
  nsCOMPtr<nsIFile> file = mPatternFiles.Get(aLocale);
  if (!file) {
    nsCOMPtr<nsIAtom> alias = mHyphAliases.Get(aLocale);
    if (alias) {
      mHyphenators.Get(alias, getter_AddRefs(hyph));
      if (hyph) {
        return hyph.forget();
      }
      file = mPatternFiles.Get(alias);
      if (file) {
        aLocale = alias;
      }
    }
    if (!file) {
      // In the case of a locale such as "de-DE-1996", we try replacing
      // successive trailing subtags with "-*" to find fallback patterns,
      // so "de-DE-1996" -> "de-DE-*" (and then recursively -> "de-*")
      nsAtomCString localeStr(aLocale);
      if (StringEndsWith(localeStr, NS_LITERAL_CSTRING("-*"))) {
        localeStr.Truncate(localeStr.Length() - 2);
      }
      PRInt32 i = localeStr.RFindChar('-');
      if (i > 1) {
        localeStr.Replace(i, localeStr.Length() - i, "-*");
        nsCOMPtr<nsIAtom> fuzzyLocale = do_GetAtom(localeStr);
        return GetHyphenator(fuzzyLocale);
      } else {
        return nsnull;
      }
    }
  }
  hyph = new nsHyphenator(file);
  if (hyph->IsValid()) {
    mHyphenators.Put(aLocale, hyph);
    return hyph.forget();
  }
#ifdef DEBUG
  nsCString msg;
  file->GetNativePath(msg);
  msg.Insert("failed to load patterns from ", 0);
  NS_WARNING(msg.get());
#endif
  mPatternFiles.Remove(aLocale);
  return nsnull;
}
Ejemplo n.º 17
0
static bool
AttrHasSuffix(Implementor* aElement, nsIAtom* aNS, nsIAtom* aName,
              nsIAtom* aStr_)
{
  FakeRef<nsIAtom> aStr(aStr_);
  auto match = [aStr](const nsAttrValue* aValue) {
    nsAutoString str;
    aValue->ToString(str);
    return StringEndsWith(str, nsDependentAtomString(aStr));
  };
  return DoMatch(aElement, aNS, aName, match);
}
Ejemplo n.º 18
0
NS_IMETHODIMP
mozHunspell::LoadDictionariesFromDir(nsIFile* aDir)
{
  nsresult rv;

  bool check = false;
  rv = aDir->Exists(&check);
  if (NS_FAILED(rv) || !check)
    return NS_ERROR_UNEXPECTED;

  rv = aDir->IsDirectory(&check);
  if (NS_FAILED(rv) || !check)
    return NS_ERROR_UNEXPECTED;

  nsCOMPtr<nsISimpleEnumerator> e;
  rv = aDir->GetDirectoryEntries(getter_AddRefs(e));
  if (NS_FAILED(rv))
    return NS_ERROR_UNEXPECTED;

  nsCOMPtr<nsIDirectoryEnumerator> files(do_QueryInterface(e));
  if (!files)
    return NS_ERROR_UNEXPECTED;

  nsCOMPtr<nsIFile> file;
  while (NS_SUCCEEDED(files->GetNextFile(getter_AddRefs(file))) && file) {
    nsAutoString leafName;
    file->GetLeafName(leafName);
    if (!StringEndsWith(leafName, NS_LITERAL_STRING(".dic")))
      continue;

    nsAutoString dict(leafName);
    dict.SetLength(dict.Length() - 4); // magic length of ".dic"

    // check for the presence of the .aff file
    leafName = dict;
    leafName.AppendLiteral(".aff");
    file->SetLeafName(leafName);
    rv = file->Exists(&check);
    if (NS_FAILED(rv) || !check)
      continue;

#ifdef DEBUG_bsmedberg
    printf("Adding dictionary: %s\n", NS_ConvertUTF16toUTF8(dict).get());
#endif

    mDictionaries.Put(dict, file);
  }

  return NS_OK;
}
nsresult
nsNetscapeProfileMigratorBase::CopySignatureFiles(PBStructArray &aIdentities,
                                                  nsIPrefService* aPrefService)
{
  nsresult rv = NS_OK;

  uint32_t count = aIdentities.Length();
  for (uint32_t i = 0; i < count; ++i)
  {
    PrefBranchStruct* pref = aIdentities.ElementAt(i);
    nsDependentCString prefName(pref->prefName);

    // a partial fix for bug #255043
    // if the user's signature file from seamonkey lives in the
    // old profile root, we'll copy it over to the new profile root and
    // then set the pref to the new value. Note, this doesn't work for
    // multiple signatures that live below the seamonkey profile root
    if (StringEndsWith(prefName, NS_LITERAL_CSTRING(".sig_file")))
    {
      // turn the pref into a nsIFile
      nsCOMPtr<nsIFile> srcSigFile =
        do_CreateInstance(NS_LOCAL_FILE_CONTRACTID);
      srcSigFile->SetPersistentDescriptor(nsDependentCString(pref->stringValue));

      nsCOMPtr<nsIFile> targetSigFile;
      rv = mTargetProfile->Clone(getter_AddRefs(targetSigFile));
      NS_ENSURE_SUCCESS(rv, rv);

      // now make the copy
      bool exists;
      srcSigFile->Exists(&exists);
      if (exists)
      {
        nsAutoString leafName;
        srcSigFile->GetLeafName(leafName);
        // will fail if we've already copied a sig file here
        srcSigFile->CopyTo(targetSigFile, leafName);
        targetSigFile->Append(leafName);

        // now write out the new descriptor
        nsAutoCString descriptorString;
        targetSigFile->GetPersistentDescriptor(descriptorString);
        NS_Free(pref->stringValue);
        pref->stringValue = ToNewCString(descriptorString);
      }
    }
  }
  return NS_OK;
}
Ejemplo n.º 20
0
PRBool
LocalSearchDataSource::doMatch(nsIRDFLiteral *literal,
                               const nsAString &matchMethod,
                               const nsString &matchText)
{
	PRBool		found = PR_FALSE;

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

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

        if (matchMethod.EqualsLiteral("contains"))
	{
            if (-1 != value.Find(matchText, CaseInsensitiveCompare))
                found = PR_TRUE;
	}
        else if (matchMethod.EqualsLiteral("startswith"))
	{
            if (StringBeginsWith(value, matchText, CaseInsensitiveCompare))
                found = PR_TRUE;
	}
        else if (matchMethod.EqualsLiteral("endswith"))
	{
            if (StringEndsWith(value, matchText, CaseInsensitiveCompare))
                found = PR_TRUE;
	}
        else if (matchMethod.EqualsLiteral("is"))
	{
            if (value.Equals(matchText, CaseInsensitiveCompare))
                found = PR_TRUE;
	}
        else if (matchMethod.EqualsLiteral("isnot"))
	{
            if (!value.Equals(matchText, CaseInsensitiveCompare))
                found = PR_TRUE;
	}
        else if (matchMethod.EqualsLiteral("doesntcontain"))
	{
            if (-1 == value.Find(matchText, CaseInsensitiveCompare))
                found = PR_TRUE;
	}
        return(found);
}
Ejemplo n.º 21
0
static PRBool
nsShouldIgnoreFile(nsString& name)
{
    PRUnichar firstChar=name.CharAt(0);
    if (firstChar == '.' || firstChar == '#' || name.CharAt(name.Length() - 1) == '~')
      return PR_TRUE;

    if (name.LowerCaseEqualsLiteral("rules.dat") || name.LowerCaseEqualsLiteral("rulesbackup.dat"))
        return PR_TRUE;


    // don't add summary files to the list of folders;
    // don't add popstate files to the list either, or rules (sort.dat).
    if (StringEndsWith(name, NS_LITERAL_STRING(".snm")) ||
        name.LowerCaseEqualsLiteral("popstate.dat") ||
        name.LowerCaseEqualsLiteral("sort.dat") ||
        name.LowerCaseEqualsLiteral("mailfilt.log") ||
        name.LowerCaseEqualsLiteral("filters.js") ||
        StringEndsWith(name, NS_LITERAL_STRING(".toc")) ||
        StringEndsWith(name, NS_LITERAL_STRING(".sbd")))
        return PR_TRUE;

    return PR_FALSE;
}
bool nsMsgLocalStoreUtils::nsShouldIgnoreFile(nsAString &name) {
  if (name.IsEmpty()) return true;

  char16_t firstChar = name.First();
  if (firstChar == '.' || firstChar == '#' ||
      name.CharAt(name.Length() - 1) == '~')
    return true;

  if (name.LowerCaseEqualsLiteral("msgfilterrules.dat") ||
      name.LowerCaseEqualsLiteral("rules.dat") ||
      name.LowerCaseEqualsLiteral("filterlog.html") ||
      name.LowerCaseEqualsLiteral("junklog.html") ||
      name.LowerCaseEqualsLiteral("rulesbackup.dat"))
    return true;

  // don't add summary files to the list of folders;
  // don't add popstate files to the list either, or rules (sort.dat).
  if (StringEndsWith(name, NS_LITERAL_STRING(".snm")) ||
      name.LowerCaseEqualsLiteral("popstate.dat") ||
      name.LowerCaseEqualsLiteral("sort.dat") ||
      name.LowerCaseEqualsLiteral("mailfilt.log") ||
      name.LowerCaseEqualsLiteral("filters.js") ||
      StringEndsWith(name, NS_LITERAL_STRING(".toc")))
    return true;

  // ignore RSS data source files
  if (name.LowerCaseEqualsLiteral("feeds.rdf") ||
      name.LowerCaseEqualsLiteral("feeditems.rdf") ||
      StringBeginsWith(name, NS_LITERAL_STRING("feeditems_error")))
    return true;

  // The .mozmsgs dir is for spotlight support
  return (StringEndsWith(name, NS_LITERAL_STRING(".mozmsgs")) ||
          StringEndsWith(name, NS_LITERAL_STRING(FOLDER_SUFFIX)) ||
          StringEndsWith(name, NS_LITERAL_STRING(SUMMARY_SUFFIX)));
}
NS_IMETHODIMP
nsNativeAppSupportAmigaOS::Start(PRBool *aRetVal)
{
  NS_ASSERTION(gAppData, "gAppData must not be null.");

  nsCAutoString applicationName;
  if (gAppData->vendor) {
      applicationName.Append(gAppData->vendor);
      applicationName.Append(".");
  }
  applicationName.Append(gAppData->name);
  ToLowerCase(applicationName);

//  printf("nsNativeAppSupportAmigaOS::Start  Launch %s\n", applicationName.get());
  *aRetVal = PR_TRUE;

  // Is there a request to suppress default binary launcher?
  nsCAutoString path;
  char* argv1 = getenv("MOZ_APP_LAUNCHER");

  if(!argv1) {
    // Tell the desktop the command for restarting us so that we can be part of XSMP session restore
    NS_ASSERTION(gDirServiceProvider, "gDirServiceProvider is NULL! This shouldn't happen!");
    nsCOMPtr<nsIFile> executablePath;
    nsresult rv;

    PRBool dummy;
    rv = gDirServiceProvider->GetFile(XRE_EXECUTABLE_FILE, &dummy, getter_AddRefs(executablePath));

    if (NS_SUCCEEDED(rv)) {
      // Strip off the -bin suffix to get the shell script we should run; this is what Breakpad does
      nsCAutoString leafName;
      rv = executablePath->GetNativeLeafName(leafName);
      if (NS_SUCCEEDED(rv) && StringEndsWith(leafName, NS_LITERAL_CSTRING("-bin"))) {
        leafName.SetLength(leafName.Length() - strlen("-bin"));
        executablePath->SetNativeLeafName(leafName);
      }

      executablePath->GetNativePath(path);
      argv1 = (char*)(path.get());
    }
  }

  return NS_OK;
}
static bool HostIgnoredByProxy(const nsACString& aIgnore,
                               const nsACString& aHost)
{
  if (aIgnore.Equals(aHost, nsCaseInsensitiveCStringComparator()))
    return true;

  if (aIgnore.First() == '*' &&
      StringEndsWith(aHost, nsDependentCSubstring(aIgnore, 1),
                     nsCaseInsensitiveCStringComparator()))
    return true;

  int32_t mask = 128;
  nsReadingIterator<char> start;
  nsReadingIterator<char> slash;
  nsReadingIterator<char> end;
  aIgnore.BeginReading(start);
  aIgnore.BeginReading(slash);
  aIgnore.EndReading(end);
  if (FindCharInReadable('/', slash, end)) {
    ++slash;
    nsDependentCSubstring maskStr(slash, end);
    nsAutoCString maskStr2(maskStr);
    nsresult err;
    mask = maskStr2.ToInteger(&err);
    if (NS_FAILED(err)) {
      mask = 128;
    }
    --slash;
  } else {
    slash = end;
  }

  nsDependentCSubstring ignoreStripped(start, slash);
  PRIPv6Addr ignoreAddr, hostAddr;
  if (!ConvertToIPV6Addr(ignoreStripped, &ignoreAddr, &mask) ||
      !ConvertToIPV6Addr(aHost, &hostAddr, nullptr))
    return false;

  proxy_MaskIPv6Addr(ignoreAddr, mask);
  proxy_MaskIPv6Addr(hostAddr, mask);
  
  return memcmp(&ignoreAddr, &hostAddr, sizeof(PRIPv6Addr)) == 0;
}
Ejemplo n.º 25
0
Archivo: z05.c Proyecto: thektulu/lout
void ReadDatabaseDef(unsigned typ, OBJECT encl)
{ OBJECT symbs, t, fname;
  New(symbs, ACAT);
  t = LexGetToken();
  while( type(t)==CLOSURE || (type(t)==WORD && string(t)[0]==CH_SYMSTART) )
  { if( type(t) == CLOSURE )
    { Link(symbs, t);
    }
    else
    { Error(5, 7, "unknown or misspelt symbol %s", WARN, &fpos(t), string(t));
      Dispose(t);
    }
    t = LexGetToken();
  }
  if( type(t) != LBR )
  { Error(5, 8, "symbol name or %s expected here (%s declaration)",
      WARN, &fpos(t), KW_LBR, KW_DATABASE);
    Dispose(t);
    return;
  }
  if( Down(symbs) == symbs )
  { Error(5, 9, "symbol names missing in %s declaration",
      WARN, &fpos(t), KW_DATABASE);
  }
  fname = Parse(&t, encl, FALSE, FALSE);
  fname = ReplaceWithTidy(fname, ACAT_TIDY);
  if( !is_word(type(fname)) )
  { Error(5, 10, "name of %s file expected here", WARN, &fpos(fname),
      KW_DATABASE);
    DisposeObject(fname);
    return;
  }
  if( StringEndsWith(string(fname), DATA_SUFFIX) )
  { Error(5, 47, "%s suffix should be omitted in %s clause", WARN,
      &fpos(fname), DATA_SUFFIX, KW_DATABASE);
    DisposeObject(fname);
    return;
  }
  if( Down(symbs) != symbs )
    (void) DbLoad(fname, typ == DATABASE ? DATABASE_PATH : SYSDATABASE_PATH,
      TRUE, symbs, InMemoryDbIndexes);
} /* end ReadDatabaseDef */
static PRBool GConfIgnoreHost(const nsACString& aIgnore,
                              const nsACString& aHost)
{
  if (aIgnore.Equals(aHost, nsCaseInsensitiveCStringComparator()))
    return PR_TRUE;

  if (aIgnore.First() == '*' &&
      StringEndsWith(aHost, nsDependentCSubstring(aIgnore, 1),
                     nsCaseInsensitiveCStringComparator()))
    return PR_TRUE;

  PRInt32 mask = 128;
  nsReadingIterator<char> start;
  nsReadingIterator<char> slash;
  nsReadingIterator<char> end;
  aIgnore.BeginReading(start);
  aIgnore.BeginReading(slash);
  aIgnore.EndReading(end);
  if (FindCharInReadable('/', slash, end)) {
    ++slash;
    nsDependentCSubstring maskStr(slash, end);
    nsCAutoString maskStr2(maskStr);
    PRInt32 err;
    mask = maskStr2.ToInteger(&err);
    if (err != 0) {
      mask = 128;
    }
    --slash;
  } else {
    slash = end;
  }

  PRIPv6Addr ignoreAddr, hostAddr;
  if (!ConvertToIPV6Addr(aIgnore, &ignoreAddr) ||
      !ConvertToIPV6Addr(aHost, &hostAddr))
    return PR_FALSE;

  proxy_MaskIPv6Addr(ignoreAddr, mask);
  proxy_MaskIPv6Addr(hostAddr, mask);
  
  return memcmp(&ignoreAddr, &hostAddr, sizeof(PRIPv6Addr)) == 0;
}
bool
sbSecurityMixin::GetScopedName(nsTArray<nsCString> &aStringArray,
                               const nsAString &aMethodName,
                               nsAString &aScopedName)
{
    LOG(( "sbSecurityMixin::GetScopedName()"));
    bool approved = PR_FALSE;
    nsAutoString method;

    nsCOMPtr<nsIStringEnumerator> methods = new sbTArrayStringEnumerator(&aStringArray);
    NS_ENSURE_TRUE( methods, PR_FALSE );

    while ( NS_SUCCEEDED( methods->GetNext(method) ) ) {
        LOG(( "    -- checking method: %s", NS_ConvertUTF16toUTF8(method).get() ));
        if ( StringEndsWith( method, aMethodName ) ) {
            aScopedName = method;
            approved = PR_TRUE;
            break;
        }
    }
    return approved;
}
Ejemplo n.º 28
0
nsresult
inCSSValueSearch::SearchStyleValue(const nsAFlatString& aValue, nsIURI* aBaseURL)
{
  if (StringBeginsWith(aValue, NS_LITERAL_STRING("url(")) &&
      StringEndsWith(aValue, NS_LITERAL_STRING(")"))) {
    const nsASingleFragmentString &url =
      Substring(aValue, 4, aValue.Length() - 5);
    // XXXldb Need to do more with |mReturnRelativeURLs|, perhaps?
    nsCOMPtr<nsIURI> uri;
    nsresult rv = NS_NewURI(getter_AddRefs(uri), url, nsnull, aBaseURL);
    NS_ENSURE_SUCCESS(rv, rv);
    nsCAutoString spec;
    uri->GetSpec(spec);
    nsAutoString *result = new NS_ConvertUTF8toUTF16(spec);
    if (mReturnRelativeURLs)
      EqualizeURL(result);
    mResults->AppendElement(result);
    ++mResultCount;
  }

  return NS_OK;
}
void nsMsgServiceProviderService::LoadISPFilesFromDir(nsIFile* aDir)
{
  nsresult rv;

  bool check = false;
  rv = aDir->Exists(&check);
  if (NS_FAILED(rv) || !check)
    return;

  rv = aDir->IsDirectory(&check);
  if (NS_FAILED(rv) || !check)
    return;

  nsCOMPtr<nsISimpleEnumerator> e;
  rv = aDir->GetDirectoryEntries(getter_AddRefs(e));
  if (NS_FAILED(rv))
    return;

  nsCOMPtr<nsIDirectoryEnumerator> files(do_QueryInterface(e));
  if (!files)
    return;

  // we only care about the .rdf files in this directory
  nsCOMPtr<nsIFile> file;
  while (NS_SUCCEEDED(files->GetNextFile(getter_AddRefs(file))) && file) {
    nsAutoString leafName;
    file->GetLeafName(leafName);
    if (!StringEndsWith(leafName, NS_LITERAL_STRING(".rdf")))
      continue;

    nsAutoCString urlSpec;
    rv = NS_GetURLSpecFromFile(file, urlSpec);
    if (NS_SUCCEEDED(rv))
      LoadDataSource(urlSpec.get());
  }
}
Ejemplo n.º 30
0
  /* ovec: command line args assumed to contain all the options for the program
   * options must be in the form of key= value or key=value NOT key = value
   * both key and value may contain spaces but they have to be quoted at the 
   * command line for this to work
   */
  void CmdLineOptionsToYaml(const vector<string> &ovec, Node &options)
  {
    VecS key_val_pairs;

    StlFor(i, ovec)
    {
      if (!StringContains(ovec[i], '='))
        throw runtime_error("Unexpected token in options: " + ovec[i]);

      string key;
      string value = "";

      if (StringEndsWith(ovec[i], '='))
      {
        key = ovec[i].substr(0, ovec[i].size() - 1);

        if (i < ovec.size() - 1 && !StringContains(ovec[i+1], '='))
        {
          value = ovec[i+1];
          ++i;
        }
      }
      else // the = must be in middle like foo=bar
      {
        size_t eq_pos = ovec[i].find('=');
        key = ovec[i].substr(0, eq_pos);
        value = ovec[i].substr(eq_pos + 1);
      }

      key_val_pairs.push_back(key + ": " + value);
    }

    string yaml_str = "{" + JoinFields(key_val_pairs, ", ") + "}";

    YAML::Parse(yaml_str, options);
  }