void TPSSystemCertsVerification::Initialize (ConfigStore *cfg)
{
    if (TPSSystemCertsVerification::initialized == 0) {
        TPSSystemCertsVerification::initialized = 1;
        const char* s = cfg->GetConfigAsString(CFG_SELFTEST_STARTUP);
        if (s != NULL) {
            if (PL_strstr (s, TPSSystemCertsVerification::CRITICAL_TEST_NAME) != NULL) {
                startupCritical = true;
                startupEnabled = true;
            } else if (PL_strstr (s, TPSSystemCertsVerification::TEST_NAME) != NULL) {
                startupEnabled = true;
            }
        }
        const char* d = cfg->GetConfigAsString(CFG_SELFTEST_ONDEMAND);
        if (d != NULL) {
            if (PL_strstr (d, TPSSystemCertsVerification::CRITICAL_TEST_NAME) != NULL) {
                onDemandCritical = true;
                onDemandEnabled = true;
            } else if (PL_strstr (d, TPSSystemCertsVerification::TEST_NAME) != NULL) {
                onDemandEnabled = true;
            }
        }
        char* n = (char*)(cfg->GetConfigAsString(TPSSystemCertsVerification::SUBSYSTEM_NICKNAME));
        if (n != NULL && PL_strlen(n) > 0) {
            if (PL_strstr (n, TPSSystemCertsVerification::UNINITIALIZED_NICKNAME) != NULL) {
                TPSSystemCertsVerification::initialized = 0;
            }
        }
        if (TPSSystemCertsVerification::initialized == 1) {
            TPSSystemCertsVerification::initialized = 2;
        }
    }
    RA::SelfTestLog("TPSSystemCertsVerification::Initialize", "%s", ((initialized==2)?"successfully completed":"failed"));
}
Exemple #2
0
nsresult
nsHttpResponseHead::Parse(char *block)
{

    LOG(("nsHttpResponseHead::Parse [this=%p]\n", this));

    // this command works on a buffer as prepared by Flatten, as such it is
    // not very forgiving ;-)

    char *p = PL_strstr(block, "\r\n");
    if (!p)
        return NS_ERROR_UNEXPECTED;

    *p = 0;
    ParseStatusLine(block);

    do {
        block = p + 2;

		if (*block == 0)
			break;

        p = PL_strstr(block, "\r\n");
        if (!p)
            return NS_ERROR_UNEXPECTED;

        *p = 0;
        ParseHeaderLine(block);

    } while (1);

    return NS_OK;
}
// This function takes a message uri, converts it into a file path & msgKey 
// pair. It then turns that into a mailbox url object. It also registers a url
// listener if appropriate. AND it can take in a mailbox action and set that field
// on the returned url as well.
nsresult nsMailboxService::PrepareMessageUrl(const char * aSrcMsgMailboxURI, nsIUrlListener * aUrlListener,
                                             nsMailboxAction aMailboxAction, nsIMailboxUrl ** aMailboxUrl,
                                             nsIMsgWindow *msgWindow)
{
  nsresult rv = CallCreateInstance(kCMailboxUrl, aMailboxUrl);
  if (NS_SUCCEEDED(rv) && aMailboxUrl && *aMailboxUrl)
  {
    // okay now generate the url string
    char * urlSpec;
    nsCAutoString folderURI;
    nsFileSpec folderPath;
    nsMsgKey msgKey;
    const char *part = PL_strstr(aSrcMsgMailboxURI, "part=");
    const char *header = PL_strstr(aSrcMsgMailboxURI, "header=");
    rv = nsParseLocalMessageURI(aSrcMsgMailboxURI, folderURI, &msgKey);
    NS_ENSURE_SUCCESS(rv,rv);
    rv = nsLocalURI2Path(kMailboxRootURI, folderURI.get(), folderPath);
    
    if (NS_SUCCEEDED(rv))
    {
      // set up the url spec and initialize the url with it.
      nsFilePath filePath(folderPath); // convert to file url representation...
      nsCAutoString buf;
      NS_EscapeURL((const char *)filePath,-1,
                   esc_Directory|esc_Forced|esc_AlwaysCopy,buf);
      if (mPrintingOperation)
        urlSpec = PR_smprintf("mailbox://%s?number=%d&header=print", buf.get(), msgKey);
      else if (part)
        urlSpec = PR_smprintf("mailbox://%s?number=%d&%s", buf.get(), msgKey, part);
      else if (header)
        urlSpec = PR_smprintf("mailbox://%s?number=%d&%s", buf.get(), msgKey, header);
      else
        urlSpec = PR_smprintf("mailbox://%s?number=%d", buf.get(), msgKey);
      
      nsCOMPtr <nsIMsgMailNewsUrl> url = do_QueryInterface(*aMailboxUrl);
      url->SetSpec(nsDependentCString(urlSpec));
      PR_Free(urlSpec);
      
      (*aMailboxUrl)->SetMailboxAction(aMailboxAction);
      
      // set up the url listener
      if (aUrlListener)
        rv = url->RegisterListener(aUrlListener);
      
      url->SetMsgWindow(msgWindow);
      nsCOMPtr<nsIMsgMessageUrl> msgUrl = do_QueryInterface(url);
      if (msgUrl)
      {
        msgUrl->SetOriginalSpec(aSrcMsgMailboxURI);
        msgUrl->SetUri(aSrcMsgMailboxURI);
      }
      
    } // if we got a url
  } // if we got a url
  
  return rv;
}
// This function takes a message uri, converts it into a file path & msgKey
// pair. It then turns that into a mailbox url object. It also registers a url
// listener if appropriate. AND it can take in a mailbox action and set that field
// on the returned url as well.
nsresult nsMailboxService::PrepareMessageUrl(const char * aSrcMsgMailboxURI, nsIUrlListener * aUrlListener,
                                             nsMailboxAction aMailboxAction, nsIMailboxUrl ** aMailboxUrl,
                                             nsIMsgWindow *msgWindow)
{
  nsresult rv = CallCreateInstance(NS_MAILBOXURL_CONTRACTID, aMailboxUrl);
  if (NS_SUCCEEDED(rv) && aMailboxUrl && *aMailboxUrl)
  {
    // okay now generate the url string
    char * urlSpec;
    nsCAutoString folderURI;
    nsMsgKey msgKey;
    nsCString folderPath;
    const char *part = PL_strstr(aSrcMsgMailboxURI, "part=");
    const char *header = PL_strstr(aSrcMsgMailboxURI, "header=");
    rv = nsParseLocalMessageURI(aSrcMsgMailboxURI, folderURI, &msgKey);
    NS_ENSURE_SUCCESS(rv,rv);
    rv = nsLocalURI2Path(kMailboxRootURI, folderURI.get(), folderPath);

    if (NS_SUCCEEDED(rv))
    {
      // set up the url spec and initialize the url with it.
      nsCAutoString buf;
      MsgEscapeURL(folderPath,
                   nsINetUtil::ESCAPE_URL_DIRECTORY | nsINetUtil::ESCAPE_URL_FORCED, buf);
      if (mPrintingOperation)
        urlSpec = PR_smprintf("mailbox://%s?number=%lu&header=print", buf.get(), msgKey);
      else if (part)
        urlSpec = PR_smprintf("mailbox://%s?number=%lu&%s", buf.get(), msgKey, part);
      else if (header)
        urlSpec = PR_smprintf("mailbox://%s?number=%lu&%s", buf.get(), msgKey, header);
      else
        urlSpec = PR_smprintf("mailbox://%s?number=%lu", buf.get(), msgKey);

      nsCOMPtr <nsIMsgMailNewsUrl> url = do_QueryInterface(*aMailboxUrl);
      url->SetSpec(nsDependentCString(urlSpec));
      PR_smprintf_free(urlSpec);

      (*aMailboxUrl)->SetMailboxAction(aMailboxAction);

      // set up the url listener
      if (aUrlListener)
        rv = url->RegisterListener(aUrlListener);

      url->SetMsgWindow(msgWindow);
      nsCOMPtr<nsIMsgMessageUrl> msgUrl = do_QueryInterface(url);
      if (msgUrl)
      {
        msgUrl->SetOriginalSpec(aSrcMsgMailboxURI);
        msgUrl->SetUri(aSrcMsgMailboxURI);
      }

    } // if we got a url
  } // if we got a url

  return rv;
}
// returns -1 if this box is not part of this namespace,
// or the length of the prefix if it is part of this namespace
int nsIMAPNamespace::MailboxMatchesNamespace(const char *boxname)
{
    if (!boxname) return -1;

    // If the namespace is part of the boxname
    if (!m_prefix || !*m_prefix)
        return 0;

    if (PL_strstr(boxname, m_prefix) == boxname)
        return PL_strlen(m_prefix);

    // If the boxname is part of the prefix
    // (Used for matching Personal mailbox with Personal/ namespace, etc.)
    if (PL_strstr(m_prefix, boxname) == m_prefix)
        return PL_strlen(boxname);
    return -1;
}
char*
nsMultiMixedConv::ProbeToken(char* aBuffer, uint32_t& aTokenLen)
{
    // To sign a packaged web app in the new security model, we need
    // to add the signature to the package header. The header is the
    // data before the first token and the header format is
    //
    // [field-name]: [field-value] CR LF
    //
    // So the package may look like:
    //
    // manifest-signature: MRjdkly...
    // --gc0pJq0M:08jU534c0p
    // Content-Location: /someapp.webmanifest
    // Content-Type: application/manifest
    //
    // {
    // "name": "My App",
    // "description":"A great app!"
    // ...
    //
    //
    // We search for the first '\r\n--' and assign the subsquent chars
    // to the token until another '\r\n'. '--' will be included in the
    // token we probed. If the second '\r\n' is not found, we still treat
    // the token is not found and more data will be requested.

    char* posCRLFDashDash = PL_strstr(aBuffer, "\r\n--");
    if (!posCRLFDashDash) {
        return nullptr;
    }

    char* tokenStart = posCRLFDashDash + 2; // Skip "\r\n".
    char* tokenEnd = PL_strstr(tokenStart, "\r\n");
    if (!tokenEnd) {
        return nullptr;
    }

    aTokenLen = tokenEnd - tokenStart;

    return tokenStart;
}
Exemple #7
0
static DIR_PrefId DIR_AtomizePrefName(const char *prefname)
{
  if (!prefname)
    return idNone;

  DIR_PrefId rc = idNone;

  /* Skip the "ldap_2.servers.<server-name>." portion of the string.
   */
  if (PL_strstr(prefname, PREF_LDAP_SERVER_TREE_NAME) == prefname)
  {
    prefname = PL_strchr(&prefname[PL_strlen(PREF_LDAP_SERVER_TREE_NAME) + 1], '.');
    if (!prefname)
      return idNone;
    else
      prefname = prefname + 1;
  }

  switch (prefname[0]) {
  case 'd':
    switch (prefname[1]) {
    case 'e': /* description */
      rc = idDescription;
      break;
    case 'i': /* dirType */
      rc = idType;
      break;
    }
    break;

  case 'f':
    rc = idFileName;
    break;

  case 'p':
    switch (prefname[1]) {
    case 'o':
      switch (prefname[2]) {
      case 's': /* position */
        rc = idPosition;
        break;
      }
      break;
    }
    break;

  case 'u': /* uri */
    rc = idUri;
    break;
  }

  return rc;
}
NS_IMETHODIMP nsMailboxService::GetUrlForUri(const char *aMessageURI, nsIURI **aURL, nsIMsgWindow *aMsgWindow)
{
  if (!strncmp(aMessageURI, "file:", 5) || PL_strstr(aMessageURI, "type=application/x-message-display")
    || !strncmp(aMessageURI, "mailbox:", 8))
    return NS_NewURI(aURL, aMessageURI);

  nsresult rv = NS_OK;
  nsCOMPtr<nsIMailboxUrl> mailboxurl;
  rv = PrepareMessageUrl(aMessageURI, nsnull, nsIMailboxUrl::ActionFetchMessage, getter_AddRefs(mailboxurl), aMsgWindow);
  if (NS_SUCCEEDED(rv) && mailboxurl)
    rv = mailboxurl->QueryInterface(NS_GET_IID(nsIURI), (void **) aURL);
  return rv;
}
Exemple #9
0
// a simple helper function to improve readability:
// takes one of the #defined rules above, and performs the appropriate test.
// PR_TRUE means the test passed; PR_FALSE means the test failed.
static inline PRBool
CheckResult(const char *aLhs, PRUint32 aRule, const char *aRhs = nsnull)
{
    switch (aRule) {
        case MUST_BE_NULL:
            return !aLhs || !*aLhs;

        case MUST_EQUAL:
            return !PL_strcmp(aLhs, aRhs);

        case MUST_NOT_EQUAL:
            return PL_strcmp(aLhs, aRhs);

        case MUST_CONTAIN:
            return PL_strstr(aLhs, aRhs) != nsnull;

        case MUST_NOT_CONTAIN:
            return PL_strstr(aLhs, aRhs) == nsnull;

        default:
            return PR_FALSE; // failure
    }
}
// a simple helper function to improve readability:
// takes one of the #defined rules above, and performs the appropriate test.
// true means the test passed; false means the test failed.
static inline bool
CheckResult(const char *aLhs, uint32_t aRule, const char *aRhs = nullptr)
{
    switch (aRule) {
        case MUST_BE_NULL:
            return !aLhs || !*aLhs;

        case MUST_EQUAL:
            return !PL_strcmp(aLhs, aRhs);

        case MUST_NOT_EQUAL:
            return PL_strcmp(aLhs, aRhs);

        case MUST_CONTAIN:
            return PL_strstr(aLhs, aRhs) != nullptr;

        case MUST_NOT_CONTAIN:
            return PL_strstr(aLhs, aRhs) == nullptr;

        default:
            return false; // failure
    }
}
static void
LogHeaders(const char *lines)
{
    nsCAutoString buf;
    char *p;
    while ((p = PL_strstr(lines, "\r\n")) != nsnull) {
        buf.Assign(lines, p - lines);
        if (PL_strcasestr(buf.get(), "authorization: ") != nsnull) {
            char *p = PL_strchr(PL_strchr(buf.get(), ' ')+1, ' ');
            while (*++p) *p = '*';
        }
        LOG3(("  %s\n", buf.get()));
        lines = p + 2;
    }
}
Exemple #12
0
/* dir_matchServerPrefToServer
 *
 * This function finds the DIR_Server in the unified DIR_Server list to which
 * the given preference string belongs.
 */
