Back to index

lightning-sunbird  0.9+nobinonly
Classes | Public Member Functions | Static Public Member Functions | Public Attributes | Protected Member Functions | Static Protected Member Functions | Protected Attributes
nsPasswordManager Class Reference

#include <nsPasswordManager.h>

Inheritance diagram for nsPasswordManager:
Inheritance graph
[legend]
Collaboration diagram for nsPasswordManager:
Collaboration graph
[legend]

List of all members.

Classes

class  PasswordEntry
class  SignonDataEntry
class  SignonHashEntry

Public Member Functions

NS_DECL_ISUPPORTS
NS_DECL_NSIPASSWORDMANAGER
NS_DECL_NSIPASSWORDMANAGERINTERNAL 
nsPasswordManager ()
nsresult Init ()
 nsPasswordManager ()
virtual ~nsPasswordManager ()
nsresult Init ()
NS_DECL_ISUPPORTS
NS_DECL_NSIPASSWORDMANAGER
NS_DECL_NSIPASSWORDMANAGERINTERNAL
NS_DECL_NSIOBSERVER
NS_DECL_NSIWEBPROGRESSLISTENER
NS_IMETHOD 
Notify (nsIContent *aFormNode, nsIDOMWindowInternal *aWindow, nsIURI *aActionURL, PRBool *aCancelSubmit)
NS_IMETHOD Focus (nsIDOMEvent *aEvent)
 Processes a focus event.
NS_IMETHOD Blur (nsIDOMEvent *aEvent)
 Processes a blur event.
NS_IMETHOD HandleEvent (nsIDOMEvent *aEvent)
PRBool AutoCompleteSearch (const nsAString &aSearchString, nsIAutoCompleteResult *aPreviousResult, nsIDOMHTMLInputElement *aElement, nsIAutoCompleteResult **aResult)
void addUser (in AUTF8String aHost, in AString aUser, in AString aPassword)
 Called to add an individual login to the list of saved logins.
void removeUser (in AUTF8String aHost, in AString aUser)
 Called to remove an individual login from the list of save logins.
void addReject (in AUTF8String aHost)
 Called to add a host to the list of rejected hosts -- i.e., hosts for which the do-you-want-to-save dialog does appear.
void removeReject (in AUTF8String aHost)
 Called to remove a host from the list of rejected hosts -- i.e., hosts for which the do-you-want-to-save dialog does not appear.
void findPasswordEntry (in AUTF8String aHostURI, in AString aUsername, in AString aPassword, out AUTF8String aHostURIFound, out AString aUsernameFound, out AString aPasswordFound)
 A Call to find a login in the password manager list that matches the specified parameters.
void addUserFull (in AUTF8String aKey, in AString aUser, in AString aPassword, in AString aUserFieldName, in AString aPassFieldName)
 Called to add an individual login to the list of saved logins.
void readPasswords (in nsIFile aPasswordFile)
 Reads logins from a Mozilla Password Manager file, augmenting the current in-memory set.
void observe (in nsISupports aSubject, in string aTopic, in wstring aData)
 Observe will be called when there is a notification for the topic |aTopic|.
void onStateChange (in nsIWebProgress aWebProgress, in nsIRequest aRequest, in unsigned long aStateFlags, in nsresult aStatus)
 Notification indicating the state has changed for one of the requests associated with aWebProgress.
void onProgressChange (in nsIWebProgress aWebProgress, in nsIRequest aRequest, in long aCurSelfProgress, in long aMaxSelfProgress, in long aCurTotalProgress, in long aMaxTotalProgress)
 Notification that the progress has changed for one of the requests associated with aWebProgress.
void onLocationChange (in nsIWebProgress aWebProgress, in nsIRequest aRequest, in nsIURI aLocation)
 Called when the location of the window being watched changes.
void onStatusChange (in nsIWebProgress aWebProgress, in nsIRequest aRequest, in nsresult aStatus, in wstring aMessage)
 Notification that the status of a request has changed.
void onSecurityChange (in nsIWebProgress aWebProgress, in nsIRequest aRequest, in unsigned long aState)
 Notification called for security progress.
void handleEvent (in nsIDOMEvent event)
 This method is called whenever an event occurs of the type for which the EventListener interface was registered.

Static Public Member Functions

static nsPasswordManagerGetInstance ()
static PRBool SingleSignonEnabled ()
static NS_METHOD Register (nsIComponentManager *aCompMgr, nsIFile *aPath, const char *aRegistryLocation, const char *aComponentType, const nsModuleComponentInfo *aInfo)
static NS_METHOD Unregister (nsIComponentManager *aCompMgr, nsIFile *aPath, const char *aRegistryLocation, const nsModuleComponentInfo *aInfo)
static void Shutdown ()
static void GetLocalizedString (const nsAString &key, nsAString &aResult, PRBool aFormatted=PR_FALSE, const PRUnichar **aFormatArgs=nsnull, PRUint32 aFormatArgsLength=0)
static nsresult DecryptData (const nsAString &aData, nsAString &aPlaintext)
static nsresult EncryptData (const nsAString &aPlaintext, nsACString &aEncrypted)
static nsresult EncryptDataUCS2 (const nsAString &aPlaintext, nsAString &aEncrypted)

Public Attributes

readonly attribute
nsISimpleEnumerator 
enumerator
 Called to enumerate through each login in the password-manager list The objects enumerated over are of type nsIPassword.
readonly attribute
nsISimpleEnumerator 
rejectEnumerator
 Called to enumerate through each rejected site in the password-manager list These are sites for which the user has indicated that he doesn't want passwords saved.
const unsigned long STATE_START = 0x00000001
 State Transition Flags.
const unsigned long STATE_REDIRECTING = 0x00000002
const unsigned long STATE_TRANSFERRING = 0x00000004
const unsigned long STATE_NEGOTIATING = 0x00000008
const unsigned long STATE_STOP = 0x00000010
const unsigned long STATE_IS_REQUEST = 0x00010000
 State Type Flags.
const unsigned long STATE_IS_DOCUMENT = 0x00020000
const unsigned long STATE_IS_NETWORK = 0x00040000
const unsigned long STATE_IS_WINDOW = 0x00080000
const unsigned long STATE_RESTORING = 0x01000000
 State Modifier Flags.
const unsigned long STATE_IS_INSECURE = 0x00000004
 State Security Flags.
const unsigned long STATE_IS_BROKEN = 0x00000001
const unsigned long STATE_IS_SECURE = 0x00000002
const unsigned long STATE_SECURE_HIGH = 0x00040000
 Security Strength Flags.
const unsigned long STATE_SECURE_MED = 0x00010000
const unsigned long STATE_SECURE_LOW = 0x00020000

Protected Member Functions

virtual ~nsPasswordManager ()
void LoadPasswords ()
void WritePasswords (nsIFile *aPasswordFile)
void AddSignonData (const nsACString &aRealm, SignonDataEntry *aEntry)
nsresult FindPasswordEntryInternal (const SignonDataEntry *aEntry, const nsAString &aUser, const nsAString &aPassword, const nsAString &aUserField, SignonDataEntry **aResult)
nsresult FillDocument (nsIDOMDocument *aDomDoc)
nsresult FillPassword (nsIDOMEvent *aEvent)
void AttachToInput (nsIDOMHTMLInputElement *aElement)

Static Protected Member Functions

static PRBool GetPasswordRealm (nsIURI *aURI, nsACString &aRealm)
static nsresult GetActionRealm (nsIForm *aForm, nsCString &aURL)
static PRBool BadCharacterPresent (const nsAString &aString)
static nsresult CheckLoginValues (const nsACString &aHost, const nsAString &aUserField, const nsAString &aPassField, const nsACString &aActionOrigin)
static PLDHashOperator PR_CALLBACK FindEntryEnumerator (const nsACString &aKey, SignonHashEntry *aEntry, void *aUserData)
static PLDHashOperator PR_CALLBACK WriteRejectEntryEnumerator (const nsACString &aKey, PRInt32 aEntry, void *aUserData)
static PLDHashOperator PR_CALLBACK WriteSignonEntryEnumerator (const nsACString &aKey, SignonHashEntry *aEntry, void *aUserData)
static PLDHashOperator PR_CALLBACK BuildArrayEnumerator (const nsACString &aKey, SignonHashEntry *aEntry, void *aUserData)
static PLDHashOperator PR_CALLBACK BuildRejectArrayEnumerator (const nsACString &aKey, PRInt32 aEntry, void *aUserData)
static PLDHashOperator PR_CALLBACK RemoveForDOMDocumentEnumerator (nsISupports *aKey, PRInt32 &aEntry, void *aUserData)
static void EnsureDecoderRing ()

Protected Attributes

nsClassHashtable
< nsCStringHashKey,
SignonHashEntry
mSignonTable
nsDataHashtable
< nsCStringHashKey, PRInt32
mRejectTable
nsDataHashtable
< nsISupportsHashKey, PRInt32
mAutoCompleteInputs
nsCOMPtr< nsIFilemSignonFile
nsCOMPtr< nsIPrefBranchmPrefBranch
nsIDOMHTMLInputElementmAutoCompletingField

Detailed Description

Definition at line 45 of file nsPasswordManager.h.


Constructor & Destructor Documentation

Definition at line 155 of file nsPasswordManager.cpp.

{
}

Here is the caller graph for this function:

nsPasswordManager::~nsPasswordManager ( void  ) [protected, virtual]

Definition at line 159 of file nsPasswordManager.cpp.

{
}

Member Function Documentation

