Exemplo n.º 1
8
LPBYTE DownloadToMemory(IN LPCTSTR lpszURL, OUT PDWORD_PTR lpSize)
{
	LPBYTE lpszReturn = 0;
	*lpSize = 0;
	const HINTERNET hSession = InternetOpen(TEXT("GetGitHubRepositoryList"), INTERNET_OPEN_TYPE_PRECONFIG, 0, 0, INTERNET_FLAG_NO_COOKIES);
	if (hSession)
	{
		URL_COMPONENTS uc = { 0 };
		TCHAR HostName[MAX_PATH];
		TCHAR UrlPath[MAX_PATH];
		uc.dwStructSize = sizeof(uc);
		uc.lpszHostName = HostName;
		uc.lpszUrlPath = UrlPath;
		uc.dwHostNameLength = MAX_PATH;
		uc.dwUrlPathLength = MAX_PATH;
		InternetCrackUrl(lpszURL, 0, 0, &uc);
		const HINTERNET hConnection = InternetConnect(hSession, HostName, INTERNET_DEFAULT_HTTPS_PORT, 0, 0, INTERNET_SERVICE_HTTP, 0, 0);
		if (hConnection)
		{
			const HINTERNET hRequest = HttpOpenRequest(hConnection, TEXT("GET"), UrlPath, 0, 0, 0, INTERNET_FLAG_SECURE | INTERNET_FLAG_RELOAD, 0);
			if (hRequest)
			{
				HttpSendRequest(hRequest, 0, 0, 0, 0);
				lpszReturn = (LPBYTE)GlobalAlloc(GMEM_FIXED, 1);
				DWORD dwRead;
				static BYTE szBuf[1024 * 4];
				LPBYTE lpTmp;
				for (;;)
				{
					if (!InternetReadFile(hRequest, szBuf, (DWORD)sizeof(szBuf), &dwRead) || !dwRead) break;
					lpTmp = (LPBYTE)GlobalReAlloc(lpszReturn, (SIZE_T)(*lpSize + dwRead), GMEM_MOVEABLE);
					if (lpTmp == NULL) break;
					lpszReturn = lpTmp;
					CopyMemory(lpszReturn + *lpSize, szBuf, dwRead);
					*lpSize += dwRead;
				}
				InternetCloseHandle(hRequest);
			}
			InternetCloseHandle(hConnection);
		}
		InternetCloseHandle(hSession);
	}
	return lpszReturn;
}
Exemplo n.º 2
0
std::string WebIO::Execute(const char* command, std::string body)
{
	WebIO::OpenConnection();

	const char *acceptTypes[] = { "application/x-www-form-urlencoded", NULL };

	DWORD dwFlag = INTERNET_FLAG_RELOAD | (WebIO::IsSecuredConnection() ? INTERNET_FLAG_SECURE : 0);
	WebIO::m_hFile = HttpOpenRequest(WebIO::m_hConnect, command, WebIO::m_sUrl.document.c_str(), NULL, NULL, acceptTypes, dwFlag, 0);

	HttpSendRequest(WebIO::m_hFile, "Content-type: application/x-www-form-urlencoded", -1, (char*)body.c_str(), body.size() + 1);

	std::string returnBuffer;

	DWORD size = 0;
	char buffer[0x2001] = { 0 };

	while (InternetReadFile(WebIO::m_hFile, buffer, 0x2000, &size))
	{
		returnBuffer.append(buffer, size);
		if (!size) break;
	}

	WebIO::CloseConnection();

	return returnBuffer;
}
Exemplo n.º 3
0
string Functions::HttpGet(LPCWSTR uri, HINTERNET hHandle, LPCWSTR host)
{
	HINTERNET cHandle = InternetConnect(hHandle, host, INTERNET_DEFAULT_HTTP_PORT, NULL, NULL, INTERNET_SERVICE_HTTP, 0, 0);
	HINTERNET oHandle = HttpOpenRequest(cHandle, L"GET", uri, L"HTTP/1.1", NULL, NULL, INTERNET_FLAG_RELOAD, 0);
	BOOL sHandle = HttpSendRequest(oHandle, L"", 0, 0, 0);
	if(sHandle)
	{
		char* buffer = (char*) malloc(sizeof(char) * (1024));
		DWORD dwVal = 0;
		BOOL eHandle = InternetReadFile(oHandle, buffer, 1024, &dwVal);
		if(eHandle)
		{
			char* buffer2 = (char*) malloc(sizeof(char) * (dwVal + 1));
			buffer2[dwVal] = '\0';
			memcpy(buffer2, buffer, dwVal);
			string str = string(buffer2);

			free(buffer);
			free(buffer2);
			return str;
		}

		free(buffer);
	}

	return "";
}
Exemplo n.º 4
0
int httpPost(url_schema *urls, const char *headers, const char *data)
{
	int rc = 0;

	static const TCHAR agent[] = _T("Google Chrome");
	static LPCTSTR proxy = NULL;
	static LPCTSTR proxy_bypass = NULL;

	HINTERNET hSession = InternetOpen(agent, PRE_CONFIG_INTERNET_ACCESS, proxy, proxy_bypass, 0);
	if (hSession) {
		HINTERNET hConnect = InternetConnect(hSession, urls->host, urls->port, NULL, NULL, INTERNET_SERVICE_HTTP, 0, 1);
		if (hConnect) {
			PCTSTR accept[] = {"*/*", NULL};
			HINTERNET hRequest = HttpOpenRequest(hConnect, _T("POST"), urls->page, NULL, NULL, accept, 0, 1);
			if (hRequest) {
				if (!HttpSendRequest(hRequest, headers, lstrlen(headers), (LPVOID)data, lstrlen(data)))
					rc = ERROR_SEND_REQUEST;
				else
					rc = ERROR_SUCCESS;
				InternetCloseHandle(hRequest);
			}
			else
				rc = ERROR_OPEN_REQUEST;
			InternetCloseHandle(hConnect);
		}
		else
			rc = ERROR_CONNECT;
		InternetCloseHandle(hSession);
	}
	else 
		rc = ERROR_INTERNET;
	return rc;
}
Exemplo n.º 5
0
CNetRequestImpl::CNetRequestImpl(const char* method, const String& strUrl)
{
    pszErrFunction = NULL;
    hInet = NULL, hConnection = NULL, hRequest = NULL;
    memset(&uri, 0, sizeof(uri) );
    m_pInstance = this;

    CAtlStringW strUrlW(strUrl.c_str());

    do 
    {
        if ( !isLocalHost(strUrl.c_str()) && !SetupInternetConnection(strUrlW) )
        {
            pszErrFunction = L"SetupInternetConnection";
            break;
        }

        hInet = InternetOpen(_T("rhodes-wm"), INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, NULL );
        if ( !hInet ) 
        {
            pszErrFunction = L"InternetOpen";
            break;
        }

        DWORD dwUrlLength = 1024;
        CAtlStringW strCanonicalUrlW;
        if ( !InternetCanonicalizeUrl( strUrlW, strCanonicalUrlW.GetBuffer(dwUrlLength), &dwUrlLength, 0) )
        {
            pszErrFunction = _T("InternetCanonicalizeUrl");
            break;
        }
        strCanonicalUrlW.ReleaseBuffer();

		alloc_url_components( &uri, strCanonicalUrlW );
        if( !InternetCrackUrl( strCanonicalUrlW, strCanonicalUrlW.GetLength(), 0, &uri ) ) 
        {
			pszErrFunction = L"InternetCrackUrl";
			break;
		}

        hConnection = InternetConnect( hInet, uri.lpszHostName, uri.nPort, _T("anonymous"), NULL, 
          INTERNET_SERVICE_HTTP, 0, 0 );
        if ( !hConnection ) 
        {
            pszErrFunction = L"InternetConnect";
            break;
        }

        strReqUrlW = uri.lpszUrlPath;
        strReqUrlW += uri.lpszExtraInfo;
        hRequest = HttpOpenRequest( hConnection, CAtlStringW(method), strReqUrlW, NULL, NULL, NULL, 
          INTERNET_FLAG_KEEP_CONNECTION|INTERNET_FLAG_NO_CACHE_WRITE, NULL );
        if ( !hRequest ) 
        {
            pszErrFunction = L"HttpOpenRequest";
            break;
        }

    }while(0);
}
Exemplo n.º 6
0
int inet_sendscore(char *name, char *scorecode)
{
	char url[1000];
	int result=INET_SUCCESS;
	HINTERNET data;

	// Create request URL
	sprintf(url,"/highscore.php?yourname=%s&code=%s",name,scorecode);

	// Open request
	data = HttpOpenRequest(connection, "GET", url, "HTTP/1.0", NULL, NULL, INTERNET_FLAG_KEEP_CONNECTION, 0 );
	if(data!=NULL)
	{
		// Send data
		if(HttpSendRequest(data, NULL, 0, NULL, 0)) InternetCloseHandle(data);
		else result = INET_SENDREQUEST_FAILED;
	}
	else
	{
		result = INET_OPENREQUEST_FAILED;
	}

	return(result);

}
Exemplo n.º 7
0
	//download file from WWW in a buffer
	bool WWWFileBuffer(char *host, char *path, char *outBuffer, int outBufferSize)
	{
		bool retval = false;
		LPTSTR AcceptTypes[2] = { TEXT("*/*"), NULL };
		DWORD dwSize = outBufferSize - 1, dwFlags = INTERNET_FLAG_RELOAD | INTERNET_FLAG_NO_CACHE_WRITE;
		HINTERNET opn = NULL, con = NULL, req = NULL;
		opn = InternetOpen(TEXT("Evilzone.org"), INTERNET_OPEN_TYPE_DIRECT, NULL, NULL, 0);
		if (!opn)
			return retval;
		con = InternetConnect(opn, host, INTERNET_DEFAULT_HTTP_PORT, NULL, NULL, INTERNET_SERVICE_HTTP, 0, 0);
		if (!con)
			return retval;
		req = HttpOpenRequest(con, TEXT("GET"), path, HTTP_VERSION, NULL, (LPCTSTR*)AcceptTypes, dwFlags, 0);
		if (!req)
			return retval;
		if (HttpSendRequest(req, NULL, 0, NULL, 0))
		{
			DWORD statCodeLen = sizeof(DWORD);
			DWORD statCode;
			if (HttpQueryInfo(req,
				HTTP_QUERY_STATUS_CODE | HTTP_QUERY_FLAG_NUMBER,
				&statCode, &statCodeLen, NULL))
			{
				if (statCode == 200 && InternetReadFile(req, (LPVOID)outBuffer, outBufferSize - 1, &dwSize))
				{
					retval = TRUE;
				}
			}
		}
		InternetCloseHandle(req);
		InternetCloseHandle(con);
		InternetCloseHandle(opn);
		return retval;
	}