static DIR_Server *dir_MatchServerPrefToServer(nsVoidArray *wholeList, const char *pref)
{
  DIR_Server *server;

  PRInt32 count = wholeList->Count();
  PRInt32 i;
  for (i = 0; i < count; i++)
  {
    if ((server = (DIR_Server *)wholeList->ElementAt(i)) != nsnull)
    {
      if (server->prefName && PL_strstr(pref, server->prefName) == pref)
      {
        char c = pref[PL_strlen(server->prefName)];
        if (c == 0 || c == '.')
          return server;
      }
    }
  }
  return nsnull;
}
inline PRBool
nsSMILParserUtils::ConsumeSubstring(nsACString::const_iterator& aIter,
                                    const nsACString::const_iterator& aIterEnd,
                                    const char *aSubstring)
{
  size_t substrLen = PL_strlen(aSubstring);
  typedef nsACString::const_iterator::difference_type diff_type;

  if (aIterEnd.get() - aIter.get() < static_cast<diff_type>(substrLen))
    return PR_FALSE;

  PRBool result = PR_FALSE;

  if (PL_strstr(aIter.get(), aSubstring) == aIter.get()) {
    aIter.advance(substrLen);
    result = PR_TRUE;
  }

  return result;
}
NS_IMETHODIMP
nsMIMEHeaderParamImpl::DecodeRFC2047Header(const char* aHeaderVal, 
                                           const char* aDefaultCharset, 
                                           PRBool aOverrideCharset, 
                                           PRBool aEatContinuations,
                                           nsACString& aResult)
{
  aResult.Truncate();
  if (!aHeaderVal)
    return NS_ERROR_INVALID_ARG;
  if (!*aHeaderVal)
    return NS_OK;


  // If aHeaderVal is RFC 2047 encoded or is not a UTF-8 string  but
  // aDefaultCharset is specified, decodes RFC 2047 encoding and converts
  // to UTF-8. Otherwise, just strips away CRLF. 
  if (PL_strstr(aHeaderVal, "=?") || 
      aDefaultCharset && (!IsUTF8(nsDependentCString(aHeaderVal)) || 
      Is7bitNonAsciiString(aHeaderVal, PL_strlen(aHeaderVal)))) {
    DecodeRFC2047Str(aHeaderVal, aDefaultCharset, aOverrideCharset, aResult);
  } else if (aEatContinuations && 
             (PL_strchr(aHeaderVal, '\n') || PL_strchr(aHeaderVal, '\r'))) {
    aResult = aHeaderVal;
  } else {
    aEatContinuations = PR_FALSE;
    aResult = aHeaderVal;
  }

  if (aEatContinuations) {
    nsCAutoString temp(aResult);
    temp.ReplaceSubstring("\n\t", " ");
    temp.ReplaceSubstring("\r\t", " ");
    temp.StripChars("\r\n");
    aResult = temp;
  }

  return NS_OK;
}
// |decode_mime_part2_str| taken from comi18n.c
// Decode RFC2047-encoded words in the input and convert the result to UTF-8.
// If aOverrideCharset is true, charset in RFC2047-encoded words is 
// ignored and aDefaultCharset is assumed, instead. aDefaultCharset
// is also used to convert raw octets (without RFC 2047 encoding) to UTF-8.
//static
nsresult DecodeRFC2047Str(const char *aHeader, const char *aDefaultCharset, 
                          PRBool aOverrideCharset, nsACString &aResult)
{
  const char *p, *q, *r;
  char *decodedText;
  const char *begin; // tracking pointer for where we are in the input buffer
  PRInt32 isLastEncodedWord = 0;
  const char *charsetStart, *charsetEnd;
  char charset[80];

  // initialize charset name to an empty string
  charset[0] = '\0';

  begin = aHeader;

  // To avoid buffer realloc, if possible, set capacity in advance. No 
  // matter what,  more than 3x expansion can never happen for all charsets
  // supported by Mozilla. SCSU/BCSU with the sliding window set to a
  // non-BMP block may be exceptions, but Mozilla does not support them. 
  // Neither any known mail/news program use them. Even if there's, we're
  // safe because we don't use a raw *char any more.
  aResult.SetCapacity(3 * strlen(aHeader));

  while ((p = PL_strstr(begin, "=?")) != 0) {
    if (isLastEncodedWord) {
      // See if it's all whitespace.
      for (q = begin; q < p; ++q) {
        if (!PL_strchr(" \t\r\n", *q)) break;
      }
    }

    if (!isLastEncodedWord || q < p) {
      // copy the part before the encoded-word
      CopyRawHeader(begin, p - begin, aDefaultCharset, aResult);
      begin = p;
    }

    p += 2;

    // Get charset info
    charsetStart = p;
    charsetEnd = 0;
    for (q = p; *q != '?'; q++) {
      if (*q <= ' ' || PL_strchr(especials, *q)) {
        goto badsyntax;
      }

      // RFC 2231 section 5
      if (!charsetEnd && *q == '*') {
        charsetEnd = q; 
      }
    }
    if (!charsetEnd) {
      charsetEnd = q;
    }

    // Check for too-long charset name
    if (PRUint32(charsetEnd - charsetStart) >= sizeof(charset)) 
      goto badsyntax;
    
    memcpy(charset, charsetStart, charsetEnd - charsetStart);
    charset[charsetEnd - charsetStart] = 0;

    q++;
    if (*q != 'Q' && *q != 'q' && *q != 'B' && *q != 'b')
      goto badsyntax;

    if (q[1] != '?')
      goto badsyntax;

    r = q;
    for (r = q + 2; *r != '?'; r++) {
      if (*r < ' ') goto badsyntax;
    }
    if (r[1] != '=')
        goto badsyntax;
    else if (r == q + 2) {
        // it's empty, skip
        begin = r + 2;
        isLastEncodedWord = 1;
        continue;
    }

    if(*q == 'Q' || *q == 'q')
      decodedText = DecodeQ(q + 2, r - (q + 2));
    else {
      // bug 227290. ignore an extraneous '=' at the end.
      // (# of characters in B-encoded part has to be a multiple of 4)
      PRInt32 n = r - (q + 2);
      n -= (n % 4 == 1 && !PL_strncmp(r - 3, "===", 3)) ? 1 : 0;
      decodedText = PL_Base64Decode(q + 2, n, nsnull);
    }

    if (decodedText == nsnull)
      goto badsyntax;

    // Override charset if requested.  Never override labeled UTF-8.
    // Use default charset instead of UNKNOWN-8BIT
    if ((aOverrideCharset && 0 != nsCRT::strcasecmp(charset, "UTF-8")) ||
        (aDefaultCharset && 0 == nsCRT::strcasecmp(charset, "UNKNOWN-8BIT"))) {
      PL_strncpy(charset, aDefaultCharset, sizeof(charset) - 1);
      charset[sizeof(charset) - 1] = '\0';
    }

    {
      nsCOMPtr<nsIUTF8ConverterService> 
        cvtUTF8(do_GetService(NS_UTF8CONVERTERSERVICE_CONTRACTID));
      nsCAutoString utf8Text;
      // skip ASCIIness/UTF8ness test if aCharset is 7bit non-ascii charset.
      if (cvtUTF8 &&
          NS_SUCCEEDED(
            cvtUTF8->ConvertStringToUTF8(nsDependentCString(decodedText),
            charset, IS_7BIT_NON_ASCII_CHARSET(charset), utf8Text))) {
        aResult.Append(utf8Text);
      } else {
        aResult.Append(REPLACEMENT_CHAR);
      }
    }
    PR_Free(decodedText);
    begin = r + 2;
    isLastEncodedWord = 1;
    continue;

  badsyntax:
    // copy the part before the encoded-word
    aResult.Append(begin, p - begin);
    begin = p;
    isLastEncodedWord = 0;
  }

  // put the tail back
  CopyRawHeader(begin, strlen(begin), aDefaultCharset, aResult);

  nsCAutoString tempStr(aResult);
  tempStr.ReplaceChar('\t', ' ');
  aResult = tempStr;

  return NS_OK;
}
NS_IMETHODIMP
nsDirectoryViewerFactory::CreateInstance(const char *aCommand,
                                         nsIChannel* aChannel,
                                         nsILoadGroup* aLoadGroup,
                                         const char* aContentType, 
                                         nsISupports* aContainer,
                                         nsISupports* aExtraInfo,
                                         nsIStreamListener** aDocListenerResult,
                                         nsIContentViewer** aDocViewerResult)
{
  nsresult rv;

  // OK - are we going to be using the html listing or not?
  nsCOMPtr<nsIPrefBranch> prefSrv = do_GetService(NS_PREFSERVICE_CONTRACTID, &rv);
  if (NS_FAILED(rv)) return rv;

  PRBool useXUL = PR_FALSE;  
  PRBool viewSource = (PL_strstr(aContentType,"view-source") != 0);
  
#ifdef MOZ_RDF
  PRInt32 dirPref;
  rv = prefSrv->GetIntPref("network.dir.format", &dirPref);
  if (NS_SUCCEEDED(rv) && dirPref == FORMAT_XUL) {
    useXUL = PR_TRUE;
  }

  if ((NS_FAILED(rv) || useXUL) && !viewSource) {
    // ... and setup the original channel's content type
    (void)aChannel->SetContentType(NS_LITERAL_CSTRING("application/vnd.mozilla.xul+xml"));

    // This is where we shunt the HTTP/Index stream into our datasource,
    // and open the directory viewer XUL file as the content stream to
    // load in its place.
    
    // Create a dummy loader that will load a stub XUL document.
    nsCOMPtr<nsICategoryManager> catMan(do_GetService(NS_CATEGORYMANAGER_CONTRACTID, &rv));
    if (NS_FAILED(rv))
      return rv;
    nsXPIDLCString contractID;
    rv = catMan->GetCategoryEntry("Gecko-Content-Viewers", "application/vnd.mozilla.xul+xml",
                                  getter_Copies(contractID));
    if (NS_FAILED(rv))
      return rv;

    nsCOMPtr<nsIDocumentLoaderFactory> factory(do_GetService(contractID, &rv));
    if (NS_FAILED(rv)) return rv;
    
    nsCOMPtr<nsIURI> uri;
    rv = NS_NewURI(getter_AddRefs(uri), "chrome://communicator/content/directory/directory.xul");
    if (NS_FAILED(rv)) return rv;
    
    nsCOMPtr<nsIChannel> channel;
    rv = NS_NewChannel(getter_AddRefs(channel), uri, nsnull, aLoadGroup);
    if (NS_FAILED(rv)) return rv;
    
    nsCOMPtr<nsIStreamListener> listener;
    rv = factory->CreateInstance(aCommand, channel, aLoadGroup, "application/vnd.mozilla.xul+xml",
                                 aContainer, aExtraInfo, getter_AddRefs(listener),
                                 aDocViewerResult);
    if (NS_FAILED(rv)) return rv;

    rv = channel->AsyncOpen(listener, nsnull);
    if (NS_FAILED(rv)) return rv;
    
    // Create an HTTPIndex object so that we can stuff it into the script context
    nsCOMPtr<nsIURI> baseuri;
    rv = aChannel->GetURI(getter_AddRefs(baseuri));
    if (NS_FAILED(rv)) return rv;
    
    nsCOMPtr<nsIInterfaceRequestor> requestor = do_QueryInterface(aContainer,&rv);
    if (NS_FAILED(rv)) return rv;
    
    nsCOMPtr<nsIHTTPIndex> httpindex;
    rv = nsHTTPIndex::Create(baseuri, requestor, getter_AddRefs(httpindex));
    if (NS_FAILED(rv)) return rv;
    
    // Now shanghai the stream into our http-index parsing datasource
    // wrapper beastie.
    listener = do_QueryInterface(httpindex,&rv);
    *aDocListenerResult = listener.get();
    NS_ADDREF(*aDocListenerResult);
    
    return NS_OK;
  }
#endif

  // setup the original channel's content type
  (void)aChannel->SetContentType(NS_LITERAL_CSTRING("application/xhtml+xml"));

  // Otherwise, lets use the html listing
  nsCOMPtr<nsICategoryManager> catMan(do_GetService(NS_CATEGORYMANAGER_CONTRACTID, &rv));
  if (NS_FAILED(rv))
    return rv;
  nsXPIDLCString contractID;
  rv = catMan->GetCategoryEntry("Gecko-Content-Viewers", "application/xhtml+xml",
                                getter_Copies(contractID));
  if (NS_FAILED(rv))
    return rv;

  nsCOMPtr<nsIDocumentLoaderFactory> factory(do_GetService(contractID, &rv));
  if (NS_FAILED(rv)) return rv;
  
  nsCOMPtr<nsIStreamListener> listener;

  if (viewSource) {
    rv = factory->CreateInstance("view-source", aChannel, aLoadGroup, "application/xhtml+xml; x-view-type=view-source",
                                 aContainer, aExtraInfo, getter_AddRefs(listener),
                                 aDocViewerResult);
  } else {
    rv = factory->CreateInstance("view", aChannel, aLoadGroup, "application/xhtml+xml",
                                 aContainer, aExtraInfo, getter_AddRefs(listener),
                                 aDocViewerResult);
  }

  if (NS_FAILED(rv)) return rv;

  nsCOMPtr<nsIStreamConverterService> scs = do_GetService("@mozilla.org/streamConverters;1", &rv);
  if (NS_FAILED(rv)) return rv;

  rv = scs->AsyncConvertData("application/http-index-format",
                             "text/html",
                             listener,
                             nsnull,
                             aDocListenerResult);

  if (NS_FAILED(rv)) return rv;

  return NS_OK;
}
/*
 * FUNCTION: pkix_EscASCII_to_UTF16
 * DESCRIPTION:
 *
 *  Converts array of bytes pointed to by "escAsciiString" with length of
 *  "escAsciiLength" into a freshly allocated UTF-16 string and stores a
 *  pointer to that string at "pDest" and stores the string's length at
 *  "pLength". The caller is responsible for freeing "pDest" using
 *  PKIX_PL_Free. If "debug" is set, uses EscASCII_Debug encoding.
 *
 * PARAMETERS:
 *  "escAsciiString"
 *      Address of array of bytes representing data source. Must be non-NULL.
 *  "escAsciiLength"
 *      Length of data source. Must be even.
 *  "debug"
 *      Boolean value indicating whether debug mode is desired.
 *  "pDest"
 *      Address where data will be stored. Must be non-NULL.
 *  "pLength"
 *      Address where data length will be stored. Must be non-NULL.
 *  "plContext"
 *      Platform-specific context pointer.
 * THREAD SAFETY:
 *  Thread Safe (see Thread Safety Definitions in Programmer's Guide)
 * RETURNS:
 *  Returns NULL if the function succeeds.
 *  Returns a String Error if the function fails in a non-fatal way.
 *  Returns a Fatal Error if the function fails in an unrecoverable way.
 */