void nsIPasswordManager::addReject ( in AUTF8String  aHost) [inherited]

Called to add a host to the list of rejected hosts -- i.e., hosts for which the do-you-want-to-save dialog does appear.

Parameters:
aHostThe host for which the dialog is to not appear
void nsPasswordManager::AddSignonData ( const nsACString &  aRealm,
SignonDataEntry aEntry 
) [protected]

Definition at line 1697 of file nsPasswordManager.cpp.

{
  // See if there is already an entry for this URL
  SignonHashEntry* hashEnt;
  if (mSignonTable.Get(aRealm, &hashEnt)) {
    // Add this one at the front of the linked list
    aEntry->next = hashEnt->head;
    hashEnt->head = aEntry;
  } else {
    mSignonTable.Put(aRealm, new SignonHashEntry(aEntry));
  }
}

Here is the call graph for this function:

Here is the caller graph for this function:

void nsIPasswordManager::addUser ( in AUTF8String  aHost,
in AString  aUser,
in AString  aPassword 
) [inherited]

Called to add an individual login to the list of saved logins.

Parameters:
aHostThe host for which the login is being remembered
aUserThe username portion of the login
aPasswordThe password portion of the login
void nsIPasswordManagerInternal::addUserFull ( in AUTF8String  aKey,
in AString  aUser,
in AString  aPassword,
in AString  aUserFieldName,
in AString  aPassFieldName 
) [inherited]

Called to add an individual login to the list of saved logins.

All parameters are clear text.

Parameters:
aKeyThe key for which the login is being remembered (often the page URI)
aUserThe username portion of the login
aPasswordThe password portion of the login
aUserFieldNameThe name of the field that contained the username
aPassFieldNameThe name of the field that contained the password

Definition at line 2161 of file nsPasswordManager.cpp.

{
  nsCOMPtr<nsIDOMEventTarget> targ = do_QueryInterface(aElement);
  nsIDOMEventListener* listener = NS_STATIC_CAST(nsIDOMFocusListener*, this);

  targ->AddEventListener(NS_LITERAL_STRING("blur"), listener, PR_FALSE);
  targ->AddEventListener(NS_LITERAL_STRING("DOMAutoComplete"), listener, PR_FALSE);

  mAutoCompleteInputs.Put(aElement, 1);
}

Here is the call graph for this function:

Here is the caller graph for this function:

PRBool nsPasswordManager::AutoCompleteSearch ( const nsAString &  aSearchString,
nsIAutoCompleteResult aPreviousResult,
nsIDOMHTMLInputElement aElement,
nsIAutoCompleteResult **  aResult 
)

Definition at line 1426 of file nsPasswordManager.cpp.

{
  PRInt32 dummy;
  if (!SingleSignonEnabled() || !mAutoCompleteInputs.Get(aElement, &dummy))
    return PR_FALSE;

  UserAutoComplete* result = nsnull;

  if (aPreviousResult) {

    // We have a list of results for a shorter search string, so just
    // filter them further based on the new search string.

    result = NS_STATIC_CAST(UserAutoComplete*, aPreviousResult);

    if (result->mArray.Count()) {
      for (PRInt32 i = result->mArray.Count() - 1; i >= 0; --i) {
        nsDependentString match(NS_STATIC_CAST(PRUnichar*, result->mArray.ElementAt(i)));
        if (aSearchString.Length() > match.Length() ||
            !StringBeginsWith(match, aSearchString)) {
          nsMemory::Free(result->mArray.ElementAt(i));
          result->mArray.RemoveElementAt(i);
        }
      }
    }
  } else {

    nsCOMPtr<nsIDOMDocument> domDoc;
    aElement->GetOwnerDocument(getter_AddRefs(domDoc));

    nsCOMPtr<nsIDocument> doc = do_QueryInterface(domDoc);

    nsCAutoString realm;
    if (!GetPasswordRealm(doc->GetDocumentURI(), realm)) {
      *aResult = nsnull;
      return NS_OK;
    }

    // Get all of the matches into an array that we can sort.

    result = new UserAutoComplete(realm, aSearchString);

    SignonHashEntry* hashEnt;
    if (mSignonTable.Get(realm, &hashEnt)) {
      // Protect against a reentrant call to DecryptData.  For example, if
      // DecryptData causes the Master Password dialog to appear, we don't
      // want to respond to a blur on the input element by trying to prefill
      // the password.

      mAutoCompletingField = aElement;

      nsCOMPtr<nsIDOMHTMLFormElement> formEl;
      aElement->GetForm(getter_AddRefs(formEl));
      if (!formEl)
        return NS_OK;

      nsCOMPtr<nsIForm> form = do_QueryInterface(formEl);
      nsCAutoString formActionOrigin;

      if (NS_FAILED(GetActionRealm(form, formActionOrigin)))
        return NS_OK;

      for (SignonDataEntry* e = hashEnt->head; e; e = e->next) {

        nsAutoString userValue;
        if (NS_FAILED(DecryptData(e->userValue, userValue)))
          return NS_ERROR_FAILURE;

        // if we don't match actionOrigin, don't count this as a match
        if (!e->actionOrigin.IsEmpty() &&
            !e->actionOrigin.Equals(formActionOrigin))
          continue;

        if (aSearchString.Length() <= userValue.Length() &&
            StringBeginsWith(userValue, aSearchString)) {
          PRUnichar* data = ToNewUnicode(userValue);
          if (data)
            result->mArray.AppendElement(data);
        }
      }

      mAutoCompletingField = nsnull;
    }

    if (result->mArray.Count()) {
      result->mArray.Sort(SortPRUnicharComparator, nsnull);
      result->mResult = nsIAutoCompleteResult::RESULT_SUCCESS;
      result->mDefaultIndex = 0;
    } else {
      result->mResult = nsIAutoCompleteResult::RESULT_NOMATCH;
      result->mDefaultIndex = -1;
    }
  }

  *aResult = result;
  NS_ADDREF(*aResult);

  return PR_TRUE;
}

Here is the call graph for this function:

PRBool nsPasswordManager::BadCharacterPresent ( const nsAString &  aString) [static, protected]

Definition at line 2244 of file nsPasswordManager.cpp.

{
  if (aString.FindChar('\r') >= 0)
    return PR_TRUE;
  if (aString.FindChar('\n') >= 0)
    return PR_TRUE;
  if (aString.FindChar('\0') >= 0)
    return PR_TRUE;

  return PR_FALSE;
}

Here is the caller graph for this function:

Processes a blur event.

Parameters:
aMouseEvent
See also:
nsIDOMEvent.h
Returns:
whether the event was consumed or ignored.
See also:
nsresult

Implements nsIDOMFocusListener.

Definition at line 1282 of file nsPasswordManager.cpp.

{
  return FillPassword(aEvent);
}

Here is the call graph for this function:

PLDHashOperator PR_CALLBACK nsPasswordManager::BuildArrayEnumerator ( const nsACString &  aKey,
SignonHashEntry aEntry,
void aUserData 
) [static, protected]

Definition at line 467 of file nsPasswordManager.cpp.

{
  nsIMutableArray* array = NS_STATIC_CAST(nsIMutableArray*, aUserData);

  for (SignonDataEntry* e = aEntry->head; e; e = e->next)
    array->AppendElement(new PasswordEntry(aKey, e), PR_FALSE);

  return PL_DHASH_NEXT;
}
PLDHashOperator PR_CALLBACK nsPasswordManager::BuildRejectArrayEnumerator ( const nsACString &  aKey,
PRInt32  aEntry,
void aUserData 
) [static, protected]

Definition at line 492 of file nsPasswordManager.cpp.

{
  nsIMutableArray* array = NS_STATIC_CAST(nsIMutableArray*, aUserData);

  nsCOMPtr<nsIPassword> passwordEntry = new PasswordEntry(aKey, nsnull);
  array->AppendElement(passwordEntry, PR_FALSE);

  return PL_DHASH_NEXT;
}
nsresult nsPasswordManager::CheckLoginValues ( const nsACString &  aHost,
const nsAString &  aUserField,
const nsAString &  aPassField,
const nsACString &  aActionOrigin 
) [static, protected]

Definition at line 2257 of file nsPasswordManager.cpp.

{
  // aHost
  if (BadCharacterPresent(NS_ConvertUTF8toUTF16(aHost))) {
    NS_WARNING("Login rejected, bad character in aHost");
    return NS_ERROR_FAILURE;
  }
  // The aHost arg is used for both login entry hostnames and reject entry
  // hostnames ("never for this site"). A value of "." is not allowed for
  // reject entries. It's technically ok for login entries, but to keep the
  // code simple we'll disallow it anyway.
  if (aHost.EqualsLiteral(".")) {
    NS_WARNING("Login rejected, aHost can not be just a period");
    return NS_ERROR_FAILURE;
  }


  // aUserField
  if (BadCharacterPresent(aUserField)) {
    NS_WARNING("Login rejected, bad character in aUserField");
    return NS_ERROR_FAILURE;
  }
  if (aUserField.EqualsLiteral(".")) {
    NS_WARNING("Login rejected, aUserField can not be just a period");
    return NS_ERROR_FAILURE;
  }


  // aPassField
  if (BadCharacterPresent(aPassField)) {
    NS_WARNING("Login rejected, bad character in aPassField");
    return NS_ERROR_FAILURE;
  }


  // aActionOrigin
  if (BadCharacterPresent(NS_ConvertUTF8toUTF16(aActionOrigin))) {
    NS_WARNING("Login rejected, bad character in aActionOrigin");
    return NS_ERROR_FAILURE;
  }
  if (aActionOrigin.EqualsLiteral(".")) {
    NS_WARNING("Login rejected, aActionOrigin can not be just a period");
    return NS_ERROR_FAILURE;
  }

  return NS_OK;
}