Exemplo n.º 8
0
Arquivo: syse.cpp Projeto: eyberg/syse
BOOL do_some_shit()
{
HINTERNET Initialize,Connection,File;
DWORD BytesRead;

Initialize = InternetOpen(_T("HTTPGET"),INTERNET_OPEN_TYPE_DIRECT,NULL,NULL,0);
Connection = InternetConnect(Initialize,_T("www.clicksaw.com"),INTERNET_DEFAULT_HTTP_PORT, NULL,NULL,INTERNET_SERVICE_HTTP,0,0);
	
File = HttpOpenRequest(Connection,NULL,_T("/contact.html"),NULL,NULL,NULL,0,0);

if(HttpSendRequest(File,NULL,0,NULL,0))
{
	LPSTR szContents[400] = { '\0' } ; // = Contents.GetBuffer(400);
	 
	 while(InternetReadFile(File, szContents, 400, &BytesRead) && BytesRead != 0)
    {
	}

	MessageBoxA(NULL, (LPCSTR)(szContents), "metoo", NULL);
}

InternetCloseHandle(File);
InternetCloseHandle(Connection);
InternetCloseHandle(Initialize);
 return(TRUE);
}
Exemplo n.º 9
0
bool CHttpHelper::publish(char *payload)
{
	bool result = false;

	DWORD flags = INTERNET_FLAG_NO_CACHE_WRITE | INTERNET_FLAG_PRAGMA_NOCACHE;

	char path[1024];

	int len = sprintf(path, "%s", m_routerSettings->routerPath);
	sprintf(path + len, "%s", m_topic);

	HINTERNET httpRequest = HttpOpenRequest(m_hSession, 
											"POST",
											path,
											NULL, 
											"pocketnoc",
											NULL,
											flags,
											0);

	if(httpRequest == NULL)
		return result;

	if(HttpSendRequest(httpRequest, NULL, 0, payload, strlen(payload)))
		result = true;
	
	InternetCloseHandle(httpRequest);

	return result;
}
Exemplo n.º 10
0
    void openHTTPConnection (URL_COMPONENTS& uc, URL::OpenStreamProgressCallback* progressCallback,
                             void* progressCallbackContext)
    {
        const TCHAR* mimeTypes[] = { _T("*/*"), 0 };

        DWORD flags = INTERNET_FLAG_RELOAD | INTERNET_FLAG_NO_CACHE_WRITE | INTERNET_FLAG_NO_COOKIES;

        if (address.startsWithIgnoreCase ("https:"))
            flags |= INTERNET_FLAG_SECURE;  // (this flag only seems necessary if the OS is running IE6 -
                                            //  IE7 seems to automatically work out when it's https)

        request = HttpOpenRequest (connection, isPost ? _T("POST") : _T("GET"),
                                   uc.lpszUrlPath, 0, 0, mimeTypes, flags, 0);

        if (request != 0)
        {
            INTERNET_BUFFERS buffers = { 0 };
            buffers.dwStructSize = sizeof (INTERNET_BUFFERS);
            buffers.lpcszHeader = headers.toWideCharPointer();
            buffers.dwHeadersLength = (DWORD) headers.length();
            buffers.dwBufferTotal = (DWORD) postData.getSize();

            if (HttpSendRequestEx (request, &buffers, 0, HSR_INITIATE, 0))
            {
                int bytesSent = 0;

                for (;;)
                {
                    const int bytesToDo = jmin (1024, (int) postData.getSize() - bytesSent);
                    DWORD bytesDone = 0;

                    if (bytesToDo > 0
                         && ! InternetWriteFile (request,
                                                 static_cast <const char*> (postData.getData()) + bytesSent,
                                                 (DWORD) bytesToDo, &bytesDone))
                    {
                        break;
                    }

                    if (bytesToDo == 0 || (int) bytesDone < bytesToDo)
                    {
                        if (HttpEndRequest (request, 0, 0, 0))
                            return;

                        break;
                    }

                    bytesSent += bytesDone;

                    if (progressCallback != nullptr
                          && ! progressCallback (progressCallbackContext, bytesSent, (int) postData.getSize()))
                        break;
                }
            }
        }

        close();
    }
