Beispiel #1
0
  bool
  ParseHeader(nsACString::const_iterator& aStart,
              nsACString::const_iterator& aEnd,
              bool* aWasEmptyHeader)
  {
    nsAutoCString headerName, headerValue;
    if (!FetchUtil::ExtractHeader(aStart, aEnd,
                                  headerName, headerValue,
                                  aWasEmptyHeader)) {
      return false;
    }
    if (*aWasEmptyHeader) {
      return true;
    }

    if (headerName.LowerCaseEqualsLiteral("content-disposition")) {
      nsCCharSeparatedTokenizer tokenizer(headerValue, ';');
      bool seenFormData = false;
      while (tokenizer.hasMoreTokens()) {
        const nsDependentCSubstring& token = tokenizer.nextToken();
        if (token.IsEmpty()) {
          continue;
        }

        if (token.EqualsLiteral("form-data")) {
          seenFormData = true;
          continue;
        }

        if (seenFormData &&
            StringBeginsWith(token, NS_LITERAL_CSTRING("name="))) {
          mName = StringTail(token, token.Length() - 5);
          mName.Trim(" \"");
          continue;
        }

        if (seenFormData &&
            StringBeginsWith(token, NS_LITERAL_CSTRING("filename="))) {
          mFilename = StringTail(token, token.Length() - 9);
          mFilename.Trim(" \"");
          continue;
        }
      }

      if (mName.IsVoid()) {
        // Could not parse a valid entry name.
        return false;
      }
    } else if (headerName.LowerCaseEqualsLiteral("content-type")) {
      mContentType = headerValue;
    }

    return true;
  }
Beispiel #2
0
/* parses LocalMessageURI
 * mailbox-message://folder1/folder2#123?header=none or
 * mailbox-message://folder1/folder2#1234&part=1.2
 *
 * puts folder URI in folderURI (mailbox://folder1/folder2)
 * message key number in key
 */