Here is the call graph for this function:

Here is the caller graph for this function:

nsresult nsPasswordManager::DecryptData ( const nsAString &  aData,
nsAString &  aPlaintext 
) [static]

Definition at line 1712 of file nsPasswordManager.cpp.

{
  NS_ConvertUCS2toUTF8 flatData(aData);
  char* buffer = nsnull;

  if (flatData.CharAt(0) == '~') {

    // This is a base64-encoded string. Strip off the ~ prefix.
    PRUint32 srcLength = flatData.Length() - 1;

    if (!(buffer = PL_Base64Decode(&(flatData.get())[1], srcLength, NULL)))
      return NS_ERROR_FAILURE;

  } else {

    // This is encrypted using nsISecretDecoderRing.
    EnsureDecoderRing();
    if (!sDecoderRing) {
      NS_WARNING("Unable to get decoder ring service");
      return NS_ERROR_FAILURE;
    }

    if (NS_FAILED(sDecoderRing->DecryptString(flatData.get(), &buffer)))
      return NS_ERROR_FAILURE;

  }

  aPlaintext.Assign(NS_ConvertUTF8toUCS2(buffer));
  PR_Free(buffer);

  return NS_OK;
}

Here is the call graph for this function:

Here is the caller graph for this function:

nsresult nsPasswordManager::EncryptData ( const nsAString &  aPlaintext,
nsACString &  aEncrypted 
) [static]

Definition at line 1752 of file nsPasswordManager.cpp.

{
  EnsureDecoderRing();
  NS_ENSURE_TRUE(sDecoderRing, NS_ERROR_FAILURE);

  char* buffer;
  if (NS_FAILED(sDecoderRing->EncryptString(NS_ConvertUCS2toUTF8(aPlaintext).get(), &buffer)))
    return NS_ERROR_FAILURE;

  aEncrypted.Assign(buffer);
  PR_Free(buffer);

  return NS_OK;
}

Here is the call graph for this function:

Here is the caller graph for this function:

nsresult nsPasswordManager::EncryptDataUCS2 ( const nsAString &  aPlaintext,
nsAString &  aEncrypted 
) [static]

Definition at line 1769 of file nsPasswordManager.cpp.

{
  nsCAutoString buffer;
  nsresult rv = EncryptData(aPlaintext, buffer);
  NS_ENSURE_SUCCESS(rv, rv);

  aEncrypted.Assign(NS_ConvertUTF8toUCS2(buffer));
  return NS_OK;
}

Here is the call graph for this function:

Here is the caller graph for this function:

void nsPasswordManager::EnsureDecoderRing ( ) [static, protected]

Definition at line 1781 of file nsPasswordManager.cpp.

{
  if (!sDecoderRing) {
    CallGetService("@mozilla.org/security/sdr;1", &sDecoderRing);

    // Ensure that the master password (internal key) has been initialized.
    // If not, set a default empty master password.

    nsCOMPtr<nsIPK11TokenDB> tokenDB = do_GetService(NS_PK11TOKENDB_CONTRACTID);
    if (!tokenDB)
      return;

    nsCOMPtr<nsIPK11Token> token;
    tokenDB->GetInternalKeyToken(getter_AddRefs(token));

    PRBool needUserInit = PR_FALSE;
    token->GetNeedsUserInit(&needUserInit);

    if (needUserInit)
      token->InitPassword(EmptyString().get());
  }
}

Here is the call graph for this function:

Here is the caller graph for this function:

Definition at line 1864 of file nsPasswordManager.cpp.

{
  nsCOMPtr<nsIDOMHTMLDocument> htmlDoc = do_QueryInterface(aDomDoc);
  if (!htmlDoc)
    return NS_OK;
  nsCOMPtr<nsIDOMHTMLCollection> forms;
  htmlDoc->GetForms(getter_AddRefs(forms));

  nsCOMPtr<nsIDocument> doc = do_QueryInterface(aDomDoc);

  nsCAutoString realm;
  if (!GetPasswordRealm(doc->GetDocumentURI(), realm))
    return NS_OK;

  SignonHashEntry* hashEnt;
  if (!mSignonTable.Get(realm, &hashEnt))
    return NS_OK;

  PRUint32 formCount;
  forms->GetLength(&formCount);

  // check to see if we should formfill.  failure is non-fatal
  PRBool prefillForm = PR_TRUE;
  mPrefBranch->GetBoolPref("prefillForms", &prefillForm);

  nsCAutoString formActionOrigin;

  // We can auto-prefill the username and password if there is only
  // one stored login that matches the username and password field names
  // on the form in question.  Note that we only need to worry about a
  // single login per form.

  for (PRUint32 i = 0; i < formCount; ++i) {
    nsCOMPtr<nsIDOMNode> formNode;
    forms->Item(i, getter_AddRefs(formNode));

    nsCOMPtr<nsIForm> form = do_QueryInterface(formNode);
    SignonDataEntry* firstMatch = nsnull;
    PRBool attachedToInput = PR_FALSE;
    PRBool prefilledUser = PR_FALSE;
    nsCOMPtr<nsIDOMHTMLInputElement> userField, passField;
    nsCOMPtr<nsIDOMHTMLInputElement> temp;
    nsAutoString fieldType;

    // before we start iterating, make sure we have the action host
    if (NS_FAILED(GetActionRealm(form, formActionOrigin)))
      return NS_OK;

    for (SignonDataEntry* e = hashEnt->head; e; e = e->next) {

      nsCOMPtr<nsISupports> foundNode;
      if (!(e->userField).IsEmpty()) {
        form->ResolveName(e->userField, getter_AddRefs(foundNode));
        temp = do_QueryInterface(foundNode);
      }

      nsAutoString oldUserValue;

      if (temp) {
        temp->GetType(fieldType);
        if (!fieldType.Equals(NS_LITERAL_STRING("text")))
          continue;

        temp->GetValue(oldUserValue);
        userField = temp;
      } else if ((e->passField).IsEmpty()) {
        // Happens sometimes when we import passwords from IE since
        // their form name match is case insensitive. In this case,
        // we'll just have to do a case insensitive search for the
        // userField and hope we get something.
        PRUint32 count;
        form->GetElementCount(&count);
        PRUint32 i;
        nsCOMPtr<nsIFormControl> formControl;
        for (i = 0; i < count; i++) {
          form->GetElementAt(i, getter_AddRefs(formControl));

          if (formControl &&
              formControl->GetType() == NS_FORM_INPUT_TEXT) {
            nsCOMPtr<nsIDOMHTMLInputElement> inputField = do_QueryInterface(formControl);
            nsAutoString name;
            inputField->GetName(name);
            if (name.EqualsIgnoreCase(NS_ConvertUTF16toUTF8(e->userField).get())) {
              inputField->GetValue(oldUserValue);
              userField = inputField;
              foundNode = inputField;
              // Only the case differs, so CheckLoginValues() unneeded.
              e->userField.Assign(name);
              break;
            }
          }
        }
      }

      if (!(e->passField).IsEmpty()) {
        form->ResolveName(e->passField, getter_AddRefs(foundNode));
        temp = do_QueryInterface(foundNode);
      }
      else if (userField) {
        // No password field name was supplied, try to locate one in the form,
        // but only if we have a username field.
        nsCOMPtr<nsIFormControl> fc(do_QueryInterface(foundNode));
        PRInt32 index = -1;
        form->IndexOfControl(fc, &index);
        if (index >= 0) {
          PRUint32 count;
          form->GetElementCount(&count);

          PRUint32 i;
          temp = nsnull;

          // Search forwards
          nsCOMPtr<nsIFormControl> passField;
          for (i = index + 1; i < count; ++i) {
            form->GetElementAt(i, getter_AddRefs(passField));

            if (passField && passField->GetType() == NS_FORM_INPUT_PASSWORD) {
              foundNode = passField;
              temp = do_QueryInterface(foundNode);
            }
          }

          if (!temp && index != 0) {
            // Search backwards
            i = index;
            do {
              form->GetElementAt(i, getter_AddRefs(passField));

              if (passField && passField->GetType() == NS_FORM_INPUT_PASSWORD) {
                foundNode = passField;
                temp = do_QueryInterface(foundNode);
              }
            } while (i-- != 0);
          }
        }
      }

      nsAutoString oldPassValue;

      if (temp) {
        temp->GetType(fieldType);
        if (!fieldType.Equals(NS_LITERAL_STRING("password")))
          continue;

        temp->GetValue(oldPassValue);
        passField = temp;
        if ((e->passField).IsEmpty()) {
          nsAutoString passName;
          passField->GetName(passName);

          // Reject values that would cause problems when parsing the storage file
          if (NS_SUCCEEDED(CheckLoginValues(EmptyCString(), EmptyString(),
                                            passName, EmptyCString())))
            e->passField.Assign(passName);
        }
      } else {
        continue;
      }

      // if we don't match actionOrigin, don't count this as a match
      if (!e->actionOrigin.IsEmpty() &&
          !e->actionOrigin.Equals(formActionOrigin))
        continue;

      if (!oldUserValue.IsEmpty() && prefillForm) {
        // The page has prefilled a username.
        // If it matches any of our saved usernames, prefill the password
        // for that username.  If there are multiple saved usernames,
        // we will also attach the autocomplete listener.

        prefilledUser = PR_TRUE;
        nsAutoString userValue;
        if (NS_FAILED(DecryptData(e->userValue, userValue)))
          return NS_OK;

        if (userValue.Equals(oldUserValue)) {
          nsAutoString passValue;
          if (NS_FAILED(DecryptData(e->passValue, passValue)))
            return NS_OK;

          passField->SetValue(passValue);
        }
      }

      if (firstMatch && userField && !attachedToInput) {
        // We've found more than one possible signon for this form.

        // Listen for blur and autocomplete events on the username field so
        // that we can attempt to prefill the password after the user has
        // entered the username.

        AttachToInput(userField);
        attachedToInput = PR_TRUE;
      } else {
        firstMatch = e;
      }
    }

    // If we found more than one match, attachedToInput will be true,
    // but if we found just one, we need to attach the autocomplete listener,
    // and fill in the username and password  only if the HTML didn't prefill
    // the username.
    if (firstMatch && !attachedToInput) {
      if (!prefilledUser && prefillForm) {
        nsAutoString buffer;

        if (userField) {
          if (NS_FAILED(DecryptData(firstMatch->userValue, buffer)))
            return NS_OK;

          userField->SetValue(buffer);
        }

        if (NS_FAILED(DecryptData(firstMatch->passValue, buffer)))
          return NS_OK;

        passField->SetValue(buffer);
      }

      if (userField)
        AttachToInput(userField);
    }
  }

  return NS_OK;
}