Exemplo n.º 11
0
int CPostData::TBigDataPost()
{
	//CString sTraceBuffer;
	CUrlCrack url;
	if (!url.Crack(m_strUrl.c_str()))
		return ERR_URLCRACKERROR;

	m_hInetSession = ::InternetOpen(MS_USERAGENT, INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, 0);
	if (m_hInetSession == NULL)
		return ERR_NETWORKERROR;

	DWORD dwTimeOut = 360000;
	InternetSetOptionEx(m_hInetSession, INTERNET_OPTION_CONTROL_RECEIVE_TIMEOUT, &dwTimeOut, sizeof(DWORD), 0);
	InternetSetOptionEx(m_hInetSession, INTERNET_OPTION_CONTROL_SEND_TIMEOUT, &dwTimeOut, sizeof(DWORD), 0);
	InternetSetOptionEx(m_hInetSession, INTERNET_OPTION_SEND_TIMEOUT, &dwTimeOut, sizeof(DWORD), 0);
	InternetSetOptionEx(m_hInetSession, INTERNET_OPTION_RECEIVE_TIMEOUT, &dwTimeOut, sizeof(DWORD), 0);
	InternetSetOptionEx(m_hInetSession, INTERNET_OPTION_CONNECT_TIMEOUT, &dwTimeOut, sizeof(DWORD), 0);

	m_hInetConnection = ::InternetConnect(m_hInetSession, url.GetHostName(), url.GetPort(), NULL, NULL, INTERNET_SERVICE_HTTP, 0, (DWORD)this);
	if (m_hInetConnection == NULL)
	{
		CloseHandles();
		return  ERR_NETWORKERROR;
	}

	LPCTSTR ppszAcceptTypes[2];
	ppszAcceptTypes[0] = _T("*/*"); 
	ppszAcceptTypes[1] = NULL;

	DWORD dwFlags = 0;

	if( url.GetPort() == 443 )
	{
		dwFlags =	INTERNET_FLAG_NO_CACHE_WRITE |
					INTERNET_FLAG_KEEP_CONNECTION |
					INTERNET_FLAG_PRAGMA_NOCACHE |
					INTERNET_FLAG_SECURE |
					INTERNET_FLAG_IGNORE_CERT_CN_INVALID |
					INTERNET_FLAG_IGNORE_CERT_DATE_INVALID;
	}
	else if( url.GetPort() == 80 )
	{
		//for HTTP
		dwFlags =	INTERNET_FLAG_NO_CACHE_WRITE |
					INTERNET_FLAG_KEEP_CONNECTION |
					INTERNET_FLAG_PRAGMA_NOCACHE ;
	}

	m_hInetFile = HttpOpenRequest(m_hInetConnection, _T("POST"), url.GetPath(), NULL, NULL, ppszAcceptTypes, dwFlags, (DWORD)this);
	if (m_hInetFile == NULL)
	{
		CloseHandles();
		return  ERR_NETWORKERROR;
	}
	return ERR_SUCCESS;
}
Exemplo n.º 12
0
int CPostData::TransferDataPost()
{
	CUrlCrack url;
	if (!url.Crack(m_strUrl.c_str()))
		return ERR_URLCRACKERROR;

	m_hInetSession = ::InternetOpen(MONEYHUB_USERAGENT, INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, 0);
	if (m_hInetSession == NULL)
		return ERR_NETWORKERROR;


	DWORD dwTimeOut = 60000;
	InternetSetOptionEx(m_hInetSession, INTERNET_OPTION_CONTROL_RECEIVE_TIMEOUT, &dwTimeOut, sizeof(DWORD), 0);
	InternetSetOptionEx(m_hInetSession, INTERNET_OPTION_CONTROL_SEND_TIMEOUT, &dwTimeOut, sizeof(DWORD), 0);
	InternetSetOptionEx(m_hInetSession, INTERNET_OPTION_SEND_TIMEOUT, &dwTimeOut, sizeof(DWORD), 0);
	InternetSetOptionEx(m_hInetSession, INTERNET_OPTION_RECEIVE_TIMEOUT, &dwTimeOut, sizeof(DWORD), 0);
	InternetSetOptionEx(m_hInetSession, INTERNET_OPTION_CONNECT_TIMEOUT, &dwTimeOut, sizeof(DWORD), 0);

	m_hInetConnection = ::InternetConnect(m_hInetSession, url.GetHostName(), url.GetPort(), NULL, NULL, INTERNET_SERVICE_HTTP, 0, (DWORD)this);
	if (m_hInetConnection == NULL)
	{
		CloseHandles();
		return ERR_NETWORKERROR;
	}


	LPCTSTR ppszAcceptTypes[2];
	ppszAcceptTypes[0] = _T("*/*"); 
	ppszAcceptTypes[1] = NULL;

	m_hInetFile = HttpOpenRequest(m_hInetConnection, _T("POST"), url.GetPath(), NULL, NULL, ppszAcceptTypes, INTERNET_FLAG_RELOAD | INTERNET_FLAG_DONT_CACHE | INTERNET_FLAG_KEEP_CONNECTION, (DWORD)this);
	if (m_hInetFile == NULL)
	{
		CloseHandles();
		return ERR_NETWORKERROR;
	}


	HttpAddRequestHeaders(m_hInetFile, _T("Content-Type: application/x-www-form-urlencoded\r\n"), -1, HTTP_ADDREQ_FLAG_ADD | HTTP_ADDREQ_FLAG_REPLACE); 
	HttpAddRequestHeaders(m_hInetFile, _T("User-Agent: Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0; .NET CLR 2.0.50727; .NET CLR 3.0.04506.648; .NET CLR 3.5.21022; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729; .NET CLR 1.1.4322; .NET4.0C; .NET4.0E)\r\n"), -1, HTTP_ADDREQ_FLAG_ADD | HTTP_ADDREQ_FLAG_REPLACE); 

	TCHAR szHeaders[1024];
	_stprintf_s(szHeaders, _countof(szHeaders), _T("MoneyhubUID: %s\r\n"), m_strHWID.c_str());
	HttpAddRequestHeaders(m_hInetFile, szHeaders, -1, HTTP_ADDREQ_FLAG_ADD | HTTP_ADDREQ_FLAG_REPLACE); 

	BOOL bSend = ::HttpSendRequest(m_hInetFile, NULL, 0, m_lpPostData, m_dwPostDataLength);
	if (!bSend)
	{
		CloseHandles();
		return ERR_NETWORKERROR;
	}

	CloseHandles();

	return ERR_SUCCESS;
}
Exemplo n.º 13
0
DWORD packet_transmit_via_http_wininet(Remote *remote, Packet *packet, PacketRequestCompletion *completion) {
	DWORD res = 0;
	HINTERNET hReq;
	HINTERNET hRes;
	DWORD retries = 5;
	DWORD flags;
	DWORD flen;
	unsigned char *buffer;

	flen = sizeof(flags);

	buffer = malloc( packet->payloadLength + sizeof(TlvHeader) );
	if (! buffer) {
		SetLastError(ERROR_NOT_FOUND);
		return 0;
	}

	memcpy(buffer, &packet->header, sizeof(TlvHeader));
	memcpy(buffer + sizeof(TlvHeader), packet->payload, packet->payloadLength);

	do {

		flags = INTERNET_FLAG_RELOAD | INTERNET_FLAG_NO_CACHE_WRITE | INTERNET_FLAG_NO_AUTO_REDIRECT | INTERNET_FLAG_NO_UI;
		if (remote->transport == METERPRETER_TRANSPORT_HTTPS) {
			flags |= INTERNET_FLAG_SECURE |  INTERNET_FLAG_IGNORE_CERT_CN_INVALID  | INTERNET_FLAG_IGNORE_CERT_DATE_INVALID;
		}

		hReq = HttpOpenRequest(remote->hConnection, "POST", remote->uri, NULL, NULL, NULL, flags, 0);

		if (hReq == NULL) {
			dprintf("[PACKET RECEIVE] Failed HttpOpenRequest: %d", GetLastError());
			SetLastError(ERROR_NOT_FOUND);
			break;
		}

		if (remote->transport == METERPRETER_TRANSPORT_HTTPS) {
			InternetQueryOption( hReq, INTERNET_OPTION_SECURITY_FLAGS, &flags, &flen);
			flags |= SECURITY_FLAG_IGNORE_UNKNOWN_CA | SECURITY_FLAG_IGNORE_CERT_CN_INVALID | SECURITY_FLAG_IGNORE_UNKNOWN_CA;
			InternetSetOption(hReq, INTERNET_OPTION_SECURITY_FLAGS, &flags, flen);
		}

		hRes = HttpSendRequest(hReq, NULL, 0, buffer, packet->payloadLength + sizeof(TlvHeader) );

		if (! hRes) {
			dprintf("[PACKET RECEIVE] Failed HttpSendRequest: %d", GetLastError());
			SetLastError(ERROR_NOT_FOUND);
			break;
		}
	} while(0);

	memset(buffer, 0, packet->payloadLength + sizeof(TlvHeader));
	InternetCloseHandle(hReq);
	return res;
}
Exemplo n.º 14
0
//------------------------------------------------------------------------------
void GetCSRFToken(VIRUSTOTAL_STR *vts)
{
  HINTERNET M_connexion = 0;
  if (!use_other_proxy)M_connexion = InternetOpen("",/*INTERNET_OPEN_TYPE_DIRECT*/INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, INTERNET_FLAG_NO_CACHE_WRITE);
  else M_connexion = InternetOpen("",/*INTERNET_OPEN_TYPE_DIRECT*/INTERNET_OPEN_TYPE_PROXY, proxy_ch_auth, NULL, 0);

  if (M_connexion==NULL)M_connexion = InternetOpen("",INTERNET_OPEN_TYPE_DIRECT, NULL, NULL, INTERNET_FLAG_NO_CACHE_WRITE);
  if (M_connexion==NULL)return;

  //init connexion
  HINTERNET M_session = InternetConnect(M_connexion, "www.virustotal.com",443,"","",INTERNET_SERVICE_HTTP,0,0);
  if (M_session==NULL)
  {
    InternetCloseHandle(M_connexion);
    return;
  }

  //connexion
  HINTERNET M_requete = HttpOpenRequest(M_session,"GET","www.virustotal.com",NULL,"",NULL,
                                        INTERNET_FLAG_NO_CACHE_WRITE|INTERNET_FLAG_SECURE
                                        |INTERNET_FLAG_IGNORE_CERT_CN_INVALID|INTERNET_FLAG_IGNORE_CERT_DATE_INVALID,0);

  if (use_proxy_advanced_settings)
  {
    InternetSetOption(M_requete,INTERNET_OPTION_PROXY_USERNAME,proxy_ch_user,sizeof(proxy_ch_user));
    InternetSetOption(M_requete,INTERNET_OPTION_PROXY_PASSWORD,proxy_ch_password,sizeof(proxy_ch_password));
  }

  if (M_requete==NULL)
  {
    InternetCloseHandle(M_session);
    InternetCloseHandle(M_connexion);
    return;
  }else if (HttpSendRequest(M_requete, NULL, 0, NULL, 0))
  {
    //traitement !!!
    char buffer[MAX_PATH];
    DWORD dwNumberOfBytesRead = MAX_PATH;

    if(HttpQueryInfo(M_requete,HTTP_QUERY_SET_COOKIE, buffer, &dwNumberOfBytesRead, 0))
    {
      if (dwNumberOfBytesRead>42)buffer[42]=0;

      //on passe : csrftoken=
      strcpy(vts->token,buffer+10);
    }
    InternetCloseHandle(M_requete);
  }
  //close
  InternetCloseHandle(M_session);
  InternetCloseHandle(M_connexion);
}
Exemplo n.º 15
0
bool CHTTPParser::HTTPGet(LPCTSTR pstrServer, LPCTSTR pstrObjectName, CString& rString)
{
	bool bReturn = false;

	// are we already connected
	bReturn = IsInternetAvailable();

	if(!bReturn)
	{
		// no, then try and connect
		bReturn = openInternet();
	}

	if(bReturn == true)
	{
		HINTERNET hConnect = InternetConnect(m_hSession, pstrServer, 80, NULL, NULL, INTERNET_SERVICE_HTTP, 0, 1);

		if(hConnect != NULL)
		{
			HINTERNET hFile = NULL;
			hFile = HttpOpenRequest(hConnect, _T("GET"), pstrObjectName, HTTP_VERSION, NULL, NULL, INTERNET_FLAG_EXISTING_CONNECT, 1);

			if(hFile != NULL)
			{
				if(HttpSendRequest(hFile, NULL, 0, NULL, 0))
				{
					readString(rString, hFile);
				}
				else
				{
					bReturn = false;
				}

				InternetCloseHandle(hFile);
			}
			else
			{
				bReturn = false;
			}
			InternetCloseHandle(hConnect);
		}
		else
		{
			bReturn = false;
		}
	}

	return bReturn;
}
Exemplo n.º 16
0
STDMETHODIMP CBHttpRequest::Open(BSTR strMethod, BSTR strUrl, VARIANT_BOOL bAsync, VARIANT varUser, VARIANT varPassword)
{
    CUrl url;
    CStringA strObject;
    CStringA strUser;
    CStringA strPassword;

    Abort();

    s_cs.Enter();
    s_dwReqID ++;
    m_dwReqID = s_dwReqID;
    s_mapReq.SetAt(m_dwReqID, this);
    s_cs.Leave();

    url.CrackUrl(CBStringA(strUrl));
    m_bAsync = (bAsync != VARIANT_FALSE);

    strObject = url.GetUrlPath();
    strObject.Append(url.GetExtraInfo());

    if(varUser.vt != VT_ERROR)
    {
        HRESULT hr = varGetString(varUser, strUser);
        if(FAILED(hr))return hr;
    }

    if(varPassword.vt != VT_ERROR)
    {
        HRESULT hr = varGetString(varPassword, strPassword);
        if(FAILED(hr))return hr;
    }

    m_hConnection = InternetConnect(m_hSession, url.GetHostName(), url.GetPortNumber(),
                                    strUser.IsEmpty() ? NULL : (LPCSTR)strUser, strPassword.IsEmpty() ? NULL : (LPCSTR)strPassword,
                                    INTERNET_SERVICE_HTTP, 0, m_dwReqID);
    if(m_hConnection == NULL)
        return GetErrorResult();

    m_hFile = HttpOpenRequest(m_hConnection, CBStringA(strMethod), strObject, NULL, NULL, NULL, m_dwFlags, m_dwReqID);
    if(m_hFile == NULL)
        return GetErrorResult();

    m_eventComplete.Set();

    return S_OK;
}
Exemplo n.º 17
0
void
WinINetRequest::openRequest()
{
    m_request = HttpOpenRequest(
        m_connect,
        "GET",
        m_url.m_path.c_str(),
        HTTP_VERSION,
        NULL,
        NULL,
        m_url.m_flags,
        NULL);

    if (m_request == NULL) {
        throw XArch(new XArchEvalWindows());
    }
}
DWORD OS::GetComputerIp(char* ip, int type)
{
		if (LOCALE_IP == type)
		{
			DWORD m_HostIP = 0;
			LPHOSTENT lphost;
			char	HostName[1024];
			
			if(!gethostname(HostName, 1024))
			{
				if(lphost = gethostbyname(HostName))
					m_HostIP = ((LPIN_ADDR)lphost->h_addr)->s_addr; 
			}	
			/*	if (ip)
					memcpy(ip, inet_ntoa(*((in_addr*)lphost->h_addr_list[0])), MAX_IP_SIZE);*/
			return m_HostIP;
		}
		else
		{	
				HINTERNET hInet = InternetOpen("Mozilla/4.0 (compatible; MSIE 6.0b; Windows NT 5.0; .NET CLR 1.0.2914)", 
													INTERNET_OPEN_TYPE_PRECONFIG, 0, 0, 0); 
				if (NULL != hInet) 
				{
					HINTERNET hSession = InternetConnect(hInet, SERVER_IP_LOCALE, INTERNET_DEFAULT_HTTP_PORT, 0, 0, 
															INTERNET_SERVICE_HTTP, 0, 0);
					if (NULL != hSession)
					{
						HINTERNET hRequest = HttpOpenRequest(hSession, "GET", "/get_ip.php?loc=", 0, 0, 0,	INTERNET_FLAG_KEEP_CONNECTION, 1);	
						if (NULL == hRequest)
							return 0;
						if (HttpSendRequest(hRequest, 0, 0, 0, 0)) 
						{
							char  szReadBuff[MAX_SITE_SIZE];
							DWORD dwRead;
							InternetReadFile(hRequest, szReadBuff, sizeof(szReadBuff) - 1, &dwRead);
							if (0 == dwRead)
								return 0;
							
							ParseIpinHtml(szReadBuff, ip);
						}
					}
				}	
		}
		return 0;				
}
Exemplo n.º 19
0
int main()
{
	HINTERNET session=InternetOpen("uniquesession",INTERNET_OPEN_TYPE_DIRECT,NULL,NULL,0);
	HINTERNET http=InternetConnect(session,"localhost",80,0,0,INTERNET_SERVICE_HTTP,0,0);
	HINTERNET hHttpRequest = HttpOpenRequest(http,"POST","p.php",0,0,0,INTERNET_FLAG_RELOAD,0);
    char szHeaders[] = "Content-Type: application/x-www-form-urlencoded; charset=UTF-8";
    char szReq[1024]="cmd=winfuckinginet";
    HttpSendRequest(hHttpRequest, szHeaders, strlen(szHeaders), szReq, strlen(szReq));
    char szBuffer[1025];
    DWORD dwRead=0;
    while(InternetReadFile(hHttpRequest, szBuffer, sizeof(szBuffer)-1, &dwRead) && dwRead) {
      szBuffer[dwRead] = '\0';
      MessageBox(0,szBuffer,0,0);
}
    InternetCloseHandle(hHttpRequest);
    InternetCloseHandle(session);
    InternetCloseHandle(http);
}
Exemplo n.º 20
0
	Request::Request(const oConnection& connection, const StringRef& uri, Type type, const char* version, const char* referer, const char** acceptTypes, int flags) {
		this->_uri = RegEx::doReplace("#^[a-z]+://[^/]+#i" , "", uri.c_str() );
		this->_type = type;
		this->_connection = connection;
		const char* verb;
		switch (_type) {
			case typePost:
				verb = "POST";
				break;
			case typeHead:
				verb = "HEAD";
				break;
			default:
				verb = "GET";
		}
		_hRequest = HttpOpenRequest(connection->getHandle(), verb,
			_uri.empty() ? "/" : _uri.c_str(), version, referer, acceptTypes, flags, 1);
		if (!_hRequest) {
			throw ExceptionBadRequest();
		}
	}
