int UpStatusFb(string paramId, string paramMessage, string paramToken) { HINTERNET hopen, hconnect, hrequest; string accesstoken = paramToken; int n = accesstoken.size(); string version = "/v2.1"; string id = paramId; string edge ="/comments"; char chUrlRequset [400]; string urlRequest = version+"/"+id+edge+"?"+accesstoken; String2Char(urlRequest,chUrlRequset); char headers[]="Content-Type: application/x-www-form-urlencoded"; char formdata[300]; String2Char("message="+paramMessage,formdata); hopen = InternetOpenA("HTTPGET",INTERNET_OPEN_TYPE_DIRECT,NULL,NULL,0); hconnect = InternetConnectA(hopen,GRAPH_FB,INTERNET_DEFAULT_HTTPS_PORT,NULL,NULL,INTERNET_SERVICE_HTTP,0,0); hrequest= HttpOpenRequestA(hconnect,"POST",chUrlRequset,"HTTP/1.1",NULL, NULL,INTERNET_FLAG_SECURE , 0); if(HttpSendRequestA(hrequest,headers,strlen(headers),formdata,strlen(formdata))) { //printf("Success\n"); } InternetCloseHandle(hrequest); InternetCloseHandle(hconnect); InternetCloseHandle(hopen); return 1; }
BOOL GetInterNetURLText(CHAR *lpcInterNetURL,CHAR *lpwzReadData) { HINTERNET hSession; HINTERNET hRequest; BOOL bResult = FALSE; DWORD dwBytesRead; CHAR lpwzUserAgent[256]; memset(lpwzUserAgent,0,sizeof(lpwzUserAgent)); QueryUserAgent(HKEY_CURRENT_USER,"Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings","User Agent",lpwzUserAgent); //QueryUserAgent(lpwzUserAgent); //MessageBoxA(0,lpwzUserAgent,0,0); hSession = InternetOpenA(lpwzUserAgent, INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, 0); if (hSession != NULL) { //MessageBoxA(0,"InternetOpenA",0,0); hRequest = InternetOpenUrlA(hSession, lpcInterNetURL, NULL, 0, INTERNET_FLAG_RELOAD, 0); if (hRequest != NULL) { //MessageBoxA(0,"InternetOpenUrlA",0,0); if (InternetReadFile(hRequest, lpwzReadData,256, &dwBytesRead)) { //MessageBoxA(0,lpwzReadData,0,0); bResult = TRUE; } InternetCloseHandle(hRequest); } InternetCloseHandle(hSession); } return bResult; }
int main(void) { LPDWORD connectionDescription; if(InternetGetConnectedState(connectionDescription,0) == 1) { DWORD dwAccessType = INTERNET_OPEN_TYPE_DIRECT; HINTERNET hINet = InternetOpenA("User-Agent: Internet Explorer 8/Josh", dwAccessType, NULL,NULL,0); if(hINet) { int i = 0; while(InternetOpenUrlA(hINet, "http://urinfected.local", NULL, 0, INTERNET_FLAG_RELOAD | INTERNET_FLAG_PRAGMA_NOCACHE | INTERNET_FLAG_NO_CACHE_WRITE, 0) == 0 && i < 10) { puts("Failed to connect...."); i++; } }else { puts("No joy!"); } } else { puts("You gotz no internetz!!!"); } return 0; }
int GTHTTP_init(const char *user_agent, int init_winsock) { int res = GT_UNKNOWN_ERROR; char agent[120]; if (init_count++ > 0) { /* Nothing to do: already initialized. */ return GT_OK; } if (user_agent == NULL) { _snprintf(agent, sizeof(agent), "C SDK/%08x", GTHTTP_VERSION); } else { _snprintf(agent, sizeof(agent), "%s; C SDK/%08x", user_agent, GTHTTP_VERSION); } agent[sizeof(agent) - 1] = 0; session_handle = InternetOpenA(agent, INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, 0); if (session_handle == NULL) { res = map_impl(GetLastError()); goto cleanup; } res = GT_OK; cleanup: return res; }
bool TestWininet(std::string url){ HINTERNET hNet = InternetOpenA(NULL, INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, 0); if (hNet == NULL) { std::cout << "InternetOpenA error :" << ::GetLastError() << std::endl; return false; } // 默认TIMEOUT时间2秒 static DWORD dwTimeout = 2000; static DWORD dwRetries = 3; InternetSetOptionA(hNet, INTERNET_OPTION_CONNECT_TIMEOUT, &dwTimeout, sizeof(DWORD)); InternetSetOptionA(hNet, INTERNET_OPTION_CONNECT_RETRIES, &dwRetries, sizeof(DWORD)); HINTERNET hUrlFile = InternetOpenUrlA(hNet, url.c_str(), NULL, 0, INTERNET_FLAG_NO_CACHE_WRITE | INTERNET_FLAG_RELOAD, 0); if (hUrlFile == NULL) { std::cout << url << "InternetOpenUrlA error :" << ::GetLastError() << std::endl; InternetCloseHandle(hNet); return false; } InternetCloseHandle(hUrlFile); InternetCloseHandle(hNet) ; return true; }
int InternetDownloadFile(char *URL, char *FileDest) { DWORD dwFlags; DWORD dwResult = INTERNET_ERROR_OPEN; InternetGetConnectedState(&dwFlags, 0); CHAR strAgent[64]; sprintf(strAgent, "Agent%ld", timeGetTime()); HINTERNET hOpen; if(!(dwFlags & INTERNET_CONNECTION_PROXY)) hOpen = InternetOpenA(strAgent, INTERNET_OPEN_TYPE_PRECONFIG_WITH_NO_AUTOPROXY, NULL, NULL, 0); else hOpen = InternetOpenA(strAgent, INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, 0); if(hOpen) { dwResult = InternetGetFile(hOpen, URL, FileDest); InternetCloseHandle(hOpen); } else return INTERNET_ERROR_OPEN; return dwResult; }
int net_get_url(char * url, char * buf, int bufSize) { char * ua = "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:11.0) Gecko/20100101 Firefox/11.0"; HINTERNET hUrl = NULL; int rc = 0; DWORD recvBytes = 0; unsigned long dwCust = 0; HINTERNET hInet = InternetOpenA(ua, INTERNET_OPEN_TYPE_DIRECT, NULL, NULL, 0); if (hInet == NULL) { debug_log(LOG_ERR, "net_get_url(): failed to open Internet handle, rc: %d", WSAGetLastError()); return SOCK_IO_ERROR; } hUrl = InternetOpenUrl(hInet, url, NULL,0,INTERNET_FLAG_HYPERLINK, dwCust); if (hUrl == NULL) { debug_log(LOG_ERR, "net_get_url(): failed to open Url handle, rc: %d", WSAGetLastError()); InternetCloseHandle(hInet); return SOCK_IO_ERROR; } memset(buf, 0, bufSize); rc = InternetReadFile(hUrl, buf, bufSize, &recvBytes); if (rc == FALSE) { debug_log(LOG_ERR, "net_get_url(): failed InternetReadFile() rc: %d", WSAGetLastError()); InternetCloseHandle(hUrl); InternetCloseHandle(hInet); return SOCK_IO_ERROR; } if (InternetCloseHandle(hUrl) == FALSE) { debug_log(LOG_ERR, "net_get_url(): failed to close hUrl handle, rc: %d", WSAGetLastError()); return SOCK_IO_ERROR; } if (InternetCloseHandle(hInet) == FALSE) { debug_log(LOG_ERR, "net_get_url(): failed to close hInet handle, rc: %d", WSAGetLastError()); InternetCloseHandle(hUrl); return SOCK_IO_ERROR; } return SOCK_NO_ERROR; } // end of net_get_url()
int KSI_HttpClientImpl_init(KSI_HttpClient *client) { KSI_HttpClient *http = (KSI_HttpClient *)client; HINTERNET internet_handle; ULONG buf; KSI_CTX *ctx = NULL; int res; if (client == NULL) { res = KSI_INVALID_ARGUMENT; goto cleanup; } ctx = client->parent.ctx; KSI_ERR_clearErrors(ctx); //Initializes an application's use of the Win32 Internet functions. internet_handle = InternetOpenA(http->agentName, INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, 0); if (internet_handle == NULL) { WININET_ERROR(ctx, GetLastError(), KSI_NETWORK_ERROR, "WinINet: Unable to init."); } /* By default WinINet allows just two simultaneous connections to one server. */ buf = 1024; res = InternetSetOption(NULL, INTERNET_OPTION_MAX_CONNS_PER_SERVER, &buf, sizeof(buf)); if (res != TRUE) { WININET_ERROR(ctx, GetLastError(), KSI_UNKNOWN_ERROR, "WinINet: Unable to init."); } res = InternetSetOption(NULL, INTERNET_OPTION_MAX_CONNS_PER_1_0_SERVER, &buf, sizeof(buf)); if (res != TRUE) { WININET_ERROR(ctx, GetLastError(), KSI_UNKNOWN_ERROR, "WinINet: Unable to init."); } http->implCtx = internet_handle; http->implCtx_free = implCtx_free; internet_handle = NULL; http->sendRequest = wininetSendRequest; res = KSI_OK; cleanup: if (internet_handle) InternetCloseHandle(internet_handle); return res; }
/* initialize private data */ static BOOL wininet_init( struct soap * soap, struct wininet_data * a_pData, DWORD a_dwRequestFlags ) { DBGLOG(TEST, SOAP_MESSAGE(fdebug, "wininet %p: init private data\n", soap )); memset( a_pData, 0, sizeof(struct wininet_data) ); a_pData->dwRequestFlags = a_dwRequestFlags; /* start our internet session */ a_pData->hInternet = InternetOpenA( "gSOAP", INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, 0 ); if ( !a_pData->hInternet ) { soap->error = GetLastError(); DBGLOG(TEST, SOAP_MESSAGE(fdebug, "wininet %p: init, error %d (%s) in InternetOpen\n", soap, soap->error, wininet_error_message(soap,soap->error) )); wininet_free_error_message( a_pData ); return FALSE; } /* set the timeouts, if any of these fail the error isn't fatal */ wininet_set_timeout( soap, a_pData, "connect", INTERNET_OPTION_CONNECT_TIMEOUT, soap->connect_timeout ); wininet_set_timeout( soap, a_pData, "receive", INTERNET_OPTION_RECEIVE_TIMEOUT, soap->recv_timeout ); wininet_set_timeout( soap, a_pData, "send", INTERNET_OPTION_SEND_TIMEOUT, soap->send_timeout ); /* set up the callback function so we get notifications */ InternetSetStatusCallback( a_pData->hInternet, wininet_callback ); /* set all of our callbacks */ soap->fopen = wininet_connect; soap->fposthdr = wininet_post_header; soap->fsend = wininet_fsend; soap->frecv = wininet_frecv; soap->fclose = wininet_disconnect; return TRUE; }
// Connect to server bool FtpClient::connect(const string & url, const string & username, const string & password) { // Close current connection if (mConnected) close(); // Get a handle on the Internet mInternetHnd = InternetOpenA("FtpClient", INTERNET_OPEN_TYPE_DIRECT, NULL, NULL, 0); if (mInternetHnd == NULL) { // Report error and break OutputDebugStringA("Unable to connect to Internet:\n"); showError(); return false; } // Establish FTP connection mFtpHnd = InternetConnectA(mInternetHnd, url.c_str(), INTERNET_DEFAULT_FTP_PORT, username.c_str(), password.c_str(), INTERNET_SERVICE_FTP, INTERNET_FLAG_EXISTING_CONNECT | INTERNET_FLAG_PASSIVE, 0x00000000); if (mFtpHnd == NULL) { // Report error, close, and break OutputDebugStringA("Unable to connect to FTP server:\n"); showError(); close(); return false; } // Set connection flag mConnected = true; OutputDebugStringA("FTP connection established\n"); // Return to stop thread return true; }
bool HttpSnaffle::Open(const std::string& userAgent, const std::string& serverName, int port) { CloseHandles(); myServerName = serverName; myUserAgent = userAgent; myInet = InternetOpenA(userAgent.c_str(), INTERNET_OPEN_TYPE_PRECONFIG, "", "", 0); if (myInet == NULL) return false; myServerConnection = InternetConnectA(myInet, serverName.c_str(), port, "", "", INTERNET_SERVICE_HTTP, 0, myContext); if (myServerConnection == NULL) return false; return true; }
void CheckNewVersion () #endif { HINTERNET iInternetHandle = InternetOpenA ("wininet-agent/1.0", INTERNET_OPEN_TYPE_DIRECT, NULL, NULL, 0); receiveBuffer.Clear(); if (iInternetHandle) { HINTERNET iInternetFile = InternetOpenUrlA (iInternetHandle, VERSION_URL, NULL, 0, INTERNET_FLAG_RESYNCHRONIZE, INTERNET_NO_CALLBACK); if (iInternetFile) { // Start writing the file DWORD numBytesRead = 0; char buf[READ_BYTES_SIZE]; while (true) { buf[0] = 0; bool Passed = (!!InternetReadFile (iInternetFile, &buf, READ_BYTES_SIZE, &numBytesRead)); if (!Passed || Passed && ((numBytesRead == 0) || numBytesRead < READ_BYTES_SIZE)) break; receiveBuffer += buf; } InternetCloseHandle (iInternetFile); } InternetCloseHandle (iInternetHandle); } VersionCheckReady = true; return 0; }
static DWORD WINAPI threadProc(void* p_param) { HINTERNET inet = InternetOpenA("Scherfgen-Software Blocks 5", INTERNET_OPEN_TYPE_PRECONFIG, 0, 0, 0); if(!inet) return 1; HINTERNET url = InternetOpenUrlA(inet, "http://www.scherfgen-software.net/blocks5/version.txt", 0, 0, INTERNET_FLAG_RELOAD, 0); if(!url) { InternetCloseHandle(inet); return 1; } char buffer[17] = {0}; DWORD numBytesRead = 0; if(!InternetReadFile(url, buffer, 16, &numBytesRead)) { InternetCloseHandle(url); InternetCloseHandle(inet); return 1; } buffer[numBytesRead] = 0; if(numBytesRead == 16) buffer[0] = 0; InternetCloseHandle(url); InternetCloseHandle(inet); Task& task = *reinterpret_cast<Task*>(p_param); task.currentVersion = buffer; task.finished = true; return 0; }
/* * Download a file from an URL * Mostly taken from http://support.microsoft.com/kb/234913 * If hProgressDialog is not NULL, this function will send INIT and EXIT messages * to the dialog in question, with WPARAM being set to nonzero for EXIT on success * and also attempt to indicate progress using an IDC_PROGRESS control */ BOOL DownloadFile(const char* url, const char* file, HWND hProgressDialog) { HWND hProgressBar = NULL; BOOL r = FALSE; DWORD dwFlags, dwSize, dwDownloaded, dwTotalSize, dwStatus; FILE* fd = NULL; LONG progress_style; unsigned char buf[DOWNLOAD_BUFFER_SIZE]; char agent[64], hostname[64], urlpath[128]; HINTERNET hSession = NULL, hConnection = NULL, hRequest = NULL; URL_COMPONENTSA UrlParts = {sizeof(URL_COMPONENTSA), NULL, 1, (INTERNET_SCHEME)0, hostname, sizeof(hostname), 0, NULL, 1, urlpath, sizeof(urlpath), NULL, 1}; int i; char msg[MAX_PATH]; if (hProgressDialog != NULL) { // Use the progress control provided, if any hProgressBar = GetDlgItem(hProgressDialog, IDC_PROGRESS); if (hProgressBar != NULL) { progress_style = GetWindowLong(hProgressBar, GWL_STYLE); SetWindowLong(hProgressBar, GWL_STYLE, progress_style & (~PBS_MARQUEE)); SendMessage(hProgressBar, PBM_SETPOS, 0, 0); } SendMessage(hProgressDialog, UM_DOWNLOAD_INIT, 0, 0); } safe_sprintf(msg, sizeof(msg), "Downloading %s: Connecting...", file); print_status(0, FALSE, msg); dprintf("Downloading %s from %s\n", file, url); if ( (!InternetCrackUrlA(url, (DWORD)safe_strlen(url), 0, &UrlParts)) || (UrlParts.lpszHostName == NULL) || (UrlParts.lpszUrlPath == NULL)) { dprintf("Unable to decode URL: %s\n", WindowsErrorString()); goto out; } hostname[sizeof(hostname)-1] = 0; // Open an Internet session for (i=5; (i>0) && (!InternetGetConnectedState(&dwFlags, 0)); i--) { Sleep(1000); } if (i <= 0) { // http://msdn.microsoft.com/en-us/library/windows/desktop/aa384702.aspx is wrong... SetLastError(ERROR_INTERNET_NOT_INITIALIZED); dprintf("Network is unavailable: %s\n", WinInetErrorString()); goto out; } safe_sprintf(agent, ARRAYSIZE(agent), APPLICATION_NAME "/%d.%d.%d (Windows NT %d.%d%s)", application_version[0], application_version[1], application_version[2], nWindowsVersion >> 4, nWindowsVersion & 0x0F, is_x64() ? "; WOW64" : ""); hSession = InternetOpenA(agent, INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, 0); if (hSession == NULL) { dprintf("Could not open internet session: %s\n", WinInetErrorString()); goto out; } hConnection = InternetConnectA(hSession, UrlParts.lpszHostName, UrlParts.nPort, NULL, NULL, INTERNET_SERVICE_HTTP, 0, (DWORD_PTR)NULL); if (hConnection == NULL) { dprintf("Could not connect to server %s:%d: %s\n", UrlParts.lpszHostName, UrlParts.nPort, WinInetErrorString()); goto out; } hRequest = HttpOpenRequestA(hConnection, "GET", UrlParts.lpszUrlPath, NULL, NULL, (const char**)"*/*\0", INTERNET_FLAG_HYPERLINK|INTERNET_FLAG_IGNORE_REDIRECT_TO_HTTP|INTERNET_FLAG_IGNORE_REDIRECT_TO_HTTPS|INTERNET_FLAG_NO_COOKIES| INTERNET_FLAG_NO_UI|INTERNET_FLAG_NO_CACHE_WRITE, (DWORD_PTR)NULL); if (hRequest == NULL) { dprintf("Could not open url %s: %s\n", url, WindowsErrorString()); goto out; } if (!HttpSendRequestA(hRequest, NULL, 0, NULL, 0)) { dprintf("Unable to send request: %s\n", WinInetErrorString()); goto out; } // Get the file size dwSize = sizeof(dwStatus); dwStatus = 404; HttpQueryInfoA(hRequest, HTTP_QUERY_STATUS_CODE|HTTP_QUERY_FLAG_NUMBER, (LPVOID)&dwStatus, &dwSize, NULL); if (dwStatus != 200) { download_error = ERROR_SEVERITY_ERROR|ERROR_INTERNET_ITEM_NOT_FOUND; dprintf("Unable to access file: Server status %d\n", dwStatus); goto out; } dwSize = sizeof(dwTotalSize); if (!HttpQueryInfoA(hRequest, HTTP_QUERY_CONTENT_LENGTH|HTTP_QUERY_FLAG_NUMBER, (LPVOID)&dwTotalSize, &dwSize, NULL)) { dprintf("Unable to retrieve file length: %s\n", WinInetErrorString()); goto out; } dprintf("File length: %d bytes\n", dwTotalSize); fd = fopenU(file, "wb"); if (fd == NULL) { dprintf("Unable to create file '%s': %s\n", file, WinInetErrorString()); goto out; } // Keep checking for data until there is nothing left. dwSize = 0; while (1) { if (download_error) goto out; if (!InternetReadFile(hRequest, buf, sizeof(buf), &dwDownloaded) || (dwDownloaded == 0)) break; dwSize += dwDownloaded; SendMessage(hProgressBar, PBM_SETPOS, (WPARAM)(MAX_PROGRESS*((1.0f*dwSize)/(1.0f*dwTotalSize))), 0); safe_sprintf(msg, sizeof(msg), "Downloading: %0.1f%%", (100.0f*dwSize)/(1.0f*dwTotalSize)); print_status(0, FALSE, msg); if (fwrite(buf, 1, dwDownloaded, fd) != dwDownloaded) { dprintf("Error writing file '%s': %s\n", file, WinInetErrorString()); goto out; } } if (dwSize != dwTotalSize) { dprintf("Could not download complete file - read: %d bytes, expected: %d bytes\n", dwSize, dwTotalSize); download_error = ERROR_WRITE_FAULT; goto out; } else { r = TRUE; dprintf("Successfully downloaded '%s'\n", file); } out: if (hProgressDialog != NULL) SendMessage(hProgressDialog, UM_DOWNLOAD_EXIT, (WPARAM)r, 0); if (fd != NULL) fclose(fd); if (!r) { _unlink(file); print_status(0, FALSE, "Failed to download file."); SetLastError(download_error); MessageBoxU(hMain, WinInetErrorString(), "File download", MB_OK|MB_ICONERROR); } if (hRequest) InternetCloseHandle(hRequest); if (hConnection) InternetCloseHandle(hConnection); if (hSession) InternetCloseHandle(hSession); return r; }
/* * Download a file from an URL * Mostly taken from http://support.microsoft.com/kb/234913 * If hProgressDialog is not NULL, this function will send INIT and EXIT messages * to the dialog in question, with WPARAM being set to nonzero for EXIT on success * and also attempt to indicate progress using an IDC_PROGRESS control */ DWORD DownloadFile(const char* url, const char* file, HWND hProgressDialog) { HWND hProgressBar = NULL; BOOL r = FALSE; LONG progress_style; DWORD dwFlags, dwSize, dwWritten, dwDownloaded, dwTotalSize; DWORD DownloadStatus; HANDLE hFile = INVALID_HANDLE_VALUE; const char* accept_types[] = {"*/*\0", NULL}; unsigned char buf[DOWNLOAD_BUFFER_SIZE]; char agent[64], hostname[64], urlpath[128], msg[MAX_PATH]; HINTERNET hSession = NULL, hConnection = NULL, hRequest = NULL; URL_COMPONENTSA UrlParts = {sizeof(URL_COMPONENTSA), NULL, 1, (INTERNET_SCHEME)0, hostname, sizeof(hostname), 0, NULL, 1, urlpath, sizeof(urlpath), NULL, 1}; size_t last_slash; int i; DownloadStatus = 404; if (hProgressDialog != NULL) { // Use the progress control provided, if any hProgressBar = GetDlgItem(hProgressDialog, IDC_PROGRESS); if (hProgressBar != NULL) { progress_style = GetWindowLong(hProgressBar, GWL_STYLE); SetWindowLong(hProgressBar, GWL_STYLE, progress_style & (~PBS_MARQUEE)); SendMessage(hProgressBar, PBM_SETPOS, 0, 0); } SendMessage(hProgressDialog, UM_DOWNLOAD_INIT, 0, 0); } if (file == NULL) goto out; for (last_slash = safe_strlen(file); last_slash != 0; last_slash--) { if ((file[last_slash] == '/') || (file[last_slash] == '\\')) { last_slash++; break; } } static_sprintf(msg, "Downloading %s: Connecting...", file); print_status(0, FALSE, msg); dprintf("Downloading %s from %s\n", file, url); if ( (!InternetCrackUrlA(url, (DWORD)safe_strlen(url), 0, &UrlParts)) || (UrlParts.lpszHostName == NULL) || (UrlParts.lpszUrlPath == NULL)) { dprintf("Unable to decode URL: %s\n", WinInetErrorString()); goto out; } hostname[sizeof(hostname)-1] = 0; // Open an Internet session for (i=5; (i>0) && (!InternetGetConnectedState(&dwFlags, 0)); i--) { Sleep(1000); } if (i <= 0) { // http://msdn.microsoft.com/en-us/library/windows/desktop/aa384702.aspx is wrong... SetLastError(ERROR_INTERNET_NOT_INITIALIZED); dprintf("Network is unavailable: %s\n", WinInetErrorString()); goto out; } static_sprintf(agent, APPLICATION_NAME "/%d.%d.%d (Windows NT %d.%d%s)", application_version[0], application_version[1], application_version[2], nWindowsVersion>>4, nWindowsVersion&0x0F, is_x64()?"; WOW64":""); hSession = InternetOpenA(agent, INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, 0); if (hSession == NULL) { dprintf("Could not open Internet session: %s\n", WinInetErrorString()); goto out; } hConnection = InternetConnectA(hSession, UrlParts.lpszHostName, UrlParts.nPort, NULL, NULL, INTERNET_SERVICE_HTTP, 0, (DWORD_PTR)NULL); if (hConnection == NULL) { dprintf("Could not connect to server %s:%d: %s\n", UrlParts.lpszHostName, UrlParts.nPort, WinInetErrorString()); goto out; } hRequest = HttpOpenRequestA(hConnection, "GET", UrlParts.lpszUrlPath, NULL, NULL, accept_types, INTERNET_FLAG_IGNORE_REDIRECT_TO_HTTP|INTERNET_FLAG_IGNORE_REDIRECT_TO_HTTPS| INTERNET_FLAG_NO_COOKIES|INTERNET_FLAG_NO_UI|INTERNET_FLAG_NO_CACHE_WRITE|INTERNET_FLAG_HYPERLINK| ((UrlParts.nScheme==INTERNET_SCHEME_HTTPS)?INTERNET_FLAG_SECURE:0), (DWORD_PTR)NULL); if (hRequest == NULL) { dprintf("Could not open URL %s: %s\n", url, WinInetErrorString()); goto out; } if (!HttpSendRequestA(hRequest, NULL, 0, NULL, 0)) { dprintf("Unable to send request: %s\n", WinInetErrorString()); goto out; } // Get the file size dwSize = sizeof(DownloadStatus); HttpQueryInfoA(hRequest, HTTP_QUERY_STATUS_CODE|HTTP_QUERY_FLAG_NUMBER, (LPVOID)&DownloadStatus, &dwSize, NULL); if (DownloadStatus != 200) { error_code = ERROR_SEVERITY_ERROR|ERROR_INTERNET_ITEM_NOT_FOUND; dprintf("Unable to access file: %d\n", DownloadStatus); goto out; } dwSize = sizeof(dwTotalSize); if (!HttpQueryInfoA(hRequest, HTTP_QUERY_CONTENT_LENGTH|HTTP_QUERY_FLAG_NUMBER, (LPVOID)&dwTotalSize, &dwSize, NULL)) { dprintf("Unable to retrieve file length: %s\n", WinInetErrorString()); goto out; } dprintf("File length: %d bytes\n", dwTotalSize); hFile = CreateFileU(file, GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); if (hFile == INVALID_HANDLE_VALUE) { dprintf("Unable to create file '%s': %s\n", &file[last_slash], WinInetErrorString()); goto out; } // Keep checking for data until there is nothing left. dwSize = 0; while (1) { if (IS_ERROR(error_code)) goto out; if (!InternetReadFile(hRequest, buf, sizeof(buf), &dwDownloaded) || (dwDownloaded == 0)) break; dwSize += dwDownloaded; SendMessage(hProgressBar, PBM_SETPOS, (WPARAM)(MAX_PROGRESS*((1.0f*dwSize)/(1.0f*dwTotalSize))), 0); static_sprintf(msg, "Downloading: %0.1f%%", (100.0f*dwSize)/(1.0f*dwTotalSize)); print_status(0, FALSE, msg); if (!WriteFile(hFile, buf, dwDownloaded, &dwWritten, NULL)) { dprintf("Error writing file '%s': %s\n", &file[last_slash], WinInetErrorString()); goto out; } else if (dwDownloaded != dwWritten) { dprintf("Error writing file '%s': Only %d/%d bytes written\n", dwWritten, dwDownloaded); goto out; } } if (dwSize != dwTotalSize) { dprintf("Could not download complete file - read: %d bytes, expected: %d bytes\n", dwSize, dwTotalSize); error_code = ERROR_SEVERITY_ERROR|ERROR_WRITE_FAULT; goto out; } else { r = TRUE; dprintf("Successfully downloaded '%s'\n", &file[last_slash]); } out: if (hProgressDialog != NULL) SendMessage(hProgressDialog, UM_DOWNLOAD_EXIT, (WPARAM)r, 0); if (hFile != INVALID_HANDLE_VALUE) { // Force a flush - May help with the PKI API trying to process downloaded updates too early... FlushFileBuffers(hFile); CloseHandle(hFile); } if (!r) { if (file != NULL) _unlinkU(file); print_status(0, FALSE, "Failed to download file."); SetLastError(error_code); MessageBoxU(hMainDialog, WinInetErrorString(), "File download", MB_OK|MB_ICONERROR); } if (hRequest) InternetCloseHandle(hRequest); if (hConnection) InternetCloseHandle(hConnection); if (hSession) InternetCloseHandle(hSession); return r?dwSize:0; }
static void InternetQueryOptionA_test(void) { HINTERNET hinet,hurl; DWORD len; DWORD err; static const char useragent[] = {"Wininet Test"}; char *buffer; int retval; hinet = InternetOpenA(useragent,INTERNET_OPEN_TYPE_DIRECT,NULL,NULL, 0); ok((hinet != 0x0),"InternetOpen Failed\n"); SetLastError(0xdeadbeef); len=strlen(useragent)+1; retval=InternetQueryOptionA(hinet,INTERNET_OPTION_USER_AGENT,NULL,&len); err=GetLastError(); ok(len == strlen(useragent)+1,"Got wrong user agent length %ld instead of %d\n",len,lstrlenA(useragent)); ok(retval == 0,"Got wrong return value %d\n",retval); todo_wine ok(err == ERROR_INSUFFICIENT_BUFFER, "Got wrong error code%ld\n",err); SetLastError(0xdeadbeef); len=strlen(useragent)+1; buffer=HeapAlloc(GetProcessHeap(),0,len); retval=InternetQueryOptionA(hinet,INTERNET_OPTION_USER_AGENT,buffer,&len); err=GetLastError(); todo_wine ok(!strcmp(useragent,buffer),"Got wrong user agent string %s instead of %s\n",buffer,useragent); todo_wine ok(len == strlen(useragent),"Got wrong user agent length %ld instead of %d\n",len,lstrlenA(useragent)); todo_wine ok(retval == 1,"Got wrong return value %d\n",retval); ok(err == 0xdeadbeef, "Got wrong error code %ld\n",err); HeapFree(GetProcessHeap(),0,buffer); SetLastError(0xdeadbeef); len=0; buffer=HeapAlloc(GetProcessHeap(),0,100); retval=InternetQueryOptionA(hinet,INTERNET_OPTION_USER_AGENT,buffer,&len); err=GetLastError(); todo_wine ok(len == strlen(useragent) + 1,"Got wrong user agent length %ld instead of %d\n", len, lstrlenA(useragent) + 1); ok(!retval, "Got wrong return value %d\n", retval); todo_wine ok(err == ERROR_INSUFFICIENT_BUFFER, "Got wrong error code %ld\n", err); HeapFree(GetProcessHeap(),0,buffer); hurl = InternetConnectA(hinet,"www.winehq.com",INTERNET_DEFAULT_HTTP_PORT,NULL,NULL,INTERNET_SERVICE_HTTP,0,0); SetLastError(0xdeadbeef); len=0; retval = InternetQueryOptionA(hurl,INTERNET_OPTION_USER_AGENT,NULL,&len); err=GetLastError(); ok(len == 0,"Got wrong user agent length %ld instead of 0\n",len); ok(retval == 0,"Got wrong return value %d\n",retval); todo_wine ok(err == ERROR_INTERNET_INCORRECT_HANDLE_TYPE, "Got wrong error code %ld\n",err); InternetCloseHandle(hurl); InternetCloseHandle(hinet); hinet = InternetOpenA("",INTERNET_OPEN_TYPE_DIRECT,NULL,NULL, 0); ok((hinet != 0x0),"InternetOpen Failed\n"); SetLastError(0xdeadbeef); len=0; retval=InternetQueryOptionA(hinet,INTERNET_OPTION_USER_AGENT,NULL,&len); err=GetLastError(); todo_wine ok(len == 1,"Got wrong user agent length %ld instead of %d\n",len,1); ok(retval == 0,"Got wrong return value %d\n",retval); todo_wine ok(err == ERROR_INSUFFICIENT_BUFFER, "Got wrong error code%ld\n",err); InternetCloseHandle(hinet); hinet = InternetOpenA(NULL,INTERNET_OPEN_TYPE_DIRECT,NULL,NULL, 0); ok((hinet != 0x0),"InternetOpen Failed\n"); SetLastError(0xdeadbeef); len=0; retval=InternetQueryOptionA(hinet,INTERNET_OPTION_USER_AGENT,NULL,&len); err=GetLastError(); todo_wine ok(len == 1,"Got wrong user agent length %ld instead of %d\n",len,1); ok(retval == 0,"Got wrong return value %d\n",retval); todo_wine ok(err == ERROR_INSUFFICIENT_BUFFER, "Got wrong error code%ld\n",err); InternetCloseHandle(hinet); }
BOOL koadic_http_request(LPCSTR host, WORD port, BOOL secure, LPCSTR verb, LPCSTR path, LPCSTR szHeaders, SIZE_T nHeaderSize, LPCSTR postData, SIZE_T nPostDataSize, char **data, LPDWORD dwDataSize) { HINTERNET hIntSession = NULL; HINTERNET hHttpSession = NULL; HINTERNET hHttpRequest = NULL; DWORD dwFlags = 0; BOOL ret = FALSE; do { hIntSession = InternetOpenA("Mozilla 5.0", INTERNET_OPEN_TYPE_DIRECT, NULL, NULL, 0); if (NULL == hIntSession) break; hHttpSession = InternetConnectA(hIntSession, host, port, NULL, NULL, INTERNET_SERVICE_HTTP, 0, (DWORD_PTR)NULL); if (NULL == hHttpSession) break; dwFlags |= INTERNET_FLAG_RELOAD; if (secure) dwFlags |= INTERNET_FLAG_SECURE; hHttpRequest = HttpOpenRequestA(hHttpSession, verb, path, 0, 0, 0, dwFlags, 0); if (NULL == hHttpRequest) break; if (!HttpSendRequestA(hHttpRequest, szHeaders, (DWORD)nHeaderSize, (LPVOID)postData, (DWORD)nPostDataSize)) break; CHAR szBuffer[1024]; CHAR *output = (CHAR*)malloc(1024); DWORD dwRead = 0; DWORD dwTotalBytes = 0; memset(output, 0, 1024); memset(szBuffer, 0, sizeof(szBuffer)); while (InternetReadFile(hHttpRequest, szBuffer, sizeof(szBuffer) - 1, &dwRead) && dwRead) { DWORD dwOffset = dwTotalBytes; dwTotalBytes += dwRead; output = (CHAR*)realloc(output, dwTotalBytes); memcpy(output + dwOffset, szBuffer, dwRead); memset(szBuffer, 0, sizeof(szBuffer)); dwRead = 0; } *data = output; *dwDataSize = dwTotalBytes; ret = TRUE; } while (0); if (hHttpRequest) InternetCloseHandle(hHttpRequest); if (hHttpSession) InternetCloseHandle(hHttpSession); if (hIntSession) InternetCloseHandle(hIntSession); return ret; }
LONG WINAPI UnhandledExceptionHandler(_EXCEPTION_POINTERS *ExceptionInfo){ List<LoadedModule*> LoadedModules; EnumerateLoadedModules(GetCurrentProcess(), (PENUMLOADED_MODULES_CALLBACK)AddLoadedModule, &LoadedModules); StringList HeaderList; if(ExceptionInfo->ContextRecord->ContextFlags & CONTEXT_INTEGER){ PCONTEXT reg = ExceptionInfo->ContextRecord; HeaderList.push_back(String("Register-EAX: %1").arg(reg->Eax, 16, true, 8)); HeaderList.push_back(String("Register-ECX: %1").arg(reg->Ecx, 16, true, 8)); HeaderList.push_back(String("Register-EDX: %1").arg(reg->Edx, 16, true, 8)); HeaderList.push_back(String("Register-EBX: %1").arg(reg->Ebx, 16, true, 8)); HeaderList.push_back(String("Register-EDI: %1").arg(reg->Edi, 16, true, 8)); HeaderList.push_back(String("Register-ESI: %1").arg(reg->Esi, 16, true, 8)); } if(ExceptionInfo->ContextRecord->ContextFlags & CONTEXT_CONTROL){ PCONTEXT reg = ExceptionInfo->ContextRecord; HeaderList.push_back(String("Register-EBP: %1").arg(reg->Edi, 16, true, 8)); HeaderList.push_back(String("Register-ESP: %1").arg(reg->Esi, 16, true, 8)); } HeaderList.push_back(String("Exception-Address: %1").arg((unsigned int)ExceptionInfo->ExceptionRecord->ExceptionAddress, 16, true, 8)); HeaderList.push_back(String("Exception-Flags: %1").arg((unsigned int)ExceptionInfo->ExceptionRecord->ExceptionFlags, 16, true, 8)); HeaderList.push_back(String("Exception-Code: %1").arg((unsigned int)ExceptionInfo->ExceptionRecord->ExceptionCode, 16, true, 8)); CGameOBJ* self = CObjMGR::GetSelf(); const char* name = (self)?self->GetName():"No Character"; HeaderList.push_back(String("Character: %1").arg(name)); String module = "Unknown"; unsigned int codeAddress = (unsigned int)((char*)ExceptionInfo->ExceptionRecord->ExceptionAddress); module = GetModuleName(codeAddress, &LoadedModules); HeaderList.push_back(String("Module: %1").arg(module)); unsigned char* codePtr = (unsigned char*)ExceptionInfo->ExceptionRecord->ExceptionAddress; //if(IsBadReadPtr(codePtr - 20, 40) || !IsBadCodePtr(FARPROC(codePtr))){ String code = String("Code-Data: Version: %1 ").arg(gVersion); if(CTERRAIN::Instance()) { code += String("Zone: %1 ").arg(CTERRAIN::Instance()->m_nZoneNO); } if(gRecvPacket) { code += String("RecvPacket: %1").arg(gRecvPacket->Command(), 16); } /*}else{ for(int i = -20; i < 20; ++i) code += String::Create("%02X", codePtr[i]); }*/ HeaderList.push_back(code); OSVERSIONINFO osvi; ZeroMemory(&osvi, sizeof(OSVERSIONINFO)); osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFO); GetVersionEx(&osvi); HeaderList.push_back(String("Windows: %1.%2").arg((unsigned int)osvi.dwMajorVersion).arg((unsigned int)osvi.dwMinorVersion)); GetCallStack(ExceptionInfo, &LoadedModules, HeaderList); unsigned int bufLen = 100; for(StringList::Iterator itr = HeaderList.begin(); itr != HeaderList.end(); ++itr) bufLen += strlen(*itr) + 3; char* theHeaders = new char[bufLen]; theHeaders[0] = 0; for(StringList::Iterator itr = HeaderList.begin(); itr != HeaderList.end(); ++itr){ strcat_s(theHeaders, bufLen, *itr); strcat_s(theHeaders, bufLen, ";\r\n"); } if(MessageBoxA(NULL, "Would you like to submit this error to the titanROSE team?", "An error has occured.", MB_ICONERROR | MB_YESNO) == IDYES){ HINTERNET theInternet = InternetOpenA("titanROSE.Client", INTERNET_OPEN_TYPE_DIRECT, NULL, NULL, 0); HINTERNET theConnection = InternetConnectA(theInternet, "crash.titanrose.com", INTERNET_DEFAULT_HTTP_PORT, NULL, NULL, INTERNET_SERVICE_HTTP, 0, NULL); HINTERNET theRequest = HttpOpenRequestA(theConnection, "GET", NULL, NULL, "trose.exe", NULL, INTERNET_FLAG_PRAGMA_NOCACHE |INTERNET_FLAG_RELOAD, NULL); HttpAddRequestHeadersA(theRequest, theHeaders, -1, HTTP_ADDREQ_FLAG_ADD); BOOL theResult = HttpSendRequestA(theRequest, NULL, 0, NULL, 0); if(theResult == TRUE){ MessageBoxA(NULL, "Your error report was successfully uploaded, thank you.", "Error Report Submitted", MB_OK | MB_ICONASTERISK); }else{ strcat_s(theHeaders, bufLen, "\r\nThere was an error submitting your error report, please post this message box on the forums."); MessageBoxA(NULL, theHeaders, "Error submitting Error Report", MB_OK); } } LoadedModules.delete_values(); delete [] theHeaders; return EXCEPTION_EXECUTE_HANDLER; }
// Open the file VI_FILE *ViOpenFile(char *path) { VI_FILE *f; // Validate arguments if (path == NULL) { return NULL; } if (ViIsInternetFile(path)) { HINTERNET hHttpFile; HINTERNET hInternet = InternetOpenA(DEFAULT_USER_AGENT, INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, 0); UINT size; UINT sizesize; if (hInternet == NULL) { return NULL; } hHttpFile = InternetOpenUrlA(hInternet, path, NULL, 0, INTERNET_FLAG_NO_CACHE_WRITE | INTERNET_FLAG_RELOAD, 0); if (hHttpFile == NULL) { InternetCloseHandle(hInternet); return NULL; } size = 0; sizesize = sizeof(size); if (StartWith(path, "ftp://")) { // ftp DWORD high = 0; size = FtpGetFileSize(hHttpFile, &high); } else { UINT errorcode = 0; UINT errorcode_size = sizeof(errorcode); // http if (HttpQueryInfo(hHttpFile, HTTP_QUERY_CONTENT_LENGTH | HTTP_QUERY_FLAG_NUMBER, &size, &sizesize, NULL) == false) { size = 0; } if (HttpQueryInfo(hHttpFile, HTTP_QUERY_STATUS_CODE | HTTP_QUERY_FLAG_NUMBER, &errorcode, &errorcode_size, NULL) == false || (errorcode / 100) != 2) { // HTTP getting error InternetCloseHandle(hInternet); InternetCloseHandle(hHttpFile); return NULL; } } f = ZeroMalloc(sizeof(VI_FILE)); f->InternetFile = true; f->hInternet = hInternet; f->hHttpFile = hHttpFile; f->FileSize = size; return f; } else { IO *io; char fullpath[MAX_PATH]; char exedir[MAX_PATH]; GetExeDir(exedir, sizeof(exedir)); ConbinePath(fullpath, sizeof(fullpath), exedir, path); io = FileOpen(fullpath, false); if (io == NULL) { return NULL; } f = ZeroMalloc(sizeof(VI_FILE)); f->InternetFile = false; f->FileSize = FileSize(io); f->io = io; return f; } }
void CheckMailInbox(Account *curAcc) { // internet connection handle // internet request handle HINTERNET hHTTPConnection = 0, hHTTPRequest = 0; DBVARIANT dbv; static char *contentType = "Content-Type: application/x-www-form-urlencoded"; char requestBuffer[256] = "continue=https%3A%2F%2Fmail.google.com%2Fa%2F"; char fileBuffer[_MAX_DOWN_BUFFER] = ""; char *tail; char str[64]; char temp[_MAX_DOWN_BUFFER] = ""; unsigned long bufferLength; if (curAcc->IsChecking) return; curAcc->IsChecking = TRUE; if (!db_get_s(curAcc->hContact, "CList", "MyHandle", &dbv)) { mir_strcpy(curAcc->results.content, dbv.pszVal); db_free(&dbv); } else mir_strcpy(curAcc->results.content, curAcc->name); tail = strstr(curAcc->results.content, " ["); if (tail) *tail = '\0'; mir_strcat(curAcc->results.content, " ["); mir_strcpy(str, curAcc->results.content); mir_strcat(str, Translate("Checking...")); mir_strcat(str, "]"); db_set_s(curAcc->hContact, "CList", "MyHandle", str); // internet open handle HINTERNET hHTTPOpen = InternetOpenA("", INTERNET_OPEN_TYPE_PRECONFIG, "", "", 0); if (!hHTTPOpen) { mir_strcat(curAcc->results.content, Translate("Can't open Internet!")); goto error_handle; } if (curAcc->hosted[0]) { hHTTPConnection = InternetConnectA(hHTTPOpen, "www.google.com", INTERNET_DEFAULT_HTTPS_PORT, NULL, NULL, INTERNET_SERVICE_HTTP, 0, 0); if (!hHTTPConnection) { mir_strcat(curAcc->results.content, Translate("Can't reach server!")); goto error_handle; } mir_strcpy(str, "/a/"); mir_strcat(str, curAcc->hosted); mir_strcat(str, "/LoginAction"); hHTTPRequest = HttpOpenRequestA(hHTTPConnection, "POST", str, HTTP_VERSIONA, NULL, NULL, INTERNET_FLAG_SECURE, 0); mir_strcat(requestBuffer, curAcc->hosted); mir_strcat(requestBuffer, "%2Ffeed%2Fatom&service=mail&userName="******"&password="******"Can't send account data!")); goto error_handle; } InternetCloseHandle(hHTTPConnection); InternetCloseHandle(hHTTPRequest); hHTTPRequest = 0; } hHTTPConnection = InternetConnectA(hHTTPOpen, "mail.google.com", INTERNET_DEFAULT_HTTPS_PORT, NULL, NULL, INTERNET_SERVICE_HTTP, 0, 0); if (!hHTTPConnection) { mir_strcat(curAcc->results.content, Translate("Can't reach server!")); goto error_handle; } if (curAcc->hosted[0]) { mir_strcpy(str, "/a/"); mir_strcat(str, curAcc->hosted); mir_strcat(str, "/feed/atom"); } else mir_strcpy(str, "/mail/feed/atom"); hHTTPRequest = HttpOpenRequest(hHTTPConnection, _T("GET"), _A2T(str), NULL, NULL, NULL, INTERNET_FLAG_SECURE | INTERNET_FLAG_DONT_CACHE | INTERNET_FLAG_RELOAD, 0); InternetSetOption(hHTTPRequest, INTERNET_OPTION_USERNAME, _A2T(curAcc->name), (int)mir_strlen(curAcc->name) + 1); InternetSetOption(hHTTPRequest, INTERNET_OPTION_PASSWORD, _A2T(curAcc->pass), (int)mir_strlen(curAcc->pass) + 1); if (!HttpSendRequest(hHTTPRequest, NULL, 0, NULL, 0)) { mir_strcat(curAcc->results.content, Translate("Can't get RSS feed!")); goto error_handle; } while (InternetReadFile(hHTTPRequest, temp, _MAX_DOWN_BUFFER, &bufferLength) && bufferLength > 0) { temp[bufferLength] = '\0'; mir_strcat(fileBuffer, temp); } fileBuffer[_MAX_DOWN_BUFFER - 1] = '\0'; curAcc->results_num = ParsePage(fileBuffer, &curAcc->results); if (curAcc->results_num == -1) { mir_strcat(curAcc->results.content, Translate("Wrong name or password!")); goto error_handle; } InternetCloseHandle(hHTTPOpen); InternetCloseHandle(hHTTPConnection); InternetCloseHandle(hHTTPRequest); mir_strcat(curAcc->results.content, _itoa(curAcc->results_num, str, 10)); mir_strcat(curAcc->results.content, "]"); curAcc->IsChecking = FALSE; return; error_handle: curAcc->results_num = -1; InternetCloseHandle(hHTTPOpen); InternetCloseHandle(hHTTPConnection); InternetCloseHandle(hHTTPRequest); mir_strcat(curAcc->results.content, "]"); curAcc->IsChecking = FALSE; }
/* * Download a file from an URL * Mostly taken from http://support.microsoft.com/kb/234913 * If hProgressDialog is not NULL, this function will send INIT and EXIT messages * to the dialog in question, with WPARAM being set to nonzero for EXIT on success * and also attempt to indicate progress using an IDC_PROGRESS control */ DWORD DownloadFile(const char* url, const char* file, HWND hProgressDialog) { HWND hProgressBar = NULL; BOOL r = FALSE; DWORD dwFlags, dwSize, dwDownloaded, dwTotalSize, dwStatus; FILE* fd = NULL; LONG progress_style; const char* accept_types[] = {"*/*\0", NULL}; unsigned char buf[DOWNLOAD_BUFFER_SIZE]; char agent[64], hostname[64], urlpath[128]; HINTERNET hSession = NULL, hConnection = NULL, hRequest = NULL; URL_COMPONENTSA UrlParts = {sizeof(URL_COMPONENTSA), NULL, 1, (INTERNET_SCHEME)0, hostname, sizeof(hostname), 0, NULL, 1, urlpath, sizeof(urlpath), NULL, 1}; size_t last_slash; int i; if (hProgressDialog != NULL) { // Use the progress control provided, if any hProgressBar = GetDlgItem(hProgressDialog, IDC_PROGRESS); if (hProgressBar != NULL) { progress_style = GetWindowLong(hProgressBar, GWL_STYLE); SetWindowLong(hProgressBar, GWL_STYLE, progress_style & (~PBS_MARQUEE)); SendMessage(hProgressBar, PBM_SETPOS, 0, 0); } SendMessage(hProgressDialog, UM_ISO_INIT, 0, 0); } for (last_slash = safe_strlen(file); last_slash != 0; last_slash--) { if ((file[last_slash] == '/') || (file[last_slash] == '\\')) { last_slash++; break; } } PrintStatus(0, FALSE, MSG_240, &file[last_slash]); uprintf("Downloading '%s' from %s\n", &file[last_slash], url); if (!InternetCrackUrlA(url, (DWORD)safe_strlen(url), 0, &UrlParts)) { uprintf("Unable to decode URL: %s\n", WinInetErrorString()); goto out; } hostname[sizeof(hostname)-1] = 0; // Open an Internet session for (i=5; (i>0) && (!InternetGetConnectedState(&dwFlags, 0)); i--) { Sleep(1000); } if (i <= 0) { // http://msdn.microsoft.com/en-us/library/windows/desktop/aa384702.aspx is wrong... SetLastError(ERROR_INTERNET_NOT_INITIALIZED); uprintf("Network is unavailable: %s\n", WinInetErrorString()); goto out; } _snprintf(agent, ARRAYSIZE(agent), APPLICATION_NAME "/%d.%d.%d.%d", rufus_version[0], rufus_version[1], rufus_version[2], rufus_version[3]); hSession = InternetOpenA(agent, INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, 0); if (hSession == NULL) { uprintf("Could not open Internet session: %s\n", WinInetErrorString()); goto out; } hConnection = InternetConnectA(hSession, UrlParts.lpszHostName, UrlParts.nPort, NULL, NULL, INTERNET_SERVICE_HTTP, 0, (DWORD_PTR)NULL); if (hConnection == NULL) { uprintf("Could not connect to server %s:%d: %s\n", UrlParts.lpszHostName, UrlParts.nPort, WinInetErrorString()); goto out; } hRequest = HttpOpenRequestA(hConnection, "GET", UrlParts.lpszUrlPath, NULL, NULL, accept_types, INTERNET_FLAG_HYPERLINK|INTERNET_FLAG_IGNORE_REDIRECT_TO_HTTP|INTERNET_FLAG_IGNORE_REDIRECT_TO_HTTPS|INTERNET_FLAG_NO_COOKIES| INTERNET_FLAG_NO_UI|INTERNET_FLAG_NO_CACHE_WRITE, (DWORD_PTR)NULL); if (hRequest == NULL) { uprintf("Could not open URL %s: %s\n", url, WinInetErrorString()); goto out; } if (!HttpSendRequestA(hRequest, NULL, 0, NULL, 0)) { uprintf("Unable to send request: %s\n", WinInetErrorString()); goto out; } // Get the file size dwSize = sizeof(dwStatus); dwStatus = 404; HttpQueryInfoA(hRequest, HTTP_QUERY_STATUS_CODE|HTTP_QUERY_FLAG_NUMBER, (LPVOID)&dwStatus, &dwSize, NULL); if (dwStatus != 200) { error_code = ERROR_INTERNET_ITEM_NOT_FOUND; uprintf("Unable to access file: Server status %d\n", dwStatus); goto out; } dwSize = sizeof(dwTotalSize); if (!HttpQueryInfoA(hRequest, HTTP_QUERY_CONTENT_LENGTH|HTTP_QUERY_FLAG_NUMBER, (LPVOID)&dwTotalSize, &dwSize, NULL)) { uprintf("Unable to retrieve file length: %s\n", WinInetErrorString()); goto out; } uprintf("File length: %d bytes\n", dwTotalSize); fd = fopenU(file, "wb"); if (fd == NULL) { uprintf("Unable to create file '%s': %s\n", &file[last_slash], WinInetErrorString()); goto out; } // Keep checking for data until there is nothing left. dwSize = 0; while (1) { if (IS_ERROR(FormatStatus)) goto out; if (!InternetReadFile(hRequest, buf, sizeof(buf), &dwDownloaded) || (dwDownloaded == 0)) break; dwSize += dwDownloaded; SendMessage(hProgressBar, PBM_SETPOS, (WPARAM)(MAX_PROGRESS*((1.0f*dwSize)/(1.0f*dwTotalSize))), 0); PrintStatus(0, FALSE, MSG_241, (100.0f*dwSize)/(1.0f*dwTotalSize)); if (fwrite(buf, 1, dwDownloaded, fd) != dwDownloaded) { uprintf("Error writing file '%s': %s\n", &file[last_slash], WinInetErrorString()); goto out; } } if (dwSize != dwTotalSize) { uprintf("Could not download complete file - read: %d bytes, expected: %d bytes\n", dwSize, dwTotalSize); FormatStatus = ERROR_SEVERITY_ERROR|FAC(FACILITY_STORAGE)|ERROR_WRITE_FAULT; goto out; } else { r = TRUE; uprintf("Successfully downloaded '%s'\n", &file[last_slash]); } out: if (hProgressDialog != NULL) SendMessage(hProgressDialog, UM_ISO_EXIT, (WPARAM)r, 0); if (fd != NULL) fclose(fd); if (!r) { _unlink(file); PrintStatus(0, FALSE, MSG_242); SetLastError(error_code); MessageBoxU(hMainDialog, IS_ERROR(FormatStatus)?StrError(FormatStatus, FALSE):WinInetErrorString(), lmprintf(MSG_044), MB_OK|MB_ICONERROR|MB_IS_RTL); } if (hRequest) InternetCloseHandle(hRequest); if (hConnection) InternetCloseHandle(hConnection); if (hSession) InternetCloseHandle(hSession); return r?dwSize:0; }
/****************************************************************************** * URLMoniker_BindToStorage ******************************************************************************/ static HRESULT URLMonikerImpl_BindToStorage_hack(LPCWSTR URLName, IBindCtx* pbc, VOID** ppvObject) { HRESULT hres; BINDINFO bi; DWORD bindf; WCHAR szFileName[MAX_PATH + 1]; Binding *bind; int len; WARN("(%s %p %p)\n", debugstr_w(URLName), pbc, ppvObject); bind = heap_alloc_zero(sizeof(Binding)); bind->lpVtbl = &BindingVtbl; bind->ref = 1; URLMON_LockModule(); len = lstrlenW(URLName)+1; bind->URLName = heap_alloc(len*sizeof(WCHAR)); memcpy(bind->URLName, URLName, len*sizeof(WCHAR)); hres = UMCreateStreamOnCacheFile(bind->URLName, 0, szFileName, &bind->hCacheFile, &bind->pstrCache); if(SUCCEEDED(hres)) { TRACE("Created stream...\n"); *ppvObject = (void *) bind->pstrCache; IStream_AddRef((IStream *) bind->pstrCache); hres = IBindCtx_GetObjectParam(pbc, BSCBHolder, (IUnknown**)&bind->pbscb); if(SUCCEEDED(hres)) { TRACE("Got IBindStatusCallback...\n"); memset(&bi, 0, sizeof(bi)); bi.cbSize = sizeof(bi); bindf = 0; hres = IBindStatusCallback_GetBindInfo(bind->pbscb, &bindf, &bi); if(SUCCEEDED(hres)) { URL_COMPONENTSW url; WCHAR *host, *path, *user, *pass; DWORD dwService = 0; BOOL bSuccess; TRACE("got bindinfo. bindf = %08x extrainfo = %s bindinfof = %08x bindverb = %08x iid %s\n", bindf, debugstr_w(bi.szExtraInfo), bi.grfBindInfoF, bi.dwBindVerb, debugstr_guid(&bi.iid)); hres = IBindStatusCallback_OnStartBinding(bind->pbscb, 0, (IBinding*)bind); TRACE("OnStartBinding rets %08x\n", hres); bind->expected_size = 0; bind->total_read = 0; memset(&url, 0, sizeof(url)); url.dwStructSize = sizeof(url); url.dwSchemeLength = url.dwHostNameLength = url.dwUrlPathLength = url.dwUserNameLength = url.dwPasswordLength = 1; InternetCrackUrlW(URLName, 0, ICU_ESCAPE, &url); host = heap_alloc((url.dwHostNameLength + 1) * sizeof(WCHAR)); memcpy(host, url.lpszHostName, url.dwHostNameLength * sizeof(WCHAR)); host[url.dwHostNameLength] = '\0'; path = heap_alloc((url.dwUrlPathLength + 1) * sizeof(WCHAR)); memcpy(path, url.lpszUrlPath, url.dwUrlPathLength * sizeof(WCHAR)); path[url.dwUrlPathLength] = '\0'; if (url.dwUserNameLength) { user = heap_alloc(((url.dwUserNameLength + 1) * sizeof(WCHAR))); memcpy(user, url.lpszUserName, url.dwUserNameLength * sizeof(WCHAR)); user[url.dwUserNameLength] = 0; } else { user = 0; } if (url.dwPasswordLength) { pass = heap_alloc(((url.dwPasswordLength + 1) * sizeof(WCHAR))); memcpy(pass, url.lpszPassword, url.dwPasswordLength * sizeof(WCHAR)); pass[url.dwPasswordLength] = 0; } else { pass = 0; } do { bind->hinternet = InternetOpenA("User Agent", 0, NULL, NULL, 0); if (!bind->hinternet) { hres = HRESULT_FROM_WIN32(GetLastError()); break; } switch ((DWORD) url.nScheme) { case INTERNET_SCHEME_FTP: if (!url.nPort) url.nPort = INTERNET_DEFAULT_FTP_PORT; dwService = INTERNET_SERVICE_FTP; break; case INTERNET_SCHEME_GOPHER: if (!url.nPort) url.nPort = INTERNET_DEFAULT_GOPHER_PORT; dwService = INTERNET_SERVICE_GOPHER; break; } bind->hconnect = InternetConnectW(bind->hinternet, host, url.nPort, user, pass, dwService, 0, (DWORD_PTR)bind); if (!bind->hconnect) { hres = HRESULT_FROM_WIN32(GetLastError()); CloseHandle(bind->hinternet); break; } hres = IBindStatusCallback_OnProgress(bind->pbscb, 0, 0, 0x22, NULL); hres = IBindStatusCallback_OnProgress(bind->pbscb, 0, 0, BINDSTATUS_FINDINGRESOURCE, NULL); hres = IBindStatusCallback_OnProgress(bind->pbscb, 0, 0, BINDSTATUS_CONNECTING, NULL); hres = IBindStatusCallback_OnProgress(bind->pbscb, 0, 0, BINDSTATUS_SENDINGREQUEST, NULL); bSuccess = FALSE; switch (dwService) { case INTERNET_SERVICE_GOPHER: bind->hrequest = GopherOpenFileW(bind->hconnect, path, 0, INTERNET_FLAG_RELOAD, 0); if (bind->hrequest) bSuccess = TRUE; else hres = HRESULT_FROM_WIN32(GetLastError()); break; case INTERNET_SERVICE_FTP: bind->hrequest = FtpOpenFileW(bind->hconnect, path, GENERIC_READ, FTP_TRANSFER_TYPE_BINARY | INTERNET_FLAG_TRANSFER_BINARY | INTERNET_FLAG_RELOAD, 0); if (bind->hrequest) bSuccess = TRUE; else hres = HRESULT_FROM_WIN32(GetLastError()); break; } if(bSuccess) { TRACE("res = %d gle = %u url len = %d\n", hres, GetLastError(), bind->expected_size); IBindStatusCallback_OnProgress(bind->pbscb, 0, 0, BINDSTATUS_CACHEFILENAMEAVAILABLE, szFileName); while(1) { char buf[4096]; DWORD bufread; if(InternetReadFile(bind->hrequest, buf, sizeof(buf), &bufread)) { TRACE("read %d bytes %s...\n", bufread, debugstr_an(buf, 10)); if(bufread == 0) break; hres = Binding_MoreCacheData(bind, buf, bufread); } else break; } InternetCloseHandle(bind->hrequest); hres = S_OK; } InternetCloseHandle(bind->hconnect); InternetCloseHandle(bind->hinternet); } while(0); Binding_FinishedDownload(bind, hres); Binding_CloseCacheDownload(bind); heap_free(user); heap_free(pass); heap_free(path); heap_free(host); } } } IBinding_Release((IBinding*)bind); return hres; }
// Open the Internet file VW_FILE *VwOpenFile(char *path) { VW_FILE *f; HINTERNET hHttpFile; HINTERNET hInternet = InternetOpenA( "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; .NET CLR 1.1.4322)", INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, 0); UINT size; UINT sizesize; char tmp[8]; // Validate arguments if (path == NULL) { return NULL; } if (hInternet == NULL) { return NULL; } hHttpFile = InternetOpenUrlA(hInternet, path, NULL, 0, INTERNET_FLAG_NO_CACHE_WRITE | INTERNET_FLAG_RELOAD, 0); if (hHttpFile == NULL) { InternetCloseHandle(hInternet); return NULL; } size = 0; sizesize = sizeof(size); ZeroMemory(tmp, sizeof(tmp)); if (strlen(path) >= 6) { CopyMemory(tmp, path, 6); } if (lstrcmpi(tmp, "ftp://") == 0) { // ftp DWORD high = 0; size = FtpGetFileSize(hHttpFile, &high); } else { UINT errorcode = 0; UINT errorcode_size = sizeof(errorcode); // http if (HttpQueryInfo(hHttpFile, HTTP_QUERY_CONTENT_LENGTH | HTTP_QUERY_FLAG_NUMBER, &size, &sizesize, NULL) == false) { size = 0; } if (HttpQueryInfo(hHttpFile, HTTP_QUERY_STATUS_CODE | HTTP_QUERY_FLAG_NUMBER, &errorcode, &errorcode_size, NULL) == false || (errorcode / 100) != 2) { // HTTP getting error InternetCloseHandle(hInternet); InternetCloseHandle(hHttpFile); return NULL; } } f = ZeroMalloc(sizeof(VW_FILE)); f->hInternet = hInternet; f->hHttpFile = hHttpFile; f->FileSize = size; return f; }
// 通过HTTP协议从制定网址下载文件并保存到磁盘 // sURL:网址 // sSaveFilename:要保存的本地文件全路径 // sHeader:HTTP请求头信息 // hProgressWindow:接收下载文件进度消息并显示的窗口句柄 int Internet::InternetGetURL(const char* sURL, const char* sSaveFilename, const char* sHeader, HWND hProgressWindow) { const int BUFFER_SIZE = 32768; const int iInterval = 250; DWORD iFlags; char sAgent[64]; HINTERNET hInternet; HINTERNET hConnect; char acBuffer[BUFFER_SIZE]; DWORD iReadBytes; DWORD iTotalReadBytes = 0; FILE *pFile = NULL; DWORD iStartTime; DWORD iCurrentTime; DWORD iDuration = 10; DWORD iLastRefreshTime = 0; DOWNLOAD_PROGRESS_STRU DownloadProgress = {0}; DWORD iBytesToRead = 0; DWORD iReadBytesOfRq = 4; DWORD iCPUTickStart; DWORD iCPUTickEnd; // Get connection state InternetGetConnectedState(&iFlags, 0); if (iFlags & INTERNET_CONNECTION_OFFLINE) // take appropriate steps { return INTERNET_ERROR_OPEN; } // Set agent string _snprintf(sAgent, 64, "Agent%ld", GetTickCount() / 1000); // Open internet session if (!(iFlags & INTERNET_CONNECTION_PROXY)) { hInternet = InternetOpenA(sAgent, INTERNET_OPEN_TYPE_PRECONFIG_WITH_NO_AUTOPROXY, NULL, NULL, 0); } else { hInternet = InternetOpenA(sAgent, INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, 0); } if (hInternet) { if (sHeader == NULL) { sHeader = "Accept: */*\r\n\r\n"; } // Get URL if (!(hConnect = InternetOpenUrlA (hInternet, sURL, sHeader, lstrlenA(sHeader) , INTERNET_FLAG_DONT_CACHE | INTERNET_FLAG_PRAGMA_NOCACHE | INTERNET_FLAG_RELOAD, 0))) { InternetCloseHandle(hInternet); return INTERNET_ERROR_OPENURL; } // Open file to write if (!(pFile = fopen(sSaveFilename, "wb"))) { InternetCloseHandle(hInternet); return INTERNET_ERROR_FILEOPEN; } // Get content size if (!HttpQueryInfo(hConnect, HTTP_QUERY_CONTENT_LENGTH | HTTP_QUERY_FLAG_NUMBER , (LPVOID)&iBytesToRead, &iReadBytesOfRq, NULL)) { iBytesToRead = 0; } DownloadProgress.iCurrentFileSize = iBytesToRead; iStartTime = GetTickCount(); iCPUTickStart = GetTickCount(); do { if (bInternetGetURLUserBreak) { break; } // Keep copying in 16 KB chunks, while file has any data left. // Note: bigger buffer will greatly improve performance. if (!InternetReadFile(hConnect, acBuffer, BUFFER_SIZE, &iReadBytes)) { fclose(pFile); InternetCloseHandle(hInternet); return INTERNET_ERROR_READFILE; } if (iReadBytes > 0) { // Write to file fwrite(acBuffer, sizeof(char), iReadBytes, pFile); } iTotalReadBytes += iReadBytes; iCurrentTime = GetTickCount(); iDuration = iCurrentTime - iStartTime; if (iDuration < 10) { iDuration = 10; } if (iBytesToRead > 0 && hProgressWindow != NULL && iCurrentTime - iLastRefreshTime > iInterval || iTotalReadBytes == iBytesToRead) { // Show progress iLastRefreshTime = iCurrentTime; memset(acBuffer, 0, BUFFER_SIZE); DownloadProgress.iCurrentFileFinishedSize = iTotalReadBytes; SendMessage(hProgressWindow, WM_USER, (WPARAM)NOTIFY_DOWNLOAD_PROGRESS, (LPARAM)&DownloadProgress); #ifdef _DEBUG Sleep(100); // Delay some time to see progress clearly #endif } if (iReadBytes <= 0) { break; // Condition of iReadBytes=0 indicate EOF. Stop. } // 降低资源CPU占用率 iCPUTickEnd = GetTickCount(); if (iCPUTickEnd - iCPUTickStart > 50) { Sleep(iCPUTickEnd - iCPUTickStart); iCPUTickStart = GetTickCount(); } } while (TRUE); fflush (pFile); fclose (pFile); InternetCloseHandle(hInternet); } else { return INTERNET_ERROR_OPEN; } return INTERNET_SUCCESS; }
// POST JSON to URL string saveUrl(const Value & value, const string & url) { // Tokenize URL vector<string> tokens; boost::split(tokens, url, boost::is_any_of("/")); if (tokens.size() < 3) return "Invalid URL. Please include protocol."; // Get server portion of URL string server = tokens[2]; // Remove server portion of URL for (int32_t i = 0; i < 3; i++) tokens.erase(tokens.begin()); // Get action portion of URL string action = ""; for (vector<string>::const_iterator tokenIt = tokens.begin(); tokenIt != tokens.end(); ++tokenIt) action += "/" + * tokenIt; // Serialize data string data = serialize(value); // Open Internet connection HINTERNET session = InternetOpenA("WinInetConnection", INTERNET_OPEN_TYPE_PRECONFIG_WITH_NO_AUTOPROXY, NULL, NULL, 0); if (session == NULL) return "Unable to establish Internet session."; // Open server HINTERNET connection = InternetConnectA(session, server.c_str(), INTERNET_DEFAULT_HTTP_PORT, NULL, NULL, INTERNET_SERVICE_HTTP, 0, NULL); if (connection == NULL) return "Unable to establish Internet connection."; // Open request flags DWORD mOpenRequestFlags = INTERNET_FLAG_IGNORE_REDIRECT_TO_HTTP | INTERNET_FLAG_IGNORE_REDIRECT_TO_HTTPS | INTERNET_FLAG_KEEP_CONNECTION | INTERNET_FLAG_NO_AUTO_REDIRECT | INTERNET_FLAG_NO_COOKIES | INTERNET_FLAG_NO_CACHE_WRITE | INTERNET_FLAG_NO_UI | INTERNET_FLAG_RELOAD; // Open request HINTERNET request = HttpOpenRequestA(connection, "POST", action.c_str(), "HTTP/1.0", NULL, NULL, mOpenRequestFlags, 0); if (request == NULL) return "Unable to create request."; // Send request int_fast8_t buffer; DWORD size; string headers = "Content-Type: application/x-www-form-urlencoded"; string response = ""; if (HttpSendRequestA(request, headers.c_str(), headers.length(), (LPVOID)(data.c_str()), data.length())) { // Read request into buffer while (InternetReadFile(request, &buffer, 1, &size)) { if (size != 1) break; response += buffer; } } // Close Internet handles InternetCloseHandle(request); InternetCloseHandle(connection); InternetCloseHandle(session); // Return response return response; }
//Imago 9/14 ZString UTL::DoHTTP(char * szHdrs, char * szHost, char * szVerb, char * szUri, char * PostData, int PostLength, bool bSecure) { // BT - 7/15 - Fixing handle leaks. ZString Response("Finished\n"); HINTERNET hSession = InternetOpenA( "Allegiance", INTERNET_OPEN_TYPE_PRECONFIG,NULL,NULL,0); if(hSession) { HINTERNET hConnect = InternetConnectA(hSession,szHost,(bSecure) ? INTERNET_DEFAULT_HTTPS_PORT : INTERNET_DEFAULT_HTTP_PORT,NULL,NULL,INTERNET_SERVICE_HTTP,NULL,NULL); if (!hConnect) debugf( "Failed to connect to %s\n", szHost); else { debugf("%s %s",szVerb,szUri); HINTERNET hRequest = HttpOpenRequestA(hConnect,szVerb,szUri,NULL,NULL,NULL,(bSecure) ? INTERNET_FLAG_SECURE|INTERNET_FLAG_NO_CACHE_WRITE : INTERNET_FLAG_NO_CACHE_WRITE,0); if (!hRequest) debugf( "Failed to open request handle\n" ); else { DWORD dwFlags; DWORD dwBuffLen = sizeof(dwFlags); InternetQueryOption(hRequest, INTERNET_OPTION_SECURITY_FLAGS,(LPVOID)&dwFlags, &dwBuffLen); dwFlags |= SECURITY_FLAG_IGNORE_UNKNOWN_CA; // BT - 7/15 - CSS Service integration dwFlags |= INTERNET_FLAG_IGNORE_CERT_CN_INVALID; // Enables usage of locally generated certs. Not very secure, but works if you are on a shoestring budget! dwFlags |= INTERNET_FLAG_IGNORE_CERT_DATE_INVALID; // Enables usage of locally generated certs. Not very secure, but works if you are on a shoestring budget! InternetSetOption(hRequest, INTERNET_OPTION_SECURITY_FLAGS,&dwFlags,sizeof(dwFlags)); if (PostLength == 0) PostData = NULL; // BT - 7/15 - Cleaned up handle leaks. if(HttpSendRequestA(hRequest,szHdrs,strlen(szHdrs),PostData,PostLength)) { char pcBuffer[4096]; DWORD dwBytesRead = 0; debugf("\nThe following was returned by the server:\n"); if(InternetReadFile(hRequest, pcBuffer, 4096-1, &dwBytesRead)) { pcBuffer[dwBytesRead]=0x00; // Null-terminate buffer debugf("%s", pcBuffer); Response = ZString(pcBuffer, (int)dwBytesRead); } else { debugf("\nInternetReadFile failed\n"); } debugf("\n"); } if (!InternetCloseHandle(hRequest)) debugf( "Failed to close Request handle\n" ); } if(!InternetCloseHandle(hConnect)) debugf("Failed to close Connect handle\n"); } if( InternetCloseHandle( hSession ) == FALSE ) debugf( "Failed to close Session handle\n" ); DWORD dwError = GetLastError(); debugf( "\nFinished: %d.\n",dwError); return Response; } else { debugf("Failed to open WinInet session\n"); return "Failed to open WinInet session\n"; } }
int CDownFile::InternetGetFile(CString szUrl,CString szFileName) { DWORD dwFlags; InternetGetConnectedState(&dwFlags, 0); CHAR strAgent[64]; sprintf(strAgent, "Agent%ld", timeGetTime()); HINTERNET hOpen; if(!(dwFlags & INTERNET_CONNECTION_PROXY)) hOpen = InternetOpenA(strAgent, INTERNET_OPEN_TYPE_PRECONFIG_WITH_NO_AUTOPROXY, NULL, NULL, 0); else hOpen = InternetOpenA(strAgent, INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, 0); if(!hOpen) { //AfxMessageBox("Internet连接错误!"); return -1; } DWORD dwSize; CHAR szHead[] = "Accept: */*\r\n\r\n"; VOID* szTemp[16384]; HINTERNET hConnect; CFile file; USES_CONVERSION; if ( !(hConnect = InternetOpenUrlA ( hOpen,CW2A(szUrl), szHead, lstrlenA (szHead), INTERNET_FLAG_DONT_CACHE | INTERNET_FLAG_PRAGMA_NOCACHE | INTERNET_FLAG_RELOAD, 0))) { // AfxMessageBox("不能打开该URL!"); return -1; } if (file.Open(szFileName,CFile::modeWrite|CFile::modeCreate)==FALSE ) { //AfxMessageBox("不能打开本地的文件!"); return -1; } DWORD dwByteToRead = 0; DWORD dwSizeOfRq = 4; DWORD dwBytes = 0; if (!HttpQueryInfo(hConnect, HTTP_QUERY_CONTENT_LENGTH | HTTP_QUERY_FLAG_NUMBER, (LPVOID)&dwByteToRead, &dwSizeOfRq, NULL)) { dwByteToRead = 0; } do { if (!InternetReadFile (hConnect, szTemp, 16384, &dwSize)) { //AfxMessageBox("读文件出错!"); file.Close(); return -1; } if (dwSize==0) break; else file.Write(szTemp,dwSize); dwBytes+=dwSize; }while (TRUE); file.Close(); InternetCloseHandle(hOpen); return 0; }
/* * Background thread to check for updates */ static DWORD WINAPI CheckForUpdatesThread(LPVOID param) { BOOL releases_only, found_new_version = FALSE; int status = 0; const char* server_url = RUFUS_URL "/"; int i, j, k, verbose = 0, verpos[4]; static const char* archname[] = {"win_x86", "win_x64"}; static const char* channel[] = {"release", "beta"}; // release channel const char* accept_types[] = {"*/*\0", NULL}; DWORD dwFlags, dwSize, dwDownloaded, dwTotalSize, dwStatus; char* buf = NULL; char agent[64], hostname[64], urlpath[128], mime[32]; OSVERSIONINFOA os_version = {sizeof(OSVERSIONINFOA), 0, 0, 0, 0, ""}; HINTERNET hSession = NULL, hConnection = NULL, hRequest = NULL; URL_COMPONENTSA UrlParts = {sizeof(URL_COMPONENTSA), NULL, 1, (INTERNET_SCHEME)0, hostname, sizeof(hostname), 0, NULL, 1, urlpath, sizeof(urlpath), NULL, 1}; SYSTEMTIME ServerTime, LocalTime; FILETIME FileTime; int64_t local_time = 0, reg_time, server_time, update_interval; update_check_in_progress = TRUE; verbose = ReadRegistryKey32(REGKEY_HKCU, REGKEY_VERBOSE_UPDATES); // Without this the FileDialog will produce error 0x8001010E when compiled for Vista or later IGNORE_RETVAL(CoInitializeEx(NULL, COINIT_APARTMENTTHREADED)); // Unless the update was forced, wait a while before performing the update check if (!force_update_check) { // It would of course be a lot nicer to use a timer and wake the thread, but my // development time is limited and this is FASTER to implement. do { for (i=0; (i<30) && (!force_update_check); i++) Sleep(500); } while ((!force_update_check) && ((iso_op_in_progress || format_op_in_progress || (dialog_showing>0)))); if (!force_update_check) { if ((ReadRegistryKey32(REGKEY_HKCU, REGKEY_UPDATE_INTERVAL) == -1)) { vuprintf("Check for updates disabled, as per registry settings.\n"); goto out; } reg_time = ReadRegistryKey64(REGKEY_HKCU, REGKEY_LAST_UPDATE); update_interval = (int64_t)ReadRegistryKey32(REGKEY_HKCU, REGKEY_UPDATE_INTERVAL); if (update_interval == 0) { WriteRegistryKey32(REGKEY_HKCU, REGKEY_UPDATE_INTERVAL, DEFAULT_UPDATE_INTERVAL); update_interval = DEFAULT_UPDATE_INTERVAL; } GetSystemTime(&LocalTime); if (!SystemTimeToFileTime(&LocalTime, &FileTime)) goto out; local_time = ((((int64_t)FileTime.dwHighDateTime)<<32) + FileTime.dwLowDateTime) / 10000000; vvuprintf("Local time: %" PRId64 "\n", local_time); if (local_time < reg_time + update_interval) { vuprintf("Next update check in %" PRId64 " seconds.\n", reg_time + update_interval - local_time); goto out; } } } PrintStatus(3000, TRUE, MSG_243); status++; // 1 if (!GetVersionExA(&os_version)) { uprintf("Could not read Windows version - Check for updates cancelled.\n"); goto out; } if ((!InternetCrackUrlA(server_url, (DWORD)safe_strlen(server_url), 0, &UrlParts)) || (!InternetGetConnectedState(&dwFlags, 0))) goto out; hostname[sizeof(hostname)-1] = 0; safe_sprintf(agent, ARRAYSIZE(agent), APPLICATION_NAME "/%d.%d.%d.%d", rufus_version[0], rufus_version[1], rufus_version[2], rufus_version[3]); hSession = InternetOpenA(agent, INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, 0); if (hSession == NULL) goto out; hConnection = InternetConnectA(hSession, UrlParts.lpszHostName, UrlParts.nPort, NULL, NULL, INTERNET_SERVICE_HTTP, 0, (DWORD_PTR)NULL); if (hConnection == NULL) goto out; status++; // 2 releases_only = !GetRegistryKeyBool(REGKEY_HKCU, REGKEY_INCLUDE_BETAS); for (k=0; (k<(releases_only?1:(int)ARRAYSIZE(channel))) && (!found_new_version); k++) { uprintf("Checking %s channel...\n", channel[k]); // At this stage we can query the server for various update version files. // We first try to lookup for "<appname>_<os_arch>_<os_version_major>_<os_version_minor>.ver" // and then remove each each of the <os_> components until we find our match. For instance, we may first // look for rufus_win_x64_6.2.ver (Win8 x64) but only get a match for rufus_win_x64_6.ver (Vista x64 or later) // This allows sunsetting OS versions (eg XP) or providing different downloads for different archs/groups. safe_sprintf(urlpath, sizeof(urlpath), "%s%s%s_%s_%d.%d.ver", APPLICATION_NAME, (k==0)?"":"_", (k==0)?"":channel[k], archname[is_x64()?1:0], os_version.dwMajorVersion, os_version.dwMinorVersion); vuprintf("Base update check: %s\n", urlpath); for (i=0, j=(int)safe_strlen(urlpath)-5; (j>0)&&(i<ARRAYSIZE(verpos)); j--) { if ((urlpath[j] == '.') || (urlpath[j] == '_')) { verpos[i++] = j; } } if (i != ARRAYSIZE(verpos)) { uprintf("Broken code in CheckForUpdatesThread()!\n"); goto out; } UrlParts.lpszUrlPath = urlpath; UrlParts.dwUrlPathLength = sizeof(urlpath); for (i=0; i<ARRAYSIZE(verpos); i++) { vvuprintf("Trying %s\n", UrlParts.lpszUrlPath); hRequest = HttpOpenRequestA(hConnection, "GET", UrlParts.lpszUrlPath, NULL, NULL, accept_types, INTERNET_FLAG_HYPERLINK|INTERNET_FLAG_IGNORE_REDIRECT_TO_HTTP|INTERNET_FLAG_IGNORE_REDIRECT_TO_HTTPS|INTERNET_FLAG_NO_COOKIES| INTERNET_FLAG_NO_UI|INTERNET_FLAG_NO_CACHE_WRITE, (DWORD_PTR)NULL); if ((hRequest == NULL) || (!HttpSendRequestA(hRequest, NULL, 0, NULL, 0))) goto out; // Ensure that we get a text file dwSize = sizeof(dwStatus); dwStatus = 404; HttpQueryInfoA(hRequest, HTTP_QUERY_STATUS_CODE|HTTP_QUERY_FLAG_NUMBER, (LPVOID)&dwStatus, &dwSize, NULL); if (dwStatus == 200) break; InternetCloseHandle(hRequest); hRequest = NULL; safe_strcpy(&urlpath[verpos[i]], 5, ".ver"); } if (dwStatus != 200) { vuprintf("Could not find a %s version file on server %s", channel[k], server_url); if ((releases_only) || (k+1 >= ARRAYSIZE(channel))) goto out; continue; } vuprintf("Found match for %s on server %s", urlpath, server_url); dwSize = sizeof(mime); HttpQueryInfoA(hRequest, HTTP_QUERY_CONTENT_TYPE, (LPVOID)&mime, &dwSize, NULL); if (strcmp(mime, "text/plain") != 0) goto out; // We also get a date from Apache, which we'll use to avoid out of sync check, // in case some set their clock way into the future and back. // On the other hand, if local clock is set way back in the past, we will never check. dwSize = sizeof(ServerTime); // If we can't get a date we can trust, don't bother... if ( (!HttpQueryInfoA(hRequest, HTTP_QUERY_DATE|HTTP_QUERY_FLAG_SYSTEMTIME, (LPVOID)&ServerTime, &dwSize, NULL)) || (!SystemTimeToFileTime(&ServerTime, &FileTime)) ) goto out; server_time = ((((int64_t)FileTime.dwHighDateTime)<<32) + FileTime.dwLowDateTime) / 10000000; vvuprintf("Server time: %" PRId64 "\n", server_time); // Always store the server response time - the only clock we trust! WriteRegistryKey64(REGKEY_HKCU, REGKEY_LAST_UPDATE, server_time); // Might as well let the user know if (!force_update_check) { if ((local_time > server_time + 600) || (local_time < server_time - 600)) { uprintf("IMPORTANT: Your local clock is more than 10 minutes in the %s. Unless you fix this, " APPLICATION_NAME " may not be able to check for updates...", (local_time > server_time + 600)?"future":"past"); } } dwSize = sizeof(dwTotalSize); if (!HttpQueryInfoA(hRequest, HTTP_QUERY_CONTENT_LENGTH|HTTP_QUERY_FLAG_NUMBER, (LPVOID)&dwTotalSize, &dwSize, NULL)) goto out; safe_free(buf); // Make sure the file is NUL terminated buf = (char*)calloc(dwTotalSize+1, 1); if (buf == NULL) goto out; // This is a version file - we should be able to gulp it down in one go if (!InternetReadFile(hRequest, buf, dwTotalSize, &dwDownloaded) || (dwDownloaded != dwTotalSize)) goto out; status++; vuprintf("Successfully downloaded version file (%d bytes)\n", dwTotalSize); parse_update(buf, dwTotalSize+1); vuprintf("UPDATE DATA:\n"); vuprintf(" version: %d.%d.%d.%d (%s)\n", update.version[0], update.version[1], update.version[2], update.version[3], channel[k]); vuprintf(" platform_min: %d.%d\n", update.platform_min[0], update.platform_min[1]); vuprintf(" url: %s\n", update.download_url); found_new_version = ((to_uint64_t(update.version) > to_uint64_t(rufus_version)) || (force_update)) && ( (os_version.dwMajorVersion > update.platform_min[0]) || ( (os_version.dwMajorVersion == update.platform_min[0]) && (os_version.dwMinorVersion >= update.platform_min[1])) ); uprintf("N%sew %s version found%c\n", found_new_version?"":"o n", channel[k], found_new_version?'!':'.'); } out: safe_free(buf); if (hRequest) InternetCloseHandle(hRequest); if (hConnection) InternetCloseHandle(hConnection); if (hSession) InternetCloseHandle(hSession); switch(status) { case 1: PrintStatus(3000, TRUE, MSG_244); break; case 2: PrintStatus(3000, TRUE, MSG_245); break; case 3: case 4: PrintStatus(3000, FALSE, found_new_version?MSG_246:MSG_247); default: break; } // Start the new download after cleanup if (found_new_version) { // User may have started an operation while we were checking while ((!force_update_check) && (iso_op_in_progress || format_op_in_progress || (dialog_showing>0))) { Sleep(15000); } DownloadNewVersion(); } force_update_check = FALSE; update_check_in_progress = FALSE; ExitThread(0); }