Here is the call graph for this function:

Here is the caller graph for this function:

Definition at line 2092 of file nsPasswordManager.cpp.

{
  // Try to prefill the password for the just-changed username.
  nsCOMPtr<nsIDOMEventTarget> target;
  aEvent->GetTarget(getter_AddRefs(target));

  nsCOMPtr<nsIDOMHTMLInputElement> userField = do_QueryInterface(target);
  if (!userField || userField == mAutoCompletingField)
    return NS_OK;

  nsCOMPtr<nsIContent> fieldContent = do_QueryInterface(userField);

  // The document may be null during teardown, for example as Windows
  // sends a blur event as a native widget is destroyed.
  nsIDocument *doc = fieldContent->GetDocument();
  if (!doc)
    return NS_OK;

  nsCAutoString realm;
  if (!GetPasswordRealm(doc->GetDocumentURI(), realm))
    return NS_OK;

  nsAutoString userValue;
  userField->GetValue(userValue);

  if (userValue.IsEmpty())
    return NS_OK;

  nsAutoString fieldName;
  userField->GetName(fieldName);

  SignonHashEntry* hashEnt;
  if (!mSignonTable.Get(realm, &hashEnt))
    return NS_OK;

  SignonDataEntry* foundEntry;
  FindPasswordEntryInternal(hashEnt->head, userValue, EmptyString(),
                            fieldName, &foundEntry);

  if (!foundEntry)
    return NS_OK;

  nsCOMPtr<nsIDOMHTMLFormElement> formEl;
  userField->GetForm(getter_AddRefs(formEl));
  if (!formEl)
    return NS_OK;

  nsCOMPtr<nsIForm> form = do_QueryInterface(formEl);
  nsCAutoString formActionOrigin;
  GetActionRealm(form, formActionOrigin);
  if (NS_FAILED(GetActionRealm(form, formActionOrigin)))
    return NS_OK;
  if (!foundEntry->actionOrigin.IsEmpty() && !foundEntry->actionOrigin.Equals(formActionOrigin))
    return NS_OK;
  
  nsCOMPtr<nsISupports> foundNode;
  form->ResolveName(foundEntry->passField, getter_AddRefs(foundNode));
  nsCOMPtr<nsIDOMHTMLInputElement> passField = do_QueryInterface(foundNode);
  if (!passField)
    return NS_OK;

  nsAutoString passValue;
  if (NS_SUCCEEDED(DecryptData(foundEntry->passValue, passValue)))
    passField->SetValue(passValue);

  return NS_OK;
}

Here is the call graph for this function:

Here is the caller graph for this function:

PLDHashOperator PR_CALLBACK nsPasswordManager::FindEntryEnumerator ( const nsACString &  aKey,
SignonHashEntry aEntry,
void aUserData 
) [static, protected]

Definition at line 542 of file nsPasswordManager.cpp.

{
  findEntryContext* context = NS_STATIC_CAST(findEntryContext*, aUserData);
  nsPasswordManager* manager = context->manager;
  nsresult rv;

  SignonDataEntry* entry = nsnull;
  rv = manager->FindPasswordEntryInternal(aEntry->head,
                                          context->username,
                                          context->password,
                                          EmptyString(),
                                          &entry);

  if (NS_SUCCEEDED(rv) && entry) {
    if (NS_SUCCEEDED(DecryptData(entry->userValue, context->usernameFound)) &&
        NS_SUCCEEDED(DecryptData(entry->passValue, context->passwordFound))) {
      context->matched = PR_TRUE;
      context->hostURIFound.Assign(context->hostURI);
    }

    return PL_DHASH_STOP;
  }

  return PL_DHASH_NEXT;
}

Here is the call graph for this function:

void nsIPasswordManagerInternal::findPasswordEntry ( in AUTF8String  aHostURI,
in AString  aUsername,
in AString  aPassword,
out AUTF8String  aHostURIFound,
out AString  aUsernameFound,
out AString  aPasswordFound 
) [inherited]

A Call to find a login in the password manager list that matches the specified parameters.

If any input parameter is null, it is not tested for when looking for the match.

Parameters:
aHostURIThe uri part of a login to search for, or null
aUsernameThe username part of a login to search for, or null
aPasswordThe password part of a login to search for, or null
aHostURIFoundThe uri found in the login
aUsernameFoundThe username found in the login
aPasswordFoundThe password found in the login
nsresult nsPasswordManager::FindPasswordEntryInternal ( const SignonDataEntry aEntry,
const nsAString &  aUser,
const nsAString &  aPassword,
const nsAString &  aUserField,
SignonDataEntry **  aResult 
) [protected]

Definition at line 1805 of file nsPasswordManager.cpp.

{
  // host has already been checked, so just look for user/password match.
  const SignonDataEntry* entry = aEntry;
  nsAutoString buffer;

  for (; entry; entry = entry->next) {

    PRBool matched;

    if (aUser.IsEmpty()) {
      matched = PR_TRUE;
    } else {
      if (NS_FAILED(DecryptData(entry->userValue, buffer))) {
        *aResult = nsnull;
        return NS_ERROR_FAILURE;
      }
      matched = aUser.Equals(buffer);
    }

    if (!matched)
      continue;

    if (aPassword.IsEmpty()) {
      matched = PR_TRUE;
    } else {
      if (NS_FAILED(DecryptData(entry->passValue, buffer))) {
        *aResult = nsnull;
        return NS_ERROR_FAILURE;
      }
      matched = aPassword.Equals(buffer);
    }

    if (!matched)
      continue;

    if (aUserField.IsEmpty())
      matched = PR_TRUE;
    else
      matched = entry->userField.Equals(aUserField);

    if (matched)
      break;
  }

  if (entry) {
    *aResult = NS_CONST_CAST(SignonDataEntry*, entry);
    return NS_OK;
  }

  *aResult = nsnull;
  return NS_ERROR_FAILURE;
}

Here is the call graph for this function:

Here is the caller graph for this function:

Processes a focus event.

Parameters:
aMouseEvent
See also:
nsIDOMEvent.h
Returns:
whether the event was consumed or ignored.
See also:
nsresult

Implements nsIDOMFocusListener.

Definition at line 1276 of file nsPasswordManager.cpp.

{
  return NS_OK;
}
nsresult nsPasswordManager::GetActionRealm ( nsIForm aForm,
nsCString aURL 
) [static, protected]

Definition at line 2227 of file nsPasswordManager.cpp.

{
  nsCOMPtr<nsIURI> actionURI;
  nsCAutoString formActionOrigin;

  if (NS_FAILED(aForm->GetActionURL(getter_AddRefs(actionURI))) ||
      !actionURI)
    return NS_ERROR_FAILURE;

  if (!GetPasswordRealm(actionURI, formActionOrigin))
    return NS_ERROR_FAILURE;

  aURL.Assign(formActionOrigin);
  return NS_OK;
}

Here is the call graph for this function:

Here is the caller graph for this function:

Definition at line 227 of file nsPasswordManager.cpp.

{
  if (!sPasswordManager) {
    sPasswordManager = new nsPasswordManager();
    if (!sPasswordManager)
      return nsnull;

    NS_ADDREF(sPasswordManager);   // addref the global

    if (NS_FAILED(sPasswordManager->Init())) {
      NS_RELEASE(sPasswordManager);
      return nsnull;
    }
  }

  // We fail to load passwords during early initialization
  // This wrapper function allows us to handle that error and defer
  // password loading until later
  sPasswordManager->LoadPasswords();

  NS_ADDREF(sPasswordManager);   // addref the return result
  return sPasswordManager;
}

Here is the call graph for this function:

void nsPasswordManager::GetLocalizedString ( const nsAString &  key,
nsAString &  aResult,
PRBool  aFormatted = PR_FALSE,
const PRUnichar **  aFormatArgs = nsnull,
PRUint32  aFormatArgsLength = 0 
) [static]

Definition at line 2198 of file nsPasswordManager.cpp.