PKIX_Error *
pkix_EscASCII_to_UTF16(
        const char *escAsciiString,
        PKIX_UInt32 escAsciiLen,
        PKIX_Boolean debug,
        void **pDest,
        PKIX_UInt32 *pLength,
        void *plContext)
{
        PKIX_UInt32 newLen, i, j, charSize;
        PKIX_UInt32 x = 0, y = 0, z = 0;
        unsigned char *destPtr = NULL;
        unsigned char testChar, testChar2;
        unsigned char *stringData = (unsigned char *)escAsciiString;

        PKIX_ENTER(STRING, "pkix_EscASCII_to_UTF16");
        PKIX_NULLCHECK_THREE(escAsciiString, pDest, pLength);

        if (escAsciiLen == 0) {
                PKIX_CHECK(PKIX_PL_Malloc(escAsciiLen, pDest, plContext),
                            PKIX_MALLOCFAILED);
                goto cleanup;
        }

        /* Assume each unicode character takes two bytes */
        newLen = escAsciiLen*2;

        /* Count up number of unicode encoded  characters */
        for (i = 0; i < escAsciiLen; i++) {
                if (!pkix_isPlaintext(stringData[i], debug)&&
                    (stringData[i] != '&')) {
                        PKIX_ERROR(PKIX_ILLEGALCHARACTERINESCAPEDASCII);
                } else if (PL_strstr(escAsciiString+i, "&amp;") ==
                            escAsciiString+i) {
                        /* Convert EscAscii "&amp;" to two bytes */
                        newLen -= 8;
                        i += 4;
                } else if ((PL_strstr(escAsciiString+i, "&#x") ==
                            escAsciiString+i)||
                            (PL_strstr(escAsciiString+i, "&#X") ==
                            escAsciiString+i)) {
                        if (((i+7) <= escAsciiLen)&&
                            (escAsciiString[i+7] == ';')) {
                                /* Convert &#xNNNN; to two bytes */
                                newLen -= 14;
                                i += 7;
                        } else if (((i+11) <= escAsciiLen)&&
                                (escAsciiString[i+11] == ';')) {
                                /* Convert &#xNNNNNNNN; to four bytes */
                                newLen -= 20;
                                i += 11;
                        } else {
                                PKIX_ERROR(PKIX_ILLEGALUSEOFAMP);
                        }
                }
        }

        PKIX_CHECK(PKIX_PL_Malloc(newLen, pDest, plContext),
                    PKIX_MALLOCFAILED);

        /* Copy into newly allocated space */
        destPtr = (unsigned char *)*pDest;

        i = 0;
        while (i < escAsciiLen) {
                /* Copy each byte until you hit a &amp; */
                if (pkix_isPlaintext(escAsciiString[i], debug)) {
                        *destPtr++ = 0x00;
                        *destPtr++ = escAsciiString[i++];
                } else if (PL_strstr(escAsciiString+i, "&amp;") ==
                            escAsciiString+i) {
                        /* Convert EscAscii "&amp;" to two bytes */
                        *destPtr++ = 0x00;
                        *destPtr++ = '&';
                        i += 5;
                } else if (((PL_strstr(escAsciiString+i, "&#x") ==
                            escAsciiString+i)||
                            (PL_strstr(escAsciiString+i, "&#X") ==
                            escAsciiString+i))&&
                            ((i+7) <= escAsciiLen)) {

                        /* We're either looking at &#xNNNN; or &#xNNNNNNNN; */
                        charSize = (escAsciiString[i+7] == ';')?4:8;

                        /* Skip past the &#x */
                        i += 3;

                        /* Make sure there is a terminating semi-colon */
                        if (((i+charSize) > escAsciiLen)||
                            (escAsciiString[i+charSize] != ';')) {
                                PKIX_ERROR(PKIX_TRUNCATEDUNICODEINESCAPEDASCII);
                        }

                        for (j = 0; j < charSize; j++) {
                                if (!PKIX_ISXDIGIT
                                    (escAsciiString[i+j])) {
                                        PKIX_ERROR(PKIX_ILLEGALUNICODECHARACTER);
                                } else if (charSize == 8) {
                                        x |= (pkix_hex2i
                                                        (escAsciiString[i+j]))
                                                        <<(4*(7-j));
                                }
                        }

                        testChar =
                                (pkix_hex2i(escAsciiString[i])<<4)|
                                pkix_hex2i(escAsciiString[i+1]);
                        testChar2 =
                                (pkix_hex2i(escAsciiString[i+2])<<4)|
                                pkix_hex2i(escAsciiString[i+3]);

                        if (charSize == 4) {
                                if ((testChar >= 0xD8)&&
                                    (testChar <= 0xDF)) {
                                        PKIX_ERROR(PKIX_ILLEGALSURROGATEPAIR);
                                } else if ((testChar == 0x00)&&
                                  pkix_isPlaintext(testChar2, debug)) {
                                      PKIX_ERROR(
                                          PKIX_ILLEGALCHARACTERINESCAPEDASCII);
                                }
                                *destPtr++ = testChar;
                                *destPtr++ = testChar2;
                        } else if (charSize == 8) {
                                /* First two chars must be 0001-0010 */
                                if (!((testChar == 0x00)&&
                                    ((testChar2 >= 0x01)&&
                                    (testChar2 <= 0x10)))) {
                                      PKIX_ERROR(
                                          PKIX_ILLEGALCHARACTERINESCAPEDASCII);
                                }
                                /*
                                 * Unicode Strings of the form:
                                 * x =  0001 0000..0010 FFFF
                                 * Encoded as pairs of UTF-16 where
                                 * y = ((x - 0001 0000) / 400) + D800
                                 * z = ((x - 0001 0000) % 400) + DC00
                                 */
                                x -= 0x00010000;
                                y = (x/0x400)+ 0xD800;
                                z = (x%0x400)+ 0xDC00;

                                /* Copy four bytes */
                                *destPtr++ = (y&0xFF00)>>8;
                                *destPtr++ = (y&0x00FF);
                                *destPtr++ = (z&0xFF00)>>8;
                                *destPtr++ = (z&0x00FF);
                        }
                        /* Move past the Hex digits and the semi-colon */
                        i += charSize+1;
                } else {
Exemple #18
0
// Simple parser to parse META charset. 
// It only supports the case when the description is within one line. 
const char * 
nsMsgI18NParseMetaCharset(nsIFile* file) 
{ 
  static char charset[nsIMimeConverter::MAX_CHARSET_NAME_LENGTH+1];

  *charset = '\0'; 

  bool isDirectory = false;
  file->IsDirectory(&isDirectory);
  if (isDirectory) {
    NS_ERROR("file is a directory");
    return charset; 
  }

  nsresult rv;
  nsCOMPtr <nsIFileInputStream> fileStream = do_CreateInstance(NS_LOCALFILEINPUTSTREAM_CONTRACTID, &rv);
  NS_ENSURE_SUCCESS(rv, charset);
  
  rv = fileStream->Init(file, PR_RDONLY, 0664, false);
  nsCOMPtr <nsILineInputStream> lineStream = do_QueryInterface(fileStream, &rv);

  nsCString curLine;
  bool more = true;
  while (NS_SUCCEEDED(rv) && more) { 
    rv = lineStream->ReadLine(curLine, &more); 
    if (curLine.IsEmpty()) 
      continue; 

    ToUpperCase(curLine);

    if (curLine.Find("/HEAD") != -1) 
      break; 

    if (curLine.Find("META") != -1 && 
       curLine.Find("HTTP-EQUIV") != -1 && 
        curLine.Find("CONTENT-TYPE") != -1 && 
       curLine.Find("CHARSET") != -1) { 
      char *cp = (char *) PL_strchr(PL_strstr(curLine.get(), "CHARSET"), '=');
      char *token = nullptr;
      if (cp)
      {
        char *newStr = cp + 1;
        token = NS_strtok(" \"\'", &newStr);
      }
      if (token) { 
        PL_strncpy(charset, token, sizeof(charset));
        charset[sizeof(charset)-1] = '\0';

        // this function cannot parse a file if it is really
        // encoded by one of the following charsets
        // so we can say that the charset label must be incorrect for
        // the .html if we actually see those charsets parsed
        // and we should ignore them
        if (!PL_strncasecmp("UTF-16", charset, sizeof("UTF-16")-1) || 
            !PL_strncasecmp("UTF-32", charset, sizeof("UTF-32")-1))
          charset[0] = '\0';

        break;
      } 
    } 
  } 

  return charset; 
} 
//----------------------------------------------------------------------------------------
OSErr nsMacCommandLine::HandleOpenOneDoc(const FSSpec& inFileSpec, OSType inFileType)
//----------------------------------------------------------------------------------------
{
  nsCOMPtr<nsILocalFileMac> inFile;
  nsresult rv = NS_NewLocalFileWithFSSpec(&inFileSpec, PR_TRUE, getter_AddRefs(inFile));
  if (NS_FAILED(rv))
    return errAEEventNotHandled;

  if (!mStartedUp)
  {
    // Is it the right type to be a command-line file?
    if (inFileType == 'TEXT' || inFileType == 'CMDL')
    {
      // Can we open the file?
      FILE *fp = 0;
      rv = inFile->OpenANSIFileDesc("r", &fp);
      if (NS_SUCCEEDED(rv))
      {
        Boolean foundArgs = false;
        Boolean foundEnv = false;
        char chars[1024];
        static const char kCommandLinePrefix[] = "ARGS:";
        static const char kEnvVarLinePrefix[] = "ENV:";

        while (ReadLine(fp, chars, sizeof(chars)) != -1)
        {       // See if there are any command line or environment var settings
          if (PL_strstr(chars, kCommandLinePrefix) == chars)
          {
            (void)AddToCommandLine(chars + sizeof(kCommandLinePrefix) - 1);
            foundArgs = true;
          }
          else if (PL_strstr(chars, kEnvVarLinePrefix) == chars)
          {
            (void)AddToEnvironmentVars(chars + sizeof(kEnvVarLinePrefix) - 1);
            foundEnv = true;
          }
        }

        fclose(fp);
#ifndef XP_MACOSX
        // If we found any environment vars we need to re-init NSPR's logging
        // so that it knows what the new vars are
        if (foundEnv)
          PR_Init_Log();
#endif
        // If we found a command line or environment vars we want to return now
        // raather than trying to open the file as a URL
        if (foundArgs || foundEnv)
          return noErr;
      }
    }
    // If it's not a command-line argument, and we are starting up the application,
    // add a command-line "-url" argument to the global list. This means that if
    // the app is opened with documents on the mac, they'll be handled the same
    // way as if they had been typed on the command line in Unix or DOS.
    return AddToCommandLine("-url", inFileSpec);
  }

  // Final case: we're not just starting up. How do we handle this?
  nsCAutoString specBuf;
  rv = NS_GetURLSpecFromFile(inFile, specBuf);
  if (NS_FAILED(rv))
    return errAEEventNotHandled;
  
  return OpenURL(specBuf.get());
}
Exemple #20
0
NS_IMETHODIMP nsPop3Service::NewURI(const nsACString &aSpec,
                                    const char *aOriginCharset, // ignored
                                    nsIURI *aBaseURI,
                                    nsIURI **_retval)
{
    nsresult rv = NS_ERROR_FAILURE;
    if (!_retval) return rv;
    nsCAutoString folderUri(aSpec);
    nsCOMPtr<nsIRDFResource> resource;
    PRInt32 offset = folderUri.Find("?");
    if (offset != -1)
        folderUri.Truncate(offset);

    const nsCString &flatSpec = PromiseFlatCString(aSpec);
    const char *uidl = PL_strstr(flatSpec.get(), "uidl=");
    if (!uidl) return NS_ERROR_FAILURE;

    nsCOMPtr<nsIRDFService> rdfService(do_GetService(kRDFServiceCID, &rv)); 
    if (NS_FAILED(rv)) return rv;
    rv = rdfService->GetResource(folderUri, getter_AddRefs(resource));
    if (NS_FAILED(rv)) return rv;
    nsCOMPtr<nsIMsgFolder> folder = do_QueryInterface(resource, &rv);
    if (NS_FAILED(rv)) return rv;
    nsCOMPtr<nsIMsgIncomingServer> server;

    nsLocalFolderScanState folderScanState;
    nsCOMPtr<nsIMsgLocalMailFolder> localFolder = do_QueryInterface(folder);
    nsCOMPtr <nsIMailboxUrl> mailboxUrl = do_QueryInterface(aBaseURI);

    nsCOMPtr<nsIFileSpec> path;
    rv = folder->GetPath(getter_AddRefs(path));
    if (NS_FAILED(rv)) return rv;

    nsFileSpec fileSpec;
    path->GetFileSpec(&fileSpec);
    folderScanState.m_fileSpec = &fileSpec;
    if (mailboxUrl && localFolder)
    {
      rv = localFolder->GetFolderScanState(&folderScanState);
      NS_ENSURE_SUCCESS(rv, rv);
      nsCOMPtr <nsIMsgDBHdr> msgHdr;
      nsCOMPtr<nsIMsgMessageUrl> msgUrl = do_QueryInterface(mailboxUrl, &rv);
      NS_ENSURE_SUCCESS(rv,rv);
      msgUrl->GetMessageHeader(getter_AddRefs(msgHdr));
      // we do this to get the account key
      if (msgHdr)
        localFolder->GetUidlFromFolder(&folderScanState, msgHdr);
      if (!folderScanState.m_accountKey.IsEmpty())
      {
        nsCOMPtr<nsIMsgAccountManager> accountManager = 
                 do_GetService(NS_MSGACCOUNTMANAGER_CONTRACTID, &rv);
        if (accountManager)
        {
          nsCOMPtr <nsIMsgAccount> account;
          accountManager->GetAccount(folderScanState.m_accountKey.get(), getter_AddRefs(account));
          if (account)
            account->GetIncomingServer(getter_AddRefs(server));
        }
      }
    }

    if (!server)
    rv = folder->GetServer(getter_AddRefs(server));
    if (NS_FAILED(rv)) return rv;
    nsCOMPtr<nsIPop3IncomingServer> popServer = do_QueryInterface(server,&rv);
    if (NS_FAILED(rv)) return rv;
    nsXPIDLCString hostname;
    nsXPIDLCString username;
    server->GetHostName(getter_Copies(hostname));
    server->GetUsername(getter_Copies(username));

    PRInt32 port;
    server->GetPort(&port);
    if (port == -1) port = POP3_PORT;
    
	// we need to escape the username because it may contain
	// characters like / % or @
    nsXPIDLCString escapedUsername;
    *((char **)getter_Copies(escapedUsername)) =
      nsEscape(username, url_XAlphas);
    
    nsCAutoString popSpec("pop://");
    popSpec += escapedUsername;
    popSpec += "@";
    popSpec += hostname;
    popSpec += ":";
    popSpec.AppendInt(port);
    popSpec += "?";
    popSpec += uidl;
    nsCOMPtr<nsIUrlListener> urlListener = do_QueryInterface(folder, &rv);
    if (NS_FAILED(rv)) return rv;
    rv = BuildPop3Url(popSpec.get(), folder, popServer,
                      urlListener, _retval, nsnull); 
    if (NS_SUCCEEDED(rv))
    {
        nsCOMPtr<nsIMsgMailNewsUrl> mailnewsurl = 
            do_QueryInterface(*_retval, &rv);
        if (NS_SUCCEEDED(rv))
        {
			// escape the username before we call SetUsername().  we do this because GetUsername()
			// will unescape the username
            mailnewsurl->SetUsername(escapedUsername);
        }
        nsCOMPtr<nsIPop3URL> popurl = do_QueryInterface(mailnewsurl, &rv);
        if (NS_SUCCEEDED(rv))
        {
            nsCAutoString messageUri (aSpec);
            messageUri.ReplaceSubstring("mailbox:", "mailbox-message:");
            messageUri.ReplaceSubstring("?number=", "#");
            offset = messageUri.Find("&");
            if (offset != -1)
                messageUri.Truncate(offset);
            popurl->SetMessageUri(messageUri.get());
            nsCOMPtr<nsIPop3Sink> pop3Sink;
            rv = popurl->GetPop3Sink(getter_AddRefs(pop3Sink));
            if (NS_SUCCEEDED(rv))
                pop3Sink->SetBuildMessageUri(PR_TRUE);
        }
    }
    return rv;
}
Exemple #21
0
PRBool IniParser::readIniLine(char** pszSection, char** pszToken,
                              char** pszVal, PRUint32* piLine)
{
    char *p, *q, *r;

    // check for invalid parameters
    if(!m_pTextFile || !pszSection || !pszToken || !pszVal)
        return false;

    // initialization
    *pszSection = &m_pszCurrentSection[0];
    *pszToken = NULL;
    *pszVal = NULL;

    char *pszLine = NULL;
    SKERR err = noErr;

    while(err == noErr)
    {
        err = m_pTextFile->GetLine(&pszLine);
        if((err != noErr) || !pszLine)
            break;
        // increment line number if applicable
        if(piLine != NULL)
            ++*piLine;

        // strip comments
        p = PL_strstr(pszLine, "//");
        if(p)
            *p = 0;

        // right trim
        for(p = pszLine + PL_strlen(pszLine); p >= pszLine && *p <= 0x20; p--)
            *p = 0;

        // left trim
        for(p = pszLine; *p && *p <= 0x20; p++) {}

        // section
        if (*p == '[')
        {
            q = PL_strchr(p, ']');
            if (q)
                *q = 0;
            p++;
            PL_strncpy(m_pszCurrentSection, p, sizeof(m_pszCurrentSection) - 1);
            m_pszCurrentSection[sizeof(m_pszCurrentSection) - 1] = '\0';
            break;
        }

        // look for token = val pairs
        q = PL_strchr(p, '=');
        if (!q)
        {
            // skip ill-formed lines
            continue;
        }

        // right trim
        for (r = q ; r >= p && (*r <= 0x20 || *r == '=') ; r--)
            *r = 0;

        // found token
        *pszToken = p;

        // left trim
        for (q++; *q <= 0x20; q++)
        {
            if (!*q)
                break;
        }
/*
        if (!*q)
        {
            // skip ill-formed lines
            SKError(err_invalid, "[IniParser] invalid line: %s", pszLine);
            continue;
        }
*/
        // found value
        *pszVal = q;
        break;
    }

    // true on success
    return (err == noErr) && pszLine;
}
Exemple #22
0
/* Partition the headers into those which apply to the message as a whole;
those which apply to the message's contents; and the Content-Type header
itself.  (This relies on the fact that all body-related headers begin with
"Content-".)

  (How many header parsers are in this program now?)
  */
static int 
divide_content_headers(const char *headers,
                        char **message_headers,
                        char **content_headers,
                        char **content_type_header)
{
    const char *tail;
    char *message_tail, *content_tail, *type_tail;
    int L = 0;
    if (headers)
      L = PL_strlen(headers);
    
    if (L == 0)
      return 0;
    
    *message_headers = (char *)PR_Malloc(L+1);
    if (!*message_headers)
      return NS_ERROR_OUT_OF_MEMORY;
    
    *content_headers = (char *)PR_Malloc(L+1);
    if (!*content_headers) {
      PR_Free(*message_headers);
      return NS_ERROR_OUT_OF_MEMORY;
    }
    
    *content_type_header = (char *)PR_Malloc(L+1);
    if (!*content_type_header) {
      PR_Free(*message_headers);
      PR_Free(*content_headers);
      return NS_ERROR_OUT_OF_MEMORY;
    }
    
    message_tail = *message_headers;
    content_tail = *content_headers;
    type_tail    = *content_type_header;
    tail = headers;
    
    while (*tail)
    {
      const char *head = tail;
      char **out;
      while(true) {
      /* Loop until we reach a newline that is not followed by whitespace.
        */
        if (tail[0] == 0 ||
          ((tail[0] == '\r' || tail[0] == '\n') &&
          !(tail[1] == ' ' || tail[1] == '\t' || tail[1] == '\n')))
        {
          /* Swallow the whole newline. */
          if (tail[0] == '\r' && tail[1] == '\n')
            tail++;
          if (*tail)
            tail++;
          break;
        }
        tail++;
      }
      
      /* Decide which block this header goes into.
      */
      if (!PL_strncasecmp(head, "Content-Type:", 13))
        out = &type_tail;
      else
        if (!PL_strncasecmp(head, "Content-", 8))
          out = &content_tail;
        else
          out = &message_tail;
        
        memcpy(*out, head, (tail-head));
        *out += (tail-head);
    }
    
    *message_tail = 0;
    *content_tail = 0;
    *type_tail = 0;
    
    if (!**message_headers) {
      PR_Free(*message_headers);
      *message_headers = 0;
    }
    
    if (!**content_headers) {
      PR_Free(*content_headers);
      *content_headers = 0;
    }
    
    if (!**content_type_header) {
      PR_Free(*content_type_header);
      *content_type_header = 0;
    }
    
#ifdef DEBUG
    // ### mwelch Because of the extreme difficulty we've had with
    //      duplicate part headers, I'm going to put in an
    //      ASSERT here which makes sure that no duplicate
    //      Content-Type or Content-Transfer-Encoding headers
    //      leave here undetected.
    const char* tmp;
    if (*content_type_header) {
      tmp = PL_strstr(*content_type_header, "Content-Type");
      if (tmp) {
        tmp++; // get past the first occurrence
        NS_ASSERTION(!PL_strstr(tmp, "Content-Type"), "Content-part already present");
      }
    }
    
    if (*content_headers) {
      tmp = PL_strstr(*content_headers, "Content-Transfer-Encoding");
      if (tmp) {
        tmp++; // get past the first occurrence
        NS_ASSERTION(!PL_strstr(tmp, "Content-Transfer-Encoding"), "Content-Transfert already present");
      }
    }
#endif // DEBUG
    
    return 0;
}
static char *
MimeMessage_partial_message_html(const char *data, void *closure,
                 MimeHeaders *headers)
{
  MimeMessage *msg = (MimeMessage *)closure;
  nsCAutoString orig_url(data);
  char *uidl = MimeHeaders_get(headers, HEADER_X_UIDL, PR_FALSE, PR_FALSE);
  char *msgId = MimeHeaders_get(headers, HEADER_MESSAGE_ID, PR_FALSE,
                  PR_FALSE);
  char *msgIdPtr = PL_strstr(msgId, "<");
  int msgBase;

  PRInt32 pos = orig_url.Find("mailbox-message");
  if (pos != -1)
    orig_url.Cut(pos + 7, 8);

  pos = orig_url.Find("#");
  if (pos != -1)
    orig_url.Replace(pos, 1, "?number=", 8);

  if (msgIdPtr)
    msgIdPtr++;
  else
    msgIdPtr = msgId;
  char *gtPtr = PL_strstr(msgIdPtr, ">");
  if (gtPtr)
    *gtPtr = 0;

  msgBase = (msg->bodyLength > MSG_LINEBREAK_LEN) ? MIME_MSG_PARTIAL_FMT_1 : MIME_MSG_PARTIAL_FMT2_1;

  nsCString partialMsgHtml;
  nsCString item;

  item.Adopt(MimeGetStringByID(msgBase));
  partialMsgHtml += item;

  item.Adopt(MimeGetStringByID(msgBase+1));
  partialMsgHtml += item;

  partialMsgHtml.Append(orig_url);

  if (msgIdPtr) {
    partialMsgHtml.AppendLiteral("&messageid=");

    MsgEscapeString(nsDependentCString(msgIdPtr), nsINetUtil::ESCAPE_URL_PATH,
                    item);

    partialMsgHtml.Append(item);
  }

  if (uidl) {
    partialMsgHtml.AppendLiteral("&uidl=");

    MsgEscapeString(nsDependentCString(uidl), nsINetUtil::ESCAPE_XALPHAS,
                    item);

    partialMsgHtml.Append(item);
  }

  item.Adopt(MimeGetStringByID(msgBase+2));
  partialMsgHtml += item;

  return ToNewCString(partialMsgHtml);
}
Exemple #24
0
NS_IMETHODIMP nsPop3Service::NewURI(const nsACString &aSpec,
                                    const char *aOriginCharset, // ignored
                                    nsIURI *aBaseURI,
                                    nsIURI **_retval)
{
    NS_ENSURE_ARG_POINTER(_retval);

    nsCAutoString folderUri(aSpec);
    nsCOMPtr<nsIRDFResource> resource;
    PRInt32 offset = folderUri.FindChar('?');
    if (offset != kNotFound)
      folderUri.SetLength(offset);

    const char *uidl = PL_strstr(nsCString(aSpec).get(), "uidl=");
    NS_ENSURE_TRUE(uidl, NS_ERROR_FAILURE);

    nsresult rv;

    nsCOMPtr<nsIRDFService> rdfService(do_GetService(kRDFServiceCID, &rv));
    NS_ENSURE_SUCCESS(rv, rv);

    rv = rdfService->GetResource(folderUri, getter_AddRefs(resource));
    NS_ENSURE_SUCCESS(rv, rv);

    nsCOMPtr<nsIMsgFolder> folder = do_QueryInterface(resource, &rv);
    NS_ENSURE_SUCCESS(rv, rv);

    nsCOMPtr<nsIMsgIncomingServer> server;

    nsLocalFolderScanState folderScanState;
    nsCOMPtr<nsIMsgLocalMailFolder> localFolder = do_QueryInterface(folder);
    nsCOMPtr<nsIMailboxUrl> mailboxUrl = do_QueryInterface(aBaseURI);

    if (mailboxUrl && localFolder)
    {
      rv = localFolder->GetFolderScanState(&folderScanState);
      NS_ENSURE_SUCCESS(rv, rv);
      nsCOMPtr<nsIMsgDBHdr> msgHdr;
      nsMsgKey msgKey;
      mailboxUrl->GetMessageKey(&msgKey);
      folder->GetMessageHeader(msgKey, getter_AddRefs(msgHdr));
      // we do this to get the account key
      if (msgHdr)
        localFolder->GetUidlFromFolder(&folderScanState, msgHdr);
      if (!folderScanState.m_accountKey.IsEmpty())
      {
        nsCOMPtr<nsIMsgAccountManager> accountManager =
                 do_GetService(NS_MSGACCOUNTMANAGER_CONTRACTID, &rv);
        if (accountManager)
        {
          nsCOMPtr<nsIMsgAccount> account;
          accountManager->GetAccount(folderScanState.m_accountKey, getter_AddRefs(account));
          if (account)
            account->GetIncomingServer(getter_AddRefs(server));
        }
      }
    }

    if (!server)
      rv = folder->GetServer(getter_AddRefs(server));
    NS_ENSURE_SUCCESS(rv, rv);

    nsCOMPtr<nsIPop3IncomingServer> popServer = do_QueryInterface(server,&rv);
    NS_ENSURE_SUCCESS(rv, rv);

    nsCString hostname;
    nsCString username;
    server->GetHostName(hostname);
    server->GetUsername(username);

    PRInt32 port;
    server->GetPort(&port);
    if (port == -1) port = nsIPop3URL::DEFAULT_POP3_PORT;

    // we need to escape the username because it may contain
    // characters like / % or @
    nsCString escapedUsername;
    MsgEscapeString(username, nsINetUtil::ESCAPE_XALPHAS, escapedUsername);

    nsCAutoString popSpec("pop://");
    popSpec += escapedUsername;
    popSpec += "@";
    popSpec += hostname;
    popSpec += ":";
    popSpec.AppendInt(port);
    popSpec += "?";
    popSpec += uidl;
    nsCOMPtr<nsIUrlListener> urlListener = do_QueryInterface(folder, &rv);
    NS_ENSURE_SUCCESS(rv, rv);

    rv = BuildPop3Url(popSpec.get(), folder, popServer,
                      urlListener, _retval, nsnull);
    NS_ENSURE_SUCCESS(rv, rv);

    nsCOMPtr<nsIMsgMailNewsUrl> mailnewsurl = do_QueryInterface(*_retval, &rv);
    if (NS_SUCCEEDED(rv))
    {
      // escape the username before we call SetUsername().  we do this because GetUsername()
      // will unescape the username
      mailnewsurl->SetUsername(escapedUsername);
    }

    nsCOMPtr<nsIPop3URL> popurl = do_QueryInterface(mailnewsurl, &rv);
    NS_ENSURE_SUCCESS(rv, rv);

    nsCAutoString messageUri (aSpec);
    if (!strncmp(messageUri.get(), "mailbox:", 8))
      messageUri.Replace(0, 8, "mailbox-message:");
    offset = messageUri.Find("?number=");
    if (offset != kNotFound)
      messageUri.Replace(offset, 8, "#");
    offset = messageUri.FindChar('&');
    if (offset != kNotFound)
      messageUri.SetLength(offset);
    popurl->SetMessageUri(messageUri.get());
    nsCOMPtr<nsIPop3Sink> pop3Sink;
    rv = popurl->GetPop3Sink(getter_AddRefs(pop3Sink));
    NS_ENSURE_SUCCESS(rv, rv);

    pop3Sink->SetBuildMessageUri(true);

    return NS_OK;
}
Exemple #25
0
/*
 * update multiple attribute values per _do_modify
 */
static int
_update_all_per_mod(Slapi_DN *entrySDN,      /* DN of the searched entry */
                    Slapi_Attr *attr,        /* referred attribute */
                    char *attrName,
                    Slapi_DN *origDN,        /* original DN that was modified */
                    char *newRDN,            /* new RDN from modrdn */
                    const char *newsuperior, /* new superior from modrdn */
                    Slapi_PBlock *mod_pb)
{
    Slapi_Mods *smods = NULL;
    char *newDN = NULL;
    char **dnParts = NULL;
    char *sval = NULL;
    char *newvalue = NULL;
    char *p = NULL;
    size_t dnlen = 0;
    int rc = 0;
    int nval = 0;

    slapi_attr_get_numvalues(attr, &nval);

    if (NULL == newRDN && NULL == newsuperior) {
        /* in delete mode */
        LDAPMod *mods[2];
        char *values_del[2];
        LDAPMod attribute1;

        /* delete old dn so set that up */
        values_del[0] = (char *)slapi_sdn_get_dn(origDN);
        values_del[1] = NULL;
        attribute1.mod_type = attrName;
        attribute1.mod_op = LDAP_MOD_DELETE;
        attribute1.mod_values = values_del;
        mods[0] = &attribute1;
        /* terminate list of mods. */
        mods[1] = NULL;
        rc = _do_modify(mod_pb, entrySDN, mods);
        if (rc) {
            slapi_log_error( SLAPI_LOG_FATAL, REFERINT_PLUGIN_SUBSYSTEM,
                "_update_all_per_mod: entry %s: deleting \"%s: %s\" failed (%d)"
                "\n", slapi_sdn_get_dn(entrySDN), attrName, slapi_sdn_get_dn(origDN), rc);
        }
    } else {
        /* in modrdn mode */
        const char *superior = NULL;
        int nval = 0;
        Slapi_Value *v = NULL;

        if (NULL == origDN) {
            slapi_log_error(SLAPI_LOG_FATAL, REFERINT_PLUGIN_SUBSYSTEM,
                            "_update_all_per_mod: NULL dn was passed\n");
            goto bail;
        }
        /* need to put together rdn into a dn */
        dnParts = slapi_ldap_explode_dn( slapi_sdn_get_dn(origDN), 0 );
        if (NULL == dnParts) {
            slapi_log_error(SLAPI_LOG_FATAL, REFERINT_PLUGIN_SUBSYSTEM,
                            "_update_all_per_mod: failed to explode dn %s\n",
                            slapi_sdn_get_dn(origDN));
            goto bail;
        }
        if (NULL == newRDN) {
            newRDN = dnParts[0];
        }
        if (newsuperior) {
            superior = newsuperior;
        } else {
            /* do not free superior */
            superior = slapi_dn_find_parent(slapi_sdn_get_dn(origDN));
        }
        /* newRDN and superior are already normalized. */
        newDN = slapi_ch_smprintf("%s,%s", newRDN, superior);
        slapi_dn_ignore_case(newDN);
        /* 
         * Compare the modified dn with the value of 
         * the target attribute of referint to find out
         * the modified dn is the ancestor (case 2) or
         * the value itself (case 1).
         *
         * E.g., 
         * (case 1) 
         * modrdn: uid=A,ou=B,o=C --> uid=A',ou=B',o=C
         *            (origDN)             (newDN)
         * member: uid=A,ou=B,ou=C --> uid=A',ou=B',ou=C
         *            (sval)               (newDN)
         *
         * (case 2) 
         * modrdn: ou=B,o=C --> ou=B',o=C
         *         (origDN)      (newDN)
         * member: uid=A,ou=B,ou=C --> uid=A,ou=B',ou=C
         *         (sval)              (sval' + newDN)
         */
        slapi_attr_get_numvalues(attr, &nval);
        smods = slapi_mods_new();
        slapi_mods_init(smods, 2 * nval + 1);

        for (nval = slapi_attr_first_value(attr, &v);
             nval != -1;
             nval = slapi_attr_next_value(attr, nval, &v)) {
            p = NULL;
            dnlen = 0;

            /* DN syntax, which should be a string */
            sval = slapi_ch_strdup(slapi_value_get_string(v));
            rc = slapi_dn_normalize_case_ext(sval, 0,  &p, &dnlen);
            if (rc == 0) { /* sval is passed in; not terminated */
                *(p + dnlen) = '\0';
                sval = p;
            } else if (rc > 0) {
                slapi_ch_free_string(&sval);
                sval = p;
            }
            /* else: (rc < 0) Ignore the DN normalization error for now. */

            p = PL_strstr(sval, slapi_sdn_get_ndn(origDN));
            if (p == sval) {
                /* (case 1) */
                slapi_mods_add_string(smods, LDAP_MOD_DELETE, attrName, sval);
                slapi_mods_add_string(smods, LDAP_MOD_ADD, attrName, newDN);

            } else if (p) {
                /* (case 2) */
                slapi_mods_add_string(smods, LDAP_MOD_DELETE, attrName, sval);
                *p = '\0';
                newvalue = slapi_ch_smprintf("%s%s", sval, newDN);
                slapi_mods_add_string(smods, LDAP_MOD_ADD, attrName, newvalue);
                slapi_ch_free_string(&newvalue);
            } 
            /* else: value does not include the modified DN.  Ignore it. */
            slapi_ch_free_string(&sval);
        }
        rc = _do_modify(mod_pb, entrySDN, slapi_mods_get_ldapmods_byref(smods));
        if (rc) {
            slapi_log_error( SLAPI_LOG_FATAL, REFERINT_PLUGIN_SUBSYSTEM,
                        "_update_all_per_mod: entry %s failed (%d)\n",
                        slapi_sdn_get_dn(entrySDN), rc);
        }

        /* cleanup memory allocated for dnParts and newDN */
        if (dnParts){
            slapi_ldap_value_free(dnParts);
            dnParts = NULL;
        }
        slapi_ch_free_string(&newDN);
        slapi_mods_free(&smods);
    }

bail:
    return rc;
}
nsresult
nsMsgQuote::QuoteMessage(const char *msgURI, bool quoteHeaders,
                         nsIMsgQuotingOutputStreamListener * aQuoteMsgStreamListener,
                         const char * aMsgCharSet, bool headersOnly,
                         nsIMsgDBHdr *aMsgHdr)
{
  nsresult  rv;
  if (!msgURI)
    return NS_ERROR_INVALID_ARG;

  mQuoteHeaders = quoteHeaders;
  mStreamListener = aQuoteMsgStreamListener;

  nsAutoCString msgUri(msgURI);
  bool fileUrl = !strncmp(msgURI, "file:", 5);
  bool forwardedMessage = PL_strstr(msgURI, "&realtype=message/rfc822") != nullptr;
  nsCOMPtr<nsIURI> aURL;
  if (fileUrl)
  {
    msgUri.Replace(0, 5, NS_LITERAL_CSTRING("mailbox:"));
    msgUri.AppendLiteral("?number=0");
    rv = NS_NewURI(getter_AddRefs(aURL), msgUri);
    nsCOMPtr<nsIMsgMessageUrl> mailUrl(do_QueryInterface(aURL));
    if (mailUrl)
      mailUrl->SetMessageHeader(aMsgHdr);
  }
  else if (forwardedMessage)
    rv = NS_NewURI(getter_AddRefs(aURL), msgURI);
  else
  {
    nsCOMPtr <nsIMsgMessageService> msgService;
    rv = GetMessageServiceFromURI(nsDependentCString(msgURI), getter_AddRefs(msgService));
    if (NS_FAILED(rv)) return rv;
    rv = msgService->GetUrlForUri(msgURI, getter_AddRefs(aURL), nullptr);
  }
  if (NS_FAILED(rv)) return rv;

  nsCOMPtr <nsIURL> mailNewsUrl = do_QueryInterface(aURL, &rv);
  NS_ENSURE_SUCCESS(rv,rv);

  nsAutoCString queryPart;
  rv = mailNewsUrl->GetQuery(queryPart);
  if (!queryPart.IsEmpty())
    queryPart.Append('&');

  if (headersOnly) /* We don't need to quote the message body but we still need to extract the headers */
    queryPart.Append("header=only");
  else if (quoteHeaders)
    queryPart.Append("header=quote");
  else
    queryPart.Append("header=quotebody");
  rv = mailNewsUrl->SetQuery(queryPart);
  NS_ENSURE_SUCCESS(rv,rv);

  // if we were given a non empty charset, then use it
  if (aMsgCharSet && *aMsgCharSet)
  {
    nsCOMPtr<nsIMsgI18NUrl> i18nUrl (do_QueryInterface(aURL));
    if (i18nUrl)
      i18nUrl->SetCharsetOverRide(aMsgCharSet);
  }

  mQuoteListener = do_CreateInstance(NS_MSGQUOTELISTENER_CONTRACTID, &rv);
  if (NS_FAILED(rv)) return rv;
  mQuoteListener->SetMsgQuote(this);

  // funky magic go get the isupports for this class which inherits from multiple interfaces.
  nsISupports * supports;
  QueryInterface(NS_GET_IID(nsISupports), (void **) &supports);
  nsCOMPtr<nsISupports> quoteSupport = supports;
  NS_IF_RELEASE(supports);

  // now we want to create a necko channel for this url and we want to open it
  mQuoteChannel = nullptr;
  nsCOMPtr<nsIIOService> netService =
    mozilla::services::GetIOService();
  NS_ENSURE_TRUE(netService, NS_ERROR_UNEXPECTED);
  rv = netService->NewChannelFromURI(aURL, getter_AddRefs(mQuoteChannel));
  if (NS_FAILED(rv)) return rv;
  nsCOMPtr<nsISupports> ctxt = do_QueryInterface(aURL);

  nsCOMPtr<nsIStreamConverterService> streamConverterService = 
           do_GetService("@mozilla.org/streamConverters;1", &rv);
  NS_ENSURE_SUCCESS(rv,rv);

  nsCOMPtr<nsIStreamListener> convertedListener;
  rv = streamConverterService->AsyncConvertData("message/rfc822",
                                                "application/vnd.mozilla.xul+xml",
                                                mStreamListener,
                                                quoteSupport,
                                                getter_AddRefs(convertedListener));
  if (NS_FAILED(rv)) return rv;

  //  now try to open the channel passing in our display consumer as the listener 
  rv = mQuoteChannel->AsyncOpen(convertedListener, ctxt);
  return rv;
}