nsresult nsParseLocalMessageURI(const char* uri,
                                nsCString& folderURI,
                                PRUint32 *key)
{
  if(!key)
    return NS_ERROR_NULL_POINTER;

  nsCAutoString uriStr(uri);
  PRInt32 keySeparator = uriStr.FindChar('#');
  if(keySeparator != -1)
  {
    PRInt32 keyEndSeparator = MsgFindCharInSet(uriStr, "?&", keySeparator);
    folderURI = StringHead(uriStr, keySeparator);
    folderURI.Cut(7, 8);    // cut out the -message part of mailbox-message:

    nsCAutoString keyStr;
    if (keyEndSeparator != -1)
      keyStr = Substring(uriStr, keySeparator + 1,
                         keyEndSeparator - (keySeparator + 1));
    else
      keyStr = StringTail(uriStr, uriStr.Length() - (keySeparator + 1));

    *key = (PRUint32) ParseUint64Str(keyStr.get());
    return NS_OK;
  }
  return NS_ERROR_FAILURE;

}
Beispiel #3
0
NS_IMETHODIMP AsyncDeleteIconFromDisk::Run()
{
  // Construct the parent path of the passed in path
  nsCOMPtr<nsIFile> icoFile = do_CreateInstance("@mozilla.org/file/local;1");
  NS_ENSURE_TRUE(icoFile, NS_ERROR_FAILURE);
  nsresult rv = icoFile->InitWithPath(mIconPath);
  NS_ENSURE_SUCCESS(rv, rv);

  // Check if the cached ICO file exists
  bool exists;
  rv = icoFile->Exists(&exists);
  NS_ENSURE_SUCCESS(rv, rv);

  // Check that we aren't deleting some arbitrary file that is not an icon
  if (StringTail(mIconPath, 4).LowerCaseEqualsASCII(".ico")) {
    // Check if the cached ICO file exists
    bool exists;
    if (NS_FAILED(icoFile->Exists(&exists)) || !exists)
      return NS_ERROR_FAILURE;

    // We found an ICO file that exists, so we should remove it
    icoFile->Remove(false);
  }

  return NS_OK;
}
Beispiel #4
0
nsresult nsEudoraWin32::ScanAddressDir( nsIFile *pDir, nsISupportsArray *pArray, nsIImportService *impSvc)
{
  bool hasMore;
  nsCOMPtr<nsISimpleEnumerator> directoryEnumerator;
  nsresult rv = pDir->GetDirectoryEntries(getter_AddRefs(directoryEnumerator));
  NS_ENSURE_SUCCESS(rv, rv);

  nsCOMPtr <nsILocalFile> pLocalFile = do_QueryInterface(pDir, &rv);
  NS_ENSURE_SUCCESS(rv, rv);

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

  bool found = false;

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

    if (NS_SUCCEEDED( rv))
    {
      rv = entry->GetNativeLeafName(fName);
      if (NS_SUCCEEDED( rv) && !fName.IsEmpty())
      {
        if (fName.Length() > 4)
        {
          ext = StringTail(fName, 4);
          name = StringHead(fName, fName.Length() - 4);
        }
        else
        {
          ext.Truncate();
          name = fName;
        }
        ToLowerCase(ext);
        if (ext.EqualsLiteral(".txt"))
        {
          isFile = false;
          entry->IsFile( &isFile);
          if (isFile)
          {
            rv = FoundAddressBook( entry, nsnull, pArray, impSvc);
            if (NS_FAILED( rv))
              return( rv);
          }
        }
      }
    }
  }

  return( rv);
}
nsresult
nsRDFXMLSerializer::RegisterQName(nsIRDFResource* aResource)
{
    nsAutoCString uri, qname;
    aResource->GetValueUTF8(uri);

    nsNameSpaceMap::const_iterator iter = mNameSpaces.GetNameSpaceOf(uri);
    if (iter != mNameSpaces.last()) {
        NS_ENSURE_TRUE(iter->mPrefix, NS_ERROR_UNEXPECTED);
        iter->mPrefix->ToUTF8String(qname);
        qname.Append(':');
        qname += StringTail(uri, uri.Length() - iter->mURI.Length());
        mQNames.Put(aResource, qname);
        return NS_OK;
    }

    // Okay, so we don't have it in our map. Try to make one up. This
    // is very bogus.
    int32_t i = uri.RFindChar('#'); // first try a '#'
    if (i == -1) {
        i = uri.RFindChar('/');
        if (i == -1) {
            // Okay, just punt and assume there is _no_ namespace on
            // this thing...
            mQNames.Put(aResource, uri);
            return NS_OK;
        }
    }

    // Take whatever is to the right of the '#' or '/' and call it the
    // local name, make up a prefix.
    nsCOMPtr<nsIAtom> prefix = EnsureNewPrefix();
    mNameSpaces.Put(StringHead(uri, i+1), prefix);
    prefix->ToUTF8String(qname);
    qname.Append(':');
    qname += StringTail(uri, uri.Length() - (i + 1));

    mQNames.Put(aResource, qname);
    return NS_OK;
}
NS_IMETHODIMP
nsFileProtocolHandler::ReadURLFile(nsIFile* aFile, nsIURI** aURI)
{
// IUniformResourceLocator isn't supported by VC5 (bless its little heart)
#if _MSC_VER < 1200 || defined (WINCE)
    return NS_ERROR_NOT_AVAILABLE;
#else
    nsAutoString path;
    nsresult rv = aFile->GetPath(path);
    if (NS_FAILED(rv))
        return rv;

    if (path.Length() < 4)
        return NS_ERROR_NOT_AVAILABLE;
    if (!StringTail(path, 4).LowerCaseEqualsLiteral(".url"))
        return NS_ERROR_NOT_AVAILABLE;

    HRESULT result;

    rv = NS_ERROR_NOT_AVAILABLE;

    IUniformResourceLocator* urlLink = nsnull;
    result = ::CoCreateInstance(CLSID_InternetShortcut, NULL, CLSCTX_INPROC_SERVER,
                                IID_IUniformResourceLocator, (void**)&urlLink);
    if (SUCCEEDED(result) && urlLink) {
        IPersistFile* urlFile = nsnull;
        result = urlLink->QueryInterface(IID_IPersistFile, (void**)&urlFile);
        if (SUCCEEDED(result) && urlFile) {
            result = urlFile->Load(path.get(), STGM_READ);
            if (SUCCEEDED(result) ) {
                LPSTR lpTemp = nsnull;

                // The URL this method will give us back seems to be already
                // escaped. Hence, do not do escaping of our own.
                result = urlLink->GetURL(&lpTemp);
                if (SUCCEEDED(result) && lpTemp) {
                    rv = NS_NewURI(aURI, lpTemp);

                    // free the string that GetURL alloc'd
                    CoTaskMemFree(lpTemp);
                }
            }
            urlFile->Release();
        }
        urlLink->Release();
    }
    return rv;

#endif //_MSC_VER < 1200 || defined (WINCE)
}
Beispiel #7
0
/* void open (in nsIColorPickerShownCallback aColorPickerShownCallback); */
NS_IMETHODIMP nsColorPicker::Open(nsIColorPickerShownCallback *aColorPickerShownCallback)
{

  // Input color string should be 7 length (i.e. a string representing a valid
  // simple color)
  if (mInitialColor.Length() != 7) {
    return NS_ERROR_FAILURE;
  }

  const nsAString& withoutHash  = StringTail(mInitialColor, 6);
  nscolor color;
  if (!NS_HexToRGB(withoutHash, &color)) {
    return NS_ERROR_FAILURE;
  }

  GdkColor color_gdk = convertToGdkColor(color);

  if (mCallback) {
    // It means Open has already been called: this is not allowed
    NS_WARNING("mCallback is already set. Open called twice?");
    return NS_ERROR_FAILURE;
  }
  mCallback = aColorPickerShownCallback;

  nsXPIDLCString title;
  title.Adopt(ToNewUTF8String(mTitle));
  GtkWidget *color_chooser = gtk_color_selection_dialog_new(title);

  GtkWindow *parent_window = GTK_WINDOW(mParentWidget->GetNativeData(NS_NATIVE_SHELLWIDGET));
  if (parent_window) {
    GtkWindow *window = GTK_WINDOW(color_chooser);
    gtk_window_set_transient_for(window, parent_window);
    gtk_window_set_destroy_with_parent(window, TRUE);
  }

  gtk_color_selection_set_current_color(WidgetGetColorSelection(color_chooser),
                                        &color_gdk);

  NS_ADDREF_THIS();
  g_signal_connect(WidgetGetColorSelection(color_chooser), "color-changed",
                   G_CALLBACK(OnColorChanged), this);
  g_signal_connect(color_chooser, "response", G_CALLBACK(OnResponse), this);
  g_signal_connect(color_chooser, "destroy", G_CALLBACK(OnDestroy), this);
  gtk_widget_show(color_chooser);

  return NS_OK;
}
Beispiel #8
0
NS_IMETHODIMP nsAbLDAPDirectory::Init(const char* aURI)
{
    // We need to ensure that the m_DirPrefId is initialized properly
    nsCAutoString uri(aURI);

    // Find the first ? (of the search params) if there is one.
    // We know we can start at the end of the moz-abldapdirectory:// because
    // that's the URI we should have been passed.
    PRInt32 searchCharLocation = uri.FindChar('?', kLDAPDirectoryRootLen);

    if (searchCharLocation == -1)
        m_DirPrefId = StringTail(uri, uri.Length() - kLDAPDirectoryRootLen);
    else
        m_DirPrefId = Substring(uri, kLDAPDirectoryRootLen, searchCharLocation - kLDAPDirectoryRootLen);

    return nsAbDirectoryRDFResource::Init(aURI);
}
Beispiel #9
0
nsresult nsEudoraWin32::FoundAddressBook( nsIFile *file, const PRUnichar *pName, nsISupportsArray *pArray, nsIImportService *impSvc)
{
  nsCOMPtr<nsIImportABDescriptor> desc;
  nsISupports *  pInterface;
  nsString name;
  nsresult rv;

  if (pName)
    name = pName;
  else {
    nsAutoString leaf;
    rv = file->GetLeafName(leaf);
    if (NS_FAILED( rv))
      return( rv);
    if (leaf.IsEmpty())
      return( NS_ERROR_FAILURE);
    nsString  tStr;
    tStr = StringTail(leaf, 4);
    if (tStr.LowerCaseEqualsLiteral(".txt")  || tStr.LowerCaseEqualsLiteral(".nnt"))
      leaf.SetLength(leaf.Length() - 4);
  }

  nsCOMPtr<nsILocalFile> fileLoc = do_QueryInterface(file, &rv);
  NS_ENSURE_SUCCESS(rv, rv);

  rv = impSvc->CreateNewABDescriptor( getter_AddRefs( desc));
  if (NS_SUCCEEDED( rv))
  {
    PRInt64 sz = 0;
    file->GetFileSize( &sz);
    desc->SetPreferredName(name);
    desc->SetSize((PRUint32) sz);
    desc->SetAbFile(fileLoc);
    rv = desc->QueryInterface( kISupportsIID, (void **) &pInterface);
    pArray->AppendElement( pInterface);
    pInterface->Release();
  }
  if (NS_FAILED( rv))
  {
    IMPORT_LOG0( "*** Error creating address book descriptor for eudora\n");
    return( rv);
  }

  return( NS_OK);
}
Beispiel #10
0
// Ensures that we have no old ICO files left in the jump list cache
nsresult JumpListBuilder::RemoveIconCacheForAllItems() 
{
  // Construct the path of our jump list cache
  nsCOMPtr<nsIFile> jumpListCacheDir;
  nsresult rv = NS_GetSpecialDirectory("ProfLDS", 
                                       getter_AddRefs(jumpListCacheDir));
  NS_ENSURE_SUCCESS(rv, rv);
  rv = jumpListCacheDir->AppendNative(nsDependentCString(
                         mozilla::widget::FaviconHelper::kJumpListCacheDir));
  NS_ENSURE_SUCCESS(rv, rv);
  nsCOMPtr<nsISimpleEnumerator> entries;
  rv = jumpListCacheDir->GetDirectoryEntries(getter_AddRefs(entries));
  NS_ENSURE_SUCCESS(rv, rv);
  
  // Loop through each directory entry and remove all ICO files found
  do {
    bool hasMore = false;
    if (NS_FAILED(entries->HasMoreElements(&hasMore)) || !hasMore)
      break;

    nsCOMPtr<nsISupports> supp;
    if (NS_FAILED(entries->GetNext(getter_AddRefs(supp))))
      break;

    nsCOMPtr<nsIFile> currFile(do_QueryInterface(supp));
    nsAutoString path;
    if (NS_FAILED(currFile->GetPath(path)))
      continue;

    int32_t len = path.Length();
    if (StringTail(path, 4).LowerCaseEqualsASCII(".ico")) {
      // Check if the cached ICO file exists
      bool exists;
      if (NS_FAILED(currFile->Exists(&exists)) || !exists)
        continue;

      // We found an ICO file that exists, so we should remove it
      currFile->Remove(false);
    }
  } while(true);

  return NS_OK;
}
NS_IMETHODIMP nsAbBSDirectory::CreateDirectoryByURI(const nsAString &aDisplayName,
                                                    const nsACString &aURI)
{
  nsresult rv = EnsureInitialized();
  NS_ENSURE_SUCCESS(rv, rv);

  nsCString fileName;
  if (StringBeginsWith(aURI, NS_LITERAL_CSTRING(kMDBDirectoryRoot)))
    fileName = StringTail(aURI, aURI.Length() - kMDBDirectoryRootLen);

  DIR_Server * server = nsnull;
  rv = DIR_AddNewAddressBook(aDisplayName, fileName, aURI,
                             PABDirectory, EmptyCString(), &server);
  NS_ENSURE_SUCCESS(rv,rv);

  rv = CreateDirectoriesFromFactory(aURI, server, PR_TRUE /* notify */);
  NS_ENSURE_SUCCESS(rv,rv);
	return rv;
}
/* void init (in nsIDOMWindow parent, in AString title, in short mode); */
NS_IMETHODIMP nsColorPicker::Init(nsIDOMWindow *parent,
                                  const nsAString& title,
                                  const nsAString& initialColor)
{
  // Input color string should be 7 length (i.e. a string representing a valid
  // simple color)
  if (initialColor.Length() != 7) {
    return NS_ERROR_INVALID_ARG;
  }

  const nsAString& withoutHash  = StringTail(initialColor, 6);
  nscolor color;
  if (!NS_HexToRGB(withoutHash, &color)) {
    return NS_ERROR_INVALID_ARG;
  }

  mDefaultColor = convertToGdkColor(color);

  mParentWidget = mozilla::widget::WidgetUtils::DOMWindowToWidget(parent);
  mTitle.Assign(title);

  return NS_OK;
}
Beispiel #13
0
  bool
  ParseHeader(nsACString::const_iterator& aStart,
              nsACString::const_iterator& aEnd,
              bool* aWasEmptyHeader)
  {
    MOZ_ASSERT(aWasEmptyHeader);
    // Set it to a valid value here so we don't forget later.
    *aWasEmptyHeader = false;

    const char* beginning = aStart.get();
    nsACString::const_iterator end(aEnd);
    if (!FindCRLF(aStart, end)) {
      return false;
    }

    if (aStart.get() == beginning) {
      *aWasEmptyHeader = true;
      return true;
    }

    nsAutoCString header(beginning, aStart.get() - beginning);

    nsACString::const_iterator headerStart, headerEnd;
    header.BeginReading(headerStart);
    header.EndReading(headerEnd);
    if (!FindCharInReadable(':', headerStart, headerEnd)) {
      return false;
    }

    nsAutoCString headerName(StringHead(header, headerStart.size_backward()));
    headerName.CompressWhitespace();
    if (!NS_IsValidHTTPToken(headerName)) {
      return false;
    }

    nsAutoCString headerValue(Substring(++headerStart, headerEnd));
    if (!NS_IsReasonableHTTPHeaderValue(headerValue)) {
      return false;
    }
    headerValue.CompressWhitespace();

    if (headerName.LowerCaseEqualsLiteral("content-disposition")) {
      nsCCharSeparatedTokenizer tokenizer(headerValue, ';');
      bool seenFormData = false;
      while (tokenizer.hasMoreTokens()) {
        const nsDependentCSubstring& token = tokenizer.nextToken();
        if (token.IsEmpty()) {
          continue;
        }

        if (token.EqualsLiteral("form-data")) {
          seenFormData = true;
          continue;
        }

        if (seenFormData &&
            StringBeginsWith(token, NS_LITERAL_CSTRING("name="))) {
          mName = StringTail(token, token.Length() - 5);
          mName.Trim(" \"");
          continue;
        }

        if (seenFormData &&
            StringBeginsWith(token, NS_LITERAL_CSTRING("filename="))) {
          mFilename = StringTail(token, token.Length() - 9);
          mFilename.Trim(" \"");
          continue;
        }
      }

      if (mName.IsVoid()) {
        // Could not parse a valid entry name.
        return false;
      }
    } else if (headerName.LowerCaseEqualsLiteral("content-type")) {
      mContentType = headerValue;
    }

    return true;
  }