{
  if (!sPMBundle) {
    nsCOMPtr<nsIStringBundleService> bundleService = do_GetService(NS_STRINGBUNDLE_CONTRACTID);
    bundleService->CreateBundle(kPMPropertiesURL,
                                &sPMBundle);

    if (!sPMBundle) {
      NS_ERROR("string bundle not present");
      return;
    }
  }

  nsXPIDLString str;
  if (aIsFormatted)
    sPMBundle->FormatStringFromName(PromiseFlatString(key).get(),
                                    aFormatArgs, aFormatArgsLength,
                                    getter_Copies(str));
  else
    sPMBundle->GetStringFromName(PromiseFlatString(key).get(),
                                 getter_Copies(str));
  aResult.Assign(str);
}

Here is the call graph for this function:

Here is the caller graph for this function:

PRBool nsPasswordManager::GetPasswordRealm ( nsIURI aURI,
nsACString &  aRealm 
) [static, protected]

Definition at line 2173 of file nsPasswordManager.cpp.

{
  // Note: this _is_ different from getting the uri's prePath!
  // We don't want to include a username or password that's part of the
  // URL in the host key... it will cause lookups to work incorrectly, and will
  // also cause usernames and passwords to be stored in cleartext.

  nsCAutoString buffer;
  aURI->GetScheme(buffer);

  aRealm.Append(buffer);
  aRealm.Append(NS_LITERAL_CSTRING("://"));

  aURI->GetHostPort(buffer);
  if (buffer.IsEmpty()) {
    // The scheme does not support hostnames, so don't attempt to save/restore
    // any signon data. (see bug 159484)
    return PR_FALSE;
  }

  aRealm.Append(buffer);
  return PR_TRUE;
}

Here is the caller graph for this function:

This method is called whenever an event occurs of the type for which the EventListener interface was registered.

Parameters:
evtThe Event contains contextual information about the event. It also contains the stopPropagation and preventDefault methods which are used in determining the event's flow and default action.

Definition at line 1288 of file nsPasswordManager.cpp.

{
  nsAutoString type;
  aEvent->GetType(type);

  if (type.EqualsLiteral("DOMAutoComplete"))
    return FillPassword(aEvent);

  nsCOMPtr<nsIDOMEventTarget> target;
  aEvent->GetTarget(getter_AddRefs(target));

  nsCOMPtr<nsIDOMDocument> domDoc = do_QueryInterface(target);
  if (!domDoc)
    return NS_OK;

  if (type.EqualsLiteral("pagehide"))
    mAutoCompleteInputs.Enumerate(RemoveForDOMDocumentEnumerator, domDoc);
  else if (type.EqualsLiteral("DOMContentLoaded"))
    return FillDocument(domDoc);

  return NS_OK;
}

Here is the call graph for this function:

Definition at line 163 of file nsPasswordManager.cpp.

{
  return NS_OK;
}

Here is the caller graph for this function:

Definition at line 1628 of file nsPasswordManager.cpp.

{
  if (sPasswordsLoaded)
    return;

  nsXPIDLCString signonFile;
  nsresult rv;
  rv = mPrefBranch->GetCharPref("SignonFileName2", getter_Copies(signonFile));
  if (NS_FAILED(rv))
    signonFile.Assign(NS_LITERAL_CSTRING("signons2.txt"));

  NS_GetSpecialDirectory(NS_APP_USER_PROFILE_50_DIR, getter_AddRefs(mSignonFile));
  if (!mSignonFile)
    return;

  mSignonFile->AppendNative(signonFile);

  nsCAutoString path;
  mSignonFile->GetNativePath(path);

  PRBool signonExists = PR_FALSE;
  mSignonFile->Exists(&signonExists);
  if (signonExists) {
    if (NS_SUCCEEDED(ReadPasswords(mSignonFile)))
      sPasswordsLoaded = PR_TRUE;
  } else {
    // no current signons file, look for an older version
    rv = mPrefBranch->GetCharPref("SignonFileName", getter_Copies(signonFile));
    if (NS_FAILED(rv))
      signonFile.Assign(NS_LITERAL_CSTRING("signons.txt"));

    nsCOMPtr<nsIFile> oldSignonFile;
    mSignonFile->GetParent(getter_AddRefs(oldSignonFile));
    oldSignonFile->AppendNative(signonFile);

    if (NS_SUCCEEDED(ReadPasswords(oldSignonFile))) {
      sPasswordsLoaded = PR_TRUE;
      oldSignonFile->Remove(PR_FALSE);
    }
  }
}

Here is the call graph for this function:

Here is the caller graph for this function:

NS_IMETHODIMP nsPasswordManager::Notify ( nsIContent aFormNode,
nsIDOMWindowInternal aWindow,
nsIURI aActionURL,
PRBool aCancelSubmit 
) [virtual]

Implements nsIFormSubmitObserver.

Definition at line 898 of file nsPasswordManager.cpp.

