nsresult nsMimeBaseEmitter::DumpToCC() { const char * toField = GetHeaderValue(HEADER_TO); const char * ccField = GetHeaderValue(HEADER_CC); const char * bccField = GetHeaderValue(HEADER_BCC); const char * newsgroupField = GetHeaderValue(HEADER_NEWSGROUPS); // only dump these fields if we have at least one of them! When displaying news // messages that didn't have a To or Cc field, we'd always get an empty box // which looked weird. if (toField || ccField || bccField || newsgroupField) { mHTMLHeaders.Append("<table border=0 cellspacing=0 cellpadding=0 width=\"100%\" class=\"header-part2\">"); if (toField) WriteHeaderFieldHTML(HEADER_TO, toField); if (ccField) WriteHeaderFieldHTML(HEADER_CC, ccField); if (bccField) WriteHeaderFieldHTML(HEADER_BCC, bccField); if (newsgroupField) WriteHeaderFieldHTML(HEADER_NEWSGROUPS, newsgroupField); mHTMLHeaders.Append("</table>"); } return NS_OK; }
bool SSDP::ProcessSearchResponse( const QStringMap &headers ) { QString sDescURL = GetHeaderValue( headers, "LOCATION" , "" ); QString sST = GetHeaderValue( headers, "ST" , "" ); QString sUSN = GetHeaderValue( headers, "USN" , "" ); QString sCache = GetHeaderValue( headers, "CACHE-CONTROL" , "" ); LOG(VB_UPNP, LOG_DEBUG, QString( "SSDP::ProcessSearchResponse ...\n" "DescURL=%1\n" "ST =%2\n" "USN =%3\n" "Cache =%4") .arg(sDescURL).arg(sST).arg(sUSN).arg(sCache)); int nPos = sCache.indexOf("max-age", 0, Qt::CaseInsensitive); if (nPos < 0) return false; if ((nPos = sCache.indexOf("=", nPos)) < 0) return false; int nSecs = sCache.mid( nPos+1 ).toInt(); SSDPCache::Instance()->Add( sST, sUSN, sDescURL, nSecs ); return true; }
/* * Converts clipboard data from CF_HTML format to mimie clipboard format * Returns allocated buffer that contains html converted to text/html mime type * return result code * parameters - output buffer and size of output buffer * It allocates the buffer needed for storing converted fragment * Allocated buffer should be destroyed by RTMemFree after usage */ int ConvertCFHtmlToMime(const char *pcszSource, const uint32_t cch, char **ppszOutput, size_t *pcCh) { char* result = NULL; Assert(pcszSource); Assert(cch); Assert(ppszOutput); Assert(pcCh); size_t cStartOffset, cEndOffset; int rc = GetHeaderValue(pcszSource, "StartFragment:", &cStartOffset); if (!RT_SUCCESS(rc)) { LogRelFlowFunc(("Error: Unknown CF_HTML format. Expected StartFragment. rc = %Rrc.\n", rc)); return VERR_INVALID_PARAMETER; } rc = GetHeaderValue(pcszSource, "EndFragment:", &cEndOffset); if (!RT_SUCCESS(rc)) { LogRelFlowFunc(("Error: Unknown CF_HTML format. Expected EndFragment. rc = %Rrc.\n", rc)); return VERR_INVALID_PARAMETER; } if (cStartOffset > 0 && cEndOffset > 0 && cEndOffset > cStartOffset) { size_t cSubstrlen = cEndOffset - cStartOffset; result = (char*)RTMemAlloc(cSubstrlen + 1); if (result) { RT_BZERO(result, cSubstrlen + 1); rc = RTStrCopyEx(result, cSubstrlen + 1, pcszSource + cStartOffset, cSubstrlen); if (RT_SUCCESS(rc)) { *ppszOutput = result; *pcCh = cSubstrlen + 1; } else { LogRelFlowFunc(("Error: Unknown CF_HTML format. Expected EndFragment. rc = %Rrc\n", rc)); return rc; } } else { LogRelFlowFunc(("Error: Unknown CF_HTML format. Expected EndFragment.\n")); return VERR_NO_MEMORY; } } return VINF_SUCCESS; }
/////////////////////////////////////////////////////////////////////// /// Function: XosWebRtcClientConnection:: /// /// Author: $author$ /// Date: 4/1/2012 /////////////////////////////////////////////////////////////////////// bool XosWebRtcClientConnection::ParseServerResponse(const std::string& response, size_t content_length, size_t* peer_id, size_t* eoh) { LOG(INFO) << response; int status = GetResponseStatus(response.c_str()); if (status != 200) { LOG(LS_ERROR) << "Received error from server"; Close(); callback_->OnDisconnected(); return false; } *eoh = response.find("\r\n\r\n"); ASSERT(*eoh != std::string::npos); if (*eoh == std::string::npos) return false; *peer_id = -1; // See comment in peer_channel.cc for why we use the Pragma header and // not e.g. "X-Peer-Id". GetHeaderValue(response, *eoh, "\r\nPragma: ", peer_id); return true; }
bool SSDP::ProcessNotify( const QStringMap &headers ) { QString sDescURL = GetHeaderValue( headers, "LOCATION" , "" ); QString sNTS = GetHeaderValue( headers, "NTS" , "" ); QString sNT = GetHeaderValue( headers, "NT" , "" ); QString sUSN = GetHeaderValue( headers, "USN" , "" ); QString sCache = GetHeaderValue( headers, "CACHE-CONTROL" , "" ); VERBOSE( VB_UPNP+VB_EXTRA, QString( "SSDP::ProcessNotify ...\n" "DescURL=%1\n" "NTS =%2\n" "NT =%3\n" "USN =%4\n" "Cache =%5" ) .arg(sDescURL).arg(sNTS).arg(sNT).arg(sUSN).arg(sCache)); if (sNTS.contains( "ssdp:alive")) { int nPos = sCache.indexOf("max-age", 0, Qt::CaseInsensitive); if (nPos < 0) return false; if ((nPos = sCache.indexOf("=", nPos)) < 0) return false; int nSecs = sCache.mid( nPos+1 ).toInt(); SSDPCache::Instance()->Add( sNT, sUSN, sDescURL, nSecs ); return true; } if ( sNTS.contains( "ssdp:byebye" ) ) { SSDPCache::Instance()->Remove( sNT, sUSN ); return true; } return false; }
nsresult nsMimeBaseEmitter::OutputGenericHeader(const char *aHeaderVal) { const char *val = GetHeaderValue(aHeaderVal); if (val) return WriteHeaderFieldHTML(aHeaderVal, val); return NS_ERROR_FAILURE; }
/////////////////////////////////////////////////////////////////////// /// Function: XosWebRtcClientConnection:: /// /// Author: $author$ /// Date: 4/1/2012 /////////////////////////////////////////////////////////////////////// bool XosWebRtcClientConnection::ReadIntoBuffer(talk_base::AsyncSocket* socket, std::string* data, size_t* content_length) { LOG(INFO) << __FUNCTION__; char buffer[0xffff]; do { int bytes = socket->Recv(buffer, sizeof(buffer)); if (bytes <= 0) break; data->append(buffer, bytes); } while (true); bool ret = false; size_t i = data->find("\r\n\r\n"); if (i != std::string::npos) { LOG(INFO) << "Headers received"; if (GetHeaderValue(*data, i, "\r\nContent-Length: ", content_length)) { LOG(INFO) << "Expecting " << *content_length << " bytes."; size_t total_response_size = (i + 4) + *content_length; if (data->length() >= total_response_size) { ret = true; std::string should_close; const char kConnection[] = "\r\nConnection: "; if (GetHeaderValue(*data, i, kConnection, &should_close) && should_close.compare("close") == 0) { socket->Close(); // Since we closed the socket, there was no notification delivered // to us. Compensate by letting ourselves know. OnClose(socket, 0); } } else { // We haven't received everything. Just continue to accept data. } } else { LOG(LS_ERROR) << "No content length field specified by the server."; } } return ret; }
nsresult nsMimeHtmlDisplayEmitter::EndHeader(const nsACString &name) { if (mDocHeader && (mFormat != nsMimeOutput::nsMimeMessageFilterSniffer)) { UtilityWriteCRLF("<html>"); UtilityWriteCRLF("<head>"); const char * val = GetHeaderValue(HEADER_SUBJECT); // do not free this value if (val) { char * subject = MsgEscapeHTML(val); if (subject) { int32_t bufLen = strlen(subject) + 16; char *buf = new char[bufLen]; if (!buf) return NS_ERROR_OUT_OF_MEMORY; PR_snprintf(buf, bufLen, "<title>%s</title>", subject); UtilityWriteCRLF(buf); delete [] buf; nsMemory::Free(subject); } } // Stylesheet info! UtilityWriteCRLF("<link rel=\"important stylesheet\" href=\"chrome://messagebody/skin/messageBody.css\">"); UtilityWriteCRLF("</head>"); UtilityWriteCRLF("<body>"); } WriteHTMLHeaders(name); return NS_OK; }
bool SSDP::ProcessSearchRequest( const QStringMap &sHeaders, QHostAddress peerAddress, quint16 peerPort ) { QString sMAN = GetHeaderValue( sHeaders, "MAN", "" ); QString sST = GetHeaderValue( sHeaders, "ST" , "" ); QString sMX = GetHeaderValue( sHeaders, "MX" , "" ); int nMX = 0; LOG(VB_UPNP, LOG_DEBUG, QString("SSDP::ProcessSearchrequest : [%1] MX=%2") .arg(sST).arg(sMX)); // ---------------------------------------------------------------------- // Validate Header Values... // ---------------------------------------------------------------------- #if 0 if ( pRequest->m_sMethod != "*" ) return false; if ( pRequest->m_sProtocol != "HTTP" ) return false; if ( pRequest->m_nMajor != 1 ) return false; #endif if ( sMAN != "\"ssdp:discover\"" ) return false; if ( sST.length() == 0 ) return false; if ( sMX.length() == 0 ) return false; if ((nMX = sMX.toInt()) == 0 ) return false; if ( nMX < 0 ) return false; // ---------------------------------------------------------------------- // Adjust timeout to be a random interval between 0 and MX (max of 120) // ---------------------------------------------------------------------- nMX = (nMX > 120) ? 120 : nMX; int nNewMX = (int)(0 + ((unsigned short)random() % nMX)) * 1000; // ---------------------------------------------------------------------- // See what they are looking for... // ---------------------------------------------------------------------- if ((sST == "ssdp:all") || (sST == "upnp:rootdevice")) { UPnpSearchTask *pTask = new UPnpSearchTask( m_nServicePort, peerAddress, peerPort, sST, UPnp::g_UPnpDeviceDesc.m_rootDevice.GetUDN()); #if 0 // Excute task now for fastest response, queue for time-delayed response // -=>TODO: To be trully uPnp compliant, this Execute should be removed. pTask->Execute( NULL ); #endif TaskQueue::Instance()->AddTask( nNewMX, pTask ); pTask->DecrRef(); return true; } // ---------------------------------------------------------------------- // Look for a specific device/service // ---------------------------------------------------------------------- QString sUDN = UPnp::g_UPnpDeviceDesc.FindDeviceUDN( &(UPnp::g_UPnpDeviceDesc.m_rootDevice), sST ); if (sUDN.length() > 0) { UPnpSearchTask *pTask = new UPnpSearchTask( m_nServicePort, peerAddress, peerPort, sST, sUDN ); // Excute task now for fastest response, queue for time-delayed response // -=>TODO: To be trully uPnp compliant, this Execute should be removed. pTask->Execute( NULL ); TaskQueue::Instance()->AddTask( nNewMX, pTask ); pTask->DecrRef(); return true; } return false; }
// Test a message send???? nsresult nsEudoraCompose::SendTheMessage(nsIFile *pMailImportLocation, nsIFile **pMsg) { nsresult rv = CreateComponents(); if (NS_SUCCEEDED( rv)) rv = CreateIdentity(); if (NS_FAILED( rv)) return( rv); // IMPORT_LOG0( "Outlook Compose created necessary components\n"); nsString bodyType; nsString charSet; nsString headerVal; GetHeaderValue( m_pHeaders, m_headerLen, "From:", headerVal); if (!headerVal.IsEmpty()) m_pMsgFields->SetFrom( headerVal); GetHeaderValue( m_pHeaders, m_headerLen, "To:", headerVal); if (!headerVal.IsEmpty()) m_pMsgFields->SetTo( headerVal); GetHeaderValue( m_pHeaders, m_headerLen, "Subject:", headerVal); if (!headerVal.IsEmpty()) m_pMsgFields->SetSubject( headerVal); GetHeaderValue( m_pHeaders, m_headerLen, "Content-type:", headerVal); bodyType = headerVal; ExtractType( bodyType); ExtractCharset( headerVal); // Use platform charset as default if the msg doesn't specify one // (ie, no 'charset' param in the Content-Type: header). As the last // resort we'll use the mail default charset. // (ie, no 'charset' param in the Content-Type: header) or if the // charset parameter fails a length sanity check. // As the last resort we'll use the mail default charset. if ( headerVal.IsEmpty() || (headerVal.Length() > kContentTypeLengthSanityCheck) ) { CopyASCIItoUTF16(nsMsgI18NFileSystemCharset(), headerVal); if (headerVal.IsEmpty()) { // last resort if (m_defCharset.IsEmpty()) { nsString defaultCharset; NS_GetLocalizedUnicharPreferenceWithDefault(nsnull, "mailnews.view_default_charset", NS_LITERAL_STRING("ISO-8859-1"), defaultCharset); m_defCharset = defaultCharset; } headerVal = m_defCharset; } } m_pMsgFields->SetCharacterSet( NS_LossyConvertUTF16toASCII(headerVal).get() ); charSet = headerVal; GetHeaderValue( m_pHeaders, m_headerLen, "CC:", headerVal); if (!headerVal.IsEmpty()) m_pMsgFields->SetCc( headerVal); GetHeaderValue( m_pHeaders, m_headerLen, "Message-ID:", headerVal); if (!headerVal.IsEmpty()) m_pMsgFields->SetMessageId( NS_LossyConvertUTF16toASCII(headerVal).get() ); GetHeaderValue( m_pHeaders, m_headerLen, "Reply-To:", headerVal); if (!headerVal.IsEmpty()) m_pMsgFields->SetReplyTo( headerVal); // what about all of the other headers?!?!?!?!?!?! char *pMimeType; if (!bodyType.IsEmpty()) pMimeType = ToNewCString(bodyType); else pMimeType = ToNewCString(m_bodyType); // IMPORT_LOG0( "Outlook compose calling CreateAndSendMessage\n"); nsMsgAttachedFile *pAttach = GetLocalAttachments(); /* l10n - I have the body of the message in the system charset, I need to "encode" it to be the charset for the message *UNLESS* of course, I don't know what the charset of the message should be? How do I determine what the charset should be if it doesn't exist? */ nsString uniBody; NS_CopyNativeToUnicode( nsDependentCString(m_pBody), uniBody); nsCString body; rv = nsMsgI18NConvertFromUnicode( NS_LossyConvertUTF16toASCII(charSet).get(), uniBody, body); if (NS_FAILED( rv)) { // in this case, if we did not use the default compose // charset, then try that. if (!charSet.Equals( m_defCharset)) { body.Truncate(); rv = nsMsgI18NConvertFromUnicode( NS_LossyConvertUTF16toASCII(charSet).get(), uniBody, body); } } uniBody.Truncate(); // See if it's a draft msg (ie, no From: or no To: AND no Cc: AND no Bcc:). // Eudora saves sent and draft msgs in Out folder (ie, mixed) and it does // store Bcc: header in the msg itself. nsMsgDeliverMode mode = nsIMsgSend::nsMsgDeliverNow; nsAutoString from, to, cc, bcc; rv = m_pMsgFields->GetFrom(from); rv = m_pMsgFields->GetTo(to); rv = m_pMsgFields->GetCc(cc); rv = m_pMsgFields->GetBcc(bcc); if ( from.IsEmpty() || to.IsEmpty() && cc.IsEmpty() && bcc.IsEmpty() ) mode = nsIMsgSend::nsMsgSaveAsDraft; // We only get the editor interface when there's embedded content. // Otherwise pEditor remains NULL. That way we only import with the pseudo // editor when it helps. nsRefPtr<nsEudoraEditor> pEudoraEditor = new nsEudoraEditor(m_pBody, pMailImportLocation); nsCOMPtr<nsIEditor> pEditor; if (pEudoraEditor->HasEmbeddedContent()) // There's embedded content that we need to import, so query for the editor interface pEudoraEditor->QueryInterface( NS_GET_IID(nsIEditor), getter_AddRefs(pEditor) ); if (NS_FAILED( rv)) { rv = m_pSendProxy->CreateAndSendMessage( pEditor.get(), // pseudo editor shell when there's embedded content s_pIdentity, // dummy identity nsnull, // account key m_pMsgFields, // message fields PR_FALSE, // digest = NO PR_TRUE, // dont_deliver = YES, make a file mode, // mode nsnull, // no message to replace pMimeType, // body type m_pBody, // body pointer m_bodyLen, // body length nsnull, // remote attachment data pAttach, // local attachments nsnull, // related part nsnull, // parent window nsnull, // progress listener m_pListener, // listener nsnull, // password EmptyCString(), // originalMsgURI nsnull); // message compose type } else { rv = m_pSendProxy->CreateAndSendMessage( pEditor.get(), // pseudo editor shell when there's embedded content s_pIdentity, // dummy identity nsnull, // account key m_pMsgFields, // message fields PR_FALSE, // digest = NO PR_TRUE, // dont_deliver = YES, make a file mode, // mode nsnull, // no message to replace pMimeType, // body type body.get(), // body pointer body.Length(), // body length nsnull, // remote attachment data pAttach, // local attachments nsnull, // related part nsnull, // parent window nsnull, // progress listener m_pListener, // listener nsnull, // password EmptyCString(), // originalMsgURI nsnull); // message compose type } // IMPORT_LOG0( "Returned from CreateAndSendMessage\n"); if (pAttach) delete [] pAttach; EudoraSendListener *pListen = (EudoraSendListener *)m_pListener; if (NS_FAILED( rv)) { IMPORT_LOG1( "*** Error, CreateAndSendMessage FAILED: 0x%lx\n", rv); // IMPORT_LOG1( "Headers: %80s\n", m_pHeaders); } else { // wait for the listener to get done! PRInt32 abortCnt = 0; PRInt32 cnt = 0; PRInt32 sleepCnt = 1; while (!pListen->m_done && (abortCnt < kHungAbortCount)) { PR_Sleep( sleepCnt); cnt++; if (cnt > kHungCount) { abortCnt++; sleepCnt *= 2; cnt = 0; } } if (abortCnt >= kHungAbortCount) { IMPORT_LOG0( "**** Create and send message hung\n"); IMPORT_LOG1( "Headers: %s\n", m_pHeaders); IMPORT_LOG1( "Body: %s\n", m_pBody); rv = NS_ERROR_FAILURE; } } if (pMimeType) NS_Free( pMimeType); if (pListen->m_location) { pListen->m_location->Clone(pMsg); rv = NS_OK; } else { rv = NS_ERROR_FAILURE; IMPORT_LOG0( "*** Error, Outlook compose unsuccessful\n"); } pListen->Reset(); return( rv); }
nsresult nsEudoraCompose::WriteHeaders(nsIOutputStream *pDst, SimpleBufferTonyRCopiedOnce& newHeaders) { // Well, ain't this a peach? // This is rather disgusting but there really isn't much to be done about it.... // 1. For each "old" header, replace it with the new one if we want, // then right it out. // 2. Then if we haven't written the "important" new headers, write them out // 3. Terminate the headers with an extra eol. PRInt32 n = 0; nsCString header; nsCString val; nsCString replaceVal; PRUint32 written; nsresult rv = NS_OK; // it's ok if we don't have the first header on the predefined lists. PRInt32 specialHeader; PRBool specials[kMaxSpecialHeaders]; PRBool hasDateHeader = PR_FALSE; int i; for (i = 0; i < kMaxSpecialHeaders; i++) specials[i] = PR_FALSE; // m_pHeaders - contains headers from a Eudora msg. // newHeaders - contains headers from a mozilla msg (more headers here). do { GetNthHeader( m_pHeaders, m_headerLen, n, header, val, PR_FALSE); // GetNthHeader( newHeaders.m_pBuffer, newHeaders.m_writeOffset, n, header, val, PR_FALSE); if (!header.IsEmpty()) { if ((specialHeader = IsSpecialHeader( header.get())) != -1) { header.Append( ':'); GetHeaderValue( newHeaders.m_pBuffer, newHeaders.m_writeOffset - 1, header.get(), val, PR_FALSE); header.SetLength( header.Length() - 1); specials[specialHeader] = PR_TRUE; } else if (IsReplaceHeader( header.get())) { replaceVal.Truncate(); header.Append( ':'); GetHeaderValue( newHeaders.m_pBuffer, newHeaders.m_writeOffset - 1, header.get(), replaceVal, PR_FALSE); header.SetLength( header.Length() - 1); if (!replaceVal.IsEmpty()) val = replaceVal; } if (!val.IsEmpty()) { // See if we're writing out a Date: header. if (header.LowerCaseEqualsLiteral("date")) hasDateHeader = PR_TRUE; rv = pDst->Write( header.get(), header.Length(), &written); if (NS_SUCCEEDED( rv)) rv = pDst->Write( ": ", 2, &written); if (NS_SUCCEEDED( rv)) rv = pDst->Write( val.get(), val.Length(), &written); if (NS_SUCCEEDED( rv)) rv = pDst->Write( "\x0D\x0A", 2, &written); } } n++; } while (NS_SUCCEEDED( rv) && !header.IsEmpty()); // If we don't have Date: header so far then use the default one (taken from Eudora "From " line). if (!hasDateHeader) { rv = pDst->Write(m_defaultDate.get(), m_defaultDate.Length(), &written); if (NS_SUCCEEDED( rv)) rv = pDst->Write( "\x0D\x0A", 2, &written); } for (i = 0; (i < kMaxSpecialHeaders) && NS_SUCCEEDED( rv); i++) { if (!specials[i]) { header = gSpecialHeaders[i]; header.Append( ':'); GetHeaderValue( newHeaders.m_pBuffer, newHeaders.m_writeOffset - 1, header.get(), val, PR_FALSE); header.SetLength( header.Length() - 1); if (!val.IsEmpty()) { rv = pDst->Write( header.get(), header.Length(), &written); if (NS_SUCCEEDED( rv)) rv = pDst->Write( ": ", 2, &written); if (NS_SUCCEEDED( rv)) rv = pDst->Write( val.get(), val.Length(), &written); if (NS_SUCCEEDED( rv)) rv = pDst->Write( "\x0D\x0A", 2, &written); } } } if (NS_SUCCEEDED( rv)) rv = pDst->Write( "\x0D\x0A", 2, &written); return( rv); }
// Test a message send???? nsresult nsEudoraCompose::SendTheMessage(nsIFile *pMailImportLocation, nsIFile **pMsg) { nsresult rv = CreateComponents(); if (NS_FAILED(rv)) return rv; // IMPORT_LOG0("Outlook Compose created necessary components\n"); nsString bodyType; nsString charSet; nsString headerVal; GetHeaderValue(m_pHeaders, m_headerLen, "From:", headerVal); if (!headerVal.IsEmpty()) m_pMsgFields->SetFrom(headerVal); GetHeaderValue(m_pHeaders, m_headerLen, "To:", headerVal); if (!headerVal.IsEmpty()) m_pMsgFields->SetTo(headerVal); GetHeaderValue(m_pHeaders, m_headerLen, "Subject:", headerVal); if (!headerVal.IsEmpty()) m_pMsgFields->SetSubject(headerVal); GetHeaderValue(m_pHeaders, m_headerLen, "Content-type:", headerVal); bodyType = headerVal; ExtractType(bodyType); ExtractCharset(headerVal); // Use platform charset as default if the msg doesn't specify one // (ie, no 'charset' param in the Content-Type: header). As the last // resort we'll use the mail default charset. // (ie, no 'charset' param in the Content-Type: header) or if the // charset parameter fails a length sanity check. // As the last resort we'll use the mail default charset. if (headerVal.IsEmpty() || (headerVal.Length() > kContentTypeLengthSanityCheck)) { headerVal.AssignASCII(nsMsgI18NFileSystemCharset()); if (headerVal.IsEmpty()) { // last resort if (m_defCharset.IsEmpty()) { nsString defaultCharset; NS_GetLocalizedUnicharPreferenceWithDefault(nullptr, "mailnews.view_default_charset", NS_LITERAL_STRING("ISO-8859-1"), defaultCharset); m_defCharset = defaultCharset; } headerVal = m_defCharset; } } m_pMsgFields->SetCharacterSet(NS_LossyConvertUTF16toASCII(headerVal).get()); charSet = headerVal; GetHeaderValue(m_pHeaders, m_headerLen, "CC:", headerVal); if (!headerVal.IsEmpty()) m_pMsgFields->SetCc(headerVal); GetHeaderValue(m_pHeaders, m_headerLen, "Message-ID:", headerVal); if (!headerVal.IsEmpty()) m_pMsgFields->SetMessageId(NS_LossyConvertUTF16toASCII(headerVal).get()); GetHeaderValue(m_pHeaders, m_headerLen, "Reply-To:", headerVal); if (!headerVal.IsEmpty()) m_pMsgFields->SetReplyTo(headerVal); // what about all of the other headers?!?!?!?!?!?! char *pMimeType; if (!bodyType.IsEmpty()) pMimeType = ToNewCString(NS_LossyConvertUTF16toASCII(bodyType)); else pMimeType = ToNewCString(m_bodyType); nsCOMPtr<nsIArray> pAttach; GetLocalAttachments(getter_AddRefs(pAttach)); nsEudoraEditor eudoraEditor(m_pBody, pMailImportLocation); nsCOMPtr<nsIArray> embeddedObjects; if (eudoraEditor.HasEmbeddedContent()) eudoraEditor.GetEmbeddedObjects(getter_AddRefs(embeddedObjects)); nsString uniBody; NS_CopyNativeToUnicode(nsDependentCString(m_pBody), uniBody); /* l10n - I have the body of the message in the system charset, I need to "encode" it to be the charset for the message *UNLESS* of course, I don't know what the charset of the message should be? How do I determine what the charset should be if it doesn't exist? */ nsCString body; rv = nsMsgI18NConvertFromUnicode(NS_LossyConvertUTF16toASCII(charSet).get(), uniBody, body); if (NS_FAILED(rv) && !charSet.Equals(m_defCharset)) { // in this case, if we did not use the default compose // charset, then try that. body.Truncate(); rv = nsMsgI18NConvertFromUnicode(NS_LossyConvertUTF16toASCII(charSet).get(), uniBody, body); } uniBody.Truncate(); // See if it's a draft msg (ie, no From: or no To: AND no Cc: AND no Bcc:). // Eudora saves sent and draft msgs in Out folder (ie, mixed) and it does // store Bcc: header in the msg itself. nsAutoString from, to, cc, bcc; rv = m_pMsgFields->GetFrom(from); rv = m_pMsgFields->GetTo(to); rv = m_pMsgFields->GetCc(cc); rv = m_pMsgFields->GetBcc(bcc); bool createAsDraft = from.IsEmpty() || (to.IsEmpty() && cc.IsEmpty() && bcc.IsEmpty()); nsCOMPtr<nsIImportService> impService(do_GetService(NS_IMPORTSERVICE_CONTRACTID, &rv)); NS_ENSURE_SUCCESS(rv, rv); rv = impService->CreateRFC822Message( s_pIdentity, // dummy identity m_pMsgFields, // message fields pMimeType, // body type body, // body pointer createAsDraft, pAttach, // local attachments embeddedObjects, m_pListener); // listener EudoraSendListener *pListen = (EudoraSendListener *)m_pListener; if (NS_FAILED(rv)) { IMPORT_LOG1("*** Error, CreateAndSendMessage FAILED: 0x%lx\n", rv); // IMPORT_LOG1("Headers: %80s\n", m_pHeaders); } else { // wait for the listener to get done! int32_t abortCnt = 0; int32_t cnt = 0; int32_t sleepCnt = 1; while (!pListen->m_done && (abortCnt < kHungAbortCount)) { PR_Sleep(sleepCnt); cnt++; if (cnt > kHungCount) { abortCnt++; sleepCnt *= 2; cnt = 0; } } if (abortCnt >= kHungAbortCount) { IMPORT_LOG0("**** Create and send message hung\n"); IMPORT_LOG1("Headers: %s\n", m_pHeaders); IMPORT_LOG1("Body: %s\n", m_pBody); rv = NS_ERROR_FAILURE; } } if (pMimeType) NS_Free(pMimeType); if (pListen->m_location) { pListen->m_location->Clone(pMsg); rv = NS_OK; } else { rv = NS_ERROR_FAILURE; IMPORT_LOG0("*** Error, Outlook compose unsuccessful\n"); } pListen->Reset(); return rv; }
void CHttpClient::HandleEntity() { int bytes_total = 0; int bytes_read = 0; char *buffer = (char *)malloc(RECV_BUFFER_SIZE); char *response = (char *)malloc(1); char *header; char *head_end; char *pcontent_buf; char *content_len_str; bool header_got = false; bool has_content_len = false; int header_len = 0; int content_len = 0; while((bytes_read=Recv(buffer,RECV_BUFFER_SIZE)) > 0) { bytes_total+=bytes_read; response=(char *)realloc(response,bytes_total+1); memcpy(response+(bytes_total-bytes_read),buffer,(unsigned int)bytes_read); if(!header_got) { if((head_end=strstr(response,"\r\n\r\n"))!=NULL || (head_end=strstr(response,"\n\n"))!=NULL) { header_got=true; header_len=(head_end-response); header=(char *)malloc(header_len+1); memcpy(header,response,header_len); header[header_len]='\0'; if((*(response+header_len))=='\n') /* LFLF */ { bytes_total-=(header_len+2); memmove(response,(response+(header_len+2)),bytes_total); } else /* assume CRLFCRLF */ { bytes_total-=(header_len+4); memmove(response,(response+(header_len+4)),bytes_total); } /* find the content-length if available */ if((pcontent_buf=Util_stristr(header,"CONTENT-LENGTH:"))!=NULL) { has_content_len=true; pcontent_buf+=16; while(*pcontent_buf!='\n' && *pcontent_buf) { *pcontent_buf++; content_len++; } content_len_str=(char *)malloc(content_len+1); pcontent_buf-=content_len; memcpy(content_len_str,pcontent_buf,content_len); if(content_len_str[content_len-1] == '\r') { content_len_str[content_len-1]='\0'; } else { content_len_str[content_len]='\0'; } content_len=atoi(content_len_str); free(content_len_str); if(content_len > MAX_ENTITY_LENGTH) { CloseConnection(); m_iError = HTTP_ERROR_CONTENT_TOO_BIG; return; } } } } if(header_got && has_content_len) if(bytes_total>=content_len) break; } CloseConnection(); response[bytes_total]='\0'; free(buffer); // check the returned header if(!header_got || *(DWORD *)header != 0x50545448) { // 'HTTP' m_iError = HTTP_ERROR_MALFORMED_RESPONSE; return; } // Now fill in the response code char response_code_str[4]; response_code_str[0] = *(header+9); response_code_str[1] = *(header+10); response_code_str[2] = *(header+11); response_code_str[3] = '\0'; m_Response.response_code = atoi(response_code_str); // Copy over the document entity strings and sizes m_Response.header = header; m_Response.header_len = header_len; m_Response.response = response; m_Response.response_len = bytes_total; //printf("Code: %u\n\n%s\n",m_Response.response_code,m_Response.header); // Try and determine the document type m_Response.content_type = CONTENT_TYPE_HTML; // default to html char szContentType[256]; if(GetHeaderValue("CONTENT-TYPE:",szContentType,256) == true) { if(strstr(szContentType,"text/html") != NULL) { m_Response.content_type = CONTENT_TYPE_HTML; } else if(strstr(szContentType,"text/plain") != NULL) { m_Response.content_type = CONTENT_TYPE_TEXT; } else { m_Response.content_type = CONTENT_TYPE_UNKNOWN; } } }
/* ParseHeader() Analizza l'header ICY, caricando la lista interna con i valori dei campi. */ int CIcy::ParseHeader(LPCSTR pIcyHeaderData) { /* header icy: ICY 200 OK icy-notice1:<BR>This stream requires <a href="http://www.winamp.com/">Winamp</a><BR> icy-notice2:SHOUTcast Distributed Network Audio Server/SolarisSparc v1.9.2<BR> icy-name:Secret Agent: The soundtrack for your stylish, mysterious, dangerous life. For Spys and P.I.'s too! [SomaFM] icy-genre:Downtempo Lounge Spy icy-url:http://www.somafm.com Content-Type:audio/mpeg icy-pub:1 icy-metaint:24576 icy-br:128 errori: ICY 400 Server Full icy-notice1:<BR>SHOUTcast Distributed Network Audio Server/win32 v1.9.2<BR> icy-notice2:This server has reached its user limit<BR> ICY 403 Service Forbidden icy-notice1:<BR>SHOUTcast Distributed Network Audio Server/Linux v1.8.9<BR> icy-notice2:The resource requested is forbidden<BR> streamripper/live365: http://streamripper.sourceforge.net/dc.php http://www.dslreports.com/shownews/3472 */ if(strnicmp(pIcyHeaderData,"ICY",3)!=0 && strnicmp(pIcyHeaderData,"HTTP",4)!=0) return(HTTP_STATUS_BAD_REQUEST); int nCode = 0; char szCode[8]; int i = 0; char* p = (char*)pIcyHeaderData; // salta per arrivare al codice d'errore dato che con http la risposta inizia con (ad es.): HTTP/1.1 301 [...] if(strnicmp(pIcyHeaderData,"HTTP",4)==0) p+=8; while(*p && !isdigit(*p)) p++; for(i=0; *p && isdigit(*p) && i < sizeof(szCode);) szCode[i++] = *p++; nCode = atoi(szCode); switch(nCode) { case HTTP_CODE_MOVED_PERMANENTLY: case HTTP_CODE_MOVED_TEMPORARILY: GetHeaderValue(pIcyHeaderData,"Location",m_szLocation,sizeof(m_szLocation)); return(nCode); default: break; } char* pIcyHeaders[] = { "Content-Type:", // Content-Type: application/octet-stream, Content-Type: audio/mpeg, etc. "ice-audio-info", // ice-audio-info: bitrate=128;samplerate=44100;channels=2 "icy-br", "icy-description", "icy-genre", "icy-metaint", "icy-name", "icy-notice1", "icy-notice2", "icy-pub", "icy-url", "Server:", // Server: Icecast 2.3.2 oppure icy-notice2: SHOUTcast Distributed Network Audio Server/win32 v1.9.5<BR> "Location:", NULL, }; m_listICYHeaders.DeleteAll(); for(i=0; pIcyHeaders[i]!=NULL; i++) { HTTPHEADER* h = (HTTPHEADER*)m_listICYHeaders.Add(); if(h) { strcpyn(h->name,pIcyHeaders[i],HTTPHEADER_NAME_LEN+1); if(GetHeaderValue(pIcyHeaderData,h->name,h->value,HTTPHEADER_VALUE_LEN)!=0) { strcpy(h->value,""); } else { char buffer[HTTPHEADER_VALUE_LEN+1]; while(substr(h->value,"<BR>","",buffer,sizeof(buffer))!=0) strcpyn(h->value,buffer,HTTPHEADER_VALUE_LEN); while(substr(h->value,"<br>","",buffer,sizeof(buffer))!=0) strcpyn(h->value,buffer,HTTPHEADER_VALUE_LEN); } TRACEEXPR((_TRACE_FLAG_INFO,__NOFILE__,__NOLINE__,"CIcy::ParseHeader(): [%s]->[%s]\n",h->name,h->value)); } } if(strnull(GetHeaderValue("Server:")) && stristr(GetHeaderValue("icy-notice2"),"shoutcast") && stristr(GetHeaderValue("icy-notice2"),"server")) { ITERATOR iter; HTTPHEADER* h; if((iter = m_listICYHeaders.First())!=(ITERATOR)NULL) { do { if((h = (HTTPHEADER*)iter->data)!=(HTTPHEADER*)NULL) { if(stricmp(h->name,"Server:")==0) { strcpyn(h->value,GetHeaderValue("icy-notice2"),HTTPHEADER_VALUE_LEN); break; } } iter = m_listICYHeaders.Next(iter); } while(iter!=(ITERATOR)NULL); } } TRACEEXPR((_TRACE_FLAG_INFO,__NOFILE__,__NOLINE__,"\nCIcy::GetHeaderValue(): Content-Type [%s]\n",GetHeaderValue("Content-Type:"))); TRACEEXPR((_TRACE_FLAG_INFO,__NOFILE__,__NOLINE__,"CIcy::GetHeaderValue(): ice-audio-info [%s]\n",GetHeaderValue("ice-audio-info"))); TRACEEXPR((_TRACE_FLAG_INFO,__NOFILE__,__NOLINE__,"CIcy::GetHeaderValue(): icy-br [%s]\n",GetHeaderValue("icy-br"))); TRACEEXPR((_TRACE_FLAG_INFO,__NOFILE__,__NOLINE__,"CIcy::GetHeaderValue(): icy-description [%s]\n",GetHeaderValue("icy-description"))); TRACEEXPR((_TRACE_FLAG_INFO,__NOFILE__,__NOLINE__,"CIcy::GetHeaderValue(): icy-genre [%s]\n",GetHeaderValue("icy-genre"))); TRACEEXPR((_TRACE_FLAG_INFO,__NOFILE__,__NOLINE__,"CIcy::GetHeaderValue(): icy-metaint [%s]\n",GetHeaderValue("icy-metaint"))); TRACEEXPR((_TRACE_FLAG_INFO,__NOFILE__,__NOLINE__,"CIcy::GetHeaderValue(): icy-name [%s]\n",GetHeaderValue("icy-name"))); TRACEEXPR((_TRACE_FLAG_INFO,__NOFILE__,__NOLINE__,"CIcy::GetHeaderValue(): icy-notice1 [%s]\n",GetHeaderValue("icy-notice1"))); TRACEEXPR((_TRACE_FLAG_INFO,__NOFILE__,__NOLINE__,"CIcy::GetHeaderValue(): icy-notice2 [%s]\n",GetHeaderValue("icy-notice2"))); TRACEEXPR((_TRACE_FLAG_INFO,__NOFILE__,__NOLINE__,"CIcy::GetHeaderValue(): icy-pub [%s]\n",GetHeaderValue("icy-pub"))); TRACEEXPR((_TRACE_FLAG_INFO,__NOFILE__,__NOLINE__,"CIcy::GetHeaderValue(): icy-url [%s]\n",GetHeaderValue("icy-url"))); TRACEEXPR((_TRACE_FLAG_INFO,__NOFILE__,__NOLINE__,"CIcy::GetHeaderValue(): Server [%s]\n",GetHeaderValue("Server:"))); TRACEEXPR((_TRACE_FLAG_INFO,__NOFILE__,__NOLINE__,"CIcy::GetHeaderValue(): Location [%s]\n\n",GetHeaderValue("Location:"))); return(nCode); }