Example #1
0
void CGI::RemoveCookie(const std::string &key,
                       const std::string &path,
                       const std::string &domain)
{
    // From PHP: 1 year and 1 second ago.
    SetCookie(key, "deleted", -31536001, std::string(), path, domain);
}
Example #2
0
CBuddyItem::CBuddyItem(CStdString& strLabel) : CKaiItem(strLabel)
{
  SetCookie( CKaiClient::Player );

  m_strVector = "/";
  m_strGeoLocation = "";

  m_bIsContact = FALSE;
  m_bIsOnline = FALSE;
  m_bBusy = FALSE;
  m_bKeyboard = FALSE;
  m_bHeadset = FALSE; // does this buddy have a headset connected?
  m_bSpeex = FALSE; // have you enabled speex for this buddy?
  m_bIsTalking = FALSE; // is this buddy chatting?
  m_bProfileRequested = FALSE;

  m_dwPing = 0;

  m_dwSpeexCounter = 0;
  m_dwRingCounter = 0;
  m_bRingIndicator = TRUE;
  m_bInvite = FALSE;

  m_nStatus = 0;
}
Example #3
0
TStr TDatabaseSession::GetValue(
	const TStr &Cookie,
	const TStr &Name)
{
	SetCookie(Cookie);
	return SessionList.Values(Name);
}
Example #4
0
void 
HttpChannelChild::OnStartRequest(const nsHttpResponseHead& responseHead,
                                 const PRBool& useResponseHead,
                                 const PRBool& isFromCache,
                                 const PRBool& cacheEntryAvailable,
                                 const PRUint32& cacheExpirationTime,
                                 const nsCString& cachedCharset,
                                 const nsCString& securityInfoSerialization)
{
  LOG(("HttpChannelChild::RecvOnStartRequest [this=%x]\n", this));

  if (useResponseHead && !mCanceled)
    mResponseHead = new nsHttpResponseHead(responseHead);

  if (!securityInfoSerialization.IsEmpty()) {
    NS_DeserializeObject(securityInfoSerialization, 
                         getter_AddRefs(mSecurityInfo));
  }
 
  mIsFromCache = isFromCache;
  mCacheEntryAvailable = cacheEntryAvailable;
  mCacheExpirationTime = cacheExpirationTime;
  mCachedCharset = cachedCharset;

  AutoEventEnqueuer ensureSerialDispatch(this);

  nsresult rv = mListener->OnStartRequest(this, mListenerContext);
  if (NS_SUCCEEDED(rv)) {
    if (mResponseHead)
      SetCookie(mResponseHead->PeekHeader(nsHttp::Set_Cookie));
  } else {
    Cancel(rv);
  }
}
Example #5
0
 void RestApiOutput::ResetCookie(const std::string& name)
 {
   // This marks the cookie to be deleted by the browser in 1 second,
   // and before it actually gets deleted, its value is set to the
   // empty string
   SetCookie(name, "", 1);
 }