{
  // This function must never return a failure code or the form submit
  // will be cancelled.

  NS_ENSURE_TRUE(aWindow, NS_OK);

  // Don't do anything if the global signon pref is disabled
  if (!SingleSignonEnabled())
    return NS_OK;

  // Check the reject list
  nsCAutoString realm;
  // XXX bug 281125: GetDocument() could sometimes be null here, hinting
  // XXX at a problem with document teardown while a modal dialog is posted.
  if (!GetPasswordRealm(aFormNode->GetOwnerDoc()->GetDocumentURI(), realm))
    return NS_OK;

  PRInt32 rejectValue;
  if (mRejectTable.Get(realm, &rejectValue)) {
    // The user has opted to never save passwords for this site.
    return NS_OK;
  }

  nsCOMPtr<nsIForm> formElement = do_QueryInterface(aFormNode);

  PRUint32 numControls;
  formElement->GetElementCount(&numControls);

  // Count the number of password fields in the form.

  nsCOMPtr<nsIDOMHTMLInputElement> userField;
  nsCOMArray<nsIDOMHTMLInputElement> passFields;

  PRUint32 i, firstPasswordIndex = numControls;

  for (i = 0; i < numControls; ++i) {

    nsCOMPtr<nsIFormControl> control;
    formElement->GetElementAt(i, getter_AddRefs(control));

    if (control->GetType() == NS_FORM_INPUT_PASSWORD) {
      nsCOMPtr<nsIDOMHTMLInputElement> elem = do_QueryInterface(control);
      passFields.AppendObject(elem);
      if (firstPasswordIndex == numControls)
        firstPasswordIndex = i;
    }
  }

  nsCOMPtr<nsIPrompt> prompt;
  aWindow->GetPrompter(getter_AddRefs(prompt));

  switch (passFields.Count()) {
  case 1:  // normal login
    {
      // Search backwards from the password field to find a username field.
      for (PRInt32 j = (PRInt32) firstPasswordIndex - 1; j >= 0; --j) {
        nsCOMPtr<nsIFormControl> control;
        formElement->GetElementAt(j, getter_AddRefs(control));

        if (control->GetType() == NS_FORM_INPUT_TEXT) {
          userField = do_QueryInterface(control);
          break;
        }
      }

      // If the username field or the form has autocomplete=off,
      // we don't store the login

      nsAutoString autocomplete;

      if (userField) {
        nsCOMPtr<nsIDOMElement> userFieldElement = do_QueryInterface(userField);
        userFieldElement->GetAttribute(NS_LITERAL_STRING("autocomplete"),
                                       autocomplete);

        if (autocomplete.EqualsIgnoreCase("off"))
          return NS_OK;
      }

      nsCOMPtr<nsIDOMElement> formDOMEl = do_QueryInterface(aFormNode);
      formDOMEl->GetAttribute(NS_LITERAL_STRING("autocomplete"), autocomplete);
      if (autocomplete.EqualsIgnoreCase("off"))
        return NS_OK;

      nsCOMPtr<nsIDOMElement> passFieldElement = do_QueryInterface(passFields.ObjectAt(0));
      passFieldElement->GetAttribute(NS_LITERAL_STRING("autocomplete"), autocomplete);
      if (autocomplete.EqualsIgnoreCase("off"))
        return NS_OK;


      // Check whether this signon is already stored.
      // Note that we don't prompt the user if only the password doesn't match;
      // we instead just silently change the stored password.

      nsAutoString userValue, passValue, userFieldName, passFieldName, actionOrigin;

      if (userField) {
        userField->GetValue(userValue);
        userField->GetName(userFieldName);
      }

      passFields.ObjectAt(0)->GetValue(passValue);
      passFields.ObjectAt(0)->GetName(passFieldName);

      // If the password is empty, there is no reason to store this login.
      if (passValue.IsEmpty())
        return NS_OK;

      SignonHashEntry* hashEnt;
      nsCAutoString formActionOrigin;

      if (mSignonTable.Get(realm, &hashEnt)) {

        SignonDataEntry* entry;
        nsAutoString buffer;

        for (entry = hashEnt->head; entry; entry = entry->next) {
          if (entry->userField.Equals(userFieldName) &&
              entry->passField.Equals(passFieldName)) {

            if (NS_FAILED(DecryptData(entry->userValue, buffer)))
              return NS_OK;

            if (buffer.Equals(userValue)) {

              if (NS_FAILED(DecryptData(entry->passValue, buffer)))
                return NS_OK;

              PRBool writePasswords = PR_FALSE;
              
              if (!buffer.Equals(passValue)) {
                if (NS_FAILED(EncryptDataUCS2(passValue, entry->passValue)))
                  return NS_OK;

                writePasswords = PR_TRUE;
              }

              if (NS_SUCCEEDED(GetActionRealm(formElement, formActionOrigin)) &&
                  !entry->actionOrigin.Equals(formActionOrigin)) {

                // Reject values that would cause problems when parsing the storage file
                if (NS_SUCCEEDED(CheckLoginValues(EmptyCString(), EmptyString(),
                                                  EmptyString(), formActionOrigin))) {
                  // update the action URL
                  entry->actionOrigin.Assign(formActionOrigin);
                  writePasswords = PR_TRUE;
                }
              }

              if (writePasswords)
                WritePasswords(mSignonFile);

              return NS_OK;
            }
          }
        }
      }

      nsresult rv;
      nsCOMPtr<nsIStringBundleService> bundleService =
        do_GetService(NS_STRINGBUNDLE_CONTRACTID, &rv);
      nsCOMPtr<nsIStringBundle> brandBundle;
      rv = bundleService->CreateBundle("chrome://branding/locale/brand.properties",
                                       getter_AddRefs(brandBundle));
      NS_ENSURE_SUCCESS(rv, rv);
      nsXPIDLString brandShortName;
      rv = brandBundle->GetStringFromName(NS_LITERAL_STRING("brandShortName").get(),
                                          getter_Copies(brandShortName));
      NS_ENSURE_SUCCESS(rv, rv);
      const PRUnichar* formatArgs[1] = { brandShortName.get() };

      nsAutoString dialogText;
      GetLocalizedString(NS_LITERAL_STRING("savePasswordText"),
                         dialogText,
                         PR_TRUE,
                         formatArgs,
                         1);

      nsAutoString dialogTitle, neverButtonText, rememberButtonText,
                   notNowButtonText;
      GetLocalizedString(NS_LITERAL_STRING("savePasswordTitle"), dialogTitle);

      GetLocalizedString(NS_LITERAL_STRING("neverForSiteButtonText"),
                         neverButtonText);
      GetLocalizedString(NS_LITERAL_STRING("rememberButtonText"),
                         rememberButtonText);
      GetLocalizedString(NS_LITERAL_STRING("notNowButtonText"),
                         notNowButtonText);

      PRInt32 selection;
      prompt->ConfirmEx(dialogTitle.get(),
                        dialogText.get(),
                        nsIPrompt::BUTTON_POS_1_DEFAULT +
                        (nsIPrompt::BUTTON_TITLE_IS_STRING * nsIPrompt::BUTTON_POS_0) +
                        (nsIPrompt::BUTTON_TITLE_IS_STRING * nsIPrompt::BUTTON_POS_1) +
                        (nsIPrompt::BUTTON_TITLE_IS_STRING * nsIPrompt::BUTTON_POS_2),
                        rememberButtonText.get(),
                        notNowButtonText.get(),
                        neverButtonText.get(),
                        nsnull, nsnull,
                        &selection);

      if (selection == 0) {
        SignonDataEntry* entry = new SignonDataEntry();
        entry->userField.Assign(userFieldName);
        entry->passField.Assign(passFieldName);

        // save the hostname of the action URL
        if (NS_FAILED(GetActionRealm(formElement, formActionOrigin))) {
          delete entry;
          return NS_OK;
        }

        entry->actionOrigin.Assign(formActionOrigin);

        if (NS_FAILED(EncryptDataUCS2(userValue, entry->userValue)) ||
            NS_FAILED(EncryptDataUCS2(passValue, entry->passValue))) {
          delete entry;
          return NS_OK;
        }

        // Reject values that would cause problems when parsing the storage file
        // We do this after prompting, lest any code somehow change the values
        // during the prompting.
        nsresult rv = CheckLoginValues(realm,
                                       entry->userField, entry->passField,
                                       entry->actionOrigin);
        NS_ENSURE_SUCCESS(rv, NS_OK);

        AddSignonData(realm, entry);
        WritePasswords(mSignonFile);
      } else if (selection == 2) {
        // Reject values that would cause problems when parsing the storage file
        // We do this after prompting, lest any code run from prompt context.
        nsresult rv = CheckLoginValues(realm, EmptyString(),
                                       EmptyString(), EmptyCString());
        NS_ENSURE_SUCCESS(rv, NS_OK);

        AddReject(realm);
      }
    }
    break;

  case 2:
  case 3:
    {
      // If the following conditions are true, we guess that this is a
      // password change page:
      //   - there are 2 or 3 password fields on the page
      //   - the fields do not all have the same value
      //   - there is already a stored login for this realm
      //
      // In this situation, prompt the user to confirm that this is a password
      // change.

      SignonDataEntry* changeEntry = nsnull;
      nsAutoString value0, valueN;
      passFields.ObjectAt(0)->GetValue(value0);

      for (PRInt32 k = 1; k < passFields.Count(); ++k) {
        passFields.ObjectAt(k)->GetValue(valueN);
        if (!value0.Equals(valueN)) {

          SignonHashEntry* hashEnt;

          if (mSignonTable.Get(realm, &hashEnt)) {

            SignonDataEntry* entry = hashEnt->head;

            if (entry->next) {

              // Multiple stored logons, prompt for which username is
              // being changed.

              PRUint32 entryCount = 2;
              SignonDataEntry* temp = entry->next;
              while (temp->next) {
                ++entryCount;
                temp = temp->next;
              }

              nsAutoString* ptUsernames = new nsAutoString[entryCount];
              const PRUnichar** formatArgs = new const PRUnichar*[entryCount];
              temp = entry;

              for (PRUint32 arg = 0; arg < entryCount; ++arg) {
                if (NS_FAILED(DecryptData(temp->userValue, ptUsernames[arg]))) {
                  delete [] formatArgs;
                  delete [] ptUsernames;
                  return NS_OK;
                }

                formatArgs[arg] = ptUsernames[arg].get();
                temp = temp->next;
              }

              nsAutoString dialogTitle, dialogText;
              GetLocalizedString(NS_LITERAL_STRING("passwordChangeTitle"),
                                 dialogTitle);
              GetLocalizedString(NS_LITERAL_STRING("userSelectText"),
                                 dialogText);

              PRInt32 selection;
              PRBool confirm;
              prompt->Select(dialogTitle.get(),
                             dialogText.get(),
                             entryCount,
                             formatArgs,
                             &selection,
                             &confirm);

              delete[] formatArgs;
              delete[] ptUsernames;

              if (confirm && selection >= 0) {
                changeEntry = entry;
                for (PRInt32 m = 0; m < selection; ++m)
                  changeEntry = changeEntry->next;
              }

            } else {
              nsAutoString dialogTitle, dialogText, ptUser;

              if (NS_FAILED(DecryptData(entry->userValue, ptUser)))
                return NS_OK;

              const PRUnichar* formatArgs[1] = { ptUser.get() };

              GetLocalizedString(NS_LITERAL_STRING("passwordChangeTitle"),
                                 dialogTitle);
              GetLocalizedString(NS_LITERAL_STRING("passwordChangeText"),
                                 dialogText,
                                 PR_TRUE,
                                 formatArgs,
                                 1);

              PRInt32 selection;
              prompt->ConfirmEx(dialogTitle.get(),
                                dialogText.get(),
                                (nsIPrompt::BUTTON_TITLE_YES * nsIPrompt::BUTTON_POS_0) +
                                (nsIPrompt::BUTTON_TITLE_NO * nsIPrompt::BUTTON_POS_1),
                                nsnull, nsnull, nsnull, nsnull, nsnull,
                                &selection);

              if (selection == 0)
                changeEntry = entry;
            }
          }
          break;
        }
      }

      if (changeEntry) {
        nsAutoString newValue;
        passFields.ObjectAt(1)->GetValue(newValue);
        if (NS_FAILED(EncryptDataUCS2(newValue, changeEntry->passValue)))
          return NS_OK;

        WritePasswords(mSignonFile);
      }
    }
    break;

  default:  // no passwords or something odd; be safe and just don't store anything
    break;
  }


  return NS_OK;
}

Here is the call graph for this function:

void nsIObserver::observe ( in nsISupports  aSubject,
in string  aTopic,
in wstring  aData 
) [inherited]

Observe will be called when there is a notification for the topic |aTopic|.

This assumes that the object implementing this interface has been registered with an observer service such as the nsIObserverService.

If you expect multiple topics/subjects, the impl is responsible for filtering.

You should not modify, add, remove, or enumerate notifications in the implemention of observe.

Parameters:
aSubject: Notification specific interface pointer.
aTopic: The notification topic or subject.
aData: Notification specific wide string. subject event.
void nsIWebProgressListener::onLocationChange ( in nsIWebProgress  aWebProgress,
in nsIRequest  aRequest,
in nsIURI  aLocation 
) [inherited]

Called when the location of the window being watched changes.

This is not when a load is requested, but rather once it is verified that the load is going to occur in the given window. For instance, a load that starts in a window might send progress and status messages for the new site, but it will not send the onLocationChange until we are sure that we are loading this new page here.

Parameters:
aWebProgressThe nsIWebProgress instance that fired the notification.
aRequestThe associated nsIRequest. This may be null in some cases.
aLocationThe URI of the location that is being loaded.
void nsIWebProgressListener::onProgressChange ( in nsIWebProgress  aWebProgress,
in nsIRequest  aRequest,
in long  aCurSelfProgress,
in long  aMaxSelfProgress,
in long  aCurTotalProgress,
in long  aMaxTotalProgress 
) [inherited]

Notification that the progress has changed for one of the requests associated with aWebProgress.

