Back to index

lightning-sunbird  0.9+nobinonly
nsMsgUtils.cpp
Go to the documentation of this file.
00001 /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
00002 /* ***** BEGIN LICENSE BLOCK *****
00003  * Version: MPL 1.1/GPL 2.0/LGPL 2.1
00004  *
00005  * The contents of this file are subject to the Mozilla Public License Version
00006  * 1.1 (the "License"); you may not use this file except in compliance with
00007  * the License. You may obtain a copy of the License at
00008  * http://www.mozilla.org/MPL/
00009  *
00010  * Software distributed under the License is distributed on an "AS IS" basis,
00011  * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
00012  * for the specific language governing rights and limitations under the
00013  * License.
00014  *
00015  * The Original Code is mozilla.org code.
00016  *
00017  * The Initial Developer of the Original Code is
00018  * Netscape Communications Corporation.
00019  * Portions created by the Initial Developer are Copyright (C) 1999
00020  * the Initial Developer. All Rights Reserved.
00021  *
00022  * Contributor(s):
00023  *   Pierre Phaneuf <pp@ludusdesign.com>
00024  *
00025  * Alternatively, the contents of this file may be used under the terms of
00026  * either of the GNU General Public License Version 2 or later (the "GPL"),
00027  * or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
00028  * in which case the provisions of the GPL or the LGPL are applicable instead
00029  * of those above. If you wish to allow use of your version of this file only
00030  * under the terms of either the GPL or the LGPL, and not to allow others to
00031  * use your version of this file under the terms of the MPL, indicate your
00032  * decision by deleting the provisions above and replace them with the notice
00033  * and other provisions required by the GPL or the LGPL. If you do not delete
00034  * the provisions above, a recipient may use your version of this file under
00035  * the terms of any one of the MPL, the GPL or the LGPL.
00036  *
00037  * ***** END LICENSE BLOCK ***** */
00038 
00039 #include "msgCore.h"
00040 #include "nsIMsgHdr.h"
00041 #include "nsMsgUtils.h"
00042 #include "nsString.h"
00043 #include "nsReadableUtils.h"
00044 #include "nsFileSpec.h"
00045 #include "nsEscape.h"
00046 #include "nsIServiceManager.h"
00047 #include "nsCOMPtr.h"
00048 #include "nsIImapUrl.h"
00049 #include "nsIMailboxUrl.h"
00050 #include "nsINntpUrl.h"
00051 #include "nsMsgNewsCID.h"
00052 #include "nsMsgLocalCID.h"
00053 #include "nsMsgBaseCID.h"
00054 #include "nsMsgImapCID.h"
00055 #include "nsMsgI18N.h"
00056 #include "nsNativeCharsetUtils.h"
00057 #include "nsUnicharUtils.h"
00058 #include "prprf.h"
00059 #include "nsNetCID.h"
00060 #include "nsIIOService.h"
00061 #include "nsIRDFService.h"
00062 #include "nsIMimeConverter.h"
00063 #include "nsMsgMimeCID.h"
00064 #include "nsIPrefService.h"
00065 #include "nsIPrefBranch.h"
00066 #include "nsISupportsPrimitives.h"
00067 #include "nsIPrefLocalizedString.h"
00068 #include "nsIRelativeFilePref.h"
00069 #include "nsAppDirectoryServiceDefs.h"
00070 #include "nsICategoryManager.h"
00071 #include "nsCategoryManagerUtils.h"
00072 #include "nsISpamSettings.h"
00073 #include "nsISignatureVerifier.h"
00074 #include "nsICryptoHash.h"
00075 #include "nsNativeCharsetUtils.h"
00076 #include "nsIRssIncomingServer.h"
00077 #include "nsIMsgFolder.h"
00078 #include "nsIMsgMessageService.h"
00079 #include "nsIMsgAccountManager.h"
00080 
00081 
00082 static NS_DEFINE_CID(kImapUrlCID, NS_IMAPURL_CID);
00083 static NS_DEFINE_CID(kCMailboxUrl, NS_MAILBOXURL_CID);
00084 static NS_DEFINE_CID(kCNntpUrlCID, NS_NNTPURL_CID);
00085 
00086 #define ILLEGAL_FOLDER_CHARS ";#"
00087 #define ILLEGAL_FOLDER_CHARS_AS_FIRST_LETTER "." 
00088 #define ILLEGAL_FOLDER_CHARS_AS_LAST_LETTER  ".~ "
00089 
00090 #define NS_PASSWORDMANAGER_CATEGORY "passwordmanager"
00091 static PRBool gInitPasswordManager = PR_FALSE;
00092 
00093 nsresult GetMessageServiceContractIDForURI(const char *uri, nsCString &contractID)
00094 {
00095   nsresult rv = NS_OK;
00096   //Find protocol
00097   nsCAutoString uriStr(uri);
00098   PRInt32 pos = uriStr.FindChar(':');
00099   if(pos == kNotFound)
00100     return NS_ERROR_FAILURE;
00101 
00102   nsCAutoString protocol;
00103   uriStr.Left(protocol, pos);
00104 
00105   if (protocol.Equals("file") && uriStr.Find("application/x-message-display") != kNotFound)
00106     protocol.Assign("mailbox");
00107   //Build message service contractid
00108   contractID = "@mozilla.org/messenger/messageservice;1?type=";
00109   contractID += protocol.get();
00110 
00111   return rv;
00112 }
00113 
00114 nsresult GetMessageServiceFromURI(const char *uri, nsIMsgMessageService **aMessageService)
00115 {
00116   nsresult rv;
00117 
00118   nsCAutoString contractID;
00119   rv = GetMessageServiceContractIDForURI(uri, contractID);
00120   NS_ENSURE_SUCCESS(rv,rv);
00121 
00122   nsCOMPtr <nsIMsgMessageService> msgService = do_GetService(contractID.get(), &rv);
00123   NS_ENSURE_SUCCESS(rv,rv);
00124 
00125   NS_IF_ADDREF(*aMessageService = msgService);
00126   return rv;
00127 }
00128 
00129 nsresult GetMsgDBHdrFromURI(const char *uri, nsIMsgDBHdr **msgHdr)
00130 {
00131   nsCOMPtr <nsIMsgMessageService> msgMessageService;
00132   nsresult rv = GetMessageServiceFromURI(uri, getter_AddRefs(msgMessageService));
00133   NS_ENSURE_SUCCESS(rv,rv);
00134   if (!msgMessageService) return NS_ERROR_FAILURE;
00135 
00136   return msgMessageService->MessageURIToMsgHdr(uri, msgHdr);
00137 }
00138 
00139 nsresult CreateStartupUrl(const char *uri, nsIURI** aUrl)
00140 {
00141   nsresult rv = NS_ERROR_NULL_POINTER;
00142   if (!uri || !*uri || !aUrl) return rv;
00143   *aUrl = nsnull;
00144   
00145   // XXX fix this, so that base doesn't depend on imap, local or news.
00146   // we can't do NS_NewURI(uri, aUrl), because these are imap-message://, mailbox-message://, news-message:// uris.
00147   // I think we should do something like GetMessageServiceFromURI() to get the service, and then have the service create the 
00148   // appropriate nsI*Url, and then QI to nsIURI, and return it.
00149   // see bug #110689
00150   if (PL_strncasecmp(uri, "imap", 4) == 0)
00151   {
00152     nsCOMPtr<nsIImapUrl> imapUrl = do_CreateInstance(kImapUrlCID, &rv);
00153     
00154     if (NS_SUCCEEDED(rv) && imapUrl)
00155       rv = imapUrl->QueryInterface(NS_GET_IID(nsIURI),
00156       (void**) aUrl);
00157   }
00158   else if (PL_strncasecmp(uri, "mailbox", 7) == 0)
00159   {
00160     nsCOMPtr<nsIMailboxUrl> mailboxUrl = do_CreateInstance(kCMailboxUrl, &rv);
00161     if (NS_SUCCEEDED(rv) && mailboxUrl)
00162       rv = mailboxUrl->QueryInterface(NS_GET_IID(nsIURI),
00163       (void**) aUrl);
00164   }
00165   else if (PL_strncasecmp(uri, "news", 4) == 0)
00166   {
00167     nsCOMPtr<nsINntpUrl> nntpUrl = do_CreateInstance(kCNntpUrlCID, &rv);
00168     if (NS_SUCCEEDED(rv) && nntpUrl)
00169       rv = nntpUrl->QueryInterface(NS_GET_IID(nsIURI),
00170       (void**) aUrl);
00171   }
00172   if (*aUrl)
00173     (*aUrl)->SetSpec(nsDependentCString(uri));
00174   return rv;
00175 }
00176 
00177 
00178 // Where should this live? It's a utility used to convert a string priority,
00179 //  e.g., "High, Low, Normal" to an enum.
00180 // Perhaps we should have an interface that groups together all these
00181 //  utilities...
00182 nsresult NS_MsgGetPriorityFromString(
00183            const char * const priority,
00184            nsMsgPriorityValue & outPriority)
00185 {
00186   if (!priority)
00187     return NS_ERROR_NULL_POINTER;
00188 
00189   // Note: Checking the values separately and _before_ the names,
00190   //        hoping for a much faster match;
00191   //       Only _drawback_, as "priority" handling is not truly specified:
00192   //        some softwares may have the number meanings reversed (1=Lowest) !?
00193   if (PL_strchr(priority, '1'))
00194     outPriority = nsMsgPriority::highest;
00195   else if (PL_strchr(priority, '2'))
00196     outPriority = nsMsgPriority::high;
00197   else if (PL_strchr(priority, '3'))
00198     outPriority = nsMsgPriority::normal;
00199   else if (PL_strchr(priority, '4'))
00200     outPriority = nsMsgPriority::low;
00201   else if (PL_strchr(priority, '5'))
00202     outPriority = nsMsgPriority::lowest;
00203   else if (PL_strcasestr(priority, "Highest"))
00204     outPriority = nsMsgPriority::highest;
00205        // Important: "High" must be tested after "Highest" !
00206   else if (PL_strcasestr(priority, "High") ||
00207            PL_strcasestr(priority, "Urgent"))
00208     outPriority = nsMsgPriority::high;
00209   else if (PL_strcasestr(priority, "Normal"))
00210     outPriority = nsMsgPriority::normal;
00211   else if (PL_strcasestr(priority, "Lowest"))
00212     outPriority = nsMsgPriority::lowest;
00213        // Important: "Low" must be tested after "Lowest" !
00214   else if (PL_strcasestr(priority, "Low") ||
00215            PL_strcasestr(priority, "Non-urgent"))
00216     outPriority = nsMsgPriority::low;
00217   else
00218     // "Default" case gets default value.
00219     outPriority = nsMsgPriority::Default;
00220 
00221   return NS_OK;
00222 }
00223 
00224 nsresult NS_MsgGetPriorityValueString(
00225            const nsMsgPriorityValue p,
00226            nsACString & outValueString)
00227 {
00228   switch (p)
00229   {
00230     case nsMsgPriority::highest:
00231       outValueString.AssignLiteral("1");
00232       break;
00233     case nsMsgPriority::high:
00234       outValueString.AssignLiteral("2");
00235       break;
00236     case nsMsgPriority::normal:
00237       outValueString.AssignLiteral("3");
00238       break;
00239     case nsMsgPriority::low:
00240       outValueString.AssignLiteral("4");
00241       break;
00242     case nsMsgPriority::lowest:
00243       outValueString.AssignLiteral("5");
00244       break;
00245     case nsMsgPriority::none:
00246     case nsMsgPriority::notSet:
00247       // Note: '0' is a "fake" value; we expect to never be in this case.
00248       outValueString.AssignLiteral("0");
00249       break;
00250     default:
00251       NS_ASSERTION(PR_FALSE, "invalid priority value");
00252   }
00253 
00254   return NS_OK;
00255 }
00256 
00257 nsresult NS_MsgGetUntranslatedPriorityName(
00258            const nsMsgPriorityValue p,
00259            nsACString & outName)
00260 {
00261   switch (p)
00262   {
00263     case nsMsgPriority::highest:
00264       outName.AssignLiteral("Highest");
00265       break;
00266     case nsMsgPriority::high:
00267       outName.AssignLiteral("High");
00268       break;
00269     case nsMsgPriority::normal:
00270       outName.AssignLiteral("Normal");
00271       break;
00272     case nsMsgPriority::low:
00273       outName.AssignLiteral("Low");
00274       break;
00275     case nsMsgPriority::lowest:
00276       outName.AssignLiteral("Lowest");
00277       break;
00278     case nsMsgPriority::none:
00279     case nsMsgPriority::notSet:
00280       // Note: 'None' is a "fake" value; we expect to never be in this case.
00281       outName.AssignLiteral("None");
00282       break;
00283     default:
00284       NS_ASSERTION(PR_FALSE, "invalid priority value");
00285   }
00286 
00287   return NS_OK;
00288 }
00289 
00290 
00291 /* this used to be XP_StringHash2 from xp_hash.c */
00292 /* phong's linear congruential hash  */
00293 static PRUint32 StringHash(const char *ubuf, PRInt32 len = -1)
00294 {
00295   unsigned char * buf = (unsigned char*) ubuf;
00296   PRUint32 h=1;
00297   unsigned char *end = buf + (len == -1 ? strlen(ubuf) : len); 
00298   while(buf < end) {
00299     h = 0x63c63cd9*h + 0x9c39c33d + (int32)*buf;
00300     buf++;
00301   }
00302   return h;
00303 }
00304 
00305 inline PRUint32 StringHash(const nsAutoString& str)
00306 {
00307     return StringHash(NS_REINTERPRET_CAST(const char*, str.get()),
00308                       str.Length() * 2);
00309 }
00310 
00311 // XXX : this may have other clients, in which case we'd better move it to
00312 //       xpcom/io/nsNativeCharsetUtils with nsAString in place of nsAutoString
00313 static PRBool ConvertibleToNative(const nsAutoString& str)
00314 {
00315     nsCAutoString native;
00316     nsAutoString roundTripped;
00317     NS_CopyUnicodeToNative(str, native);
00318     NS_CopyNativeToUnicode(native, roundTripped);
00319     return str.Equals(roundTripped);
00320 }
00321 
00322 #if defined(XP_MAC)
00323   const static PRUint32 MAX_LEN = 25;
00324 #elif defined(XP_UNIX) || defined(XP_BEOS)
00325   const static PRUint32 MAX_LEN = 55;
00326 #elif defined(XP_WIN32)
00327   const static PRUint32 MAX_LEN = 55;
00328 #elif defined(XP_OS2)
00329   const static PRUint32 MAX_LEN = 55;
00330 #else
00331   #error need_to_define_your_max_filename_length
00332 #endif
00333 
00334 nsresult NS_MsgHashIfNecessary(nsCAutoString &name)
00335 {
00336   NS_NAMED_LITERAL_CSTRING (illegalChars, 
00337                             FILE_PATH_SEPARATOR FILE_ILLEGAL_CHARACTERS ILLEGAL_FOLDER_CHARS);
00338   nsCAutoString str(name);
00339 
00340   // Given a filename, make it safe for filesystem
00341   // certain filenames require hashing because they 
00342   // are too long or contain illegal characters
00343   PRInt32 illegalCharacterIndex = str.FindCharInSet(illegalChars);
00344 
00345   // Need to check the first ('.') and last ('.', '~' and ' ') char
00346   if (illegalCharacterIndex == kNotFound) 
00347   {
00348        NS_NAMED_LITERAL_CSTRING (illegalFirstChars, ILLEGAL_FOLDER_CHARS_AS_FIRST_LETTER);
00349        NS_NAMED_LITERAL_CSTRING (illegalLastChars, ILLEGAL_FOLDER_CHARS_AS_LAST_LETTER);
00350          
00351     PRInt32 lastIndex = str.Length() - 1;
00352     if(str.FindCharInSet(illegalFirstChars) == 0)
00353          illegalCharacterIndex = 0;
00354        else if(str.RFindCharInSet(illegalLastChars) == lastIndex)
00355          illegalCharacterIndex = lastIndex;
00356        else
00357          illegalCharacterIndex = -1;
00358   }
00359 
00360   char hashedname[MAX_LEN + 1];
00361   if (illegalCharacterIndex == kNotFound) 
00362   {
00363     // no illegal chars, it's just too long
00364     // keep the initial part of the string, but hash to make it fit
00365     if (str.Length() > MAX_LEN) 
00366     {
00367       PL_strncpy(hashedname, str.get(), MAX_LEN + 1);
00368       PR_snprintf(hashedname + MAX_LEN - 8, 9, "%08lx",
00369                 (unsigned long) StringHash(str.get()));
00370       name = hashedname;
00371     }
00372   }
00373   else 
00374   {
00375       // found illegal chars, hash the whole thing
00376       // if we do substitution, then hash, two strings
00377       // could hash to the same value.
00378       // for example, on mac:  "foo__bar", "foo:_bar", "foo::bar"
00379       // would map to "foo_bar".  this way, all three will map to
00380       // different values
00381       PR_snprintf(hashedname, 9, "%08lx",
00382                 (unsigned long) StringHash(str.get()));
00383       name = hashedname;
00384   }
00385   
00386   return NS_OK;
00387 }
00388 
00389 // XXX : The number of UTF-16 2byte code units are half the number of
00390 // bytes in legacy encodings for CJK strings and non-Latin1 in UTF-8.
00391 // The ratio can be 1/3 for CJK strings in UTF-8. However, we can
00392 // get away with using the same MAX_LEN for nsCString and nsString
00393 // because MAX_LEN is defined rather conservatively in the first place.
00394 nsresult NS_MsgHashIfNecessary(nsAutoString &name)
00395 {
00396   PRInt32 illegalCharacterIndex = name.FindCharInSet(
00397                                   FILE_PATH_SEPARATOR FILE_ILLEGAL_CHARACTERS ILLEGAL_FOLDER_CHARS);
00398 
00399   // Need to check the first ('.') and last ('.', '~' and ' ') char
00400   if (illegalCharacterIndex == kNotFound) 
00401   {
00402        NS_NAMED_LITERAL_STRING (illegalFirstChars, ILLEGAL_FOLDER_CHARS_AS_FIRST_LETTER);
00403        NS_NAMED_LITERAL_STRING (illegalLastChars, ILLEGAL_FOLDER_CHARS_AS_LAST_LETTER);
00404          
00405     PRInt32 lastIndex = name.Length() - 1;
00406     if(name.FindCharInSet(illegalFirstChars) == 0)
00407          illegalCharacterIndex = 0;
00408        else if(name.RFindCharInSet(illegalLastChars) == lastIndex)
00409          illegalCharacterIndex = lastIndex;
00410        else
00411          illegalCharacterIndex = -1;
00412   }
00413 
00414   char hashedname[9];
00415   PRInt32 keptLength = -1;
00416   if (illegalCharacterIndex != kNotFound) 
00417       keptLength = illegalCharacterIndex;
00418   else if (!ConvertibleToNative(name))
00419       keptLength = 0;
00420   else if (name.Length() > MAX_LEN) 
00421   {
00422     keptLength = MAX_LEN-8; 
00423     // To avoid keeping only the high surrogate of a surrogate pair
00424     if (IS_HIGH_SURROGATE(name.CharAt(keptLength-1)))
00425         --keptLength;
00426   }
00427 
00428   if (keptLength >= 0) {
00429     PR_snprintf(hashedname, 9, "%08lx", (unsigned long) StringHash(name));
00430     name.Truncate(keptLength);
00431     AppendASCIItoUTF16(hashedname, name);
00432   }
00433 
00434   return NS_OK;
00435 }
00436 
00437 
00438 nsresult NS_MsgCreatePathStringFromFolderURI(const char *aFolderURI,
00439                                              nsCString& aPathCString,
00440                                              PRBool aIsNewsFolder)
00441 {
00442   // A file name has to be in native charset. Here we convert 
00443   // to UTF-16 and check for 'unsafe' characters before converting 
00444   // to native charset.
00445   NS_ENSURE_TRUE(IsUTF8(nsDependentCString(aFolderURI)), NS_ERROR_UNEXPECTED); 
00446   NS_ConvertUTF8toUTF16 oldPath(aFolderURI);
00447 
00448   nsAutoString pathPiece, path;
00449 
00450   PRInt32 startSlashPos = oldPath.FindChar('/');
00451   PRInt32 endSlashPos = (startSlashPos >= 0) 
00452     ? oldPath.FindChar('/', startSlashPos + 1) - 1 : oldPath.Length() - 1;
00453   if (endSlashPos < 0)
00454     endSlashPos = oldPath.Length();
00455   // trick to make sure we only add the path to the first n-1 folders
00456   PRBool haveFirst=PR_FALSE;
00457   while (startSlashPos != -1) {
00458     oldPath.Mid(pathPiece, startSlashPos + 1, endSlashPos - startSlashPos);
00459     // skip leading '/' (and other // style things)
00460     if (!pathPiece.IsEmpty())
00461     {
00462 
00463       // add .sbd onto the previous path
00464       if (haveFirst)
00465       {
00466         path.AppendLiteral(".sbd/");
00467       }
00468 
00469       if (aIsNewsFolder)
00470       {
00471           nsCAutoString tmp;
00472           CopyUTF16toMUTF7(pathPiece, tmp); 
00473           CopyASCIItoUTF16(tmp, pathPiece);
00474       }
00475         
00476       NS_MsgHashIfNecessary(pathPiece);
00477       path += pathPiece;
00478       haveFirst=PR_TRUE;
00479     }
00480     // look for the next slash
00481     startSlashPos = endSlashPos + 1;
00482 
00483     endSlashPos = (startSlashPos >= 0) 
00484       ? oldPath.FindChar('/', startSlashPos + 1)  - 1: oldPath.Length() - 1;
00485     if (endSlashPos < 0)
00486       endSlashPos = oldPath.Length();
00487 
00488     if (startSlashPos >= endSlashPos)
00489       break;
00490   }
00491 
00492   return NS_CopyUnicodeToNative(path, aPathCString);
00493 }
00494 
00495 /* Given a string and a length, removes any "Re:" strings from the front.
00496    It also deals with that dumbass "Re[2]:" thing that some losing mailers do.
00497 
00498    If mailnews.localizedRe is set, it will also remove localized "Re:" strings.
00499 
00500    Returns PR_TRUE if it made a change, PR_FALSE otherwise.
00501 
00502    The string is not altered: the pointer to its head is merely advanced,
00503    and the length correspondingly decreased.
00504  */
00505 PRBool NS_MsgStripRE(const char **stringP, PRUint32 *lengthP, char **modifiedSubject)
00506 {
00507   const char *s, *s_end;
00508   const char *last;
00509   PRUint32 L;
00510   PRBool result = PR_FALSE;
00511   NS_ASSERTION(stringP, "bad null param");
00512   if (!stringP) return PR_FALSE;
00513 
00514   // get localizedRe pref
00515   nsresult rv;
00516   nsXPIDLCString localizedRe;
00517   nsCOMPtr<nsIPrefBranch> prefBranch(do_GetService(NS_PREFSERVICE_CONTRACTID, &rv));
00518   if (NS_SUCCEEDED(rv))
00519     prefBranch->GetCharPref("mailnews.localizedRe", getter_Copies(localizedRe));
00520     
00521   // hardcoded "Re" so that noone can configure Mozilla standards incompatible 
00522   nsCAutoString checkString("Re,RE,re,rE");
00523   if (!localizedRe.IsEmpty()) 
00524     checkString.Append(NS_LITERAL_CSTRING(",") + localizedRe);
00525 
00526   // decode the string
00527   nsXPIDLCString decodedString;
00528   nsCOMPtr<nsIMimeConverter> mimeConverter;
00529   // we cannot strip "Re:" for MIME encoded subject without modifying the original
00530   if (modifiedSubject && strstr(*stringP, "=?"))
00531   {
00532     mimeConverter = do_GetService(NS_MIME_CONVERTER_CONTRACTID, &rv);
00533     if (NS_SUCCEEDED(rv))
00534       rv = mimeConverter->DecodeMimeHeader(*stringP, getter_Copies(decodedString));
00535   }
00536 
00537   s = decodedString ? decodedString.get() : *stringP;
00538   L = lengthP ? *lengthP : strlen(s);
00539 
00540   s_end = s + L;
00541   last = s;
00542 
00543  AGAIN:
00544 
00545   while (s < s_end && IS_SPACE(*s))
00546        s++;
00547 
00548   const char *tokPtr = checkString.get();
00549   while (*tokPtr)
00550   {
00551     //tokenize the comma separated list
00552     PRSize tokenLength = 0;
00553     while (*tokPtr && *tokPtr != ',') {
00554       tokenLength++; 
00555       tokPtr++;
00556     }
00557     //check if the beginning of s is the actual token
00558     if (tokenLength && !strncmp(s, tokPtr - tokenLength, tokenLength))
00559     {
00560       if (s[tokenLength] == ':')
00561       {
00562         s = s + tokenLength + 1; /* Skip over "Re:" */
00563         result = PR_TRUE;        /* Yes, we stripped it. */
00564         goto AGAIN;              /* Skip whitespace and try again. */
00565       }
00566       else if (s[tokenLength] == '[' || s[tokenLength] == '(')
00567       {
00568         const char *s2 = s + tokenLength + 1; /* Skip over "Re[" */
00569         
00570         /* Skip forward over digits after the "[". */
00571         while (s2 < (s_end - 2) && IS_DIGIT(*s2))
00572           s2++;
00573 
00574         /* Now ensure that the following thing is "]:"
00575            Only if it is do we alter `s'. */
00576         if ((s2[0] == ']' || s2[0] == ')') && s2[1] == ':')
00577         {
00578           s = s2 + 2;       /* Skip over "]:" */
00579           result = PR_TRUE; /* Yes, we stripped it. */
00580           goto AGAIN;       /* Skip whitespace and try again. */
00581         }
00582       }
00583     }
00584     if (*tokPtr)
00585       tokPtr++;
00586   }
00587   
00588   if (decodedString)
00589   {
00590     // encode the string back if any modification is made
00591     if (s != decodedString.get())
00592     {
00593       // extract between "=?" and "?"
00594       // e.g. =?ISO-2022-JP?
00595       const char *p1 = strstr(*stringP, "=?");
00596       if (p1) 
00597       {
00598         p1 += sizeof("=?")-1;         // skip "=?"
00599         const char *p2 = strchr(p1, '?');   // then search for '?' 
00600         if (p2) 
00601         {
00602           char charset[kMAX_CSNAME] = "";
00603           if (kMAX_CSNAME >= (p2 - p1))
00604             strncpy(charset, p1, p2 - p1);
00605           rv = mimeConverter->EncodeMimePartIIStr_UTF8(s, PR_FALSE, charset, sizeof("Subject:"), 
00606                                                        kMIME_ENCODED_WORD_SIZE, modifiedSubject);
00607           if (NS_SUCCEEDED(rv)) 
00608             return result;
00609         }
00610       }
00611     }
00612     else 
00613       s = *stringP;   // no modification, set the original encoded string
00614   }
00615 
00616 
00617   /* Decrease length by difference between current ptr and original ptr.
00618         Then store the current ptr back into the caller. */
00619   if (lengthP) 
00620          *lengthP -= (s - (*stringP));
00621   *stringP = s;
00622 
00623   return result;
00624 }
00625 
00626 /*     Very similar to strdup except it free's too
00627  */
00628 char * NS_MsgSACopy (char **destination, const char *source)
00629 {
00630   if(*destination)
00631   {
00632     PR_Free(*destination);
00633     *destination = 0;
00634   }
00635   if (! source)
00636     *destination = nsnull;
00637   else 
00638   {
00639     *destination = (char *) PR_Malloc (PL_strlen(source) + 1);
00640     if (*destination == nsnull) 
00641       return(nsnull);
00642     
00643     PL_strcpy (*destination, source);
00644   }
00645   return *destination;
00646 }
00647 
00648 /*  Again like strdup but it concatinates and free's and uses Realloc
00649 */
00650 char * NS_MsgSACat (char **destination, const char *source)
00651 {
00652   if (source && *source)
00653     if (*destination)
00654     {
00655       int length = PL_strlen (*destination);
00656       *destination = (char *) PR_Realloc (*destination, length + PL_strlen(source) + 1);
00657       if (*destination == nsnull)
00658         return(nsnull);
00659 
00660       PL_strcpy (*destination + length, source);
00661     }
00662     else
00663     {
00664       *destination = (char *) PR_Malloc (PL_strlen(source) + 1);
00665       if (*destination == nsnull)
00666         return(nsnull);
00667 
00668       PL_strcpy (*destination, source);
00669     }
00670   return *destination;
00671 }
00672 
00673 nsresult NS_MsgEscapeEncodeURLPath(const nsAString& aStr, nsAFlatCString& aResult)
00674 {
00675   char *escapedString = nsEscape(NS_ConvertUTF16toUTF8(aStr).get(), url_Path); 
00676   if (!*escapedString)
00677     return NS_ERROR_OUT_OF_MEMORY;
00678   aResult.Adopt(escapedString);
00679   return NS_OK;
00680 }
00681 
00682 nsresult NS_MsgDecodeUnescapeURLPath(const nsACString& aPath,
00683                                      nsAString& aResult)
00684 {
00685   nsCAutoString unescapedName;
00686   NS_UnescapeURL(PromiseFlatCString(aPath), 
00687                  esc_FileBaseName|esc_Forced|esc_AlwaysCopy,
00688                  unescapedName);
00689   CopyUTF8toUTF16(unescapedName, aResult);
00690   return NS_OK;
00691 }
00692 
00693 PRBool WeAreOffline()
00694 {
00695   nsresult rv = NS_OK;
00696   PRBool offline = PR_FALSE;
00697 
00698   nsCOMPtr <nsIIOService> ioService = do_GetService(NS_IOSERVICE_CONTRACTID, &rv);
00699   if (NS_SUCCEEDED(rv) && ioService)
00700     ioService->GetOffline(&offline);
00701 
00702   return offline;
00703 }
00704 
00705 nsresult GetExistingFolder(const char *aFolderURI, nsIMsgFolder **aFolder)
00706 {
00707   NS_ENSURE_ARG_POINTER(aFolderURI);
00708   NS_ENSURE_ARG_POINTER(aFolder);
00709 
00710   *aFolder = nsnull;
00711 
00712   nsresult rv;
00713   nsCOMPtr<nsIRDFService> rdf(do_GetService("@mozilla.org/rdf/rdf-service;1", &rv));
00714   NS_ENSURE_SUCCESS(rv, rv);
00715 
00716   nsCOMPtr<nsIRDFResource> resource;
00717   rv = rdf->GetResource(nsDependentCString(aFolderURI), getter_AddRefs(resource));
00718   NS_ENSURE_SUCCESS(rv, rv);
00719 
00720   nsCOMPtr <nsIMsgFolder> thisFolder;
00721   thisFolder = do_QueryInterface(resource, &rv);
00722   NS_ENSURE_SUCCESS(rv, rv);
00723 
00724   // Parent doesn't exist means that this folder doesn't exist.
00725   nsCOMPtr<nsIMsgFolder> parentFolder;
00726   rv = thisFolder->GetParent(getter_AddRefs(parentFolder));
00727   if (NS_SUCCEEDED(rv) && parentFolder)
00728     NS_ADDREF(*aFolder = thisFolder);
00729   return rv;
00730 }
00731 
00732 PRBool IsAFromSpaceLine(char *start, const char *end)
00733 {
00734   nsresult rv = PR_FALSE;
00735   while ((start < end) && (*start == '>'))
00736     start++;
00737   // If the leading '>'s are followed by an 'F' then we have a possible case here.
00738   if ( (*start == 'F') && (end-start > 4) && !strncmp(start, "From ", 5) )
00739     rv = PR_TRUE;
00740   return rv;
00741 }
00742 
00743 //
00744 // This function finds all lines starting with "From " or "From " preceeding
00745 // with one or more '>' (ie, ">From", ">>From", etc) in the input buffer
00746 // (between 'start' and 'end') and prefix them with a ">" .
00747 //
00748 nsresult EscapeFromSpaceLine(nsIFileSpec *pDst, char *start, const char *end)
00749 {
00750   nsresult rv;
00751   char *pChar;
00752   PRInt32 written;
00753 
00754   pChar = start;
00755   while (start < end)
00756   {
00757     while ((pChar < end) && (*pChar != nsCRT::CR) && (*(pChar+1) != nsCRT::LF))
00758       pChar++;
00759 
00760     if (pChar < end)
00761     {
00762       // Found a line so check if it's a qualified "From " line.
00763       if (IsAFromSpaceLine(start, pChar))
00764         rv = pDst->Write(">", 1, &written);
00765       PRInt32 lineTerminatorCount = (*(pChar + 1) == nsCRT::LF) ? 2 : 1;
00766       rv = pDst->Write(start, pChar - start + lineTerminatorCount, &written);
00767       NS_ENSURE_SUCCESS(rv,rv);
00768       pChar += lineTerminatorCount;
00769       start = pChar;
00770     }
00771     else if (start < end)
00772     {
00773       // Check and flush out the remaining data and we're done.
00774       if (IsAFromSpaceLine(start, end))
00775         rv = pDst->Write(">", 1, &written);
00776       rv = pDst->Write(start, end-start, &written);
00777       NS_ENSURE_SUCCESS(rv,rv);
00778       break;
00779     }
00780   }
00781   return NS_OK;
00782 }
00783 
00784 nsresult CreateServicesForPasswordManager()
00785 {
00786   if (!gInitPasswordManager) 
00787   {
00788      // Initialize the password manager category
00789     gInitPasswordManager = PR_TRUE;
00790     return NS_CreateServicesFromCategory(NS_PASSWORDMANAGER_CATEGORY,
00791                                   nsnull,
00792                                   NS_PASSWORDMANAGER_CATEGORY);
00793   }
00794   return NS_OK;
00795 }
00796   
00797 nsresult IsRFC822HeaderFieldName(const char *aHdr, PRBool *aResult)
00798 {
00799   NS_ENSURE_ARG_POINTER(aHdr);
00800   NS_ENSURE_ARG_POINTER(aResult);
00801   PRUint32 length = strlen(aHdr);
00802   for(PRUint32 i=0; i<length; i++)
00803   {
00804     char c = aHdr[i];
00805     if ( c < '!' || c == ':' || c > '~') 
00806     {
00807       *aResult = PR_FALSE;
00808       return NS_OK;
00809     }
00810   }
00811   *aResult = PR_TRUE;
00812   return NS_OK;
00813 }
00814 
00815 // Warning, currently this routine only works for the Junk Folder
00816 nsresult
00817 GetOrCreateFolder(const nsACString &aURI, nsIUrlListener *aListener)
00818 {
00819   nsresult rv;
00820   nsCOMPtr <nsIRDFService> rdf = do_GetService("@mozilla.org/rdf/rdf-service;1", &rv);
00821   NS_ENSURE_SUCCESS(rv, rv);
00822   
00823   // get the corresponding RDF resource
00824   // RDF will create the folder resource if it doesn't already exist
00825   nsCOMPtr<nsIRDFResource> resource;
00826   rv = rdf->GetResource(aURI, getter_AddRefs(resource));
00827   NS_ENSURE_SUCCESS(rv, rv);
00828   
00829   nsCOMPtr <nsIMsgFolder> folderResource;
00830   folderResource = do_QueryInterface(resource, &rv);
00831   NS_ENSURE_SUCCESS(rv, rv);
00832 
00833   // don't check validity of folder - caller will handle creating it
00834   nsCOMPtr<nsIMsgIncomingServer> server; 
00835   // make sure that folder hierarchy is built so that legitimate parent-child relationship is established
00836   rv = folderResource->GetServer(getter_AddRefs(server));
00837   NS_ENSURE_SUCCESS(rv, rv);
00838   if (!server)
00839     return NS_ERROR_UNEXPECTED;
00840 
00841   nsCOMPtr <nsIMsgFolder> msgFolder;
00842   rv = server->GetMsgFolderFromURI(folderResource, nsCAutoString(aURI).get(), getter_AddRefs(msgFolder));
00843   NS_ENSURE_SUCCESS(rv,rv);
00844 
00845   nsCOMPtr <nsIMsgFolder> parent;
00846   rv = msgFolder->GetParent(getter_AddRefs(parent));
00847   if (NS_FAILED(rv) || !parent)
00848   {
00849     nsCOMPtr <nsIFileSpec> folderPath;
00850     // for local folders, path is to the berkeley mailbox. 
00851     // for imap folders, path needs to have .msf appended to the name
00852     msgFolder->GetPath(getter_AddRefs(folderPath));
00853 
00854     nsXPIDLCString type;
00855     rv = server->GetType(getter_Copies(type));
00856     NS_ENSURE_SUCCESS(rv,rv);
00857 
00858     PRBool isImapFolder = type.Equals("imap");
00859     // if we can't get the path from the folder, then try to create the storage.
00860     // for imap, it doesn't matter if the .msf file exists - it still might not
00861     // exist on the server, so we should try to create it
00862     PRBool exists = PR_FALSE;
00863     if (!isImapFolder && folderPath)
00864       folderPath->Exists(&exists);
00865     if (!exists)
00866     {
00867       // Hack to work around a localization bug with the Junk Folder.
00868       // Please see Bug #270261 for more information...
00869       nsXPIDLString localizedJunkName; 
00870       msgFolder->GetName(getter_Copies(localizedJunkName));
00871 
00872       // force the junk folder name to be Junk so it gets created on disk correctly...
00873       msgFolder->SetName(NS_LITERAL_STRING("Junk").get());
00874 
00875       rv = msgFolder->CreateStorageIfMissing(aListener);
00876       NS_ENSURE_SUCCESS(rv,rv);
00877 
00878       // now restore the localized folder name...
00879       msgFolder->SetName(localizedJunkName.get());
00880 
00881       // XXX TODO
00882       // JUNK MAIL RELATED
00883       // ugh, I hate this hack
00884       // we have to do this (for now)
00885       // because imap and local are different (one creates folder asynch, the other synch)
00886       // one will notify the listener, one will not.
00887       // I blame nsMsgCopy.  
00888       // we should look into making it so no matter what the folder type
00889       // we always call the listener
00890       // this code should move into local folder's version of CreateStorageIfMissing()
00891       if (!isImapFolder && aListener) {
00892         rv = aListener->OnStartRunningUrl(nsnull);
00893         NS_ENSURE_SUCCESS(rv,rv);
00894         
00895         rv = aListener->OnStopRunningUrl(nsnull, NS_OK);
00896         NS_ENSURE_SUCCESS(rv,rv);
00897       }
00898     }
00899   }
00900   else {
00901     // if the folder exists, we should set the junk flag on it
00902     // which is what the listener will do
00903     if (aListener) {
00904       rv = aListener->OnStartRunningUrl(nsnull);
00905       NS_ENSURE_SUCCESS(rv,rv);
00906       
00907       rv = aListener->OnStopRunningUrl(nsnull, NS_OK);
00908       NS_ENSURE_SUCCESS(rv,rv);
00909     }
00910   }
00911 
00912   return NS_OK;
00913 }
00914 
00915 nsresult IsRSSArticle(nsIURI * aMsgURI, PRBool *aIsRSSArticle)
00916 {
00917   nsresult rv;
00918   *aIsRSSArticle = PR_FALSE;
00919 
00920   nsCOMPtr<nsIMsgMessageUrl> msgUrl = do_QueryInterface(aMsgURI, &rv);
00921   NS_ENSURE_SUCCESS(rv, rv);
00922 
00923   nsXPIDLCString resourceURI;
00924   msgUrl->GetUri(getter_Copies(resourceURI));
00925   
00926   // get the msg service for this URI
00927   nsCOMPtr<nsIMsgMessageService> msgService;
00928   rv = GetMessageServiceFromURI(resourceURI.get(), getter_AddRefs(msgService));
00929   NS_ENSURE_SUCCESS(rv, rv);
00930   
00931   nsCOMPtr<nsIMsgDBHdr> msgHdr;
00932   rv = msgService->MessageURIToMsgHdr(resourceURI, getter_AddRefs(msgHdr));
00933   NS_ENSURE_SUCCESS(rv, rv);
00934 
00935   nsCOMPtr<nsIMsgMailNewsUrl> mailnewsUrl = do_QueryInterface(aMsgURI, &rv);
00936   NS_ENSURE_SUCCESS(rv, rv);
00937 
00938   // get the folder and the server from the msghdr
00939   nsCOMPtr<nsIRssIncomingServer> rssServer;
00940   nsCOMPtr<nsIMsgFolder> folder;
00941   rv = msgHdr->GetFolder(getter_AddRefs(folder));
00942   if (NS_SUCCEEDED(rv) && folder)
00943   {
00944     nsCOMPtr<nsIMsgIncomingServer> server;
00945     folder->GetServer(getter_AddRefs(server));
00946     rssServer = do_QueryInterface(server);
00947 
00948     if (rssServer)
00949       *aIsRSSArticle = PR_TRUE;
00950   }
00951 
00952   return rv;
00953 }
00954 
00955 
00956 // digest needs to be a pointer to a DIGEST_LENGTH (16) byte buffer
00957 nsresult MSGCramMD5(const char *text, PRInt32 text_len, const char *key, PRInt32 key_len, unsigned char *digest)
00958 {
00959   nsresult rv;
00960 
00961   nsCAutoString hash;
00962   nsCOMPtr<nsICryptoHash> hasher = do_CreateInstance("@mozilla.org/security/hash;1", &rv);
00963   NS_ENSURE_SUCCESS(rv, rv);
00964 
00965 
00966   // this code adapted from http://www.cis.ohio-state.edu/cgi-bin/rfc/rfc2104.html
00967 
00968   char innerPad[65];    /* inner padding - key XORd with innerPad */
00969   char outerPad[65];    /* outer padding - key XORd with outerPad */
00970   int i;
00971   /* if key is longer than 64 bytes reset it to key=MD5(key) */
00972   if (key_len > 64) 
00973   {
00974 
00975     rv = hasher->Init(nsICryptoHash::MD5);
00976     NS_ENSURE_SUCCESS(rv, rv);
00977 
00978     rv = hasher->Update((const PRUint8*) key, key_len);
00979     NS_ENSURE_SUCCESS(rv, rv);
00980 
00981     rv = hasher->Finish(PR_FALSE, hash);
00982     NS_ENSURE_SUCCESS(rv, rv);
00983 
00984     key = hash.get();
00985     key_len = DIGEST_LENGTH;
00986   }
00987 
00988   /*
00989    * the HMAC_MD5 transform looks like:
00990    *
00991    * MD5(K XOR outerPad, MD5(K XOR innerPad, text))
00992    *
00993    * where K is an n byte key
00994    * innerPad is the byte 0x36 repeated 64 times
00995    * outerPad is the byte 0x5c repeated 64 times
00996    * and text is the data being protected
00997    */
00998 
00999   /* start out by storing key in pads */
01000   memset(innerPad, 0, sizeof innerPad);
01001   memset(outerPad, 0, sizeof outerPad);
01002   memcpy(innerPad, key,  key_len);
01003   memcpy(outerPad, key, key_len);
01004 
01005   /* XOR key with innerPad and outerPad values */
01006   for (i=0; i<64; i++)
01007   {
01008     innerPad[i] ^= 0x36;
01009     outerPad[i] ^= 0x5c;
01010   }
01011   /*
01012    * perform inner MD5
01013    */
01014   nsCAutoString result;
01015   rv = hasher->Init(nsICryptoHash::MD5); /* init context for 1st pass */
01016   rv = hasher->Update((const PRUint8*)innerPad, 64);       /* start with inner pad */
01017   rv = hasher->Update((const PRUint8*)text, text_len);     /* then text of datagram */
01018   rv = hasher->Finish(PR_FALSE, result);   /* finish up 1st pass */
01019 
01020   /*
01021    * perform outer MD5
01022    */
01023   hasher->Init(nsICryptoHash::MD5);       /* init context for 2nd pass */
01024   rv = hasher->Update((const PRUint8*)outerPad, 64);    /* start with outer pad */
01025   rv = hasher->Update((const PRUint8*)result.get(), 16);/* then results of 1st hash */
01026   rv = hasher->Finish(PR_FALSE, result);    /* finish up 2nd pass */
01027 
01028   if (result.Length() != DIGEST_LENGTH)
01029     return NS_ERROR_UNEXPECTED;
01030 
01031   memcpy(digest, result.get(), DIGEST_LENGTH);
01032 
01033   return rv;
01034 
01035 }
01036 
01037 
01038 // digest needs to be a pointer to a DIGEST_LENGTH (16) byte buffer
01039 nsresult MSGApopMD5(const char *text, PRInt32 text_len, const char *password, PRInt32 password_len, unsigned char *digest)
01040 {
01041   nsresult rv;
01042   nsCAutoString result;
01043 
01044   nsCOMPtr<nsICryptoHash> hasher = do_CreateInstance("@mozilla.org/security/hash;1", &rv);
01045   NS_ENSURE_SUCCESS(rv, rv);
01046 
01047   rv = hasher->Init(nsICryptoHash::MD5);
01048   NS_ENSURE_SUCCESS(rv, rv);
01049 
01050   rv = hasher->Update((const PRUint8*) text, text_len);
01051   NS_ENSURE_SUCCESS(rv, rv);
01052 
01053   rv = hasher->Update((const PRUint8*) password, password_len);
01054   NS_ENSURE_SUCCESS(rv, rv);
01055 
01056   rv = hasher->Finish(PR_FALSE, result);
01057   NS_ENSURE_SUCCESS(rv, rv);
01058 
01059   if (result.Length() != DIGEST_LENGTH)
01060     return NS_ERROR_UNEXPECTED;
01061 
01062   memcpy(digest, result.get(), DIGEST_LENGTH);
01063   return rv;
01064 }
01065 
01066 NS_MSG_BASE nsresult NS_GetPersistentFile(const char *relPrefName,
01067                                           const char *absPrefName,
01068                                           const char *dirServiceProp,
01069                                           PRBool& gotRelPref,
01070                                           nsILocalFile **aFile)
01071 {
01072     NS_ENSURE_ARG_POINTER(aFile);
01073     *aFile = nsnull;
01074     NS_ENSURE_ARG(relPrefName);
01075     NS_ENSURE_ARG(absPrefName);
01076     gotRelPref = PR_FALSE;
01077     
01078     nsCOMPtr<nsIPrefService> prefService(do_GetService(NS_PREFSERVICE_CONTRACTID));
01079     if (!prefService) return NS_ERROR_FAILURE;
01080     nsCOMPtr<nsIPrefBranch> mainBranch;
01081     prefService->GetBranch(nsnull, getter_AddRefs(mainBranch));
01082     if (!mainBranch) return NS_ERROR_FAILURE;
01083 
01084     nsCOMPtr<nsILocalFile> localFile;
01085     
01086     // Get the relative first    
01087     nsCOMPtr<nsIRelativeFilePref> relFilePref;
01088     mainBranch->GetComplexValue(relPrefName,
01089                                 NS_GET_IID(nsIRelativeFilePref), getter_AddRefs(relFilePref));
01090     if (relFilePref) {
01091         relFilePref->GetFile(getter_AddRefs(localFile));
01092         NS_ASSERTION(localFile, "An nsIRelativeFilePref has no file.");
01093         if (localFile)
01094             gotRelPref = PR_TRUE;
01095     }    
01096     
01097     // If not, get the old absolute
01098     if (!localFile) {
01099         mainBranch->GetComplexValue(absPrefName,
01100                                     NS_GET_IID(nsILocalFile), getter_AddRefs(localFile));
01101                                         
01102         // If not, and given a dirServiceProp, use directory service.
01103         if (!localFile && dirServiceProp) {
01104             nsCOMPtr<nsIProperties> dirService(do_GetService("@mozilla.org/file/directory_service;1"));
01105             if (!dirService) return NS_ERROR_FAILURE;
01106             dirService->Get(dirServiceProp, NS_GET_IID(nsILocalFile), getter_AddRefs(localFile));
01107             if (!localFile) return NS_ERROR_FAILURE;
01108         }
01109     }
01110     
01111     if (localFile) {
01112         *aFile = localFile;
01113         NS_ADDREF(*aFile);
01114         return NS_OK;
01115     }
01116     
01117     return NS_ERROR_FAILURE;
01118 }
01119 
01120 NS_MSG_BASE nsresult NS_SetPersistentFile(const char *relPrefName,
01121                                           const char *absPrefName,
01122                                           nsILocalFile *aFile)
01123 {
01124     NS_ENSURE_ARG(relPrefName);
01125     NS_ENSURE_ARG(absPrefName);
01126     NS_ENSURE_ARG(aFile);
01127     
01128     nsresult rv;
01129     nsCOMPtr<nsIPrefService> prefService(do_GetService(NS_PREFSERVICE_CONTRACTID));
01130     if (!prefService) return NS_ERROR_FAILURE;
01131     nsCOMPtr<nsIPrefBranch> mainBranch;
01132     prefService->GetBranch(nsnull, getter_AddRefs(mainBranch));
01133     if (!mainBranch) return NS_ERROR_FAILURE;
01134 
01135     // Write the absolute for backwards compatibilty's sake.
01136     // Or, if aPath is on a different drive than the profile dir.
01137     rv = mainBranch->SetComplexValue(absPrefName, NS_GET_IID(nsILocalFile), aFile);
01138     
01139     // Write the relative path.
01140     nsCOMPtr<nsIRelativeFilePref> relFilePref;
01141     NS_NewRelativeFilePref(aFile, nsDependentCString(NS_APP_USER_PROFILE_50_DIR), getter_AddRefs(relFilePref));
01142     if (relFilePref) {
01143         nsresult rv2 = mainBranch->SetComplexValue(relPrefName, NS_GET_IID(nsIRelativeFilePref), relFilePref);
01144         if (NS_FAILED(rv2) && NS_SUCCEEDED(rv))
01145             mainBranch->ClearUserPref(relPrefName);
01146     }
01147 
01148     return rv;
01149 }
01150 
01151 NS_MSG_BASE nsresult NS_GetUnicharPreferenceWithDefault(nsIPrefBranch *prefBranch,  //can be null, if so uses the root branch
01152                                                         const char *prefName,
01153                                                         const nsString& defValue,
01154                                                         nsString& prefValue)
01155 {
01156     NS_ENSURE_ARG(prefName);
01157 
01158     nsCOMPtr<nsIPrefBranch> pbr;
01159     if(!prefBranch) {
01160         pbr = do_GetService(NS_PREFSERVICE_CONTRACTID);
01161         prefBranch = pbr;
01162     }
01163     nsCOMPtr<nsISupportsString> str;
01164 
01165     nsresult rv = prefBranch->GetComplexValue(prefName, NS_GET_IID(nsISupportsString), getter_AddRefs(str));
01166     if (NS_SUCCEEDED(rv))
01167         return str->GetData(prefValue);
01168 
01169     prefValue = defValue;
01170     return NS_OK;
01171 }
01172  
01173 NS_MSG_BASE nsresult NS_GetLocalizedUnicharPreferenceWithDefault(nsIPrefBranch *prefBranch,  //can be null, if so uses the root branch
01174                                                                  const char *prefName,
01175                                                                  const nsString& defValue,
01176                                                                  nsXPIDLString& prefValue)
01177 {
01178     NS_ENSURE_ARG(prefName);
01179 
01180     nsCOMPtr<nsIPrefBranch> pbr;
01181     if(!prefBranch) {
01182         pbr = do_GetService(NS_PREFSERVICE_CONTRACTID);
01183         prefBranch = pbr;
01184     }
01185 
01186     nsCOMPtr<nsIPrefLocalizedString> str;
01187 
01188     nsresult rv = prefBranch->GetComplexValue(prefName, NS_GET_IID(nsIPrefLocalizedString), getter_AddRefs(str));
01189     if (NS_SUCCEEDED(rv))
01190         str->ToString(getter_Copies(prefValue));
01191     else
01192         prefValue = defValue;
01193     return NS_OK;
01194 }
01195 
01196 void PRTime2Seconds(PRTime prTime, PRUint32 *seconds)
01197 {
01198   PRInt64 microSecondsPerSecond, intermediateResult;
01199   
01200   LL_I2L(microSecondsPerSecond, PR_USEC_PER_SEC);
01201   LL_DIV(intermediateResult, prTime, microSecondsPerSecond);
01202   LL_L2UI((*seconds), intermediateResult);
01203 }
01204 
01205 void PRTime2Seconds(PRTime prTime, PRInt32 *seconds)
01206 {
01207   PRInt64 microSecondsPerSecond, intermediateResult;
01208   
01209   LL_I2L(microSecondsPerSecond, PR_USEC_PER_SEC);
01210   LL_DIV(intermediateResult, prTime, microSecondsPerSecond);
01211   LL_L2I((*seconds), intermediateResult);
01212 }
01213 
01214 void Seconds2PRTime(PRUint32 seconds, PRTime *prTime)
01215 {
01216   PRInt64 microSecondsPerSecond, intermediateResult;
01217   
01218   LL_I2L(microSecondsPerSecond, PR_USEC_PER_SEC);
01219   LL_UI2L(intermediateResult, seconds);
01220   LL_MUL((*prTime), intermediateResult, microSecondsPerSecond);
01221 }
01222 
01223 void MsgGenerateNowStr(nsACString &nowStr)
01224 {
01225   char dateBuf[100];
01226   dateBuf[0] = '\0';
01227   PRExplodedTime exploded;
01228   PR_ExplodeTime(PR_Now(), PR_LocalTimeParameters, &exploded);
01229   PR_FormatTimeUSEnglish(dateBuf, sizeof(dateBuf), "%a %b %d %H:%M:%S %Y", &exploded);
01230   nowStr.Assign(dateBuf);
01231 }
01232 
01233 PRBool MsgFindKeyword(const nsACString &keyword, nsACString &keywords, nsACString::const_iterator &start, nsACString::const_iterator &end)
01234 {
01235   keywords.BeginReading(start);
01236   keywords.EndReading(end);
01237   if (*start == ' ')
01238     start++;
01239   nsACString::const_iterator saveStart(start), saveEnd(end);
01240   while (PR_TRUE)
01241   {
01242     if (FindInReadable(keyword, start, end))
01243     {
01244       PRBool beginMatches = start == saveStart;
01245       PRBool endMatches = end == saveEnd;
01246       nsACString::const_iterator beforeStart(start);
01247       beforeStart--;
01248       // start and end point to the beginning and end of the match
01249       if (beginMatches && (end == saveEnd || *end == ' ')
01250         || (endMatches && *beforeStart == ' ')
01251         || *beforeStart == ' ' && *end == ' ')
01252       {
01253         if (*end == ' ')
01254           end++;
01255         if (*beforeStart == ' ' && endMatches)
01256           start--;
01257         return PR_TRUE;
01258       }
01259       else 
01260         start = end; // advance past bogus match.
01261     }
01262     else
01263       break;
01264   }
01265   return PR_FALSE;
01266 }
01267 
01268 PRBool MsgHostDomainIsTrusted(nsCString &host, nsCString &trustedMailDomains)
01269 {
01270   const char *domain, *domainEnd, *end;
01271   PRUint32 hostLen, domainLen;
01272   PRBool domainIsTrusted = PR_FALSE;
01273   
01274   domain = trustedMailDomains.BeginReading();
01275   domainEnd = trustedMailDomains.EndReading(); 
01276   nsACString::const_iterator hostStart;
01277   
01278   host.BeginReading(hostStart);
01279   hostLen = host.Length();
01280   
01281   do {
01282     // skip any whitespace
01283     while (*domain == ' ' || *domain == '\t')
01284       ++domain;
01285     
01286     // find end of this domain in the string
01287     end = strchr(domain, ',');
01288     if (!end)
01289       end = domainEnd;
01290     
01291     // to see if the hostname is in the domain, check if the domain
01292     // matches the end of the hostname.
01293     domainLen = end - domain;
01294     if (domainLen && hostLen >= domainLen) {
01295       const char *hostTail = hostStart.get() + hostLen - domainLen;
01296       if (PL_strncasecmp(domain, hostTail, domainLen) == 0) 
01297       {
01298         // now, make sure either that the hostname is a direct match or
01299         // that the hostname begins with a dot.
01300         if (hostLen == domainLen || *hostTail == '.' || *(hostTail - 1) == '.')
01301         {
01302           domainIsTrusted = PR_TRUE;
01303           break;
01304         }
01305       }
01306     }
01307     
01308     domain = end + 1;
01309   } while (*end);
01310   return domainIsTrusted;
01311 }
01312 
01313 nsresult MsgMailboxGetURI(const char *nativepath, nsCString &mailboxUri)
01314 {
01315   
01316   nsresult rv;
01317   
01318   nsCOMPtr<nsIMsgAccountManager> accountManager = 
01319     do_GetService(NS_MSGACCOUNTMANAGER_CONTRACTID, &rv);
01320   
01321   NS_ENSURE_SUCCESS(rv, rv);
01322   nsCOMPtr<nsISupportsArray> serverArray;
01323   accountManager->GetAllServers(getter_AddRefs(serverArray));
01324   
01325   // do a char*->fileSpec->char* conversion to normalize the path
01326   nsFilePath filePath(nativepath);
01327   
01328   PRUint32 cnt;
01329   rv = serverArray->Count(&cnt);
01330   NS_ENSURE_SUCCESS(rv, rv);
01331   PRInt32 count = cnt;
01332   PRInt32 i;
01333   for (i=0; i<count; i++) 
01334   {
01335     
01336     nsCOMPtr<nsIMsgIncomingServer> server = do_QueryElementAt(serverArray, i);
01337     
01338     if (!server) continue;
01339     
01340     // get the path string, convert it to an nsFilePath
01341     nsCOMPtr<nsIFileSpec> nativeServerPath;
01342     rv = server->GetLocalPath(getter_AddRefs(nativeServerPath));
01343     if (NS_FAILED(rv)) continue;
01344     
01345     nsFileSpec spec;
01346     nativeServerPath->GetFileSpec(&spec);
01347     nsFilePath serverPath(spec);
01348     
01349     // check if filepath begins with serverPath
01350     PRInt32 len = PL_strlen(serverPath);
01351     if (PL_strncasecmp(serverPath, filePath, len) == 0) 
01352     {
01353       nsXPIDLCString serverURI;
01354       rv = server->GetServerURI(getter_Copies(serverURI));
01355       if (NS_FAILED(rv)) continue;
01356       
01357       // the relpath is just past the serverpath
01358       const char *relpath = nativepath + len;
01359       // skip past leading / if any
01360       while (*relpath == '/')
01361         relpath++;
01362       
01363       nsCAutoString pathStr(relpath);
01364       PRInt32 sbdIndex;
01365       while((sbdIndex = pathStr.Find(".sbd", PR_TRUE)) != -1)
01366         pathStr.Cut(sbdIndex, 4);
01367       
01368       mailboxUri = serverURI;
01369       mailboxUri.Append('/');
01370       mailboxUri.Append(pathStr);
01371       break;
01372     }
01373   }
01374   return mailboxUri.IsEmpty() ? NS_ERROR_FAILURE : NS_OK;
01375 }
01376 
01377 NS_MSG_BASE void MsgStripQuotedPrintable (unsigned char *src)
01378 {
01379   // decode quoted printable text in place
01380   
01381   if (!*src)
01382     return;
01383   unsigned char *dest = src;
01384   int srcIdx = 0, destIdx = 0;
01385   
01386   while (src[srcIdx] != 0)
01387   {
01388     if (src[srcIdx] == '=')
01389     {
01390       unsigned char *token = &src[srcIdx];
01391       unsigned char c = 0;
01392       
01393       // decode the first quoted char
01394       if (token[1] >= '0' && token[1] <= '9')
01395         c = token[1] - '0';
01396       else if (token[1] >= 'A' && token[1] <= 'F')
01397         c = token[1] - ('A' - 10);
01398       else if (token[1] >= 'a' && token[1] <= 'f')
01399         c = token[1] - ('a' - 10);
01400       else
01401       {
01402         // first char after '=' isn't hex. check if it's a normal char
01403         // or a soft line break. If it's a soft line break, eat the
01404         // CR/LF/CRLF.
01405         if (src[srcIdx + 1] == nsCRT::CR || src[srcIdx + 1] == nsCRT::LF)
01406         {
01407           srcIdx++; // soft line break, ignore the '=';
01408           if (src[srcIdx] == nsCRT::CR || src[srcIdx] == nsCRT::LF)
01409           {
01410             srcIdx++;
01411             if (src[srcIdx] == nsCRT::LF)
01412               srcIdx++;
01413           }
01414         }
01415         else // normal char, copy it.
01416         {
01417           dest[destIdx++] = src[srcIdx++]; // aka token[0]
01418         }
01419         continue;
01420       }
01421       
01422       // decode the second quoted char
01423       c = (c << 4);
01424       if (token[2] >= '0' && token[2] <= '9')
01425         c += token[2] - '0';
01426       else if (token[2] >= 'A' && token[2] <= 'F')
01427         c += token[2] - ('A' - 10);
01428       else if (token[2] >= 'a' && token[2] <= 'f')
01429         c += token[2] - ('a' - 10);
01430       else
01431       {
01432         // second char after '=' isn't hex. copy the '=' as a normal char and keep going
01433         dest[destIdx++] = src[srcIdx++]; // aka token[0]
01434         continue;
01435       }
01436       
01437       // if we got here, we successfully decoded a quoted printable sequence,
01438       // so bump each pointer past it and move on to the next char;
01439       dest[destIdx++] = c; 
01440       srcIdx += 3;
01441       
01442     }
01443     else
01444       dest[destIdx++] = src[srcIdx++];
01445   }
01446   
01447   dest[destIdx] = src[srcIdx]; // null terminate
01448 }  
01449 
01450