Exemplo n.º 21
0
bool CConnection::SendRequest(XMLMemoryWriter& xml_memory_writer,Buffer &buffer,IEventListener* event_listener)
{
	CHAR   buffer_tmp[1024];
	DWORD  bytes_read;
	const WCHAR* lplpszAcceptTypes[] = { L"*/*", NULL };
	m_request = HttpOpenRequest(m_connection, L"POST", L"/xml-rpc", NULL, 0, lplpszAcceptTypes, 0, 0);
	if (m_request)
	{
		if (HttpSendRequest(m_request, 0, 0, xml_memory_writer.xml_data, xml_memory_writer.xml_data_size))
		{
			DWORD content_len;
			DWORD content_len_size = sizeof(content_len);
			if (HttpQueryInfo(m_request, HTTP_QUERY_CONTENT_LENGTH | HTTP_QUERY_FLAG_NUMBER, &content_len, &content_len_size, 0))
			{
				if (buffer.Allocate(content_len))
				{
					while (InternetReadFile(m_request, buffer_tmp, sizeof(buffer_tmp), &bytes_read) && bytes_read)
					{
						memcpy(buffer.buffer_in + buffer.buffer_in_total, buffer_tmp, bytes_read);
						buffer.buffer_in_total += bytes_read;
					}
					return true;
				}
				else
					event_listener->OnError(L"failed to allocate memory");
			}
			else
				event_listener->OnError(L"failed to query http info");
		}
		else
			event_listener->OnError(L"failed to send http request");
	    InternetCloseHandle(m_request);
	}
	else
		event_listener->OnError(L"failed creating http request");
	return false;
}
Exemplo n.º 22
0
/*
 * TransferStart: Retrieve files; the information needed to set up the
 * transfer is in info.
 *
 * This function is run in its own thread.
 */
void __cdecl TransferStart(void *download_info)
{
    Bool done;
    char filename[MAX_PATH + FILENAME_MAX];
    char local_filename[MAX_PATH + 1];  // Local filename of current downloaded file
    int i;
    int outfile;                   // Handle to output file
    DWORD size;                      // Size of block we're reading
    int bytes_read;                // Total # of bytes we've read

#if defined VANILLA_UPDATER
    const char *mime_types[2] = { "application/x-zip-compressed" };
#else
    const char *mime_types[4] = { "application/octet-stream", "text/plain", "application/x-msdownload", NULL };
    //const char *mime_types[2] = { "application/octet-stream", NULL };
#endif

    DWORD file_size;
    DWORD file_size_buf_len;
    DWORD index = 0;
    DownloadInfo *info = (DownloadInfo *)download_info;

    aborted = False;
    hConnection = NULL;
    hSession = NULL;
    hFile = NULL;

    hConnection = InternetOpen(szAppName, INTERNET_OPEN_TYPE_PRECONFIG,
                               NULL, NULL, INTERNET_FLAG_RELOAD);

    if (hConnection == NULL)
    {
        DownloadError(info->hPostWnd, GetString(hInst, IDS_CANTINIT));
        return;
    }

    if (aborted)
    {
        TransferCloseHandles();
        return;
    }

    hSession = InternetConnect(hConnection, info->machine, INTERNET_INVALID_PORT_NUMBER,
                               NULL, NULL, INTERNET_SERVICE_HTTP, 0, 0);
    if (hSession == NULL)
    {
        DownloadError(info->hPostWnd, GetString(hInst, IDS_NOCONNECTION), info->machine);
        return;
    }

    for (i = info->current_file; i < info->num_files; i++)
    {
        if (aborted)
        {
            TransferCloseHandles();
            return;
        }

        // Skip non-guest files if we're a guest
        if (config.guest && !(info->files[i].flags & DF_GUEST))
        {
            PostMessage(info->hPostWnd, BK_FILEDONE, 0, i);
            continue;
        }

        // If not supposed to transfer file, inform main thread
        if (DownloadCommand(info->files[i].flags) != DF_RETRIEVE)
        {
            // Wait for main thread to finish processing previous file
            WaitForSingleObject(hSemaphore, INFINITE);

            if (aborted)
            {
                TransferCloseHandles();
                return;
            }

            PostMessage(info->hPostWnd, BK_FILEDONE, 0, i);
            continue;
        }
#if VANILLA_UPDATER
        sprintf(filename, "%s%s", info->path, info->files[i].filename);
#else
        sprintf(filename, "%s//%s", info->path, info->files[i].filename);
#endif
        hFile = HttpOpenRequest(hSession, NULL, filename, NULL, NULL,
                                mime_types, INTERNET_FLAG_NO_UI, 0);
        if (hFile == NULL)
        {
            debug(("HTTPOpenRequest failed, error = %d, %s\n",
                   GetLastError(), GetLastErrorStr()));
            DownloadError(info->hPostWnd, GetString(hInst, IDS_CANTFINDFILE),
                          filename, info->machine);
            return;
        }

        if (!HttpSendRequest(hFile, NULL, 0, NULL, 0)) {
            debug(("HTTPSendRequest failed, error = %d, %s\n",
                   GetLastError(), GetLastErrorStr()));
            DownloadError(info->hPostWnd, GetString(hInst, IDS_CANTSENDREQUEST),
                          filename, info->machine);
            return;
        }

        // Get file size
        file_size_buf_len = sizeof(file_size);
        index = 0;
        if (!HttpQueryInfo(hFile, HTTP_QUERY_CONTENT_LENGTH | HTTP_QUERY_FLAG_NUMBER,
                           &file_size, &file_size_buf_len, &index)) {
            debug(("HTTPQueryInfo failed, error = %d, %s\n",
                   GetLastError(), GetLastErrorStr()));
            DownloadError(info->hPostWnd, GetString(hInst, IDS_CANTGETFILESIZE),
                          filename, info->machine);
            return;
        }

        PostMessage(info->hPostWnd, BK_FILESIZE, i, file_size);
#if VANILLA_UPDATER
        sprintf(local_filename, "%s\\%s", download_dir, info->files[i].filename);
#else
        sprintf(local_filename, "%s\\%s", info->files[i].path, info->files[i].filename);
#endif
        outfile = open(local_filename, O_BINARY | O_RDWR | O_CREAT | O_TRUNC, S_IWRITE | S_IREAD);
        if (outfile <= 0)
        {
            debug(("Couldn't open local file %s for writing\n", local_filename));
            DownloadError(info->hPostWnd, GetString(hInst, IDS_CANTWRITELOCALFILE),
                          local_filename);
            return;
        }

        // Read first block
        done = False;
        bytes_read = 0;
        while (!done)
        {
            if (!InternetReadFile(hFile, buf, BUFSIZE, &size))
            {
                DownloadError(info->hPostWnd, GetString(hInst, IDS_CANTREADFTPFILE), filename);
            }

            if (size > 0)
            {
                if (write(outfile, buf, size) != size)
                {
                    DownloadError(info->hPostWnd, GetString(hInst, IDS_CANTWRITELOCALFILE),
                                  local_filename);
                    close(outfile);
                    return;
                }
            }

            // Update graph position
            bytes_read += size;
            PostMessage(info->hPostWnd, BK_PROGRESS, 0, bytes_read);

            // See if done with file
            if (size == 0)
            {
                close(outfile);
                InternetCloseHandle(hFile);
                done = True;

                // Wait for main thread to finish processing previous file
                WaitForSingleObject(hSemaphore, INFINITE);

                if (aborted)
                {
                    TransferCloseHandles();
                    return;
                }

                PostMessage(info->hPostWnd, BK_FILEDONE, 0, i);
            }
        }
    }

    InternetCloseHandle(hSession);
    InternetCloseHandle(hConnection);

    PostMessage(info->hPostWnd, BK_TRANSFERDONE, 0, 0);
}
Exemplo n.º 23
0
BOOL vmsPostRequest::Send(LPCTSTR ptszServer, LPCTSTR ptszFilePath, LPCVOID pvData, DWORD dwDataSize, LPCTSTR ptszContentType, std::string *pstrResponse)
{
	Close ();

	DWORD dwAccessType = INTERNET_OPEN_TYPE_PRECONFIG;
	if (m_pProxyInfo)
		dwAccessType = m_pProxyInfo->tstrAddr.empty () ? INTERNET_OPEN_TYPE_DIRECT : INTERNET_OPEN_TYPE_PROXY;
	m_hInet = InternetOpen (m_tstrUserAgent.c_str (), dwAccessType,
		dwAccessType == INTERNET_OPEN_TYPE_PROXY ? m_pProxyInfo->tstrAddr.c_str () : NULL, NULL, 0);
	if (m_hInet == NULL)
		return FALSE;

	PostInitWinInetHandle (m_hInet);

	m_hConnect = InternetConnect (m_hInet, ptszServer, INTERNET_DEFAULT_HTTP_PORT, 
		NULL, NULL, INTERNET_SERVICE_HTTP, 0, NULL);
	if (m_hConnect == NULL)
		return FALSE;

#ifdef DEBUG_SHOW_SERVER_REQUESTS
	TCHAR tszTmpPath [MAX_PATH];
	GetTempPath (MAX_PATH, tszTmpPath);
	TCHAR tszTmpFile [MAX_PATH];
	_stprintf (tszTmpFile, _T ("%s\\si_serv_req_%d.txt"), tszTmpPath, _c++);
	HANDLE hLog = CreateFile (tszTmpFile, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, 0, NULL);
	DWORD dwLogWritten;
	#define LOG_REQ(s) WriteFile (hLog, s, strlen (s), &dwLogWritten, NULL)
	#define LOG_REQ_OPEN	CloseHandle (hLog); ShellExecute (NULL, "open", tszTmpFile, NULL, NULL, SW_SHOW);
	char szTmp [10000] = ""; DWORD dwTmp = 10000;
	#define LOG_REQ_HTTP_HDRS *szTmp = 0; HttpQueryInfo (m_hRequest, HTTP_QUERY_RAW_HEADERS_CRLF | HTTP_QUERY_FLAG_REQUEST_HEADERS, szTmp, &dwTmp, 0); LOG_REQ (szTmp);
	#define LOG_REQ_ALL LOG_REQ_HTTP_HDRS; LOG_REQ ((LPCSTR)pvData);
	#define LOG_RESP_HTTP_HDRS *szTmp = 0; HttpQueryInfo (m_hRequest, HTTP_QUERY_RAW_HEADERS_CRLF, szTmp, &dwTmp, 0); LOG_REQ (szTmp);
	DWORD dwErr;
#else
	#define LOG_REQ(s) 
	#define LOG_REQ_OPEN
	#define LOG_REQ_HTTP_HDRS
	#define LOG_RESP_HTTP_HDRS
	#define LOG_REQ_ALL
#endif

	m_hRequest = HttpOpenRequest (m_hConnect, _T ("POST"), ptszFilePath, NULL, NULL, NULL,
		INTERNET_FLAG_NO_CACHE_WRITE | INTERNET_FLAG_KEEP_CONNECTION | INTERNET_FLAG_NO_UI | 
		INTERNET_FLAG_PRAGMA_NOCACHE, 0);
	if (m_hRequest == NULL)
	{
		DWORD dwErr = GetLastError ();
		LOG_REQ ("SERVER FAILURE\r\n");
		LOG_REQ_OPEN;
		SetLastError (dwErr);
		return FALSE;
	}

	ApplyProxyAuth (m_hRequest);

	if (ptszContentType)
	{
		tstring tstr = _T ("Content-Type: ");
		tstr += ptszContentType;
		tstr += _T ("\r\n");
		HttpAddRequestHeaders (m_hRequest, tstr.c_str (), tstr.length (), HTTP_ADDREQ_FLAG_ADD|HTTP_ADDREQ_FLAG_REPLACE);
	}

#ifdef vmsPostRequest_USE_NO_HTTPSENDREQUESTEX
	if (FALSE == HttpSendRequest (m_hRequest, NULL, 0, (LPVOID)pvData, dwDataSize))
		return FALSE;
#else
	INTERNET_BUFFERS buffs;
	ZeroMemory (&buffs, sizeof (buffs));
	buffs.dwStructSize = sizeof (buffs);
	buffs.dwBufferTotal = dwDataSize;

	if (FALSE == HttpSendRequestEx (m_hRequest, &buffs, NULL, 0, 0))
	{
		PUL (" >>> HttpSendRequestEx failed.");
		LOG_REQ ("SERVER FAILURE\r\n");
		LOG_REQ_OPEN;
		return FALSE;
	}

	if (FALSE == MyInternetWriteFile (m_hRequest, pvData, dwDataSize))
	{
		PUL (" >>> MyInternetWriteFile failed.");
		LOG_REQ ("SERVER FAILURE\r\n");
		LOG_REQ_OPEN;
		return FALSE;
	}

	if (FALSE == HttpEndRequest (m_hRequest, NULL, 0, 0))
	{
		PUL (" >>> HttpEndRequest failed.");
		LOG_REQ_ALL;
		LOG_REQ ("\r\n\r\n");
		LOG_RESP_HTTP_HDRS;
		LOG_REQ ("SERVER FAILURE\r\n");
		LOG_REQ_OPEN;
		return FALSE;
	}
#endif

	LOG_REQ_ALL;
	LOG_REQ ("\r\n\r\n");
	LOG_RESP_HTTP_HDRS;

	if (pstrResponse)
	{
		*pstrResponse = "";
		char sz [1025];
		DWORD dw;		
		while (InternetReadFile (m_hRequest, sz, sizeof (sz) - 1, &dw) && dw != 0)
		{
			sz [dw] = 0;
			(*pstrResponse) += sz;
		}
	}

	LOG_REQ_OPEN;
	return TRUE;
}
Exemplo n.º 24
0
BOOL vmsPostRequest::SendMultipart(LPCTSTR ptszServer, LPCTSTR ptszFilePath, std::string *pstrResponse)
{
	Close ();

	USES_CONVERSION;

#ifdef DEBUG_SHOW_SERVER_REQUESTS
	TCHAR tszTmpPath [MAX_PATH];
	GetTempPath (MAX_PATH, tszTmpPath);
	TCHAR tszTmpFile [MAX_PATH];
	_stprintf (tszTmpFile, _T ("%s\\si_serv_req_%d.txt"), tszTmpPath, _c++);
	HANDLE hLog = CreateFile (tszTmpFile, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, 0, NULL);
	DWORD dwLogWritten;
	#define LOG_REQ_BUFFER(buf, size) WriteFile (hLog, buf, size, &dwLogWritten, NULL)
	#define LOG_REQ(s) LOG_REQ_BUFFER (s, strlen (s))
	#define LOG_REQ_OPEN	CloseHandle (hLog); ShellExecute (NULL, "open", tszTmpFile, NULL, NULL, SW_SHOW);
	char szTmp [10000] = ""; DWORD dwTmp = 10000;
	#define LOG_REQ_HTTP_HDRS *szTmp = 0; HttpQueryInfo (m_hRequest, HTTP_QUERY_RAW_HEADERS_CRLF | HTTP_QUERY_FLAG_REQUEST_HEADERS, szTmp, &dwTmp, 0); LOG_REQ (szTmp);
	#define LOG_REQ_DATA_BUFFER LOG_REQ_BUFFER (pbSendData, pbSendDataPos-pbSendData)
	#define LOG_REQ_ALL LOG_REQ_HTTP_HDRS; LOG_REQ_DATA_BUFFER;
	#define LOG_RESP_HTTP_HDRS *szTmp = 0; HttpQueryInfo (m_hRequest, HTTP_QUERY_RAW_HEADERS_CRLF, szTmp, &dwTmp, 0); LOG_REQ (szTmp);
#else
	#define LOG_REQ(s) 
	#define LOG_REQ_OPEN
	#define LOG_REQ_DATA_BUFFER
	#define LOG_REQ_HTTP_HDRS
	#define LOG_RESP_HTTP_HDRS
	#define LOG_REQ_ALL
#endif

	LPBYTE pbSendData = NULL; LPBYTE pbSendDataPos = NULL;
	#define ADD_DATA_TO_SEND(data,len) {memcpy (pbSendDataPos, data, len); pbSendDataPos += len;}
	#define ADD_STRING_TO_SEND(s) ADD_DATA_TO_SEND (s, strlen (s));

	if (m_vParts.size () == 0)
		return FALSE;

	DWORD dwAccessType = INTERNET_OPEN_TYPE_PRECONFIG;
	if (m_pProxyInfo)
		dwAccessType = m_pProxyInfo->tstrAddr.empty () ? INTERNET_OPEN_TYPE_DIRECT : INTERNET_OPEN_TYPE_PROXY;
	m_hInet = InternetOpen (m_tstrUserAgent.c_str (), dwAccessType,
		dwAccessType == INTERNET_OPEN_TYPE_PROXY ? m_pProxyInfo->tstrAddr.c_str () : NULL, NULL, 0);
	if (m_hInet == NULL)
		return FALSE;

	PostInitWinInetHandle (m_hInet);
	
	m_hConnect = InternetConnect (m_hInet, ptszServer, INTERNET_DEFAULT_HTTP_PORT, 
		NULL, NULL, INTERNET_SERVICE_HTTP, 0, NULL);
	if (m_hConnect == NULL)
	{
		LOG_REQ ("SERVER CONNECT FAILURE\r\n");
		LOG_REQ_OPEN;
		return FALSE;
	}
	
	m_hRequest = HttpOpenRequest (m_hConnect, _T ("POST"), ptszFilePath, NULL, NULL, NULL,
		INTERNET_FLAG_NO_CACHE_WRITE | INTERNET_FLAG_KEEP_CONNECTION | INTERNET_FLAG_NO_UI | 
		INTERNET_FLAG_PRAGMA_NOCACHE, 0);
	if (m_hRequest == NULL)
	{
		LOG_REQ ("SERVER OPEN REQUEST FAILURE\r\n");
		LOG_REQ_OPEN;
		return FALSE;
	}

	ApplyProxyAuth (m_hRequest);

	std::string strLabel = "---------------------------284583012225az7";

	TCHAR tszHdr [10000] = _T ("Content-Type: multipart/form-data; boundary=");
	_tcscat (tszHdr, A2CT (strLabel.c_str ()));

	

	INTERNET_BUFFERS buffs;
	ZeroMemory (&buffs, sizeof (buffs));
	buffs.dwStructSize = sizeof (buffs);
	buffs.lpcszHeader = tszHdr;
	buffs.dwHeadersLength = buffs.dwHeadersTotal = _tcslen (tszHdr);
	buffs.dwBufferTotal = strLabel.length () + 4; 

	for (int step = 0; step < 2; step++)
	for (size_t i = 0; i < m_vParts.size (); i++)
	{
		_inc_mpart_item &item = m_vParts [i];

		CHAR sz [10000];
		if (item.strFileName.empty () == false)
		{
			sprintf (sz, "\
--%s\r\n\
Content-Disposition: form-data; name=\"%s\"; filename=\"%s\"\r\n\
Content-Type: application/octet-stream\r\n\r\n",
				strLabel.c_str (), item.strName.c_str (), item.strFileName.c_str ());
		}
		else
		{
Exemplo n.º 25
0
void IINetUtil::GetWebFile(const tchar* Parameters, const tchar* pszServer, const tchar* pszFileName, tint32* OutputLength, tchar** OutputBuffer)
{
    *OutputBuffer = NULL;
    *OutputLength = 0;
    HINTERNET Initialize = NULL;
    HINTERNET Connection = NULL;
    HINTERNET File = NULL;
    //tchar* szFullFileName = NULL;
    try {
        //combine path and filename
        //szFullFileName = new tchar[strlen(INTERFACE_PATH)+strlen((const char *) FileName)+1];
        //sprintf((char *) szFullFileName,"%s%s",INTERFACE_PATH,FileName);
        /*initialize the wininet library*/
        if (NULL == (Initialize = InternetOpen("Koblo INet Engine 1.0", INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, 0)))//INTERNET_FLAG_ASYNC)))
        {
            // Lasse, modified 2007-09-10
            //throw IException::Create(IException::TypeNetwork,
            //	IException::ReasonNetworkCannotOpen,
            //	EXCEPTION_INFO);
            tchar pszMsg[256];
            GetGetLastError(pszMsg);
            throw IException::Create(IException::TypeNetwork,
                                     IException::ReasonNetworkCannotOpen,
                                     EXCEPTION_INFO,
                                     pszMsg);
            // .. Lasse
        }
        //Set timeout
        int timeout = CONNECT_TIMEOUT * 1000;
        // Lasse, modified 2007-09-10 - check for return value
        //InternetSetOption(Initialize, INTERNET_OPTION_CONNECT_TIMEOUT, &timeout, 4);
        if (!InternetSetOption(Initialize, INTERNET_OPTION_CONNECT_TIMEOUT, &timeout, 4)) {
            tchar pszMsg[256];
            GetGetLastError(pszMsg);
            throw IException::Create(IException::TypeNetwork,
                                     IException::ReasonNetworkGeneric,
                                     EXCEPTION_INFO,
                                     pszMsg);
        }

        // Lasse, added 2007-09-10 - context identifier for application
        DWORD dwContext = 0;
        DWORD_PTR pdwContext = (DWORD_PTR)&dwContext;
        // .. Lasse

        /*connect to the server*/
        // Lasse, modified 2007-09-10 - avoid risky NULL pointer read; use context identifier correctly
        //if (NULL == (Connection = InternetConnect(Initialize,WEB_SERVER,INTERNET_DEFAULT_HTTP_PORT,
        //	NULL,NULL,INTERNET_SERVICE_HTTP,0,0)))
        if (NULL == (Connection = InternetConnect(Initialize, pszServer, INTERNET_DEFAULT_HTTP_PORT,
                                  NULL, NULL, INTERNET_SERVICE_HTTP, 0, pdwContext)))
            // .. Lasse
        {
            // Lasse, modified 2007-09-10
            //throw IException::Create(IException::TypeNetwork,
            //	IException::ReasonCouldntConnectToServer,
            //	EXCEPTION_INFO);
            tchar pszMsg[256];
            GetGetLastError(pszMsg);
            throw IException::Create(IException::TypeNetwork,
                                     IException::ReasonCouldntConnectToServer,
                                     EXCEPTION_INFO,
                                     pszMsg);
            // .. Lasse
        }
        /*open up an HTTP request*/
        // Lasse, modified 2007-09-10 - 1: avoid risky NULL pointer read; use context identifier correctly, 2: avoid using cache
        //if (NULL == (File = HttpOpenRequest(Connection,POST_GET("POST","GET"),(const char*) szFullFileName,NULL,NULL,NULL,0,0)))
        //if (NULL == (File = HttpOpenRequest(Connection, POST_GET("POST","GET"), (const char*)szFullFileName, NULL, NULL, NULL, INTERNET_FLAG_NO_CACHE_WRITE|INTERNET_FLAG_RELOAD, pdwContext)))
        if (NULL == (File = HttpOpenRequest(Connection, POST_GET("POST","GET"), (const char*)pszFileName, NULL, NULL, NULL, INTERNET_FLAG_NO_CACHE_WRITE|INTERNET_FLAG_RELOAD, pdwContext)))
            // .. Lasse
        {
            // Lasse, modified 2007-09-10
            //throw IException::Create(IException::TypeNetwork,
            //	IException::ReasonCouldntConnectToAppl,
            //	EXCEPTION_INFO);
            tchar pszMsg[256];
            GetGetLastError(pszMsg);
            throw IException::Create(IException::TypeNetwork,
                                     IException::ReasonCouldntConnectToAppl,
                                     EXCEPTION_INFO,
                                     pszMsg);
            // .. Lasse
        }
        /*Read the file*/
        if(HttpSendRequest(
                    File,
                    POST_GET(POST_CONTENT_TYPE,NULL),
                    POST_GET(strlen(POST_CONTENT_TYPE),0),
                    POST_GET((void*)Parameters,NULL),
                    POST_GET(strlen((const char *) Parameters),0)
                ))
        {
            *OutputBuffer = new tchar[MAX_PAGE_SIZE];
            // Lasse, changed 2007-09-11 - fix for prematurely return before all data have been received
            //InternetReadFile(File,*OutputBuffer,MAX_PAGE_SIZE, (unsigned long *) OutputLength);
            DWORD dwLen = 0;
            *OutputLength = 0;
            tuint32 uiRemainingBuffer = MAX_PAGE_SIZE;
            tchar* pszBuff = *OutputBuffer;
            // This is the correct approach: Read until 0 bytes are received
            do {
                if (!InternetReadFile(File, pszBuff, uiRemainingBuffer, &dwLen)) {
                    // Time-out reading page
                    tchar pszMsg[256];
                    GetGetLastError(pszMsg);
                    throw IException::Create(IException::TypeNetwork,
                                             IException::ReasonNetworkTimeOut,
                                             EXCEPTION_INFO,
                                             pszMsg);
                }
                // Prepare for more data - advance buffer pointer etc.
                pszBuff += dwLen;
                *OutputLength += dwLen;
                uiRemainingBuffer -= dwLen;
            } while (dwLen > 0);
            // .. Lasse
            if (*OutputLength == MAX_PAGE_SIZE) {
                throw IException::Create(IException::TypeNetwork, IException::ReasonPageToLarge, EXCEPTION_INFO);
            }
            (*OutputBuffer)[*OutputLength] = NULL; //zero termination
        } else {
            // Lasse, modified 2007-09-10
            //throw IException::Create(IException::TypeNetwork,
            //	IException::ReasonErrorReadingFromAppl,
            //	EXCEPTION_INFO);
            tchar pszMsg[256];
            GetGetLastError(pszMsg);
            throw IException::Create(IException::TypeNetwork,
                                     IException::ReasonErrorReadingFromAppl,
                                     EXCEPTION_INFO,
                                     pszMsg);
            // .. Lasse
        }
    }
    catch (...) {
        /*close file , terminate server connection and deinitialize the wininet library*/
        if (File != NULL) InternetCloseHandle(File);
        if (Connection != NULL) InternetCloseHandle(Connection);
        if (Initialize != NULL) InternetCloseHandle(Initialize);
        throw;
    }
    if (File != NULL) InternetCloseHandle(File);
    if (Connection != NULL) InternetCloseHandle(Connection);
    if (Initialize != NULL) InternetCloseHandle(Initialize);
}
Exemplo n.º 26
0
void CHttpDownloadDlg::DownloadThread()
{
	ENCODING_INIT;
	//Create the Internet session handle
	ASSERT(m_hInternetSession == NULL);
	m_hInternetSession = ::InternetOpen(AfxGetAppName(), INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, 0);
	if (m_hInternetSession == NULL)
	{
		TRACE(_T("Failed in call to InternetOpen, Error:%d\n"), ::GetLastError());
		HandleThreadErrorWithLastError(GetResString(IDS_HTTPDOWNLOAD_GENERIC_ERROR));
		return;
	}

	//Should we exit the thread
	if (m_bAbort)
	{
		PostMessage(WM_HTTPDOWNLOAD_THREAD_FINISHED);
		return;
	}  

	//Setup the status callback function
	if (::InternetSetStatusCallback(m_hInternetSession, _OnStatusCallBack) == INTERNET_INVALID_STATUS_CALLBACK)
	{
		TRACE(_T("Failed in call to InternetSetStatusCallback, Error:%d\n"), ::GetLastError());
		HandleThreadErrorWithLastError(GetResString(IDS_HTTPDOWNLOAD_GENERIC_ERROR));
		return;
	}

	//Should we exit the thread
	if (m_bAbort)
	{
		PostMessage(WM_HTTPDOWNLOAD_THREAD_FINISHED);
		return;
	}

	//Make the connection to the HTTP server
	ASSERT(m_hHttpConnection == NULL);
	if (m_sUserName.GetLength())
		// Elandal: Assumes sizeof(void*) == sizeof(unsigned long)
		m_hHttpConnection = ::InternetConnect(m_hInternetSession, m_sServer, m_nPort, m_sUserName, 
                                          m_sPassword, m_dwServiceType, 0, (DWORD) this);
	else
		// Elandal: Assumes sizeof(void*) == sizeof(unsigned long)
		m_hHttpConnection = ::InternetConnect(m_hInternetSession, m_sServer, m_nPort, NULL, 
                                          NULL, m_dwServiceType, 0, (DWORD) this);
	if (m_hHttpConnection == NULL)
	{
		TRACE(_T("Failed in call to InternetConnect, Error:%d\n"), ::GetLastError());
		HandleThreadErrorWithLastError(GetResString(IDS_HTTPDOWNLOAD_FAIL_CONNECT_SERVER));
		return;
	}

	//Should we exit the thread
	if (m_bAbort)
	{
		PostMessage(WM_HTTPDOWNLOAD_THREAD_FINISHED);
		return;
	}

	//Start the animation to signify that the download is taking place
	PlayAnimation();

	//Issue the request to read the file
	LPCTSTR ppszAcceptTypes[2];
	ppszAcceptTypes[0] = _T("*/*");  //We support accepting any mime file type since this is a simple download of a file
	ppszAcceptTypes[1] = NULL;
	ASSERT(m_hHttpFile == NULL);
	// Elandal: Assumes sizeof(void*) == sizeof(unsigned long)
	m_hHttpFile = HttpOpenRequest(m_hHttpConnection, NULL, m_sObject, NULL, NULL, ppszAcceptTypes, INTERNET_FLAG_RELOAD | 
								  INTERNET_FLAG_DONT_CACHE | INTERNET_FLAG_KEEP_CONNECTION, (DWORD)this);
	if (m_hHttpFile == NULL)
	{
		TRACE(_T("Failed in call to HttpOpenRequest, Error:%d\n"), ::GetLastError());
		HandleThreadErrorWithLastError(GetResString(IDS_HTTPDOWNLOAD_FAIL_CONNECT_SERVER));
		return;
	}

	//Should we exit the thread
	if (m_bAbort)
	{
		PostMessage(WM_HTTPDOWNLOAD_THREAD_FINISHED);
		return;
	}

	//fill in what encoding we support
	HttpAddRequestHeaders(m_hHttpFile, ACCEPT_ENCODING_HEADER, (DWORD)-1L, HTTP_ADDREQ_FLAG_ADD);

//label used to jump to if we need to resend the request
resend:

	//Issue the request
	BOOL bSend = ::HttpSendRequest(m_hHttpFile, NULL, 0, NULL, 0);
	if (!bSend)
	{
		TRACE(_T("Failed in call to HttpSendRequest, Error:%d\n"), ::GetLastError());
		HandleThreadErrorWithLastError(GetResString(IDS_HTTPDOWNLOAD_FAIL_CONNECT_SERVER));
		return;
	}

	//Check the HTTP status code
	TCHAR szStatusCode[32];
	DWORD dwInfoSize = 32;
	if (!HttpQueryInfo(m_hHttpFile, HTTP_QUERY_STATUS_CODE, szStatusCode, &dwInfoSize, NULL))
	{
		TRACE(_T("Failed in call to HttpQueryInfo for HTTP query status code, Error:%d\n"), ::GetLastError());
		HandleThreadError(GetResString(IDS_HTTPDOWNLOAD_INVALID_SERVER_RESPONSE));
		return;
	}
	else
	{
		long nStatusCode = _ttol(szStatusCode);

		//Handle any authentication errors
		if (nStatusCode == HTTP_STATUS_PROXY_AUTH_REQ || nStatusCode == HTTP_STATUS_DENIED)
		{
			// We have to read all outstanding data on the Internet handle
			// before we can resubmit request. Just discard the data.
			char szData[51];
			DWORD dwSize;
			do
			{
				::InternetReadFile(m_hHttpFile, (LPVOID)szData, 50, &dwSize);
			}
			while (dwSize != 0);

			//Bring up the standard authentication dialog
			if (::InternetErrorDlg(GetSafeHwnd(), m_hHttpFile, ERROR_INTERNET_INCORRECT_PASSWORD, FLAGS_ERROR_UI_FILTER_FOR_ERRORS |
                             FLAGS_ERROR_UI_FLAGS_GENERATE_DATA | FLAGS_ERROR_UI_FLAGS_CHANGE_OPTIONS, NULL) == ERROR_INTERNET_FORCE_RETRY)
				goto resend;
		}
		else if (nStatusCode != HTTP_STATUS_OK)
		{
			TRACE(_T("Failed to retrieve a HTTP 200 status, Status Code:%d\n"), nStatusCode);
			HandleThreadErrorWithLastError(GetResString(IDS_HTTPDOWNLOAD_INVALID_HTTP_RESPONSE), nStatusCode);
			return;
		}
	}

	//Check to see if any encodings are supported
	//  ENCODING_QUERY;
	TCHAR szContentEncoding[32];
	DWORD dwEncodeStringSize = 32;
	if(::HttpQueryInfo(m_hHttpFile, HTTP_QUERY_CONTENT_ENCODING, szContentEncoding, &dwEncodeStringSize, NULL))
	{
		if(!_tcsicmp(szContentEncoding, _T("gzip")) || !_tcsicmp(szContentEncoding, _T("x-gzip")))
			bEncodedWithGZIP = TRUE;
	}

	//Update the status control to reflect that we are getting the file information
	SetStatus(GetResString(IDS_HTTPDOWNLOAD_GETTING_FILE_INFORMATION));

	// Get the length of the file.
	TCHAR szContentLength[32];
	dwInfoSize = 32;
	DWORD dwFileSize = 0;
	BOOL bGotFileSize = FALSE;
	if (::HttpQueryInfo(m_hHttpFile, HTTP_QUERY_CONTENT_LENGTH, szContentLength, &dwInfoSize, NULL))
	{
		//Set the progress control range
		bGotFileSize = TRUE;
		dwFileSize = (DWORD) _ttol(szContentLength);
		SetProgressRange(dwFileSize);
	}

	//Update the status to say that we are now downloading the file
	SetStatus(GetResString(IDS_HTTPDOWNLOAD_RETREIVEING_FILE));

	//Now do the actual read of the file
	DWORD dwStartTicks = ::GetTickCount();
	DWORD dwCurrentTicks = dwStartTicks;
	DWORD dwBytesRead = 0;
	char szReadBuf[1024];
	DWORD dwBytesToRead = 1024;
	DWORD dwTotalBytesRead = 0;
	DWORD dwLastTotalBytes = 0;
	DWORD dwLastPercentage = 0;

	PREPARE_DECODER;
	do
	{
		if (!::InternetReadFile(m_hHttpFile, szReadBuf, dwBytesToRead, &dwBytesRead))
		{
			TRACE(_T("Failed in call to InternetReadFile, Error:%d\n"), ::GetLastError());
			HandleThreadErrorWithLastError(GetResString(IDS_HTTPDOWNLOAD_ERROR_READFILE));
			return;
		}
		else if (dwBytesRead && !m_bAbort)
		{
			//Write the data to file
			TRY
			{
				DECODE_DATA(m_FileToWrite, szReadBuf, dwBytesRead);
			}
			CATCH(CFileException, e);
			{
				TRACE(_T("An exception occured while writing to the download file\n"));
				HandleThreadErrorWithLastError(GetResString(IDS_HTTPDOWNLOAD_ERROR_READFILE), e->m_lOsError);
				e->Delete();
				//clean up any encoding data before we return
				ENCODING_CLEAN_UP;
				return;
			}
			END_CATCH

			//Increment the total number of bytes read
			dwTotalBytesRead += dwBytesRead;  

			UpdateControlsDuringTransfer(dwStartTicks, dwCurrentTicks, dwTotalBytesRead, dwLastTotalBytes, 
                                     dwLastPercentage, bGotFileSize, dwFileSize);
		}
	}
	while (dwBytesRead && !m_bAbort);

	//Delete the file being downloaded to if it is present and the download was aborted
	m_FileToWrite.Close();
	if (m_bAbort)
		::DeleteFile(m_sFileToDownloadInto);

	//clean up any encoding data before we return
	ENCODING_CLEAN_UP;;

	//We're finished
	PostMessage(WM_HTTPDOWNLOAD_THREAD_FINISHED);
}
fsInternetResult fsHttpFile::OpenEx(LPCSTR pszFilePath, UINT64 uStartPos, UINT64 uUploadPartSize, UINT64 uUploadTotalSize)
{
	if (uUploadTotalSize == _UI64_MAX)
		return Open_imp (pszFilePath, uStartPos, 0);

	if (uStartPos + uUploadPartSize > uUploadTotalSize)
		return IR_INVALIDPARAM;

	if (!m_pServer) 
		return IR_NOTINITIALIZED;

	HINTERNET hServer = m_pServer->GetHandle ();  

	if (!hServer)
		return IR_NOTINITIALIZED;

	CloseHandle ();

	if (lstrlen (pszFilePath) > 9000)
		return IR_BADURL;

	fsString strFilePath = pszFilePath;
	fsString strFileName;
	if (m_bUseMultipart)
	{
		LPSTR psz = strrchr (strFilePath, '/');
		if (psz)
		{
			strFileName = psz + 1;
			psz [1] = 0;
		}
		else
			strFileName = pszFilePath;
	}

	LPTSTR ppszAcceptedTypes [2] = { "*/*", NULL }; 

	m_hFile = HttpOpenRequest (hServer, "POST", strFilePath, m_pszHttpVersion,
		NULL, (LPCSTR*)ppszAcceptedTypes, INTERNET_FLAG_NO_CACHE_WRITE | INTERNET_FLAG_KEEP_CONNECTION, 0);

	if (m_hFile == NULL)
		return fsWinInetErrorToIR ();

	fsInternetResult ir = SetupProxy ();
	if (ir != IR_SUCCESS)
	{
		CloseHandle ();
		return ir;
	}

	
	CHAR szHdr [10000] = "";
	
	if (m_bUseMultipart)
		lstrcpy (szHdr, "Content-Type: multipart/form-data; boundary=---------------------------284583012225247");
	else
	{
		lstrcpy (szHdr, "Content-Type: application/x-www-form-urlencoded");
		if (m_strCharset.IsEmpty () == FALSE)
		{
			lstrcat (szHdr, "; charset=");
			lstrcat (szHdr, m_strCharset);
		}
	}

	if (uStartPos || uUploadPartSize != uUploadTotalSize)
	{
		if (*szHdr)
			lstrcat (szHdr, "\r\n");
		sprintf (szHdr + lstrlen (szHdr), "Range: bytes=%I64u-%I64u/%I64u", uStartPos, 
			uStartPos + uUploadPartSize - 1, uUploadTotalSize); 
	}

	if (m_pszCookies)
	{
		if (*szHdr)
			lstrcat (szHdr, "\r\n");
		sprintf (szHdr + lstrlen (szHdr), "Cookie: %s", m_pszCookies); 
	}

	if (m_pszAdditionalHeaders)
	{
		if (*szHdr)
			lstrcat (szHdr, "\r\n");
		lstrcat (szHdr, m_pszAdditionalHeaders);
	}

	
	IgnoreSecurityProblems ();

	int nSizeAdd = 0;
	fsString strMultipartHdr;

	if (m_bUseMultipart)
	{
		m_strLabel = "-----------------------------284583012225247";

		strMultipartHdr = m_strLabel; strMultipartHdr += "\r\n";
		strMultipartHdr += "Content-Disposition: form-data; name=\"uploadFormFile\"; filename=\"";
		strMultipartHdr += strFileName; strMultipartHdr += "\"\r\n";
		strMultipartHdr += "Content-Type: application/octet-stream\r\n\r\n";

		nSizeAdd = strMultipartHdr.GetLength () + m_strLabel.GetLength () + 6;
	}
 
	INTERNET_BUFFERS BufferIn = {0};
	BufferIn.dwStructSize = sizeof (INTERNET_BUFFERS);
	BufferIn.lpcszHeader = szHdr;
	BufferIn.dwHeadersLength = BufferIn.dwHeadersTotal = lstrlen (szHdr);
	BufferIn.dwBufferTotal = (DWORD) (uUploadPartSize + nSizeAdd);

	if (!HttpSendRequestEx (m_hFile, &BufferIn, NULL, HSR_INITIATE, 0))
	{
		ir = fsWinInetErrorToIR ();
		CloseHandle ();
		return  ir; 
	}

	if (m_bUseMultipart)
	{
		DWORD dw;
		if (FALSE == InternetWriteFile (m_hFile, strMultipartHdr, strMultipartHdr.GetLength (), &dw))
		{
			ir = fsWinInetErrorToIR ();
			CloseHandle ();
			return  ir; 
		}
	}

	m_uLeftToUpload = uUploadPartSize;

	return IR_SUCCESS;
}
Exemplo n.º 28
0
int wms_get_file_1(HINTERNET hConnect, LPCSTR pathname, LPCSTR strReferer, LPCSTR tx_saveto)
{
HINTERNET hReq;
DWORD  dwSize, dwCode;
CHAR szData[HTTP_GET_SIZE+1];

//CString strReferer = "http://maps.peterrobins.co.uk/f/m.html";

//strReferer = "http://map.geoportail.lu";

	if ( !(hReq = HttpOpenRequest (hConnect, "GET", pathname, HTTP_VERSION, strReferer, NULL, 0 ,0 ))) {
		ErrorOut (GetLastError(), "HttpOpenRequest");
		return FALSE;
	}


	if (!HttpSendRequest (hReq, NULL, 0, NULL, 0) ) {
		ErrorOut (GetLastError(), "HttpSend");
		return FALSE;
	}

	dwSize = sizeof (DWORD) ;
	if ( !HttpQueryInfo (hReq, HTTP_QUERY_STATUS_CODE | HTTP_QUERY_FLAG_NUMBER, &dwCode, &dwSize, NULL)) {
		ErrorOut (GetLastError(), "HttpQueryInfo");
		return FALSE;
	}

	if ( dwCode == HTTP_STATUS_DENIED || dwCode == HTTP_STATUS_PROXY_AUTH_REQ) {
		// This is a secure page.
		fprintf(stderr, "This page is password protected.\n");
		return FALSE;
	}
	if ( dwCode == 404) {
		fprintf(stderr, "Page not found.\n");
		return FALSE;
	}

	FILE * fp = fopen(tx_saveto, "wb+");
	if (fp == NULL) {
		printf("Couldn't create %s\n", tx_saveto);
		return FALSE;
	}
	long file_len=0;
	while (!abortProgram) {
		if (!InternetReadFile (hReq, (LPVOID)szData, HTTP_GET_SIZE, &dwSize) ) {
			ErrorOut (GetLastError (), "InternetReadFile");
			file_len = -1;
			break;
		}
		if (dwSize == 0)
			break;

		if (fwrite(szData, sizeof(char), dwSize, fp) != dwSize) {
			printf("Error writing %d bytes to %s\n", dwSize, tx_saveto);
			file_len = -1;
			break;
		}
		file_len += dwSize;
//		printf("%d \r", file_len);
	}
	fclose(fp);

	if (!InternetCloseHandle (hReq) ) {
		ErrorOut (GetLastError (), "CloseHandle on hReq");
		file_len = -1;
	}
	if (file_len <= 0)
		return FALSE;

	// Validate PNG
	LPBYTE buffer = (LPBYTE)malloc(file_len+1);
	if (buffer == 0) {
		fprintf(stderr, "Couldn't allocate %d bytes to verify %s\n", file_len, tx_saveto);
		return FALSE;
	}
	memset(buffer, 0, file_len+1);
	fp = fopen(tx_saveto, "rb");
	if (fp == NULL) {
		fprintf(stderr, "Failed to reopen %s\n", tx_saveto);
		free(buffer);
		return FALSE;
	}
	if (fread(buffer, 1, file_len, fp) != file_len) {
		fprintf(stderr, "Error reading %s\n", tx_saveto);
		free(buffer);
		return FALSE;
	}
	fclose(fp);

	unsigned char pnghdr[] = {0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a};
	unsigned char jpghdr[] = {0xFF, 0xD8, 0xFF, 0xE0, 0x00, 0x10, 0x4A, 0x46, 0x49, 0x46};
	unsigned char gifhdr[] = {0x47, 0x49, 0x46, 0x38, 0x39, 0x61};

	if ((memcmp(buffer, pnghdr, sizeof(pnghdr)) == 0)
	||  (memcmp(buffer, jpghdr, sizeof(jpghdr)) == 0)
	||  (memcmp(buffer, gifhdr, sizeof(gifhdr)) == 0)) {
		free(buffer);
		return TRUE;
	} else {
		fprintf(stderr, "Error retrieving %s\n", tx_saveto);
		free(buffer);
		return FALSE;
	}
}
Exemplo n.º 29
0
CHECK_RESULT _UpdWatcher_Check (UPDWATCHER * p)
{
  BOOL bSuccess ;
  CHECK_RESULT nResult = CHECK_UNDEFINED ;

  if( Config_GetInteger(CFGINT_CHECK_FOR_UPDATES) )
    {
      DWORD dwState = INTERNET_CONNECTION_OFFLINE ;
      
      // check if a connection is available
      bSuccess = InternetGetConnectedState (&dwState, 0) ;

      // connection available ?
      if( bSuccess ) 
	{
	  // open session
	  HINTERNET hSession = InternetOpen (TEXT(APPLICATION_NAME), 0, NULL, NULL, 0) ;
	  
	  // session opened ?
	  if( hSession )
	    {
	      // open connection
	      HINTERNET hConnect = InternetConnect (hSession, szServerName, nServerPort,
						    szUsername, szPassword, 
						    INTERNET_SERVICE_HTTP, 0,0) ;
	      
	      // connexion opened ?
	      if( hConnect )
		{
		  // open request
		  HINTERNET hRequest = HttpOpenRequest (hConnect, TEXT("GET"), szObjectName,
							HTTP_VERSION, NULL, NULL, 
							INTERNET_FLAG_RELOAD,0) ;
		  
		  // request opened ?
		  if( hRequest )
		    {  
		      // send request
		      bSuccess = HttpSendRequest (hRequest, NULL, 0, 0, 0) ;
		      
		      // request sent ?
		      if( bSuccess )
			{
			  char	szContent[256] ;
			  DWORD dwContentMax = 256 ;
			  DWORD dwBytesRead ;
			  
			  // read file
			  bSuccess = InternetReadFile (hRequest, szContent,
						       dwContentMax, 
						       &dwBytesRead);
			  
			  // failed to read file ?
			  if( bSuccess )
			    {			      
			      char * szVersion ;
			      
			      szContent[dwBytesRead] = 0 ;	      
			      
			      // look for version string
			      szVersion = strstr (szContent, "<!-- Version: ") ;
			      
			      // failed ?
			      if( szVersion )
				{
				  int nHigh, nMed, nLow ;
				  int nNetVersion, nMyVersion ;

				  szVersion += 14 ;

				  // read net's version
				  sscanf (szVersion, "%d.%d.%d", 
					  &nHigh, &nMed, &nLow) ;
				  nNetVersion = (nHigh*256 + nMed)*256 + nLow ;
				  TRACE_INFO (TEXT("Net version = %d.%d.%d\n"), nHigh, nMed, nLow) ;

				  // save net version
				  wsprintf (p->szNewVersion, TEXT("%d.%d.%d"), nHigh, nMed, nLow) ;
				  
				  // read my version
				  sscanf (APPLICATION_VERSION_STRING, "%d.%d.%d", 
					  &nHigh, &nMed, &nLow) ;			  
				  nMyVersion = (nHigh*256 + nMed)*256 + nLow ;
				  TRACE_INFO  (TEXT("Local version = %d.%d.%d\n"), nHigh, nMed, nLow) ;
				  			
				  // compare versions
				  bSuccess = nNetVersion > nMyVersion ;	      
		      				  
				  nResult = bSuccess ? CHECK_DIFFERENT_VERSION : CHECK_SAME_VERSION ;

				  if( bSuccess )
				    {
				      char *szStartPage, *szEndPage ;
				      
				      // look for page address
				      szStartPage = strstr (szContent, "<!-- Page: ") ;
				      
				      // failed ?
				      if( szStartPage )
					{
					  szStartPage += 11 ;
					  
					  szEndPage = strstr (szStartPage, " -->") ;
					  
					  if( szEndPage )
					    {
					      int nLen = min (szEndPage-szStartPage, MAX_PATH) ;
					      
					      nLen = MultiByteToWideChar (CP_ACP, 0,
									  szStartPage, nLen,
									  p->szDownloadPage, MAX_PATH) ;
					      p->szDownloadPage[nLen] = 0 ;

					      TRACE_INFO (TEXT("Download page = %s\n"), p->szDownloadPage) ;
					    }
					}
				    }
				}
			      else nResult = CHECK_LOOK_FOR_VERSION_FAILED ;
			      
			    }
			  else nResult = CHECK_READ_FILE_FAILED ;
			}
		      else nResult = CHECK_SEND_REQUEST_FAILED ;
		      
		      // close request
		      InternetCloseHandle (hRequest) ;
		    }
		  else nResult = CHECK_OPEN_REQUEST_FAILED ;
		  
		  // close connection
		  InternetCloseHandle (hConnect) ;
		}
	      else nResult = CHECK_OPEN_CONNECT_FAILED ;
	      
	      // close session
	      InternetCloseHandle (hSession) ;
	    }
	  else nResult = CHECK_OPEN_SESSION_FAILED ;
	}
      else nResult = CHECK_NO_CONNECTION ;
    }
  else nResult = CHECK_DISABLED ;
  
  return nResult ;
}
fsInternetResult fsHttpFile::Open_imp(LPCSTR pszFilePath, UINT64 uStartPos, int cTryings)
{
	if (!m_pServer) 
		return IR_NOTINITIALIZED;

	HINTERNET hServer = m_pServer->GetHandle ();  

	if (!hServer)	
		return IR_NOTINITIALIZED;

	CloseHandle ();

	if (lstrlen (pszFilePath) > 9000)
		return IR_BADURL;

	if (cTryings > 1)
		return IR_WININETUNKERROR;

	DWORD dwFlags = m_dwFlags;
	if (m_pszCookies)
		dwFlags |= INTERNET_FLAG_NO_COOKIES;
	if (m_bEnableAutoRedirect == FALSE)
		dwFlags |= INTERNET_FLAG_NO_AUTO_REDIRECT;

	LPTSTR ppszAcceptedTypes [2] = { "*/*", NULL }; 

	
	
	
	

	LPCSTR pszVerb = "GET";
	if (m_pszPostData)
		pszVerb = "POST";
	else if (m_bHeadersOnly)
		pszVerb = "HEAD";

	
	m_hFile = HttpOpenRequest (hServer, pszVerb, pszFilePath, m_pszHttpVersion,
		m_pszReferer, (LPCSTR*) ppszAcceptedTypes, 
		dwFlags | INTERNET_FLAG_RELOAD | INTERNET_FLAG_PRAGMA_NOCACHE | 
		INTERNET_FLAG_NO_CACHE_WRITE, NULL);

	if (m_hFile == NULL)
		return fsWinInetErrorToIR ();

	fsInternetResult ir = SetupProxy ();
	if (ir != IR_SUCCESS)
	{
		CloseHandle ();
		return ir;
	}

	
	CHAR szHdr [20000] = "";

	if (uStartPos)
		sprintf (szHdr, "Range: bytes=%I64u-\r\n", uStartPos); 

	if (m_pszCookies)
		sprintf (szHdr + lstrlen (szHdr), "Cookie: %s\r\n", m_pszCookies); 

	if (m_pszPostData)
		strcat (szHdr, "Content-Type: application/x-www-form-urlencoded\r\n");

	if (m_pszAdditionalHeaders)
		strcat (szHdr, m_pszAdditionalHeaders);

	if (cTryings == 0)
	{
		
		char szReq [90000];
		sprintf (szReq, "%s %s %s\r\nReferer: %s", pszVerb, 
			pszFilePath, m_pszHttpVersion, 
			m_pszReferer ? m_pszReferer : "-");

		if (*szHdr)
		{
			strcat (szReq, "\r\n");
			strcat (szReq, szHdr);
			szReq [strlen (szReq) - 2] = 0;	
		}

		if ((dwFlags & INTERNET_FLAG_NO_COOKIES) == 0)
		{
			char szUrl [10000]; DWORD dw = sizeof (szUrl);
			fsURL url;
			url.Create (m_dwFlags & INTERNET_FLAG_SECURE ? INTERNET_SCHEME_HTTPS : INTERNET_SCHEME_HTTP,
				m_pServer->GetServerName (), m_pServer->GetServerPort (), 
				NULL, NULL, pszFilePath, szUrl, &dw);

			char szCookie [10000]; dw = sizeof (szCookie);
			*szCookie = 0;
			
			InternetGetCookie (szUrl, NULL, szCookie, &dw);

			if (*szCookie)
			{
				strcat (szReq, "\r\n");
				strcat (szReq, "Cookie: ");
				strcat (szReq, szCookie);
			}
		}

		strcat (szReq, "\r\nHost: ");
		strcat (szReq, m_pServer->GetServerName ());

		if (m_pszPostData)
		{
			strcat (szReq, "\r\n");
			strcat (szReq, m_pszPostData);
		}

		Dialog (IFDD_TOSERVER, szReq);	
	}

	
	IgnoreSecurityProblems ();

	
	if (!HttpSendRequest (m_hFile, *szHdr ? szHdr : NULL, (UINT)-1, 
			m_pszPostData, m_pszPostData ? lstrlen (m_pszPostData) : 0))
	{
		ir = fsWinInetErrorToIR ();

		DialogHttpResponse (m_hFile);	
									
		CloseHandle ();
		return  ir; 
	}

	char szResp [10000];
	DWORD dwRespLen = sizeof (szResp), dwIndex = 0;
	
	
	if (HttpQueryInfo (m_hFile, HTTP_QUERY_RAW_HEADERS_CRLF, szResp, &dwRespLen, &dwIndex))
	{
		int cLines = 0; 

		

		LPCSTR pszLine = szResp;
		while (pszLine)
		{
			pszLine = strchr (pszLine, '\n');
			if (pszLine)
			{
				while (*pszLine == '\r' || *pszLine == '\n')
					pszLine++;
				cLines++;
			}
		}

		if (cLines == 0 || cLines == 1)
		{
			
			
			return Open_imp (pszFilePath, uStartPos, ++cTryings);
		}
	}

	DialogHttpResponse (m_hFile);	

	DWORD dwStatusCode;	
	DWORD dwSize = sizeof (DWORD);
	if (!HttpQueryInfo(m_hFile, HTTP_QUERY_STATUS_CODE|HTTP_QUERY_FLAG_NUMBER, 
			&dwStatusCode, &dwSize, NULL))	
		return fsWinInetErrorToIR ();

	if (dwStatusCode < 200 || dwStatusCode >= 300)	
	{
		ir = fsHttpStatusCodeToIR (dwStatusCode);

		if (ir == IR_NEEDREDIRECT)	
		{
			DWORD dwNeedLen = 0;

			HttpQueryInfo (m_hFile, HTTP_QUERY_LOCATION, NULL, &dwNeedLen,
				NULL);

			if (::GetLastError () == ERROR_INSUFFICIENT_BUFFER)
			{
				SAFE_DELETE_ARRAY (m_pszLastError);
				try {
					m_pszLastError = new char [++dwNeedLen];
				}catch (...) {return IR_OUTOFMEMORY;}
				if (m_pszLastError == NULL)
					return IR_OUTOFMEMORY;
				if (!HttpQueryInfo (m_hFile, HTTP_QUERY_LOCATION, m_pszLastError, &dwNeedLen,
						NULL)) 
					return IR_SERVERUNKERROR;
			}
			else
				return IR_SERVERUNKERROR;

		}

		return ir;
	}

	
	char szContLen [1000];
	DWORD dwLen = sizeof (szContLen);
	if (HttpQueryInfo (m_hFile, HTTP_QUERY_CONTENT_LENGTH,	szContLen, &dwLen, NULL)) {
		__int64 iSize = _atoi64 (szContLen);
		if (iSize < 0)
			return IR_SERVERUNKERROR;
		m_uFileSize = (UINT64) iSize;
	}
	else
		m_uFileSize = _UI64_MAX; 

	ir = IR_SUCCESS;
	if (uStartPos)
	{
		
		ir = ProcessRangesResponse ();
		if (ir == IR_RANGESNOTAVAIL) 
			return ir;
	}
	else
	{
		CHAR sz [10000];
		DWORD dw = sizeof (sz);
		
		
		if (HttpQueryInfo (m_hFile, HTTP_QUERY_ACCEPT_RANGES, sz, &dw, NULL))
		{
			if (stricmp (sz, "bytes") == 0)
				m_enRST = RST_PRESENT;
			else
				m_enRST = RST_NONE;
		}
		else
			m_enRST = RST_UNKNOWN;
	}

	m_bContentTypeValid = FALSE;
	m_bDateValid = FALSE;

	CHAR szContentType [10000];	
	DWORD dwCL = sizeof (szContentType);
	if (HttpQueryInfo (m_hFile, HTTP_QUERY_CONTENT_TYPE, szContentType, &dwCL, NULL))
	{
		m_strContentType = szContentType;
		m_bContentTypeValid = TRUE;
	}

	SYSTEMTIME time; 
	DWORD dwTL = sizeof (time);
	if (HttpQueryInfo (m_hFile, HTTP_QUERY_LAST_MODIFIED | HTTP_QUERY_FLAG_SYSTEMTIME,
		&time, &dwTL, NULL))
	{
		SystemTimeToFileTime (&time, &m_date);
		m_bDateValid = TRUE;
	}

	RetreiveSuggFileName ();	

	return ir;
}