Progress totals are reset to zero when all requests in aWebProgress complete (corresponding to onStateChange being called with aStateFlags including the STATE_STOP and STATE_IS_WINDOW flags).

Parameters:
aWebProgressThe nsIWebProgress instance that fired the notification.
aRequestThe nsIRequest that has new progress.
aCurSelfProgressThe current progress for aRequest.
aMaxSelfProgressThe maximum progress for aRequest.
aCurTotalProgressThe current progress for all requests associated with aWebProgress.
aMaxTotalProgressThe total progress for all requests associated with aWebProgress.

NOTE: If any progress value is unknown, or if its value would exceed the maximum value of type long, then its value is replaced with -1.

NOTE: If the object also implements nsIWebProgressListener2 and the caller knows about that interface, this function will not be called. Instead, nsIWebProgressListener2::onProgressChange64 will be called.

void nsIWebProgressListener::onSecurityChange ( in nsIWebProgress  aWebProgress,
in nsIRequest  aRequest,
in unsigned long  aState 
) [inherited]

Notification called for security progress.

This method will be called on security transitions (eg HTTP -> HTTPS, HTTPS -> HTTP, FOO -> HTTPS) and after document load completion. It might also be called if an error occurs during network loading.

Parameters:
aWebProgressThe nsIWebProgress instance that fired the notification.
aRequestThe nsIRequest that has new security state.
aStateA value composed of the Security State Flags and the Security Strength Flags listed above. Any undefined bits are reserved for future use.

NOTE: These notifications will only occur if a security package is installed.

void nsIWebProgressListener::onStateChange ( in nsIWebProgress  aWebProgress,
in nsIRequest  aRequest,
in unsigned long  aStateFlags,
in nsresult  aStatus 
) [inherited]

Notification indicating the state has changed for one of the requests associated with aWebProgress.

Parameters:
aWebProgressThe nsIWebProgress instance that fired the notification
aRequestThe nsIRequest that has changed state.
aStateFlagsFlags indicating the new state. This value is a combination of one of the State Transition Flags and one or more of the State Type Flags defined above. Any undefined bits are reserved for future use.
aStatusError status code associated with the state change. This parameter should be ignored unless aStateFlags includes the STATE_STOP bit. The status code indicates success or failure of the request associated with the state change. NOTE: aStatus may be a success code even for server generated errors, such as the HTTP 404 error. In such cases, the request itself should be queried for extended error information (e.g., for HTTP requests see nsIHttpChannel).
void nsIWebProgressListener::onStatusChange ( in nsIWebProgress  aWebProgress,
in nsIRequest  aRequest,
in nsresult  aStatus,
in wstring  aMessage 
) [inherited]

Notification that the status of a request has changed.

The status message is intended to be displayed to the user (e.g., in the status bar of the browser).

Parameters:
aWebProgressThe nsIWebProgress instance that fired the notification.
aRequestThe nsIRequest that has new status.
aStatusThis value is not an error code. Instead, it is a numeric value that indicates the current status of the request. This interface does not define the set of possible status codes. NOTE: Some status values are defined by nsITransport and nsISocketTransport.
aMessageLocalized text corresponding to aStatus.
void nsIPasswordManagerInternal::readPasswords ( in nsIFile  aPasswordFile) [inherited]

Reads logins from a Mozilla Password Manager file, augmenting the current in-memory set.

If a duplicate entry is encountered, the data from the file being read replaces that currently held.

Parameters:
aPasswordFileThe file to read logins from.
NS_METHOD nsPasswordManager::Register ( nsIComponentManager aCompMgr,
nsIFile aPath,
const char *  aRegistryLocation,
const char *  aComponentType,
const nsModuleComponentInfo aInfo 
) [static]

Definition at line 307 of file nsPasswordManager.cpp.

{
  // By registering in NS_PASSWORDMANAGER_CATEGORY, an instance of the password
  // manager will be created when a password input is added to a form.  We
  // can then register that singleton instance as a form submission                 .

  nsresult rv;
  nsCOMPtr<nsICategoryManager> catman = do_GetService(NS_CATEGORYMANAGER_CONTRACTID, &rv);
  NS_ENSURE_SUCCESS(rv, rv);

  nsXPIDLCString prevEntry;
  catman->AddCategoryEntry(NS_PASSWORDMANAGER_CATEGORY,
                           "Password Manager",
                           NS_PASSWORDMANAGER_CONTRACTID,
                           PR_TRUE,
                           PR_TRUE,
                           getter_Copies(prevEntry));

  catman->AddCategoryEntry("app-startup",
                           "Password Manager",
                           NS_PASSWORDMANAGER_CONTRACTID,
                           PR_TRUE,
                           PR_TRUE,
                           getter_Copies(prevEntry));

  return NS_OK;
}

Here is the call graph for this function:

PLDHashOperator PR_CALLBACK nsPasswordManager::RemoveForDOMDocumentEnumerator ( nsISupports *  aKey,
PRInt32 aEntry,
void aUserData 
) [static, protected]

Definition at line 1530 of file nsPasswordManager.cpp.

{
  nsIDOMDocument* domDoc = NS_STATIC_CAST(nsIDOMDocument*, aUserData);
  nsCOMPtr<nsIDOMHTMLInputElement> element = do_QueryInterface(aKey);
  nsCOMPtr<nsIDOMDocument> elementDoc;
  element->GetOwnerDocument(getter_AddRefs(elementDoc));
  if (elementDoc == domDoc)
    return PL_DHASH_REMOVE;

  return PL_DHASH_NEXT;
}

Here is the call graph for this function:

Here is the caller graph for this function:

void nsIPasswordManager::removeReject ( in AUTF8String  aHost) [inherited]

Called to remove a host from the list of rejected hosts -- i.e., hosts for which the do-you-want-to-save dialog does not appear.

Parameters:
aHostThe host for which the dialog is to not appear
void nsIPasswordManager::removeUser ( in AUTF8String  aHost,
in AString  aUser 
) [inherited]

Called to remove an individual login from the list of save logins.

Parameters:
aHostThe host for which the login is being remembered
aUserThe username portion of the login

Definition at line 357 of file nsPasswordManager.cpp.

Here is the caller graph for this function:

Definition at line 296 of file nsPasswordManager.cpp.

{
  if (!sPrefsInitialized) {
    // Create the PasswordManager service to initialize the prefs and callback
    nsCOMPtr<nsIPasswordManager> manager = do_GetService(NS_PASSWORDMANAGER_CONTRACTID);
  }

  return sRememberPasswords;
}

Here is the call graph for this function:

Here is the caller graph for this function:

NS_METHOD nsPasswordManager::Unregister ( nsIComponentManager aCompMgr,
nsIFile aPath,
const char *  aRegistryLocation,
const nsModuleComponentInfo aInfo 
) [static]

Definition at line 340 of file nsPasswordManager.cpp.

Here is the call graph for this function:

void nsPasswordManager::WritePasswords ( nsIFile aPasswordFile) [protected]

Definition at line 1671 of file nsPasswordManager.cpp.

{
  nsCOMPtr<nsIOutputStream> fileStream;
  NS_NewLocalFileOutputStream(getter_AddRefs(fileStream), aPasswordFile, -1,
                              0600, 0);

  if (!fileStream)
    return;

  PRUint32 bytesWritten;

  // File header
  nsCAutoString buffer("#2d" NS_LINEBREAK);
  fileStream->Write(buffer.get(), buffer.Length(), &bytesWritten);

  // Write out the reject list.
  mRejectTable.EnumerateRead(WriteRejectEntryEnumerator, fileStream);

  buffer.Assign("." NS_LINEBREAK);
  fileStream->Write(buffer.get(), buffer.Length(), &bytesWritten);

  // Write out the signon data.
  mSignonTable.EnumerateRead(WriteSignonEntryEnumerator, fileStream);
}

Here is the call graph for this function:

Here is the caller graph for this function:

PLDHashOperator PR_CALLBACK nsPasswordManager::WriteRejectEntryEnumerator ( const nsACString &  aKey,
PRInt32  aEntry,
void aUserData 
) [static, protected]

Definition at line 1571 of file nsPasswordManager.cpp.

{
  nsIOutputStream* stream = NS_STATIC_CAST(nsIOutputStream*, aUserData);
  PRUint32 bytesWritten;

  nsCAutoString buffer(aKey);
  buffer.Append(NS_LINEBREAK);
  stream->Write(buffer.get(), buffer.Length(), &bytesWritten);

  return PL_DHASH_NEXT;
}

Here is the call graph for this function:

Here is the caller graph for this function:

PLDHashOperator PR_CALLBACK nsPasswordManager::WriteSignonEntryEnumerator ( const nsACString &  aKey,
SignonHashEntry aEntry,
void aUserData 
) [static, protected]

Definition at line 1586 of file nsPasswordManager.cpp.

