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; }
// 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; } }
bool ResourceHandle::start(Frame* frame) { ref(); if (url().isLocalFile()) { String path = url().path(); // windows does not enjoy a leading slash on paths if (path[0] == '/') path = path.substring(1); // FIXME: This is wrong. Need to use wide version of this call. d->m_fileHandle = CreateFileA(path.utf8().data(), GENERIC_READ, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); // FIXME: perhaps this error should be reported asynchronously for // consistency. if (d->m_fileHandle == INVALID_HANDLE_VALUE) { delete this; return false; } d->m_fileLoadTimer.startOneShot(0.0); return true; } else { static HINTERNET internetHandle = 0; if (!internetHandle) { String userAgentStr = frame->loader()->userAgent() + String("", 1); LPCWSTR userAgent = reinterpret_cast<const WCHAR*>(userAgentStr.characters()); // leak the Internet for now internetHandle = InternetOpen(userAgent, INTERNET_OPEN_TYPE_PRECONFIG, 0, 0, INTERNET_FLAG_ASYNC); } if (!internetHandle) { delete this; return false; } static INTERNET_STATUS_CALLBACK callbackHandle = InternetSetStatusCallback(internetHandle, transferJobStatusCallback); initializeOffScreenResourceHandleWindow(); d->m_jobId = addToOutstandingJobs(this); DWORD flags = INTERNET_FLAG_KEEP_CONNECTION | INTERNET_FLAG_IGNORE_REDIRECT_TO_HTTPS | INTERNET_FLAG_IGNORE_REDIRECT_TO_HTTP; // For form posting, we can't use InternetOpenURL. We have to use // InternetConnect followed by HttpSendRequest. HINTERNET urlHandle; String referrer = frame->loader()->referrer(); if (method() == "POST") { d->m_postReferrer = referrer; String host = url().host(); urlHandle = InternetConnectA(internetHandle, host.latin1().data(), url().port(), NULL, // no username NULL, // no password INTERNET_SERVICE_HTTP, flags, (DWORD_PTR)d->m_jobId); } else { String urlStr = url().string(); int fragmentIndex = urlStr.find('#'); if (fragmentIndex != -1) urlStr = urlStr.left(fragmentIndex); String headers; if (!referrer.isEmpty()) headers += String("Referer: ") + referrer + "\r\n"; urlHandle = InternetOpenUrlA(internetHandle, urlStr.latin1().data(), headers.latin1().data(), headers.length(), flags, (DWORD_PTR)d->m_jobId); } if (urlHandle == INVALID_HANDLE_VALUE) { delete this; return false; } d->m_threadId = GetCurrentThreadId(); return true; } }
/* Downloads the given url and returns the webpage as dynamically allocated string. You need to free the returned string after use! */ BYTE* DownloadUrl(HINTERNET handle, std::wstring& url, DWORD* dataSize, bool forceReload) { DWORD flags = INTERNET_FLAG_RESYNCHRONIZE; if (forceReload) { flags = INTERNET_FLAG_RELOAD; } HINTERNET hUrlDump = InternetOpenUrl(handle, url.c_str(), nullptr, 0, flags, 0); if (!hUrlDump) { if (_wcsnicmp(url.c_str(), L"file://", 7) == 0) // file scheme { const std::string urlACP = StringUtil::Narrow(url); hUrlDump = InternetOpenUrlA(handle, urlACP.c_str(), nullptr, 0, flags, 0); } if (!hUrlDump) { return nullptr; } } // Allocate buffer with 3 extra bytes for triple null termination in case the string is // invalid (e.g. when incorrectly using the UTF-16LE codepage for the data). const int CHUNK_SIZE = 8192; DWORD bufferSize = CHUNK_SIZE; BYTE* buffer = (BYTE*)malloc(bufferSize + 3); *dataSize = 0; // Read the data. do { DWORD readSize; if (!InternetReadFile(hUrlDump, buffer + *dataSize, bufferSize - *dataSize, &readSize)) { free(buffer); InternetCloseHandle(hUrlDump); return nullptr; } else if (readSize == 0) { // All data read. break; } *dataSize += readSize; bufferSize += CHUNK_SIZE; buffer = (BYTE*)realloc(buffer, bufferSize + 3); } while (true); InternetCloseHandle(hUrlDump); // Triple null terminate the buffer. buffer[*dataSize] = 0; buffer[*dataSize + 1] = 0; buffer[*dataSize + 2] = 0; return buffer; }
// 通过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; }
// 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; }
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; }