Example #6
0
BOOL CCookieMgr::SetCookie(const CStringA& strCookie, BOOL bOnlyUpdateValueIfExists)
{
	unique_ptr<CCookie> pCookie(CCookie::FromString(strCookie));
	if(!pCookie) return FALSE;

	return SetCookie(*pCookie, bOnlyUpdateValueIfExists);
}
Example #7
0
void
HttpChannelChild::Redirect1Begin(const PRUint32& newChannelId,
                                 const IPC::URI& newURI,
                                 const PRUint32& redirectFlags,
                                 const nsHttpResponseHead& responseHead)
{
  nsresult rv;

  nsCOMPtr<nsIIOService> ioService;
  rv = gHttpHandler->GetIOService(getter_AddRefs(ioService));
  if (NS_FAILED(rv)) {
    // Veto redirect.  nsHttpChannel decides to cancel or continue.
    OnRedirectVerifyCallback(rv);
    return;
  }

  nsCOMPtr<nsIURI> uri(newURI);

  nsCOMPtr<nsIChannel> newChannel;
  rv = ioService->NewChannelFromURI(uri, getter_AddRefs(newChannel));
  if (NS_FAILED(rv)) {
    // Veto redirect.  nsHttpChannel decides to cancel or continue.
    OnRedirectVerifyCallback(rv);
    return;
  }

  // We won't get OnStartRequest, set cookies here.
  mResponseHead = new nsHttpResponseHead(responseHead);
  SetCookie(mResponseHead->PeekHeader(nsHttp::Set_Cookie));

  bool rewriteToGET = ShouldRewriteRedirectToGET(mResponseHead->Status(), 
                                                 mRequestHead.Method());
  
  rv = SetupReplacementChannel(uri, newChannel, !rewriteToGET, false);
  if (NS_FAILED(rv)) {
    // Veto redirect.  nsHttpChannel decides to cancel or continue.
    OnRedirectVerifyCallback(rv);
    return;
  }

  mRedirectChannelChild = do_QueryInterface(newChannel);
  if (mRedirectChannelChild) {
    mRedirectChannelChild->ConnectParent(newChannelId);
  } else {
    NS_ERROR("Redirecting to a protocol that doesn't support universal protocol redirect");
  }

  rv = gHttpHandler->AsyncOnChannelRedirect(this, 
                                            newChannel,
                                            redirectFlags);
  if (NS_FAILED(rv))
    OnRedirectVerifyCallback(rv);
}
Example #8
0
void
HttpChannelChild::OnStartRequest(const nsHttpResponseHead& responseHead,
                                 const PRBool& useResponseHead,
                                 const RequestHeaderTuples& requestHeaders,
                                 const PRBool& isFromCache,
                                 const PRBool& cacheEntryAvailable,
                                 const PRUint32& cacheExpirationTime,
                                 const nsCString& cachedCharset,
                                 const nsCString& securityInfoSerialization,
                                 const PRNetAddr& selfAddr,
                                 const PRNetAddr& peerAddr)
{
    LOG(("HttpChannelChild::RecvOnStartRequest [this=%x]\n", this));

    if (useResponseHead && !mCanceled)
        mResponseHead = new nsHttpResponseHead(responseHead);

    if (!securityInfoSerialization.IsEmpty()) {
        NS_DeserializeObject(securityInfoSerialization,
                             getter_AddRefs(mSecurityInfo));
    }

    mIsFromCache = isFromCache;
    mCacheEntryAvailable = cacheEntryAvailable;
    mCacheExpirationTime = cacheExpirationTime;
    mCachedCharset = cachedCharset;

    AutoEventEnqueuer ensureSerialDispatch(this);

    // replace our request headers with what actually got sent in the parent
    mRequestHead.ClearHeaders();
    for (PRUint32 i = 0; i < requestHeaders.Length(); i++) {
        mRequestHead.Headers().SetHeader(nsHttp::ResolveAtom(requestHeaders[i].mHeader),
                                         requestHeaders[i].mValue);
    }

    nsresult rv = mListener->OnStartRequest(this, mListenerContext);
    if (NS_FAILED(rv)) {
        Cancel(rv);
        return;
    }

    if (mResponseHead)
        SetCookie(mResponseHead->PeekHeader(nsHttp::Set_Cookie));

    rv = ApplyContentConversions();
    if (NS_FAILED(rv))
        Cancel(rv);

    mSelfAddr = selfAddr;
    mPeerAddr = peerAddr;
}
Example #9
0
void 
HttpChannelChild::OnStartRequest(const nsHttpResponseHead& responseHead,
                                 const bool& useResponseHead,
                                 const nsHttpHeaderArray& requestHeaders,
                                 const bool& isFromCache,
                                 const bool& cacheEntryAvailable,
                                 const PRUint32& cacheExpirationTime,
                                 const nsCString& cachedCharset,
                                 const nsCString& securityInfoSerialization,
                                 const PRNetAddr& selfAddr,
                                 const PRNetAddr& peerAddr)
{
  LOG(("HttpChannelChild::RecvOnStartRequest [this=%x]\n", this));

  if (useResponseHead && !mCanceled)
    mResponseHead = new nsHttpResponseHead(responseHead);

  if (!securityInfoSerialization.IsEmpty()) {
    NS_DeserializeObject(securityInfoSerialization, 
                         getter_AddRefs(mSecurityInfo));
  }

  mIsFromCache = isFromCache;
  mCacheEntryAvailable = cacheEntryAvailable;
  mCacheExpirationTime = cacheExpirationTime;
  mCachedCharset = cachedCharset;

  AutoEventEnqueuer ensureSerialDispatch(mEventQ);

  // replace our request headers with what actually got sent in the parent
  mRequestHead.Headers() = requestHeaders;

  // notify "http-on-examine-response" observers
  gHttpHandler->OnExamineResponse(this);
  mTracingEnabled = false;

  nsresult rv = mListener->OnStartRequest(this, mListenerContext);
  if (NS_FAILED(rv)) {
    Cancel(rv);
    return;
  }

  if (mResponseHead)
    SetCookie(mResponseHead->PeekHeader(nsHttp::Set_Cookie));

  rv = ApplyContentConversions();
  if (NS_FAILED(rv))
    Cancel(rv);

  mSelfAddr = selfAddr;
  mPeerAddr = peerAddr;
}
Example #10
0
void CASpeexDecoder::SetMagicCookie(const void* inMagicCookieData, UInt32 inMagicCookieDataByteSize)
{
    dbg_printf(" >> [%08lx] CASpeexDecoder :: SetMagicCookie()\n", (UInt32) this);
    if (mIsInitialized)
        CODEC_THROW(kAudioCodecStateError);

    SetCookie(inMagicCookieData, inMagicCookieDataByteSize);

    InitializeCompressionSettings();

    if (!mCompressionInitialized)
        CODEC_THROW(kAudioCodecUnsupportedFormatError);
    dbg_printf("<.. [%08lx] CASpeexDecoder :: SetMagicCookie()\n", (UInt32) this);
}
Example #11
0
void TDatabaseSession::SetValue(
	const TStr &Cookie,
	const TStr &Name,
	const TStr &Value)
{
	SetCookie(Cookie);
	if( Cookie.Length() > 0 ) {
		m_ssi::TMapItem<TStr> *p = SessionList.Find(Name);
		if( p == NULL ) {
			query->execSql("INSERT INTO tbs_session (FName,FCookie,FValue,FDate) VALUES ('"+Name+"','"+Cookie+"','"+Value+"',now())");
			SessionList.Add(Name,Value);
		} else {
			query->execSql("UPDATE tbs_session SET FValue='"+Value+"', FDate=now() WHERE FName='"+Name+"' and FCookie='"+Cookie+"'");
			p->SetValue(Value);
		}
	}
}
Example #12
0
NS_IMETHODIMP nsBrowserListener::WebNav(nsIWebNavigation *nav,const nsACString &url)
{
     nsresult rv;
     aurl=url;
     LOG<<"acess:"<<aurl.get()<<"\n";
     if(aurl.Length()>0)
     {

	  GetHost(aurl,mTarDomain);
	  LOG<<"domain:"<<mTarDomain.get()<<"\n";
	  if(cookie.Length()>0)
	       SetCookie(cookie);

	  rv = nav->LoadURI(NS_ConvertUTF8toUTF16(aurl).get(),nsIWebNavigation::LOAD_FLAGS_STOP_CONTENT, nsnull, nsnull, nsnull);
	  if (NS_FAILED(rv)) {
	       return rv;
	  }
     }
     return NS_OK;
}
Example #13
0
bool CWebViewData::OutputCookie()
{
	std::map<std::string, COOKIE_T>::iterator it = m_oCookieMap.begin();
	for(; it != m_oCookieMap.end(); ++it)
	{
		COOKIE_T& rCookie = (*it).second;
		if(rCookie.bSet)
		{
			SetCookie(
				(*it).first.c_str(), 
				rCookie.sVal.c_str(), 
				(rCookie.sTime.empty() ? NULL : rCookie.sTime.c_str()),
				"/", 
				rCookie.sDomain.c_str(), 
				0,
				rCookie.sEncodeType.c_str()); 	
		} // 未被Set的Cookie项表示无需让ie更新了
	}
	return m_bEncodeWithChn;
}
Example #14
0
void
HttpChannelChild::Redirect1Begin(PHttpChannelChild* newChannel,
                                 const IPC::URI& newURI,
                                 const PRUint32& redirectFlags,
                                 const nsHttpResponseHead& responseHead)
{
  HttpChannelChild* 
    newHttpChannelChild = static_cast<HttpChannelChild*>(newChannel);
  nsCOMPtr<nsIURI> uri(newURI);

  nsresult rv = 
    newHttpChannelChild->HttpBaseChannel::Init(uri, mCaps,
                                               mConnectionInfo->ProxyInfo());
  if (NS_FAILED(rv)) {
    // Cancel the channel and veto the redirect.
    Cancel(rv);
    SendRedirect2Result(rv, mRedirectChannelChild->mRequestHeaders);
    return;
  }

  // We won't get OnStartRequest, set cookies here.
  mResponseHead = new nsHttpResponseHead(responseHead);
  SetCookie(mResponseHead->PeekHeader(nsHttp::Set_Cookie));

  PRBool preserveMethod = (mResponseHead->Status() == 307);
  rv = SetupReplacementChannel(uri, newHttpChannelChild, preserveMethod);
  if (NS_FAILED(rv)) {
    // Cancel the channel and veto the redirect.
    Cancel(rv);
    SendRedirect2Result(rv, mRedirectChannelChild->mRequestHeaders);
    return;
  }

  mRedirectChannelChild = newHttpChannelChild;

  rv = gHttpHandler->AsyncOnChannelRedirect(this, 
                                            newHttpChannelChild, 
                                            redirectFlags);
  if (NS_FAILED(rv))
    OnRedirectVerifyCallback(rv);
}
Example #15
0
BOOL CCookieMgr::SetCookie(LPCSTR lpszName, LPCSTR lpszValue, LPCSTR lpszDomain, LPCSTR lpszPath, int iMaxAge, BOOL bHttpOnly, BOOL bSecure, CCookie::EnSameSite enSameSite, BOOL bOnlyUpdateValueIfExists)
{
	CCookie cookie(lpszName, lpszValue, lpszDomain, lpszPath, iMaxAge, bHttpOnly, bSecure, enSameSite);

	return SetCookie(cookie, bOnlyUpdateValueIfExists);
}
Example #16
0
int GetHTTPData(const char * url, unsigned short **body, string referer, bool b_post, string post_data) 
{
	CInternetSession session("Azereus 2.2.0.2");
	//DWORD dwValue;
	//session.QueryOption(INTERNET_OPTION_CONNECT_TIMEOUT, dwValue);
	//TRACE("timeout: %d\n", dwValue );
	session.SetOption(INTERNET_OPTION_CONNECT_TIMEOUT, 10*1000);
	CHttpConnection * pServer = NULL;
	CHttpFile* pFile = NULL;
	bool bProgressMode = false; 
	bool bStripMode = false; 
	bool isGzipped = false;
	string line = "";
	int size = 0;
	unsigned short * buf = *body;
	try {
		CString strServerName; 
		CString strObject; 
		INTERNET_PORT nPort; 
		DWORD dwServiceType; 

		if (!AfxParseURL(url, dwServiceType, strServerName, strObject, nPort) || 
		dwServiceType != INTERNET_SERVICE_HTTP) 
		{ 
			//TRACE("Error: can only use URLs beginning with http://\n");
			//TRACE("URL: '%s'\n", url);
			line =  "request failed - can only use URLs beginning with http://";
		} 

		if (bProgressMode) 
		{ 
			TRACE( _T("Opening Internet...")); 
			VERIFY(session.EnableStatusCallback(TRUE)); 
		} 
		
		pServer = session.GetHttpConnection(strServerName, INTERNET_FLAG_DONT_CACHE, nPort); 
		
		string file = url;
		int file_start = -1;
		if(file.length() > 8) {
			file_start = (int)file.find("//");
			file_start = (int)file.find("/", file_start+2);
		}
		if(file_start > 0) file = file.substr(file_start);
		else file = "";
		
		if(!b_post) {
			pFile = pServer->OpenRequest(CHttpConnection::HTTP_VERB_GET,file.c_str(), referer.c_str()); 
			string header = "Accept: text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5\r\n";
			header += "Accept-Language: en-us,en;q=0.5\n\r";
			header += "Accept-Encoding: gzip\r\n";
			header += "Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7\n\r";
			pFile->SendRequest(header.c_str(),(DWORD)header.length()); 
		}
		else {
			pFile = pServer->OpenRequest(CHttpConnection::HTTP_VERB_POST, file.c_str(), referer.c_str());
			string header = "Content-Type: application/x-www-form-urlencoded\n\r";
			pFile->SendRequest(header.c_str(),(DWORD)header.length(),(LPVOID)post_data.c_str(), (DWORD)post_data.length() );
		}


		DWORD dwRet; 
		pFile->QueryInfoStatusCode(dwRet); 

		// if access was denied, prompt the user for the password 

		if (dwRet == HTTP_STATUS_DENIED) 
		{ 
			DWORD dwPrompt; 
			dwPrompt = pFile->ErrorDlg(NULL, ERROR_INTERNET_INCORRECT_PASSWORD, 
			FLAGS_ERROR_UI_FLAGS_GENERATE_DATA | FLAGS_ERROR_UI_FLAGS_CHANGE_OPTIONS, NULL); 

			// if the user cancelled the diaTRACE, bail out 

			if (dwPrompt != ERROR_INTERNET_FORCE_RETRY) 
			{ 
				TRACE(_T("Access denied: Invalid password\n")); 
				line =   "request failed - Access denied: Invalid password";
			} 

			pFile->SendRequest(); 
			pFile->QueryInfoStatusCode(dwRet); 
		} 

		CString strNewLocation; 
		pFile->QueryInfo(HTTP_QUERY_RAW_HEADERS_CRLF, strNewLocation); 

		// were we redirected? 
		// these response status codes come from WININET.H 

		if (dwRet == HTTP_STATUS_MOVED || 
		dwRet == HTTP_STATUS_REDIRECT || 
		dwRet == HTTP_STATUS_REDIRECT_METHOD) 
		{ 
			CString strNewLocation; 
			pFile->QueryInfo(HTTP_QUERY_RAW_HEADERS_CRLF, strNewLocation); 

			int nPlace = strNewLocation.Find(_T("Location: ")); 
			if (nPlace == -1) 
			{ 
				TRACE( _T("Error: Site redirects with no new location")); 
				line =  "request failed - Site redirects with no new location";
			} 

			strNewLocation = strNewLocation.Mid(nPlace + 10); 
			nPlace = strNewLocation.Find('\n'); 
			if (nPlace > 0) 
				strNewLocation = strNewLocation.Left(nPlace); 

			// close up the redirected site 

			pFile->Close(); 
			delete pFile; 
			pServer->Close(); 
			delete pServer; 

			if (bProgressMode) 
			{ 
				TRACE( _T("Caution: redirected to ")); 
				TRACE((LPCTSTR) strNewLocation); 
			} 

			// figure out what the old place was 
			if (!AfxParseURL(strNewLocation, dwServiceType, strServerName, strObject, nPort)) 
			{ 
				TRACE(_T("Error: the redirected URL could not be parsed.")); 
				line =  "request failed - the redirected URL could not be parsed.";
			} 

			if (dwServiceType != INTERNET_SERVICE_HTTP) 
			{ 
				TRACE(_T("Error: the redirected URL does not reference a HTTP resource."));
				line =  "request failed - the redirected URL does not reference a HTTP resource";
			} 

			// try again at the new location 
			pServer = session.GetHttpConnection(strServerName, nPort); 
			if(!b_post) {
				pFile = pServer->OpenRequest(CHttpConnection::HTTP_VERB_GET, strObject);
			}
			else {
				pFile = pServer->OpenRequest(CHttpConnection::HTTP_VERB_POST, file.c_str());
			}
			//pFile->AddRequestHeaders(szHeaders); 
			pFile->SendRequest(); 

			pFile->QueryInfoStatusCode(dwRet); 
			if (dwRet != HTTP_STATUS_OK) 
			{ 
				TRACE(_T("Error: Got status code %d\n"), dwRet);
				line =  "request failed - Got status code " + dwRet;
			} 
		}
		CString content_type = "";
		pFile->QueryInfo(HTTP_QUERY_RAW_HEADERS_CRLF , content_type);
		if(content_type.Find(": gzip") > 0) isGzipped = true;

		const int read_size = 1024;
		TCHAR sz[read_size+1]; 
		UINT nRead = pFile->Read(sz, read_size); 
		int curPos = 0;
 		size = nRead;
		int cur_size = 10240;
		buf = new unsigned short[cur_size];
		while (nRead > 0) 
		{ 
			if(size > cur_size) {
				int new_size = cur_size * 2;
				unsigned short *temp = new unsigned short[new_size];
				for(int i = 0; i < cur_size; i++) {
					temp[i] = buf[i];
				}
				delete [] buf;
				buf = temp;
				cur_size = new_size;
			}
			for(UINT i = 0; i < nRead; i++) {
				buf[i+curPos] = sz[i];
			}
			curPos += nRead;
			nRead = pFile->Read(sz, read_size); 
			size += nRead;
		}
		unsigned short * temp = new unsigned short[size+1];
		for(int i = 0; i < size; i++) {
			temp[i] = buf[i];
		}
		delete [] buf;
		buf = temp;
		SetCookie(&session, strServerName);
		SetCookie(&session, url);

	}
	catch (exception e) {
		TRACE(e.what());
		line = "request failed - status code N/A";
	}
	catch (CInternetException * e) {
		TCHAR error[256];
		if(e->GetErrorMessage(error, 256)) {
			//TRACE("URL: '%s'\n", url);
			TRACE("%s\n", error);
		}
		e->Delete();
		e = NULL;
		line = "request failed - status code N/A";
	}
	if(pFile != NULL) {
		pFile->Flush();
		pFile->Close();
		delete pFile;
		pFile = NULL;
	}
	if(pServer != NULL) {
		pServer->Close();
		delete pServer;
		pServer = NULL;
	}
	if(isGzipped) {
		unsigned short *data = NULL;
		size = UnZip(&data, buf, size);
		if(size == 0) {
			delete [] data;
			data = NULL;
		}
		delete [] buf;
		*body = data;
	}			
	else *body = buf;
	return size;

}
Example #17
0
string GetData(const char * url, const string referer) 
{

	CInternetSession session("Mozilla/4.0");
	session.SetOption(INTERNET_OPTION_CONNECT_TIMEOUT, 10*1000);
	CHttpConnection * pServer = NULL;
	CHttpFile* pFile = NULL;
	bool bProgressMode = false; 
	bool bStripMode = false; 
	string line = "";

	try {
		CString strServerName; 
		CString strObject; 
		INTERNET_PORT nPort; 
		DWORD dwServiceType; 

		if (!AfxParseURL(url, dwServiceType, strServerName, strObject, nPort) || 
		dwServiceType != INTERNET_SERVICE_HTTP) 
		{ 
			TRACE( _T("Error: can only use URLs beginning with http://") );
			return "request failed - can only use URLs beginning with http://";
		} 

		if (bProgressMode) 
		{ 
			TRACE("Opening Internet...%s\n", url);
			VERIFY(session.EnableStatusCallback(TRUE)); 
		} 
		
		pServer = session.GetHttpConnection(strServerName, nPort); 
		string file = url;


		int file_start = -1;
		if(file.length() > 8) {
			file_start = (int)file.find("//");
			file_start = (int)file.find("/", file_start+2);
			if(file_start > (int)file.length()) file_start = -1;
		}
		if(file_start > 0) file = file.substr(file_start);
		else file = "";
		LPCTSTR ref = NULL;
		if(referer != "") ref = referer.c_str();
 		pFile = pServer->OpenRequest(CHttpConnection::HTTP_VERB_GET,file.c_str(), ref); 

		SetCookie(&session, url); 

		pFile->SendRequest(); 

		DWORD dwRet; 
		pFile->QueryInfoStatusCode(dwRet); 

		// if access was denied, prompt the user for the password 

		if (dwRet == HTTP_STATUS_DENIED) 
		{ 
			DWORD dwPrompt; 
			dwPrompt = pFile->ErrorDlg(NULL, ERROR_INTERNET_INCORRECT_PASSWORD, 
			FLAGS_ERROR_UI_FLAGS_GENERATE_DATA | FLAGS_ERROR_UI_FLAGS_CHANGE_OPTIONS, NULL); 

			// if the user cancelled the diaTRACE, bail out 

			if (dwPrompt != ERROR_INTERNET_FORCE_RETRY) 
			{ 
				TRACE( _T("Access denied: Invalid password"));
				return "request failed - Access denied: Invalid password";
			} 

			pFile->SendRequest(); 
			pFile->QueryInfoStatusCode(dwRet); 
		} 

		CString strNewLocation; 
		pFile->QueryInfo(HTTP_QUERY_RAW_HEADERS_CRLF, strNewLocation); 

		// were we redirected? 
		// these response status codes come from WININET.H 

		if (dwRet == HTTP_STATUS_MOVED || 
		dwRet == HTTP_STATUS_REDIRECT || 
		dwRet == HTTP_STATUS_REDIRECT_METHOD) 
		{ 
			CString strNewLocation; 
			pFile->QueryInfo(HTTP_QUERY_RAW_HEADERS_CRLF, strNewLocation); 

			int nPlace = strNewLocation.Find(_T("Location: ")); 
			if (nPlace == -1) 
			{ 
				TRACE( _T("Error: Site redirects with no new location") );
				return "request failed - Site redirects with no new location";
			} 

			strNewLocation = strNewLocation.Mid(nPlace + 10); 
			nPlace = strNewLocation.Find('\n'); 
			if (nPlace > 0) 
				strNewLocation = strNewLocation.Left(nPlace); 

			// close up the redirected site 

			pFile->Close(); 
			delete pFile; 
			pServer->Close(); 
			delete pServer; 

			if (bProgressMode) 
			{ 
				TRACE( _T("Caution: redirected to "));
				TRACE( (LPCTSTR) strNewLocation ); 
			} 

			// figure out what the old place was 
			if (!AfxParseURL(strNewLocation, dwServiceType, strServerName, strObject, nPort)) 
			{ 
				TRACE( _T("Error: the redirected URL could not be parsed.") );
				return "request failed - the redirected URL could not be parsed.";
			} 

			if (dwServiceType != INTERNET_SERVICE_HTTP) 
			{ 
				TRACE( _T("Error: the redirected URL does not reference a HTTP resource.") );
				return "request failed - the redirected URL does not reference a HTTP resource";
			} 

			// try again at the new location 
			pServer = session.GetHttpConnection(strServerName, nPort); 
			pFile = pServer->OpenRequest(CHttpConnection::HTTP_VERB_GET, strObject);
			pFile->SendRequest(); 

			pFile->QueryInfoStatusCode(dwRet); 
			if (dwRet != HTTP_STATUS_OK) 
			{ 
				//TRACE( _T("Error: Got status code ") dwRet );
				return "request failed - Got status code " + dwRet;
			} 
		}

		TCHAR sz[1024]; 
		sz[1023] = 0;
		while (pFile->ReadString(sz, 1023)) 
		{ 
			line += sz;
		} 	
		SetCookie(&session, strServerName);
		SetCookie(&session, url);

	}
	catch (exception e) {
		TRACE(e.what());
		line = "request failed - status code N/A";
	}
	catch (CInternetException *e) {
		TCHAR error[256];
		if(e->GetErrorMessage(error, 256)) {
			TRACE(error);
		}
		e->Delete();
		e = NULL;
		line = "request failed - status code N/A";
	}
	if(pServer != NULL) {
		pServer->Close();
		delete pServer;
		pServer = NULL;
	}
	if(pFile != NULL) {
		pFile->Close();
		delete pFile;
		pFile = NULL;
	}
	return line;

}
Example #18
0
/**
 *  @brief HTTP每次请求接收到的第一个数据包
 *
 * 处理第一个数据包
 *
 *  @return TBool 是否继续处理数据包
 */
TBool CSocketEngine::GetFirstData(){
  iTotalLen=0;
  //备份Http头
  TInt pos=GetHttpHeadOverPos(iData1);
  if(pos>0){
    if(pos>2048) iHeader=iHeader->ReAllocL(pos);
    iHeader->Des().Copy(iData1.Left(pos));
    Log(_L8("Http(response) header:"));
    Log(iHeader->Des());
  }

  TInt sc=GetStatusCode(iData1);
  //获得当前网络请求状态
  //if(GetSHttpConnStatus(iData1)) 
  if(200==sc||206==sc||301==sc||302==sc){
    if(iData1.Find(_L8("www.wapforum.org"))>0&&iAppUi->iCountConnect<1){
      //iType = EFalse;
      iCount=0;
      iHeader->Des().Zero();
      Cancel();
      iSocket.Close();
      iAppUi->iCountConnect=1;
      WeaveUrl(preUri);//重新连接
      return EFalse;
    }
    iAppUi->iCountConnect=2;
    
    CDesC8ArrayFlat* cookies=new (ELeave) CDesC8ArrayFlat(1);
    GetCookieArray(iData1,*cookies);
    if(cookies->Count()) iObserver->OnGetCookieArray(*cookies);
    delete cookies;
    TInt statusCode=GetStatusCode(iData1);
    if(301==statusCode||302==statusCode){
      Log(_L8("302 Location:"));
      iCount=0;
      iHeader->Des().Zero();
      Cancel();
      iSocket.Close();
      TPtrC8 urlRedir=GetHttpHeaderInfo(iData1,_L8("Location"));
      Log(urlRedir);
      
      CDesC8ArrayFlat* cookies=new (ELeave) CDesC8ArrayFlat(1);
      GetCookieArray(iData1,*cookies);
      HBufC8* t=CookiesString(*cookies);
      if(t){
        Log(*t);
        SetCookie(*t);
      }
      delete cookies;
      delete t;
      if(urlRedir.Length()) WeaveUrl(urlRedir);
      else OnHttpError(EHttpBadHttpHeader);
      return EFalse;
    }

    //获得请求文件的总长度
    iHttpHeadOverPos=GetHttpHeadOverPos(iData1);
    iTotalLen=GetLength(iData1);
    if(iTotalLen<0){
      OnHttpError(EHttpContentLengthError);
      return EFalse;
    }
  }else{
    OnHttpError(EHttpBadHttpHeader);
    return EFalse;
  }
  
  return ETrue;
}