{
  nsIOutputStream* stream = NS_STATIC_CAST(nsIOutputStream*, aUserData);
  PRUint32 bytesWritten;

  nsCAutoString buffer(aKey);
  buffer.Append(NS_LINEBREAK);
  stream->Write(buffer.get(), buffer.Length(), &bytesWritten);

  for (SignonDataEntry* e = aEntry->head; e; e = e->next) {
    NS_ConvertUCS2toUTF8 userField(e->userField);
    userField.Append(NS_LINEBREAK);
    stream->Write(userField.get(), userField.Length(), &bytesWritten);

    buffer.Assign(NS_ConvertUCS2toUTF8(e->userValue));
    buffer.Append(NS_LINEBREAK);
    stream->Write(buffer.get(), buffer.Length(), &bytesWritten);

    buffer.Assign("*");
    buffer.Append(NS_ConvertUCS2toUTF8(e->passField));
    buffer.Append(NS_LINEBREAK);
    stream->Write(buffer.get(), buffer.Length(), &bytesWritten);

    buffer.Assign(NS_ConvertUCS2toUTF8(e->passValue));
    buffer.Append(NS_LINEBREAK);
    stream->Write(buffer.get(), buffer.Length(), &bytesWritten);

    buffer.Assign(e->actionOrigin);
    buffer.Append(NS_LINEBREAK);
    stream->Write(buffer.get(), buffer.Length(), &bytesWritten);
  }

  buffer.Assign("." NS_LINEBREAK);
  stream->Write(buffer.get(), buffer.Length(), &bytesWritten);

  return PL_DHASH_NEXT;
}

Here is the call graph for this function:

Here is the caller graph for this function:


Member Data Documentation

Called to enumerate through each login in the password-manager list The objects enumerated over are of type nsIPassword.

Definition at line 94 of file nsIPasswordManager.idl.

Definition at line 190 of file nsPasswordManager.h.

Definition at line 194 of file nsPasswordManager.h.

Definition at line 193 of file nsPasswordManager.h.

Definition at line 189 of file nsPasswordManager.h.

Definition at line 192 of file nsPasswordManager.h.

Definition at line 188 of file nsPasswordManager.h.

Called to enumerate through each rejected site in the password-manager list These are sites for which the user has indicated that he doesn't want passwords saved.

The objects enumerated over are of type nsIPassword, although the only member of that object that is relevent is the host (the user and password members are ignored).

Definition at line 102 of file nsIPasswordManager.idl.

const unsigned long nsIWebProgressListener::STATE_IS_BROKEN = 0x00000001 [inherited]

Definition at line 205 of file nsIWebProgressListener.idl.

const unsigned long nsIWebProgressListener::STATE_IS_DOCUMENT = 0x00020000 [inherited]

Definition at line 163 of file nsIWebProgressListener.idl.

const unsigned long nsIWebProgressListener::STATE_IS_INSECURE = 0x00000004 [inherited]

State Security Flags.

These flags describe the security state reported by a call to the onSecurityChange method. These flags are mutually exclusive.

STATE_IS_INSECURE This flag indicates that the data corresponding to the request was received over an insecure channel.

STATE_IS_BROKEN This flag indicates an unknown security state. This may mean that the request is being loaded as part of a page in which some content was received over an insecure channel.

STATE_IS_SECURE This flag indicates that the data corresponding to the request was received over a secure channel. The degree of security is expressed by STATE_SECURE_HIGH, STATE_SECURE_MED, or STATE_SECURE_LOW.

Definition at line 204 of file nsIWebProgressListener.idl.

const unsigned long nsIWebProgressListener::STATE_IS_NETWORK = 0x00040000 [inherited]

Definition at line 164 of file nsIWebProgressListener.idl.

const unsigned long nsIWebProgressListener::STATE_IS_REQUEST = 0x00010000 [inherited]

State Type Flags.

These flags further describe the entity for which the state transition is occuring. These flags are NOT mutually exclusive (i.e., an onStateChange event may indicate some combination of these flags).

STATE_IS_REQUEST This flag indicates that the state transition is for a request, which includes but is not limited to document requests. (See below for a description of document requests.) Other types of requests, such as requests for inline content (e.g., images and stylesheets) are considered normal requests.

STATE_IS_DOCUMENT This flag indicates that the state transition is for a document request. This flag is set in addition to STATE_IS_REQUEST. A document request supports the nsIChannel interface and its loadFlags attribute includes the nsIChannel::LOAD_DOCUMENT_URI flag.

A document request does not complete until all requests associated with the loading of its corresponding document have completed. This includes other document requests (e.g., corresponding to HTML <iframe> elements). The document corresponding to a document request is available via the DOMWindow attribute of onStateChange's aWebProgress parameter.

STATE_IS_NETWORK This flag indicates that the state transition corresponds to the start or stop of activity in the indicated nsIWebProgress instance. This flag is accompanied by either STATE_START or STATE_STOP, and it may be combined with other State Type Flags.

Unlike STATE_IS_WINDOW, this flag is only set when activity within the nsIWebProgress instance being observed starts or stops. If activity only occurs in a child nsIWebProgress instance, then this flag will be set to indicate the start and stop of that activity.

For example, in the case of navigation within a single frame of a HTML frameset, a nsIWebProgressListener instance attached to the nsIWebProgress of the frameset window will receive onStateChange calls with the STATE_IS_NETWORK flag set to indicate the start and stop of said navigation. In other words, an observer of an outer window can determine when activity, that may be constrained to a child window or set of child windows, starts and stops.

STATE_IS_WINDOW This flag indicates that the state transition corresponds to the start or stop of activity in the indicated nsIWebProgress instance. This flag is accompanied by either STATE_START or STATE_STOP, and it may be combined with other State Type Flags.

This flag is similar to STATE_IS_DOCUMENT. However, when a document request completes, two onStateChange calls with STATE_STOP are generated. The document request is passed as aRequest to both calls. The first has STATE_IS_REQUEST and STATE_IS_DOCUMENT set, and the second has the STATE_IS_WINDOW flag set (and possibly the STATE_IS_NETWORK flag set as well -- see above for a description of when the STATE_IS_NETWORK flag may be set). This second STATE_STOP event may be useful as a way to partition the work that occurs when a document request completes.

Definition at line 162 of file nsIWebProgressListener.idl.

const unsigned long nsIWebProgressListener::STATE_IS_SECURE = 0x00000002 [inherited]

Definition at line 206 of file nsIWebProgressListener.idl.

const unsigned long nsIWebProgressListener::STATE_IS_WINDOW = 0x00080000 [inherited]

Definition at line 165 of file nsIWebProgressListener.idl.

const unsigned long nsIWebProgressListener::STATE_NEGOTIATING = 0x00000008 [inherited]

Definition at line 98 of file nsIWebProgressListener.idl.

const unsigned long nsIWebProgressListener::STATE_REDIRECTING = 0x00000002 [inherited]

Definition at line 96 of file nsIWebProgressListener.idl.

const unsigned long nsIWebProgressListener::STATE_RESTORING = 0x01000000 [inherited]

State Modifier Flags.

These flags further describe the transition which is occuring. These flags are NOT mutually exclusive (i.e., an onStateChange event may indicate some combination of these flags).

STATE_RESTORING This flag indicates that the state transition corresponds to the start or stop of activity for restoring a previously-rendered presentation. As such, there is no actual network activity associated with this request, and any modifications made to the document or presentation when it was originally loaded will still be present.

Definition at line 182 of file nsIWebProgressListener.idl.

const unsigned long nsIWebProgressListener::STATE_SECURE_HIGH = 0x00040000 [inherited]

Security Strength Flags.

These flags describe the security strength and accompany STATE_IS_SECURE in a call to the onSecurityChange method. These flags are mutually exclusive.

These flags are not meant to provide a precise description of data transfer security. These are instead intended as a rough indicator that may be used to, for example, color code a security indicator or otherwise provide basic data transfer security feedback to the user.

STATE_SECURE_HIGH This flag indicates a high degree of security.

STATE_SECURE_MED This flag indicates a medium degree of security.

STATE_SECURE_LOW This flag indicates a low degree of security.

Definition at line 229 of file nsIWebProgressListener.idl.

const unsigned long nsIWebProgressListener::STATE_SECURE_LOW = 0x00020000 [inherited]

Definition at line 231 of file nsIWebProgressListener.idl.

const unsigned long nsIWebProgressListener::STATE_SECURE_MED = 0x00010000 [inherited]

Definition at line 230 of file nsIWebProgressListener.idl.

const unsigned long nsIWebProgressListener::STATE_START = 0x00000001 [inherited]

State Transition Flags.

These flags indicate the various states that requests may transition through as they are being loaded. These flags are mutually exclusive.

For any given request, onStateChange is called once with the STATE_START flag, zero or more times with the STATE_TRANSFERRING flag or once with the STATE_REDIRECTING flag, and then finally once with the STATE_STOP flag. NOTE: For document requests, a second STATE_STOP is generated (see the description of STATE_IS_WINDOW for more details).

STATE_START This flag indicates the start of a request. This flag is set when a request is initiated. The request is complete when onStateChange is called for the same request with the STATE_STOP flag set.

STATE_REDIRECTING This flag indicates that a request is being redirected. The request passed to onStateChange is the request that is being redirected. When a redirect occurs, a new request is generated automatically to process the new request. Expect a corresponding STATE_START event for the new request, and a STATE_STOP for the redirected request.

STATE_TRANSFERRING This flag indicates that data for a request is being transferred to an end consumer. This flag indicates that the request has been targeted, and that the user may start seeing content corresponding to the request.

STATE_NEGOTIATING This flag is not used.

STATE_STOP This flag indicates the completion of a request. The aStatus parameter to onStateChange indicates the final status of the request.

Definition at line 95 of file nsIWebProgressListener.idl.

const unsigned long nsIWebProgressListener::STATE_STOP = 0x00000010 [inherited]

Definition at line 99 of file nsIWebProgressListener.idl.

const unsigned long nsIWebProgressListener::STATE_TRANSFERRING = 0x00000004 [inherited]

Definition at line 97 of file nsIWebProgressListener.idl.


The documentation for this class was generated from the following files: