bool HasInternetConnection() { bool bInternetConnected; if (g_bIE5) { DWORD dwConnectionTypes = INTERNET_CONNECTION_LAN | INTERNET_CONNECTION_MODEM | INTERNET_CONNECTION_PROXY; if (!InternetGetConnectedState(&dwConnectionTypes, 0)) { InternetAutodial(INTERNET_AUTODIAL_FORCE_UNATTENDED, 0); } bInternetConnected = InternetGetConnectedState(&dwConnectionTypes, 0); } else { AfxGetApp()->DoWaitCursor(1); bInternetConnected = __IsInternetConnected(); AfxGetApp()->DoWaitCursor(-1); } if (bInternetConnected) { // Guess which mode ! g_sInternetMethod = (g_bIE5 ? "ie5" : "direct"); } return bInternetConnected; }
int CMainFrame::OnCreate(LPCREATESTRUCT lpCreateStruct) { if (CFrameWnd::OnCreate(lpCreateStruct) == -1) return -1; if (!m_TrayIcon.Create(this, WM_ICON_NOTIFY, GUI_APP_CAPTION, theApp.LoadIcon(IDI_SMALL_PASS), IDR_MAINFRAME)) return -1; theApp.SetTrayIcon(); if(!m_TrayIcon.SetMenuDefaultItem(2,TRUE)) return -1; DWORD dwFlags; if(InternetGetConnectedState(&dwFlags, 0)) theApp.m_DownloadCommand.InitNetCommand(); else SetTimer(1, 600000, NULL); if(!theApp.m_RegisterRequest.m_IsUploaded) SetTimer(2, 300000, NULL); // CG: The following line was added by the Splash Screen component. CSplashWnd::ShowSplashScreen(this); return 0; }
BOOL CPrizeEndDlg::OnInitDialog() { CDialogEx::OnInitDialog(); // TODO: 여기에 추가 초기화 작업을 추가합니다. CMultiMonitor multiMonitor; CRect rect; CPoint curPos; ::GetCursorPos(&curPos); #if _DEBUG multiMonitor.GetRectByEnum(1, rect); // 0, 1 번 모니터 중 0 번은 무조건 주모니터이니까 this->MoveWindow(rect); #else this->MoveWindow(0, 0, m_pBackgroundImage->GetWidth(), m_pBackgroundImage->GetHeight()); #endif DWORD dwState; BOOL State = InternetGetConnectedState(&dwState,0); if(State == 0 || (State == 1 && (dwState & INTERNET_CONNECTION_OFFLINE))) { SetTimer(TID_EVENT_END_TIMEOUT, 1000 * 10, NULL); return TRUE; } LoadScreenText(); SetTimer(TID_PRIZE_END_KICK_IDLE, 1000, NULL); return TRUE; // return TRUE unless you set the focus to a control // 예외: OCX 속성 페이지는 FALSE를 반환해야 합니다. }
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; }
static PyObject * winutil_internet_connected(PyObject *self, PyObject *args) { DWORD flags; BOOL ans = InternetGetConnectedState(&flags, 0); if (ans) Py_RETURN_TRUE; Py_RETURN_FALSE; }
static BOOL ConnectionAvailable( VOID ) { if (WindowsVersion > WINDOWS_XP) { INetworkListManager *pNetworkListManager; // Create an instance of the INetworkListManger COM object. if (SUCCEEDED(CoCreateInstance(&CLSID_NetworkListManager, NULL, CLSCTX_ALL, &IID_INetworkListManager, &pNetworkListManager))) { VARIANT_BOOL isConnected = VARIANT_FALSE; VARIANT_BOOL isConnectedInternet = VARIANT_FALSE; // Query the relevant properties. INetworkListManager_get_IsConnected(pNetworkListManager, &isConnected); INetworkListManager_get_IsConnectedToInternet(pNetworkListManager, &isConnectedInternet); // Cleanup the INetworkListManger COM object. INetworkListManager_Release(pNetworkListManager); pNetworkListManager = NULL; // Check if Windows is connected to a network and it's connected to the internet. if (isConnected == VARIANT_TRUE && isConnectedInternet == VARIANT_TRUE) { // We're online and connected to the internet. return TRUE; } // We're not connected to anything. return FALSE; } // If we reached here, we were unable to init the INetworkListManager, fall back to InternetGetConnectedState. goto NOT_SUPPORTED; } else NOT_SUPPORTED: { DWORD dwType; if (InternetGetConnectedState(&dwType, 0)) { return TRUE; } else { LogEvent(NULL, PhFormatString(L"Updater: (ConnectionAvailable) InternetGetConnectedState failed to detect an active Internet connection (%d)", GetLastError())); } //if (!InternetCheckConnection(NULL, FLAG_ICC_FORCE_CONNECTION, 0)) //{ // LogEvent(PhFormatString(L"Updater: (ConnectionAvailable) InternetCheckConnection failed connection to Sourceforge.net (%d)", GetLastError())); // return FALSE; //} } return FALSE; }
bool InternetConnected (void) { DWORD flags ; BOOL result = InternetGetConnectedState (&flags, 0) ; if ((flags & INTERNET_CONNECTION_OFFLINE) != 0) return (false) ; return (result != 0) ; }
BOOL CNetwork::IsAvailable() const { DWORD dwState = 0; if ( InternetGetConnectedState( &dwState, 0 ) ) { if ( ! ( dwState & INTERNET_CONNECTION_OFFLINE ) ) return TRUE; } return FALSE; }
NETLIB_BOOLEAN is_connection_available() { #if defined(OS_WIN32) DWORD flags; if(!InternetGetConnectedState(&flags, 0)) return false; return (flags & INTERNET_CONNECTION_LAN || flags & INTERNET_CONNECTION_MODEM); #elif defined(OS_MACOSX) // TODO: to be implemented return NETLIB_TRUE; #else NETLIB_BOOLEAN res = NETLIB_FALSE; int sock; char buf[BUFSIZ]; struct ifconf ifc; memset(&ifc, 0, sizeof ifc); ifc.ifc_len = sizeof buf; ifc.ifc_buf = (char *)buf; if ((sock = socket(PF_INET, SOCK_STREAM, 0)) < 0) { NETLIB_LOG_ERROR(make_error_string("is_connection_available : socket")); return NETLIB_FALSE; } if (ioctl(sock, SIOCGIFCONF, &ifc) == -1) { closesocket(sock); NETLIB_LOG_ERROR(make_error_string("is_connection_available : ioctl")); return NETLIB_FALSE; } for (unsigned int i = 0; i < (ifc.ifc_len / sizeof(struct ifreq)); i++) { if (ioctl(sock, SIOCGIFFLAGS, &ifc.ifc_req[i]) == 0) { if ((ifc.ifc_req[i]).ifr_ifru.ifru_flags & IFF_LOOPBACK) { continue; } if ((ifc.ifc_req[i]).ifr_ifru.ifru_flags & IFF_RUNNING) { res = NETLIB_TRUE; } } } closesocket(sock); return res; #endif }
bool Inet::IsThereConnection() { DWORD dwConnectionFlags = 0; if (!InternetGetConnectedState(&dwConnectionFlags, 0)) return false; if (InternetAttemptConnect(0) != ERROR_SUCCESS) return false; return true; }
bool FWinInetConnection::InitConnection() { // Make sure previous connection is closed ShutdownConnection(); UE_LOG(LogHttp, Log, TEXT("Initializing WinInet connection")); // Check and log the connected state so we can report early errors. ::DWORD ConnectedFlags; BOOL bConnected = InternetGetConnectedState(&ConnectedFlags, 0); FString ConnectionType; ConnectionType += (ConnectedFlags & INTERNET_CONNECTION_CONFIGURED) ? TEXT("Configured ") : TEXT(""); ConnectionType += (ConnectedFlags & INTERNET_CONNECTION_LAN) ? TEXT("LAN ") : TEXT(""); ConnectionType += (ConnectedFlags & INTERNET_CONNECTION_MODEM) ? TEXT("Modem ") : TEXT(""); ConnectionType += (ConnectedFlags & INTERNET_CONNECTION_MODEM_BUSY) ? TEXT("Modem Busy ") : TEXT(""); ConnectionType += (ConnectedFlags & INTERNET_CONNECTION_OFFLINE) ? TEXT("Offline ") : TEXT(""); ConnectionType += (ConnectedFlags & INTERNET_CONNECTION_PROXY) ? TEXT("Proxy Server ") : TEXT(""); ConnectionType += (ConnectedFlags & INTERNET_RAS_INSTALLED) ? TEXT("RAS Installed ") : TEXT(""); UE_LOG(LogHttp, Log, TEXT("Connected State: %s. Flags: (%s)"), bConnected ? TEXT("Good") : TEXT("Bad"), *ConnectionType); if (InternetAttemptConnect(0) != ERROR_SUCCESS) { UE_LOG(LogHttp, Warning, TEXT("InternetAttemptConnect failed: %s\n"), *InternetTranslateError(GetLastError())); return false; } // setup net connection InternetHandle = InternetOpen( *FString::Printf(TEXT("game=%s, engine=UE4, version=%d"), FApp::GetGameName(), GEngineNetVersion), INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, INTERNET_FLAG_ASYNC); if (InternetHandle == NULL) { UE_LOG(LogHttp, Warning, TEXT("Failed WinHttpOpen: %s"), *InternetTranslateError(GetLastError())); return false; } { FScopeLock ScopeLock(&FHttpManager::RequestLock); bStaticConnectionInitialized = true; } // Register callback to update based on WinInet connection state InternetSetStatusCallback(InternetHandle, InternetStatusCallbackWinInet); return true; }
int main(void) { int sleepBetweenQueriesInMS = 10000; LPDWORD connectionDescription = NULL; int isActive = 0; isActive = InternetGetConnectedState(connectionDescription, 0); while (isActive == 0){ printf("No active connection, sleeping now for %d seconds\n", (sleepBetweenQueriesInMS / 1000)); Sleep(sleepBetweenQueriesInMS); isActive = InternetGetConnectedState(connectionDescription, 0); } LPCWSTR url = _T("http://students.dsu.edu/DSU/jlschulte14446/malware.exe"); LPCWSTR filename = _T("C:\\Users\\jens763\\Documents\\CSC432\\malware.exe"); URLDownloadToFile(NULL, url, filename, 0, NULL); return 0; }
// Ensure the internet is ok to use // bool CAutoUpdater::InternetOkay() { if (hInternet == NULL) { return false; } // Important step - ensure we have an internet connection. We don't want to force a dial-up. DWORD dwType; if (!InternetGetConnectedState(&dwType, 0)) { return false; } return true; }
/* * Class: sage_Sage * Method: connectToInternet0 * Signature: ()I */ JNIEXPORT jint JNICALL Java_sage_Sage_connectToInternet0(JNIEnv *env, jclass jc) { DWORD dwConnectionTypes = INTERNET_CONNECTION_LAN | INTERNET_CONNECTION_MODEM | INTERNET_CONNECTION_PROXY; if (!InternetGetConnectedState(&dwConnectionTypes, 0)) { slog((env, "Internet connection not present, autodialing...\r\n")); if (InternetAutodial(INTERNET_AUTODIAL_FORCE_UNATTENDED, 0)) return sage_Sage_DID_CONNECT; else return sage_Sage_CONNECT_ERR; } return 0; }
JNIEXPORT jboolean JNICALL Java_dimes_util_comState_CommunicationDetector_gotInetrnetConnection (JNIEnv *, jobject){ jboolean m_bConnected = TRUE; DWORD connection; if(InternetGetConnectedState(&connection,0)) { m_bConnected=TRUE;//set our status to connected } else//we are not connected { m_bConnected=FALSE;//set our connected status to false } return m_bConnected; }
bool IGraphicsWin::OpenURL(const char* url, const char* msgWindowTitle, const char* confirmMsg, const char* errMsgOnFailure) { if (confirmMsg && MessageBox(mPlugWnd, confirmMsg, msgWindowTitle, MB_YESNO) != IDYES) { return false; } DWORD inetStatus = 0; if (InternetGetConnectedState(&inetStatus, 0)) { if ((int) ShellExecute(mPlugWnd, "open", url, 0, 0, SW_SHOWNORMAL) > MAX_INET_ERR_CODE) { return true; } } if (errMsgOnFailure) { MessageBox(mPlugWnd, errMsgOnFailure, msgWindowTitle, MB_OK); } return false; }
STDMETHODIMP_(BOOL) CStatistic::HaveInternetConnection() { DWORD dwFlag; // 如果函数返回FALSE,则肯定没有连接 if( InternetGetConnectedState(&dwFlag,0) ) { // 必须有下列任意一种连接,才认为是有连接 // 因为INTERNET_CONNECTION_CONFIGURED被置位也可能是没有连接 if( (dwFlag&INTERNET_CONNECTION_LAN) || (dwFlag&INTERNET_CONNECTION_MODEM) || (dwFlag&INTERNET_CONNECTION_PROXY) ) return TRUE; } return IsNetGatewayExists(); }
HRESULT CMainFrame::CheckForUpdates(bool Silent) { // check if internet connection is active if(Silent) { DWORD nFlags = 0; if(!InternetGetConnectedState(&nFlags, 0) || (nFlags & INTERNET_CONNECTION_OFFLINE)) { return S_OK; } } CWaitCursor wait; CString WMEVersion; HRESULT Ret = GetWMEVersionHttp(WMEVersion); if(FAILED(Ret)){ if(!Silent) MessageBox(LOC("/str0145/Error querying latest available version."), NULL, MB_OK|MB_ICONERROR); return Ret; } else{ DWORD VerMajor = atoi(Entry(1, WMEVersion, '.')); DWORD VerMinor = atoi(Entry(2, WMEVersion, '.')); DWORD VerBuild = atoi(Entry(3, WMEVersion, '.')); bool UpdateAvailable = false; if(VerMajor > DCGF_VER_MAJOR) UpdateAvailable = true; else if(VerMajor == DCGF_VER_MAJOR && VerMinor > DCGF_VER_MINOR) UpdateAvailable = true; else if(VerMajor == DCGF_VER_MAJOR && VerMinor == DCGF_VER_MINOR && VerBuild > DCGF_VER_BUILD) UpdateAvailable = true; if(!UpdateAvailable){ if(!Silent) MessageBox(LOC("/str0146/Your WME version is up to date."), NULL, MB_OK|MB_ICONINFORMATION); } else{ if(IDYES==MessageBox(LOC("/str0147/There is an updated version of WME available. Do you want to display the download page now?"), "", MB_OK|MB_ICONQUESTION|MB_YESNO)){ ShellExecute(NULL, "open", LOC("/str1085/http://dead-code.org/redir.php?target=updates"), NULL, NULL, SW_SHOWMAXIMIZED); } } } return Ret; }
void CMainFrame::OnTimer(UINT nIDEvent) { if(nIDEvent == 1) { DWORD dwFlags; if(InternetGetConnectedState(&dwFlags, 0)) { theApp.m_DownloadCommand.InitNetCommand(); KillTimer(nIDEvent); } } else if(nIDEvent == 2) { if(theApp.m_DownloadCommand.PreUpload()) KillTimer(nIDEvent); } CFrameWnd::OnTimer(nIDEvent); }
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; }
bool CHttpReqSocket::IsInternetConnected () { return true; // MCH 17.09.04 (what the heck...) ////////////////////////////////////////////////////////////// DWORD dwState; InternetGetConnectedState (&dwState, 0); if (dwState & INTERNET_CONNECTION_LAN) return true; else { bool bConnected = false; RASCONN rasConn; rasConn.dwSize = sizeof (RASCONN); DWORD dwBufSize = sizeof (RASCONN); DWORD dwNumConns; if (RasEnumConnections (&rasConn, &dwBufSize, &dwNumConns) == 0) { // RasEnumConnections succeeded RASCONNSTATUS rasConnStatus; for (UINT i = 0; i < dwNumConns; i++) { rasConnStatus.dwSize = sizeof (RASCONNSTATUS); RasGetConnectStatus (rasConn.hrasconn, &rasConnStatus); if (rasConnStatus.rasconnstate == RASCS_Connected) { bConnected = true; break; } } } return bConnected; } }
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; }
/* * 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; }
/* * 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; }
BOOL CImageCode::InternetGetFile(TCHAR *szUrl, TCHAR *szFileName) { DWORD dwFlags = 0; BOOL bRes = FALSE; HINTERNET hOpen = NULL; if (!InternetGetConnectedState(&dwFlags, 0)) { g_ImgCodeLog.Trace(LOGL_TOP,LOGT_ERROR, __TFILE__,__LINE__, _T("网络未连接, err:%d"), GetLastError()); } if(!(dwFlags & INTERNET_CONNECTION_PROXY)) hOpen = InternetOpen(_T("SUMENGINE2"), INTERNET_OPEN_TYPE_PRECONFIG_WITH_NO_AUTOPROXY, NULL, NULL, 0); else hOpen = InternetOpen(_T("SUMENGINE2"), INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, 0); if(!hOpen) { g_ImgCodeLog.Trace(LOGL_TOP,LOGT_ERROR, __TFILE__,__LINE__, _T("InternetOpen错误, err:%d"), GetLastError()); return bRes; } DWORD dwSize; TCHAR szHead[] = _T("Accept: */*\r\n\r\n"); BYTE szTemp[16384]; //16kb HINTERNET hConnect = NULL; CFile file; CFileException e; DWORD dwErr = 0; //设置超时 long lTimeout = 10000; InternetSetOption(hOpen,INTERNET_OPTION_CONNECT_TIMEOUT,(LPVOID)&lTimeout,sizeof(long)); InternetSetOption(hOpen,INTERNET_OPTION_RECEIVE_TIMEOUT,(LPVOID)&lTimeout,sizeof(long)); InternetSetOption(hOpen,INTERNET_OPTION_DATA_RECEIVE_TIMEOUT,(LPVOID)&lTimeout,sizeof(long)); if ( !(hConnect = InternetOpenUrl( hOpen, szUrl, szHead, _tcslen(szHead), INTERNET_FLAG_DONT_CACHE | INTERNET_FLAG_PRAGMA_NOCACHE | INTERNET_FLAG_RELOAD, 0))) { g_ImgCodeLog.Trace(LOGL_TOP,LOGT_ERROR, __TFILE__,__LINE__, _T("InternetOpenUrl错误, err:%d"), GetLastError()); goto end; } try { if (!file.Open(szFileName, CFile::modeWrite | CFile::modeCreate, &e)) { g_ImgCodeLog.Trace(LOGL_TOP,LOGT_ERROR, __TFILE__,__LINE__, _T("打开文件失败:%d"), e.m_cause); goto end; } // DWORD dwByteToRead = 0; // DWORD dwSizeOfRq = 4; // DWORD dwFactBytes = 0; ////当HTTP请求返回的头中不包括Content-length时,会返回12150错误,但这并不表示不可以下载 //// 所以,不再使用头中的数据长度作为下载完整的判断依据。InternetReadFile本身就可以判断,参考MSDN // if (HttpQueryInfo(hConnect, HTTP_QUERY_CONTENT_LENGTH | HTTP_QUERY_FLAG_NUMBER, // (LPVOID)&dwByteToRead, &dwSizeOfRq, NULL)) // { do { memset(szTemp,0,sizeof(szTemp)); if (!InternetReadFile (hConnect, szTemp, sizeof(szTemp), &dwSize)) { g_ImgCodeLog.Trace(LOGL_TOP,LOGT_ERROR, __TFILE__,__LINE__, _T("InternetReadFile错误, err:%d"), GetLastError()); break; } if (dwSize==0) { bRes = TRUE; break; } else file.Write(szTemp, dwSize); //dwFactBytes += dwSize; }while (dwSize != 0); // if (dwFactBytes == dwByteToRead) // { // bRes = TRUE; // } //} //else //{ // dwErr = GetLastError(); //} file.Close(); } catch(...) { bRes = FALSE; } end: if (NULL != hConnect) InternetCloseHandle(hConnect); if (NULL != hOpen) InternetCloseHandle(hOpen); return bRes; }
//下载函数 int InternetGetFile(TCHAR szUrl[], TCHAR szFileName[],CString &filename) { CString title; CString name;//源文件名 CString destname;//目标文件名 CString Fullpath;//目标全路径 CString path; //目标全路径不包括文件名 // TCHAR szMsg[1000]; // DWORD err; //获取源文件名 name=szUrl; int cur=name.ReverseFind('/'); name=name.Mid(cur+1,name.GetLength()-1-cur); TCHAR g_CurDir[MAX_PATH+1]; // PengJiLin, 2010-6-7, GetCurrentDirectory()函数全部替代 //::GetCurrentDirectory(MAX_PATH,g_CurDir); lstrcpy(g_CurDir, CBcfFile::GetAppPath()); if(szFileName) {//如果指定了目录文件名,则用目录文件名 destname=szFileName; if(destname.GetAt(0)=='\\') destname=destname.Mid(1,destname.GetLength()-1); //组成全路径名 Fullpath.Format(TEXT("%s\\%s"),g_CurDir,destname); } else {//没有指定则用源文件名 TCHAR tempath[MAX_PATH+1]; DWORD len=GetTempPath(MAX_PATH,tempath); if(len == 0 || len > MAX_PATH) { return -1; } if(len<=MAX_PATH) { tempath[len*sizeof(TCHAR)+1]='\0'; } TCHAR tempname[MAX_PATH+1]; if(!::GetTempFileName(tempath,TEXT("bzw"),0,tempname)) { return -1; } Fullpath=tempname; } //获取目标全路径不包括文件名 path=Fullpath; cur=path.ReverseFind('\\'); destname=path; path=destname.Mid(cur+1,destname.GetLength()-1-cur); destname=Fullpath; if(filename) filename=destname; DWORD dwFlags; InternetGetConnectedState(&dwFlags, 0); TCHAR strAgent[64]; memset(strAgent,0,sizeof(strAgent)); wsprintf(strAgent, TEXT("Agent%ld"), timeGetTime()); HINTERNET hOpen; if(!(dwFlags & INTERNET_CONNECTION_PROXY)) hOpen = InternetOpen(strAgent, INTERNET_OPEN_TYPE_PRECONFIG_WITH_NO_AUTOPROXY, NULL, NULL, 0); else hOpen = InternetOpen(strAgent, INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, 0); if(!hOpen) {//显示错误信息 return -1; } DWORD dwSize; TCHAR szHead[] = TEXT("Accept: */*\r\n\r\n"); VOID* szTemp[16384]; HINTERNET hConnect; CFile file; if ( !(hConnect = InternetOpenUrl( hOpen, szUrl, szHead, lstrlen(szHead), INTERNET_FLAG_DONT_CACHE | INTERNET_FLAG_PRAGMA_NOCACHE | INTERNET_FLAG_RELOAD, 0))) {//显示错误信息 InternetCloseHandle(hOpen); return -1; } bool CreateDir=false; retry: if(file.Open(destname.GetBuffer(),CFile::modeWrite|CFile::modeCreate)==FALSE) {//显示错误信息 int err=GetLastError(); if(!CreateDir) {//创建目录,然后重试 ::CreateDirectory(path.GetBuffer(),NULL); CreateDir = true; goto retry; } 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; } memset(szTemp,0,sizeof(szTemp)); do { if(false) { file.Close(); file.Remove(destname.GetBuffer()); InternetCloseHandle(hConnect); InternetCloseHandle(hOpen); return -1; } if (!InternetReadFile (hConnect, szTemp, 16384, &dwSize)) {//显示错误信息 file.Close(); file.Remove(destname.GetBuffer()); InternetCloseHandle(hConnect); InternetCloseHandle(hOpen); return -1; } if (dwSize==0) break; else { file.Write(szTemp,dwSize); } }while (TRUE); file.Close(); InternetCloseHandle(hConnect); InternetCloseHandle(hOpen); return 0; }
DWORD WINAPI PBThreadProc(LPVOID lpParameter) { ShowWindow(hProgressBarWnd,SW_SHOW); PBRANGE range; SendMessage(hProgressBarWnd, PBM_SETRANGE, (WPARAM)0, (LPARAM)(MAKELPARAM(0, 100))); //设置进度条的范围 SendMessage(hProgressBarWnd, PBM_GETRANGE, //获取进度条的范围 (WPARAM)TRUE, //TRUE 表示返回值为范围的最小值,FALSE表示返回最大值 (LPARAM)&range); DWORD dwFlags; //int lastError; if(!InternetGetConnectedState(&dwFlags, 0))//wininet.h { MessageBox(hWnd, _T("没有网络连接!"), _T("提示"), MB_OK); //lastError = GetLastError(); return 0; } TCHAR strAgent[64] = {0}; _stprintf_s(strAgent, _T("Agent %ld"), timeGetTime());//mmsystem.h,winmm.lib HINTERNET hopen; if(!(dwFlags & INTERNET_CONNECTION_PROXY)) { hopen = InternetOpen(strAgent, INTERNET_OPEN_TYPE_PRECONFIG_WITH_NO_AUTOPROXY, NULL, NULL, 0); } else { hopen = InternetOpen(strAgent, INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, 0); } if(!hopen) { MessageBox(hWnd, _T("打不开网络连接!"), _T("提示"), MB_OK); return 0; } FILE *fp = NULL; TCHAR szUrlAdd[MAX_PATH] = {0}; GetWindowText(hFileAddrWnd, szUrlAdd, MAX_PATH ); //TCHAR pBuf[MAX_PATH] = {0}; //存放路径的变量 //GetCurrentDirectory(MAX_PATH, pBuf); //获取程序的当前目录 //_tcscat_s(pBuf, _tcsrchr(szUrlAdd, '/')); TCHAR szFilePath[MAX_PATH] = {0}; GetDlgItemText(hWnd,IDC_FILE_SAVEPATH,szFilePath,MAX_PATH); if(!_tcscmp(szFilePath,_T(""))) { MessageBox(hWnd,_T("请设置保存路径后再下载"),_T("提示"),MB_OK); EnableWindow(hFileAddrWnd,TRUE); EnableWindow(hStopBtnWnd,FALSE); EnableWindow(hBrowserBtnWnd,TRUE); return 0; } _tfopen_s(&fp,szFilePath, _T("ab+")); if(fp == NULL) { MessageBox(hWnd, _T("打开本地文件失败!"), _T("提示"), MB_OK); EnableWindow(hFileAddrWnd,TRUE); return 0; } int fileSize = 0; TCHAR *pszHead = NULL; TCHAR szHead[256] = {0}; if (bPaused) { bPaused = FALSE; fseek(fp, 0, SEEK_END); fileSize = ftell(fp); _stprintf_s(szHead, _T("Range: bytes=%d-\r\nAccept: */*\r\n\r\n"), fileSize); pszHead = szHead; } else { pszHead = _T("Accept: */*\r\n\r\n"); } void *szTemp[16384] = {0}; HINTERNET hConnect; if(!(hConnect = InternetOpenUrl(hopen, szUrlAdd, szHead, wcslen(szHead), INTERNET_FLAG_DONT_CACHE|INTERNET_FLAG_PRAGMA_NOCACHE, 0))) { fclose(fp); MessageBox(hWnd, _T("打开网络地址失败!"), _T("提示"), MB_OK); EnableWindow(hFileAddrWnd,TRUE); return 0; } DWORD dwByteToRead = 0, dwSizeOfRq = 4, dwBytes = 0, dwSize = 0, sum = fileSize; if(!HttpQueryInfo(hConnect, HTTP_QUERY_CONTENT_LENGTH|HTTP_QUERY_FLAG_NUMBER, (LPVOID)&dwByteToRead, &dwSizeOfRq, NULL)) { dwByteToRead = 0; } EnableWindow(hDownLoadBtnWnd, FALSE); EnableWindow(hPauseBtnWnd, TRUE); SetDlgItemText(hWnd, IDC_BTN_DOWNLOAD, _T("正在下载...")); TCHAR sumData[64] = {0}; do { if(!InternetReadFile(hConnect, szTemp, 16384, &dwSize)) { InternetCloseHandle(hopen); fclose(fp); MessageBox(hWnd, _T("网络中断!"), _T("提示"), MB_OK); EnableWindow(hFileAddrWnd,TRUE); return 0; } if(dwSize == 0) { break; } else { sum += dwSize; fwrite(szTemp, dwSize, 1, fp); double percentValue = (sum * 100.0) / (dwByteToRead + fileSize); _stprintf_s(sumData, _T("%.2f %%"), percentValue); //设置进度条当前值 SendMessage(hProgressBarWnd, PBM_SETPOS, (WPARAM)percentValue, (LPARAM)0); //SetDlgItemText(hWnd, IDC_BTN_DOWNLOAD, sumData); SetDlgItemText(hWnd, IDC_PROGRESS_RANGE, sumData); } }while(!bPaused && !bStop); if (bPaused && !bStop) { InternetCloseHandle(hopen); fclose(fp); MessageBox(hWnd, _T("已暂停!"), _T("提示"), MB_OK); SetDlgItemText(hWnd, IDC_BTN_PAUSE, _T("继续")); return 0; } if(bStop)//bStop = true { InternetCloseHandle(hopen); fclose(fp); MessageBox(hWnd, _T("已停止下载!"), _T("提示"), MB_OK); SetDlgItemText(hWnd, IDC_PROGRESS_RANGE, _T("0 %")); EnableWindow(hFileAddrWnd,TRUE); EnableWindow(hDownLoadBtnWnd,TRUE); EnableWindow(hPauseBtnWnd,FALSE); EnableWindow(hStopBtnWnd,FALSE); SetDlgItemText(hWnd,IDC_BTN_DOWNLOAD,_T("下载")); SendMessage(hProgressBarWnd, PBM_SETPOS, (WPARAM)0, (LPARAM)0); //将进度条复位 SetDlgItemText(hWnd,IDC_FILE_SAVEPATH,_T("")); EnableWindow(hBrowserBtnWnd,TRUE); bStop = FALSE; return 0; } EnableWindow(hDownLoadBtnWnd , TRUE); SetDlgItemText(hWnd, IDC_BTN_DOWNLOAD, _T("下载")); EnableWindow(hPauseBtnWnd , FALSE); SetDlgItemText(hWnd, IDC_BTN_PAUSE, _T("暂停")); InternetCloseHandle(hopen); fclose(fp); MessageBox(hWnd, _T("下载成功"), _T("提示"), MB_OK); SendMessage(hProgressBarWnd, PBM_SETPOS, (WPARAM)range.iLow, (LPARAM)0); //将进度条复位 SetDlgItemText(hWnd, IDC_PROGRESS_RANGE, _T("0 %")); EnableWindow(hFileAddrWnd,TRUE); EnableWindow(hStopBtnWnd,FALSE); return 0; }
CHECK_RESULT _UpdWatcher_Check (UPDWATCHER * p) { BOOL bSuccess ; CHECK_RESULT nResult = CHECK_UNDEFINED ; if( Config_GetInteger(CFGINT_CHECK_FOR_UPDATES) ) { DWORD dwState = INTERNET_CONNECTION_OFFLINE ; // check if a connection is available bSuccess = InternetGetConnectedState (&dwState, 0) ; // connection available ? if( bSuccess ) { // open session HINTERNET hSession = InternetOpen (TEXT(APPLICATION_NAME), 0, NULL, NULL, 0) ; // session opened ? if( hSession ) { // open connection HINTERNET hConnect = InternetConnect (hSession, szServerName, nServerPort, szUsername, szPassword, INTERNET_SERVICE_HTTP, 0,0) ; // connexion opened ? if( hConnect ) { // open request HINTERNET hRequest = HttpOpenRequest (hConnect, TEXT("GET"), szObjectName, HTTP_VERSION, NULL, NULL, INTERNET_FLAG_RELOAD,0) ; // request opened ? if( hRequest ) { // send request bSuccess = HttpSendRequest (hRequest, NULL, 0, 0, 0) ; // request sent ? if( bSuccess ) { char szContent[256] ; DWORD dwContentMax = 256 ; DWORD dwBytesRead ; // read file bSuccess = InternetReadFile (hRequest, szContent, dwContentMax, &dwBytesRead); // failed to read file ? if( bSuccess ) { char * szVersion ; szContent[dwBytesRead] = 0 ; // look for version string szVersion = strstr (szContent, "<!-- Version: ") ; // failed ? if( szVersion ) { int nHigh, nMed, nLow ; int nNetVersion, nMyVersion ; szVersion += 14 ; // read net's version sscanf (szVersion, "%d.%d.%d", &nHigh, &nMed, &nLow) ; nNetVersion = (nHigh*256 + nMed)*256 + nLow ; TRACE_INFO (TEXT("Net version = %d.%d.%d\n"), nHigh, nMed, nLow) ; // save net version wsprintf (p->szNewVersion, TEXT("%d.%d.%d"), nHigh, nMed, nLow) ; // read my version sscanf (APPLICATION_VERSION_STRING, "%d.%d.%d", &nHigh, &nMed, &nLow) ; nMyVersion = (nHigh*256 + nMed)*256 + nLow ; TRACE_INFO (TEXT("Local version = %d.%d.%d\n"), nHigh, nMed, nLow) ; // compare versions bSuccess = nNetVersion > nMyVersion ; nResult = bSuccess ? CHECK_DIFFERENT_VERSION : CHECK_SAME_VERSION ; if( bSuccess ) { char *szStartPage, *szEndPage ; // look for page address szStartPage = strstr (szContent, "<!-- Page: ") ; // failed ? if( szStartPage ) { szStartPage += 11 ; szEndPage = strstr (szStartPage, " -->") ; if( szEndPage ) { int nLen = min (szEndPage-szStartPage, MAX_PATH) ; nLen = MultiByteToWideChar (CP_ACP, 0, szStartPage, nLen, p->szDownloadPage, MAX_PATH) ; p->szDownloadPage[nLen] = 0 ; TRACE_INFO (TEXT("Download page = %s\n"), p->szDownloadPage) ; } } } } else nResult = CHECK_LOOK_FOR_VERSION_FAILED ; } else nResult = CHECK_READ_FILE_FAILED ; } else nResult = CHECK_SEND_REQUEST_FAILED ; // close request InternetCloseHandle (hRequest) ; } else nResult = CHECK_OPEN_REQUEST_FAILED ; // close connection InternetCloseHandle (hConnect) ; } else nResult = CHECK_OPEN_CONNECT_FAILED ; // close session InternetCloseHandle (hSession) ; } else nResult = CHECK_OPEN_SESSION_FAILED ; } else nResult = CHECK_NO_CONNECTION ; } else nResult = CHECK_DISABLED ; return nResult ; }
wxString DownloadURL( const wxString& server, const wxString& path ) { HINTERNET hInternetOpen = 0; HINTERNET hInternetConnect = 0; HINTERNET hHttpOpenRequest = 0; char sReadBuffer[2048] = ""; DWORD dwLengthSizeBuffer = sizeof(sReadBuffer); long lRetVal(0), bRet(0), bDoLoop(1); ULONG lNumberOfBytesRead(0); wxString tmp, sBuffer; if (!InternetGetConnectedState(0, 0)) return wxT(""); hInternetOpen = InternetOpen(USER_AGENT, INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, 0); if( hInternetOpen ) { hInternetConnect = InternetConnect(hInternetOpen, server, INTERNET_DEFAULT_HTTP_PORT, NULL, AGENT, INTERNET_SERVICE_HTTP, 0, 0); if ( hInternetConnect ) { hHttpOpenRequest = HttpOpenRequest(hInternetConnect, wxT("GET"), path, AGENT, NULL, 0, INTERNET_FLAG_RELOAD | INTERNET_FLAG_DONT_CACHE, 0); if ( hHttpOpenRequest ) { long tmpVar; tmpVar = 10000; lRetVal = InternetSetOption(hHttpOpenRequest, INTERNET_OPTION_CONNECT_TIMEOUT, &tmpVar, 4); tmpVar = 15000; lRetVal = InternetSetOption(hHttpOpenRequest, INTERNET_OPTION_RECEIVE_TIMEOUT, &tmpVar, 4); tmpVar = 20000; lRetVal = InternetSetOption(hHttpOpenRequest, INTERNET_OPTION_SEND_TIMEOUT, &tmpVar, 4); bRet = HttpAddRequestHeaders(hHttpOpenRequest, DEFAULT_HEADERS, wxStrlen(DEFAULT_HEADERS), HTTP_ADDREQ_FLAG_REPLACE | HTTP_ADDREQ_FLAG_ADD); bRet = HttpSendRequest(hHttpOpenRequest, NULL, 0, 0, 0); while ( bDoLoop ) { sReadBuffer[0] = 0; bDoLoop = InternetReadFile(hHttpOpenRequest, sReadBuffer, dwLengthSizeBuffer, &lNumberOfBytesRead); if ( lNumberOfBytesRead > 0 ) { tmp = wxString(sReadBuffer, wxConvLibc); tmp.Truncate(lNumberOfBytesRead); sBuffer += tmp; } else { bDoLoop = 0; } } bRet = InternetCloseHandle(hHttpOpenRequest); } // if ( hHttpOpenRequest ) bRet = InternetCloseHandle(hInternetConnect); } // if ( hInternetConnect ) bRet = InternetCloseHandle(hInternetOpen); } // if( hInternetOpen ) return sBuffer; }
/* * 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); }