nsNetscapeProfileMigratorBase.cpp
Go to the documentation of this file.
1 /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
2 /* ***** BEGIN LICENSE BLOCK *****
3  * Version: MPL 1.1/GPL 2.0/LGPL 2.1
4  *
5  * The contents of this file are subject to the Mozilla Public License Version
6  * 1.1 (the "License"); you may not use this file except in compliance with
7  * the License. You may obtain a copy of the License at
8  * http://www.mozilla.org/MPL/
9  *
10  * Software distributed under the License is distributed on an "AS IS" basis,
11  * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
12  * for the specific language governing rights and limitations under the
13  * License.
14  *
15  * The Original Code is The Browser Profile Migrator.
16  *
17  * The Initial Developer of the Original Code is Ben Goodger.
18  * Portions created by the Initial Developer are Copyright (C) 2004
19  * the Initial Developer. All Rights Reserved.
20  *
21  * Contributor(s):
22  * Ben Goodger <ben@bengoodger.com>
23  *
24  * Alternatively, the contents of this file may be used under the terms of
25  * either the GNU General Public License Version 2 or later (the "GPL"), or
26  * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
27  * in which case the provisions of the GPL or the LGPL are applicable instead
28  * of those above. If you wish to allow use of your version of this file only
29  * under the terms of either the GPL or the LGPL, and not to allow others to
30  * use your version of this file under the terms of the MPL, indicate your
31  * decision by deleting the provisions above and replace them with the notice
32  * and other provisions required by the GPL or the LGPL. If you do not delete
33  * the provisions above, a recipient may use your version of this file under
34  * the terms of any one of the MPL, the GPL or the LGPL.
35  *
36  * ***** END LICENSE BLOCK ***** */
37 
38 #include "nsAppDirectoryServiceDefs.h"
40 #include "nsICookieManager2.h"
41 #include "nsIFile.h"
42 #include "nsILineInputStream.h"
43 #include "nsIOutputStream.h"
44 #include "nsIPrefBranch.h"
45 #include "nsIPrefLocalizedString.h"
46 #include "nsIPrefService.h"
47 #include "NSReg.h"
48 #include "nsIServiceManager.h"
49 #include "nsISupportsPrimitives.h"
50 #include "nsIURL.h"
52 #include "nsNetUtil.h"
53 #include "prtime.h"
54 #include "prprf.h"
55 
56 #ifdef XP_MACOSX
57 #define NEED_TO_FIX_4X_COOKIES 1
58 #define SECONDS_BETWEEN_1900_AND_1970 2208988800UL
59 #endif /* XP_MACOSX */
60 
61 #define FILE_NAME_PREFS_5X NS_LITERAL_STRING("prefs.js")
62 
64 // nsNetscapeProfileMigratorBase
66 {
67 }
68 
69 static nsresult
70 regerr2nsresult(REGERR errCode)
71 {
72  switch (errCode) {
73  case REGERR_PARAM:
74  case REGERR_BADTYPE:
75  case REGERR_BADNAME:
76  return NS_ERROR_INVALID_ARG;
77 
78  case REGERR_MEMORY:
79  return NS_ERROR_OUT_OF_MEMORY;
80  }
81  return NS_ERROR_FAILURE;
82 }
83 
84 nsresult
86  nsISupportsArray* aProfileNames,
87  nsISupportsArray* aProfileLocations)
88 {
89  nsresult rv;
90  REGERR errCode;
91 
92  // Ensure aRegistryFile exists before open it
93  PRBool regFileExists = PR_FALSE;
94  rv = aRegistryFile->Exists(&regFileExists);
95  NS_ENSURE_SUCCESS(rv, rv);
96  if (!regFileExists)
97  return NS_ERROR_FILE_NOT_FOUND;
98 
99  // Open It
100  nsCAutoString regPath;
101  rv = aRegistryFile->GetNativePath(regPath);
102  NS_ENSURE_SUCCESS(rv, rv);
103 
104  if ((errCode = NR_StartupRegistry()))
105  return regerr2nsresult(errCode);
106 
107  HREG reg;
108  if ((errCode = NR_RegOpen(regPath.get(), &reg))) {
109  NR_ShutdownRegistry();
110 
111  return regerr2nsresult(errCode);
112  }
113 
114  RKEY profilesTree;
115  if ((errCode = NR_RegGetKey(reg, ROOTKEY_COMMON, "Profiles", &profilesTree))) {
116  NR_RegClose(reg);
117  NR_ShutdownRegistry();
118 
119  return regerr2nsresult(errCode);
120  }
121 
122  char profileStr[MAXREGPATHLEN];
123  REGENUM enumState = nsnull;
124 
125  while (!NR_RegEnumSubkeys(reg, profilesTree, &enumState, profileStr,
126  sizeof(profileStr), REGENUM_CHILDREN))
127  {
128  RKEY profileKey;
129  if (NR_RegGetKey(reg, profilesTree, profileStr, &profileKey))
130  continue;
131 
132  // "migrated" is "yes" for all valid Seamonkey profiles. It is only "no"
133  // for 4.x profiles.
134  char migratedStr[3];
135  errCode = NR_RegGetEntryString(reg, profileKey, (char *)"migrated",
136  migratedStr, sizeof(migratedStr));
137  if ((errCode != REGERR_OK && errCode != REGERR_BUFTOOSMALL) ||
138  strcmp(migratedStr, "no") == 0)
139  continue;
140 
141  // Get the profile location and add it to the locations array
142  REGINFO regInfo;
143  regInfo.size = sizeof(REGINFO);
144 
145  if (NR_RegGetEntryInfo(reg, profileKey, (char *)"directory", &regInfo))
146  continue;
147 
148  nsCAutoString dirStr;
149  dirStr.SetLength(regInfo.entryLength);
150 
151  errCode = NR_RegGetEntryString(reg, profileKey, (char *)"directory",
152  dirStr.BeginWriting(), regInfo.entryLength);
153  // Remove trailing \0
154  dirStr.SetLength(regInfo.entryLength-1);
155 
156  nsCOMPtr<nsILocalFile> dir;
157 #ifdef XP_MACOSX
158  rv = NS_NewNativeLocalFile(EmptyCString(), PR_TRUE, getter_AddRefs(dir));
159  if (NS_FAILED(rv)) break;
160  dir->SetPersistentDescriptor(dirStr);
161 #else
162  rv = NS_NewLocalFile(NS_ConvertUTF8toUTF16(dirStr), PR_TRUE,
163  getter_AddRefs(dir));
164  if (NS_FAILED(rv)) break;
165 #endif
166 
167  PRBool exists;
168  dir->Exists(&exists);
169 
170  if (exists) {
171  aProfileLocations->AppendElement(dir);
172 
173  // Get the profile name and add it to the names array
174  nsString profileName;
175  CopyUTF8toUTF16(nsDependentCString(profileStr), profileName);
176 
177  nsCOMPtr<nsISupportsString> profileNameString(
178  do_CreateInstance("@mozilla.org/supports-string;1"));
179 
180  profileNameString->SetData(profileName);
181  aProfileNames->AppendElement(profileNameString);
182  }
183  }
184  NR_RegClose(reg);
185  NR_ShutdownRegistry();
186 
187  return rv;
188 }
189 
190 #define GETPREF(xform, method, value) \
191  nsresult rv = aBranch->method(xform->sourcePrefName, value); \
192  if (NS_SUCCEEDED(rv)) \
193  xform->prefHasValue = PR_TRUE; \
194  return rv;
195 
196 #define SETPREF(xform, method, value) \
197  if (xform->prefHasValue) { \
198  return aBranch->method(xform->targetPrefName ? xform->targetPrefName : xform->sourcePrefName, value); \
199  } \
200  return NS_OK;
201 
202 nsresult
204 {
205  PrefTransform* xform = (PrefTransform*)aTransform;
206  GETPREF(xform, GetCharPref, &xform->stringValue);
207 }
208 
209 nsresult
211 {
212  PrefTransform* xform = (PrefTransform*)aTransform;
213  SETPREF(xform, SetCharPref, xform->stringValue);
214 }
215 
216 nsresult
218 {
219  PrefTransform* xform = (PrefTransform*)aTransform;
220  nsCOMPtr<nsIPrefLocalizedString> prefValue;
221  nsresult rv = aBranch->GetComplexValue(xform->sourcePrefName,
222  NS_GET_IID(nsIPrefLocalizedString),
223  getter_AddRefs(prefValue));
224 
225  if (NS_SUCCEEDED(rv) && prefValue) {
226  nsString data;
227  prefValue->ToString(getter_Copies(data));
228 
229  xform->stringValue = ToNewCString(NS_ConvertUTF16toUTF8(data));
230  xform->prefHasValue = PR_TRUE;
231  }
232  return rv;
233 }
234 
235 nsresult
237 {
238  PrefTransform* xform = (PrefTransform*)aTransform;
239  if (xform->prefHasValue) {
240  nsCOMPtr<nsIPrefLocalizedString> pls(do_CreateInstance("@mozilla.org/pref-localizedstring;1"));
241  NS_ConvertUTF8toUTF16 data(xform->stringValue);
242  pls->SetData(data.get());
243  return aBranch->SetComplexValue(xform->targetPrefName ? xform->targetPrefName : xform->sourcePrefName, NS_GET_IID(nsIPrefLocalizedString), pls);
244  }
245  return NS_OK;
246 }
247 
248 nsresult
250 {
251  PrefTransform* xform = (PrefTransform*)aTransform;
252  if (xform->prefHasValue) {
253  nsCOMPtr<nsIPrefLocalizedString> pls(do_CreateInstance("@mozilla.org/pref-localizedstring;1"));
254  nsAutoString data = NS_ConvertUTF8toUTF16(xform->stringValue);
255  pls->SetData(data.get());
256  return aBranch->SetComplexValue(xform->targetPrefName ? xform->targetPrefName : xform->sourcePrefName, NS_GET_IID(nsIPrefLocalizedString), pls);
257  }
258  return NS_OK;
259 }
260 
261 
262 nsresult
264 {
265  PrefTransform* xform = (PrefTransform*)aTransform;
266  GETPREF(xform, GetBoolPref, &xform->boolValue);
267 }
268 
269 nsresult
271 {
272  PrefTransform* xform = (PrefTransform*)aTransform;
273  SETPREF(xform, SetBoolPref, xform->boolValue);
274 }
275 
276 nsresult
278 {
279  PrefTransform* xform = (PrefTransform*)aTransform;
280  GETPREF(xform, GetIntPref, &xform->intValue);
281 }
282 
283 nsresult
285 {
286  PrefTransform* xform = (PrefTransform*)aTransform;
287  SETPREF(xform, SetIntPref, xform->intValue);
288 }
289 
290 nsresult
291 nsNetscapeProfileMigratorBase::CopyFile(const nsAString& aSourceFileName, const nsAString& aTargetFileName)
292 {
293  nsCOMPtr<nsIFile> sourceFile;
294  mSourceProfile->Clone(getter_AddRefs(sourceFile));
295 
296  sourceFile->Append(aSourceFileName);
297  PRBool exists = PR_FALSE;
298  sourceFile->Exists(&exists);
299  if (!exists)
300  return NS_OK;
301 
302  nsCOMPtr<nsIFile> targetFile;
303  mTargetProfile->Clone(getter_AddRefs(targetFile));
304 
305  targetFile->Append(aTargetFileName);
306  targetFile->Exists(&exists);
307  if (exists)
308  targetFile->Remove(PR_FALSE);
309 
310  return sourceFile->CopyTo(mTargetProfile, aTargetFileName);
311 }
312 
313 nsresult
314 nsNetscapeProfileMigratorBase::ImportNetscapeBookmarks(const nsAString& aBookmarksFileName,
315  const PRUnichar* aImportSourceNameKey)
316 {
317  nsCOMPtr<nsIFile> bookmarksFile;
318  mSourceProfile->Clone(getter_AddRefs(bookmarksFile));
319  bookmarksFile->Append(aBookmarksFileName);
320 
321  return ImportBookmarksHTML(bookmarksFile, PR_FALSE, PR_FALSE, aImportSourceNameKey);
322 }
323 
324 nsresult
326 {
327  nsresult rv;
328  nsCOMPtr<nsIInputStream> cookiesStream;
329  rv = NS_NewLocalFileInputStream(getter_AddRefs(cookiesStream), aCookiesFile);
330  if (NS_FAILED(rv)) return rv;
331 
332  nsCOMPtr<nsILineInputStream> lineInputStream(do_QueryInterface(cookiesStream));
333 
334  // This code is copied from mozilla/netwerk/cookie/src/nsCookieManager.cpp
335  static NS_NAMED_LITERAL_CSTRING(kTrue, "TRUE");
336 
337  nsCAutoString buffer;
338  PRBool isMore = PR_TRUE;
339  PRInt32 hostIndex = 0, isDomainIndex, pathIndex, secureIndex, expiresIndex, nameIndex, cookieIndex;
340  PRInt32 numInts;
341  PRInt64 expires;
342  PRBool isDomain;
343  PRInt64 currentTime = PR_Now() / PR_USEC_PER_SEC;
344 
345  nsCOMPtr<nsICookieManager2> cookieManager(do_GetService(NS_COOKIEMANAGER_CONTRACTID, &rv));
346  if (NS_FAILED(rv)) return rv;
347 
348  /* file format is:
349  *
350  * host \t isDomain \t path \t secure \t expires \t name \t cookie
351  *
352  * if this format isn't respected we move onto the next line in the file.
353  * isDomain is "TRUE" or "FALSE" (default to "FALSE")
354  * isSecure is "TRUE" or "FALSE" (default to "TRUE")
355  * expires is a PRInt64 integer
356  * note 1: cookie can contain tabs.
357  * note 2: cookies are written in order of lastAccessed time:
358  * most-recently used come first; least-recently-used come last.
359  */
360 
361  while (isMore && NS_SUCCEEDED(lineInputStream->ReadLine(buffer, &isMore))) {
362  if (buffer.IsEmpty() || buffer.First() == '#')
363  continue;
364 
365  // this is a cheap, cheesy way of parsing a tab-delimited line into
366  // string indexes, which can be lopped off into substrings. just for
367  // purposes of obfuscation, it also checks that each token was found.
368  // todo: use iterators?
369  if ((isDomainIndex = buffer.FindChar('\t', hostIndex) + 1) == 0 ||
370  (pathIndex = buffer.FindChar('\t', isDomainIndex) + 1) == 0 ||
371  (secureIndex = buffer.FindChar('\t', pathIndex) + 1) == 0 ||
372  (expiresIndex = buffer.FindChar('\t', secureIndex) + 1) == 0 ||
373  (nameIndex = buffer.FindChar('\t', expiresIndex) + 1) == 0 ||
374  (cookieIndex = buffer.FindChar('\t', nameIndex) + 1) == 0)
375  continue;
376 
377  // check the expirytime first - if it's expired, ignore
378  // nullstomp the trailing tab, to avoid copying the string
379  char *iter = buffer.BeginWriting();
380  *(iter += nameIndex - 1) = char(0);
381  numInts = PR_sscanf(buffer.get() + expiresIndex, "%lld", &expires);
382  if (numInts != 1 || expires < currentTime)
383  continue;
384 
385  isDomain = Substring(buffer, isDomainIndex, pathIndex - isDomainIndex - 1).Equals(kTrue);
386  const nsDependentCSubstring host =
387  Substring(buffer, hostIndex, isDomainIndex - hostIndex - 1);
388  // check for bad legacy cookies (domain not starting with a dot, or containing a port),
389  // and discard
390  if (isDomain && !host.IsEmpty() && host.First() != '.' ||
391  host.FindChar(':') != -1)
392  continue;
393 
394  // create a new nsCookie and assign the data.
395  rv = cookieManager->Add(host,
396  Substring(buffer, pathIndex, secureIndex - pathIndex - 1),
397  Substring(buffer, nameIndex, cookieIndex - nameIndex - 1),
398  Substring(buffer, cookieIndex, buffer.Length() - cookieIndex),
399  Substring(buffer, secureIndex, expiresIndex - secureIndex - 1).Equals(kTrue),
400  PR_FALSE, // isHttpOnly
401  PR_FALSE, // isSession
402  expires);
403  }
404 
405  return rv;
406 }
407 
408 nsresult
409 nsNetscapeProfileMigratorBase::GetSignonFileName(PRBool aReplace, char** aFileName)
410 {
411  nsresult rv;
412  if (aReplace) {
413  // Find out what the signons file was called, this is stored in a pref
414  // in Seamonkey.
415  nsCOMPtr<nsIPrefService> psvc(do_GetService(NS_PREFSERVICE_CONTRACTID));
416  psvc->ResetPrefs();
417 
418  nsCOMPtr<nsIFile> sourcePrefsName;
419  mSourceProfile->Clone(getter_AddRefs(sourcePrefsName));
420  sourcePrefsName->Append(FILE_NAME_PREFS_5X);
421  psvc->ReadUserPrefs(sourcePrefsName);
422 
423  nsCOMPtr<nsIPrefBranch> branch(do_QueryInterface(psvc));
424  rv = branch->GetCharPref("signon.SignonFileName", aFileName);
425  }
426  else
427  rv = LocateSignonsFile(aFileName);
428  return rv;
429 }
430 
431 nsresult
433 {
434  nsCOMPtr<nsISimpleEnumerator> entries;
435  nsresult rv = mSourceProfile->GetDirectoryEntries(getter_AddRefs(entries));
436  if (NS_FAILED(rv)) return rv;
437 
438  nsCAutoString fileName;
439  do {
440  PRBool hasMore = PR_FALSE;
441  rv = entries->HasMoreElements(&hasMore);
442  if (NS_FAILED(rv) || !hasMore) break;
443 
444  nsCOMPtr<nsISupports> supp;
445  rv = entries->GetNext(getter_AddRefs(supp));
446  if (NS_FAILED(rv)) break;
447 
448  nsCOMPtr<nsIFile> currFile(do_QueryInterface(supp));
449 
450  nsCOMPtr<nsIURI> uri;
451  rv = NS_NewFileURI(getter_AddRefs(uri), currFile);
452  if (NS_FAILED(rv)) break;
453  nsCOMPtr<nsIURL> url(do_QueryInterface(uri));
454 
455  nsCAutoString extn;
456  url->GetFileExtension(extn);
457 
458  if (extn.Equals("s", CaseInsensitiveCompare)) {
459  url->GetFileName(fileName);
460  break;
461  }
462  }
463  while (1);
464 
465  *aResult = ToNewCString(fileName);
466 
467  return NS_OK;
468 }
469 
nsresult CopyFile(const nsAString &aSourceFileName, const nsAString &aTargetFileName)
nsresult ImportNetscapeBookmarks(const nsAString &aBookmarksFileName, const PRUnichar *aImportSourceNameKey)
return NS_OK
static nsresult SetInt(void *aTransform, nsIPrefBranch *aBranch)
static nsresult GetInt(void *aTransform, nsIPrefBranch *aBranch)
const NS_PREFSERVICE_CONTRACTID
const nsIPrefLocalizedString
static nsresult regerr2nsresult(REGERR errCode)
#define SETPREF(xform, method, value)
#define FILE_NAME_PREFS_5X
nsresult ImportBookmarksHTML(nsIFile *aBookmarksFile, PRBool aImportIntoRoot, PRBool aOverwriteDefaults, const PRUnichar *aImportSourceNameKey)
static nsresult SetWString(void *aTransform, nsIPrefBranch *aBranch)
const nsIPrefBranch
nsresult GetProfileDataFromRegistry(nsILocalFile *aRegistryFile, nsISupportsArray *aProfileNames, nsISupportsArray *aProfileLocations)
static nsresult GetWString(void *aTransform, nsIPrefBranch *aBranch)
static nsresult GetBool(void *aTransform, nsIPrefBranch *aBranch)
static nsresult SetWStringFromASCII(void *aTransform, nsIPrefBranch *aBranch)
static nsresult SetString(void *aTransform, nsIPrefBranch *aBranch)
function url(spec)
var uri
Definition: FeedWriter.js:1135
StringArrayEnumerator prototype hasMore
static nsresult SetBool(void *aTransform, nsIPrefBranch *aBranch)
static nsresult GetString(void *aTransform, nsIPrefBranch *aBranch)
#define GETPREF(xform, method, value)
observe data
Definition: FeedWriter.js:1329
nsresult ImportNetscapeCookies(nsIFile *aCookiesFile)
nsresult GetSignonFileName(PRBool aReplace, char **aFileName)