NS_IMETHODIMP
mozJSComponentLoader::LoadModule(nsILocalFile* aComponentFile,
                                 nsIModule* *aResult)
{
    nsresult rv;

    nsCAutoString leafName;
    aComponentFile->GetNativeLeafName(leafName);
    if (!StringTail(leafName, 3).LowerCaseEqualsLiteral(".js"))
        return NS_ERROR_INVALID_ARG;

    if (!mInitialized) {
        rv = ReallyInit();
        if (NS_FAILED(rv))
            return rv;
    }

    nsCOMPtr<nsIHashable> lfhash(do_QueryInterface(aComponentFile));
    if (!lfhash) {
        NS_ERROR("nsLocalFile not implementing nsIHashable");
        return NS_NOINTERFACE;
    }

    ModuleEntry* mod;
    if (mModules.Get(lfhash, &mod)) {
        NS_ASSERTION(mod->module, "Bad hashtable data!");
        NS_ADDREF(*aResult = mod->module);
        return NS_OK;
    }

    nsAutoPtr<ModuleEntry> entry(new ModuleEntry);
    if (!entry)
        return NS_ERROR_OUT_OF_MEMORY;

    rv = GlobalForLocation(aComponentFile, &entry->global, &entry->location);
    if (NS_FAILED(rv)) {
#ifdef DEBUG_shaver
        fprintf(stderr, "GlobalForLocation failed!\n");
#endif
        return rv;
    }

    nsCOMPtr<nsIXPConnect> xpc = do_GetService(kXPConnectServiceContractID,
                                               &rv);
    if (NS_FAILED(rv))
        return rv;

    nsCOMPtr<nsIComponentManager> cm;
    rv = NS_GetComponentManager(getter_AddRefs(cm));
    if (NS_FAILED(rv))
        return rv;

    JSCLContextHelper cx(mContext);

    JSObject* cm_jsobj;
    nsCOMPtr<nsIXPConnectJSObjectHolder> cm_holder;
    rv = xpc->WrapNative(cx, entry->global, cm, 
                         NS_GET_IID(nsIComponentManager),
                         getter_AddRefs(cm_holder));

    if (NS_FAILED(rv)) {
#ifdef DEBUG_shaver
        fprintf(stderr, "WrapNative(%p,%p,nsIComponentManager) failed: %x\n",
                (void *)(JSContext*)cx, (void *)mCompMgr, rv);
#endif
        return rv;
    }

    rv = cm_holder->GetJSObject(&cm_jsobj);
    if (NS_FAILED(rv)) {
#ifdef DEBUG_shaver
        fprintf(stderr, "GetJSObject of ComponentManager failed\n");
#endif
        return rv;
    }

    JSObject* file_jsobj;
    nsCOMPtr<nsIXPConnectJSObjectHolder> file_holder;
    rv = xpc->WrapNative(cx, entry->global, aComponentFile, 
                         NS_GET_IID(nsIFile),
                         getter_AddRefs(file_holder));

    if (NS_FAILED(rv)) {
        return rv;
    }

    rv = file_holder->GetJSObject(&file_jsobj);
    if (NS_FAILED(rv)) {
        return rv;
    }

    JSCLAutoErrorReporterSetter aers(cx, mozJSLoaderErrorReporter);

    jsval argv[2], retval, NSGetModule_val;

    if (!JS_GetProperty(cx, entry->global, "NSGetModule", &NSGetModule_val) ||
        JSVAL_IS_VOID(NSGetModule_val)) {
        return NS_ERROR_FAILURE;
    }

    if (JS_TypeOfValue(cx, NSGetModule_val) != JSTYPE_FUNCTION) {
        nsCAutoString path;
        aComponentFile->GetNativePath(path);

        JS_ReportError(cx, "%s has NSGetModule property that is not a function",
                       path.get());
        return NS_ERROR_FAILURE;
    }
    
    argv[0] = OBJECT_TO_JSVAL(cm_jsobj);
    argv[1] = OBJECT_TO_JSVAL(file_jsobj);
    if (!JS_CallFunctionValue(cx, entry->global, NSGetModule_val,
                              2, argv, &retval)) {
        return NS_ERROR_FAILURE;
    }

#ifdef DEBUG_shaver_off
    JSString *s = JS_ValueToString(cx, retval);
    fprintf(stderr, "mJCL: %s::NSGetModule returned %s\n",
            registryLocation, JS_GetStringBytes(s));
#endif

    JSObject *jsModuleObj;
    if (!JS_ValueToObject(cx, retval, &jsModuleObj)) {
        /* XXX report error properly */
        return NS_ERROR_FAILURE;
    }

    rv = xpc->WrapJS(cx, jsModuleObj,
                     NS_GET_IID(nsIModule), getter_AddRefs(entry->module));
    if (NS_FAILED(rv)) {
        /* XXX report error properly */
#ifdef DEBUG
        fprintf(stderr, "mJCL: couldn't get nsIModule from jsval\n");
#endif
        return rv;
    }

    // Cache this module for later
    if (!mModules.Put(lfhash, entry))
        return NS_ERROR_OUT_OF_MEMORY;

    NS_ADDREF(*aResult = entry->module);

    // The hash owns the ModuleEntry now, forget about it
    entry.forget();

    return NS_OK;
}
Beispiel #15
0
bool nsEudoraWin32::FindMimeIniFile( nsIFile *pFile)
{
  bool hasMore;
  nsCOMPtr<nsISimpleEnumerator> directoryEnumerator;
  nsresult rv = pFile->GetDirectoryEntries(getter_AddRefs(directoryEnumerator));
  NS_ENSURE_SUCCESS(rv, rv);

  nsCOMPtr <nsILocalFile> pLocalFile = do_QueryInterface(pFile, &rv);
  NS_ENSURE_SUCCESS(rv, rv);

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

  bool found = false;

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


    if (NS_SUCCEEDED( rv))
    {
      rv = entry->GetNativeLeafName(fName);
      if (NS_SUCCEEDED( rv) && !fName.IsEmpty())
      {
        if (fName.Length() > 4)
        {
          ext = StringTail(fName, 4);
          name = StringHead(fName, fName.Length() - 4);
        }
        else
        {
          ext.Truncate();
          name = fName;
        }
        ToLowerCase(ext);
        if (ext.EqualsLiteral(".ini"))
        {
          isFile = false;
          entry->IsFile( &isFile);
          if (isFile)
          {
            if (found)
            {
              // which one of these files is newer?
              PRInt64  modDate1, modDate2;
              entry->GetLastModifiedTime( &modDate2);
              pFile->GetLastModifiedTime( &modDate1);
              if (modDate2 > modDate1)
                                  pLocalFile->InitWithFile( entry);
            }
            else
            {
              pLocalFile->InitWithFile( entry);
              found = true;
            }
          }
        }
      }
    }
  }
  return found;
}
Beispiel #16
0
nsresult nsEudoraWin32::IterateMailDir( nsIFile *pFolder, nsISupportsArray *pArray, nsIImportService *pImport)
{
  bool hasMore;
  nsCOMPtr<nsISimpleEnumerator> directoryEnumerator;
  nsresult rv = pFolder->GetDirectoryEntries(getter_AddRefs(directoryEnumerator));
  NS_ENSURE_SUCCESS(rv, rv);

  directoryEnumerator->HasMoreElements(&hasMore);
  bool              isFolder;
  bool              isFile;
  nsCOMPtr<nsIFile> entry;
  nsCString         fName;
  nsCString         ext;
  nsCString         name;

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

    if (NS_SUCCEEDED( rv))
    {
      rv = entry->GetNativeLeafName(fName);
      if (NS_SUCCEEDED( rv) && !fName.IsEmpty())
      {
        if (fName.Length() > 4)
        {
          ext = StringTail(fName, 4);
          name = StringHead(fName, fName.Length() - 4);
        }
        else
        {
          ext.Truncate();
          name = fName;
        }
        ToLowerCase(ext);
        if (ext.EqualsLiteral(".fol"))
        {
          isFolder = false;
          entry->IsDirectory( &isFolder);
          if (isFolder)
          {
            // add the folder
            rv = FoundMailFolder( entry, name.get(), pArray, pImport);
            if (NS_SUCCEEDED( rv))
            {
              rv = ScanMailDir( entry, pArray, pImport);
              if (NS_FAILED( rv))
                IMPORT_LOG0( "*** Error scanning mail directory\n");
            }
          }
        }
        else if (ext.EqualsLiteral(".mbx"))
        {
          isFile = false;
          entry->IsFile( &isFile);
          if (isFile)
            rv = FoundMailbox( entry, name.get(), pArray, pImport);
        }
      }
    }
  }
  return( rv);
}
Beispiel #17
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;
}
NS_IMETHODIMP nsAbMDBDirectory::Init(const char *aUri)
{
  // We need to ensure  that the m_DirPrefId is initialized properly
  nsDependentCString uri(aUri);

  if (uri.Find("MailList") != -1)
    m_IsMailList = PR_TRUE;

  // Mailing lists don't have their own prefs.
  if (m_DirPrefId.IsEmpty() && !m_IsMailList)
  {
    // Find the first ? (of the search params) if there is one.
    // We know we can start at the end of the moz-abmdbdirectory:// because
    // that's the URI we should have been passed.
    PRInt32 searchCharLocation = uri.FindChar('?', kMDBDirectoryRootLen);

    nsCAutoString filename;

    // extract the filename from the uri.
    if (searchCharLocation == -1)
      filename = StringTail(uri, uri.Length() - kMDBDirectoryRootLen);
    else
      filename = Substring(uri, kMDBDirectoryRootLen, searchCharLocation - kMDBDirectoryRootLen);

    // Get the pref servers and the address book directory branch
    nsresult rv;
    nsCOMPtr<nsIPrefService> prefService(do_GetService(NS_PREFSERVICE_CONTRACTID, &rv));
    NS_ENSURE_SUCCESS(rv, rv);

    nsCOMPtr<nsIPrefBranch> prefBranch;
    rv = prefService->GetBranch(NS_LITERAL_CSTRING(PREF_LDAP_SERVER_TREE_NAME ".").get(),
                                getter_AddRefs(prefBranch));
    NS_ENSURE_SUCCESS(rv, rv);

    char** childArray;
    PRUint32 childCount, i;
    PRInt32 dotOffset;
    nsCString childValue;
    nsDependentCString child;

    rv = prefBranch->GetChildList("", &childCount, &childArray);
    NS_ENSURE_SUCCESS(rv, rv);

    for (i = 0; i < childCount; ++i)
    {
      child.Assign(childArray[i]);

      if (StringEndsWith(child, NS_LITERAL_CSTRING(".filename")))
      {
        if (NS_SUCCEEDED(prefBranch->GetCharPref(child.get(),
                                                 getter_Copies(childValue))))
        {
          if (childValue == filename)
          {
            dotOffset = child.RFindChar('.');
            if (dotOffset != -1)
            {
              nsCAutoString prefName(StringHead(child, dotOffset));
              m_DirPrefId.AssignLiteral(PREF_LDAP_SERVER_TREE_NAME ".");
              m_DirPrefId.Append(prefName);
            }
          }
        }
      }
    }     
    NS_FREE_XPCOM_ALLOCATED_POINTER_ARRAY(childCount, childArray);

    NS_ASSERTION(!m_DirPrefId.IsEmpty(),
                 "Error, Could not set m_DirPrefId in nsAbMDBDirectory::Init");
  }

  return nsAbDirectoryRDFResource::Init(aUri);
}
Beispiel #19
0
/* nsIURI createFixupURI (in nsAUTF8String aURIText, in unsigned long aFixupFlags); */
NS_IMETHODIMP
nsDefaultURIFixup::CreateFixupURI(const nsACString& aStringURI, PRUint32 aFixupFlags, nsIURI **aURI)
{
    NS_ENSURE_ARG(!aStringURI.IsEmpty());
    NS_ENSURE_ARG_POINTER(aURI);

    nsresult rv;
    *aURI = nsnull;

    nsCAutoString uriString(aStringURI);
    uriString.Trim(" ");  // Cleanup the empty spaces that might be on each end.

    // Eliminate embedded newlines, which single-line text fields now allow:
    uriString.StripChars("\r\n");

    NS_ENSURE_TRUE(!uriString.IsEmpty(), NS_ERROR_FAILURE);

    nsCOMPtr<nsIIOService> ioService = do_GetService(NS_IOSERVICE_CONTRACTID, &rv);
    NS_ENSURE_SUCCESS(rv, rv);
    nsCAutoString scheme;
    ioService->ExtractScheme(aStringURI, scheme);
    
    // View-source is a pseudo scheme. We're interested in fixing up the stuff
    // after it. The easiest way to do that is to call this method again with the
    // "view-source:" lopped off and then prepend it again afterwards.

    if (scheme.LowerCaseEqualsLiteral("view-source"))
    {
        nsCOMPtr<nsIURI> uri;
        PRUint32 newFixupFlags = aFixupFlags & ~FIXUP_FLAG_ALLOW_KEYWORD_LOOKUP;

        rv =  CreateFixupURI(Substring(uriString,
                                       sizeof("view-source:") - 1,
                                       uriString.Length() -
                                         (sizeof("view-source:") - 1)),
                             newFixupFlags, getter_AddRefs(uri));
        if (NS_FAILED(rv))
            return NS_ERROR_FAILURE;
        nsCAutoString spec;
        uri->GetSpec(spec);
        uriString.Assign(NS_LITERAL_CSTRING("view-source:") + spec);
    }
    else {
        // Check for if it is a file URL
        FileURIFixup(uriString, aURI);
        if(*aURI)
            return NS_OK;

#if defined(XP_WIN) || defined(XP_OS2)
        // Not a file URL, so translate '\' to '/' for convenience in the common protocols
        // e.g. catch
        //
        //   http:\\broken.com\address
        //   http:\\broken.com/blah
        //   broken.com\blah
        //
        // Code will also do partial fix up the following urls
        //
        //   http:\\broken.com\address/somewhere\image.jpg (stops at first forward slash)
        //   http:\\broken.com\blah?arg=somearg\foo.jpg (stops at question mark)
        //   http:\\broken.com#odd\ref (stops at hash)
        //  
        if (scheme.IsEmpty() ||
            scheme.LowerCaseEqualsLiteral("http") ||
            scheme.LowerCaseEqualsLiteral("https") ||
            scheme.LowerCaseEqualsLiteral("ftp"))
        {
            // Walk the string replacing backslashes with forward slashes until
            // the end is reached, or a question mark, or a hash, or a forward
            // slash. The forward slash test is to stop before trampling over
            // URIs which legitimately contain a mix of both forward and
            // backward slashes.
            nsCAutoString::iterator start;
            nsCAutoString::iterator end;
            uriString.BeginWriting(start);
            uriString.EndWriting(end);
            while (start != end) {
                if (*start == '?' || *start == '#' || *start == '/')
                    break;
                if (*start == '\\')
                    *start = '/';
                ++start;
            }
        }
#endif
    }

    // For these protocols, use system charset instead of the default UTF-8,
    // if the URI is non ASCII.
    PRBool bAsciiURI = IsASCII(uriString);
    PRBool bUseNonDefaultCharsetForURI =
                        !bAsciiURI &&
                        (scheme.IsEmpty() ||
                         scheme.LowerCaseEqualsLiteral("http") ||
                         scheme.LowerCaseEqualsLiteral("https") ||
                         scheme.LowerCaseEqualsLiteral("ftp") ||
                         scheme.LowerCaseEqualsLiteral("file"));

    // Now we need to check whether "scheme" is something we don't
    // really know about.
    nsCOMPtr<nsIProtocolHandler> ourHandler, extHandler;
    
    ioService->GetProtocolHandler(scheme.get(), getter_AddRefs(ourHandler));
    extHandler = do_GetService(NS_NETWORK_PROTOCOL_CONTRACTID_PREFIX"default");
    
    if (ourHandler != extHandler || !PossiblyHostPortUrl(uriString)) {
        // Just try to create an URL out of it
        rv = NS_NewURI(aURI, uriString,
                       bUseNonDefaultCharsetForURI ? GetCharsetForUrlBar() : nsnull);

        if (!*aURI && rv != NS_ERROR_MALFORMED_URI) {
            return rv;
        }
    }
    
    if (*aURI) {
        if (aFixupFlags & FIXUP_FLAGS_MAKE_ALTERNATE_URI)
            MakeAlternateURI(*aURI);
        return NS_OK;
    }

    // See if it is a keyword
    // Test whether keywords need to be fixed up
    PRBool fixupKeywords = PR_FALSE;
    if (aFixupFlags & FIXUP_FLAG_ALLOW_KEYWORD_LOOKUP) {
        if (mPrefBranch)
        {
            NS_ENSURE_SUCCESS(mPrefBranch->GetBoolPref("keyword.enabled", &fixupKeywords), NS_ERROR_FAILURE);
        }
        if (fixupKeywords)
        {
            KeywordURIFixup(uriString, aURI);
            if(*aURI)
                return NS_OK;
        }
    }

    // Prune duff protocol schemes
    //
    //   ://totallybroken.url.com
    //   //shorthand.url.com
    //
    if (StringBeginsWith(uriString, NS_LITERAL_CSTRING("://")))
    {
        uriString = StringTail(uriString, uriString.Length() - 3);
    }
    else if (StringBeginsWith(uriString, NS_LITERAL_CSTRING("//")))
    {
        uriString = StringTail(uriString, uriString.Length() - 2);
    }

    // Add ftp:// or http:// to front of url if it has no spec
    //
    // Should fix:
    //
    //   no-scheme.com
    //   ftp.no-scheme.com
    //   ftp4.no-scheme.com
    //   no-scheme.com/query?foo=http://www.foo.com
    //
    PRInt32 schemeDelim = uriString.Find("://",0);
    PRInt32 firstDelim = uriString.FindCharInSet("/:");
    if (schemeDelim <= 0 ||
        (firstDelim != -1 && schemeDelim > firstDelim)) {
        // find host name
        PRInt32 hostPos = uriString.FindCharInSet("/:?#");
        if (hostPos == -1) 
            hostPos = uriString.Length();

        // extract host name
        nsCAutoString hostSpec;
        uriString.Left(hostSpec, hostPos);

        // insert url spec corresponding to host name
        if (IsLikelyFTP(hostSpec))
            uriString.Assign(NS_LITERAL_CSTRING("ftp://") + uriString);
        else 
            uriString.Assign(NS_LITERAL_CSTRING("http://") + uriString);

        // For ftp & http, we want to use system charset.
        if (!bAsciiURI)
          bUseNonDefaultCharsetForURI = PR_TRUE;
    } // end if checkprotocol

    rv = NS_NewURI(aURI, uriString, bUseNonDefaultCharsetForURI ? GetCharsetForUrlBar() : nsnull);

    // Did the caller want us to try an alternative URI?
    // If so, attempt to fixup http://foo into http://www.foo.com

    if (*aURI && aFixupFlags & FIXUP_FLAGS_MAKE_ALTERNATE_URI) {
        MakeAlternateURI(*aURI);
    }

    // If we still haven't been able to construct a valid URI, try to force a
    // keyword match.  This catches search strings with '.' or ':' in them.
    if (!*aURI && fixupKeywords)
    {
        KeywordToURI(aStringURI, aURI);
        if(*aURI)
            return NS_OK;
    }

    return rv;
}