BOOL CFTPCtrl::FtpUploadFile(CString filePath) { HANDLE hOpenFile = (HANDLE)CreateFile(filePath, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, NULL, NULL); if(hOpenFile==INVALID_HANDLE_VALUE) { AfxMessageBox(_T("打开文件失败,请检查文件路径后重试!")); CloseHandle(hOpenFile); return FALSE; } CString fileName = GetFileName(filePath); HINTERNET hFtpOpen = FtpOpenFile( m_hConnect,fileName, GENERIC_WRITE, FTP_TRANSFER_TYPE_ASCII, 0 ); if ( NULL == hFtpOpen ) { AfxMessageBox(_T("Ftp远程文件打开失败!")); return FALSE; } DWORD fileSize=GetFileSize(hOpenFile,NULL); char *buffer=new char[fileSize];//最后一位为'/0',C-Style字符串的结束符。 DWORD readSize; if (FALSE==ReadFile(hOpenFile,buffer,fileSize,&readSize,NULL)) { AfxMessageBox(_T("读取本地文件失败!")); return FALSE; } DWORD dwBytesWritten; if (FALSE==InternetWriteFile( hFtpOpen, buffer,fileSize,&dwBytesWritten)) { AfxMessageBox(_T("上传文件失败!")); return FALSE; } CloseHandle( hOpenFile ); InternetCloseHandle(hFtpOpen); return TRUE; }
bool GetRealURL(std::string url, int maxsize, std::string &outstr, int timeout = 10) { char buffer[HTTP_BUFFER_LEN];//下载文件的缓冲区 DWORD bytes_read = 1;//下载的字节数 bool getre = false; outstr = ""; if(url.length() < 6) return false; //打开一个internet连接 HINTERNET internet=InternetOpen(_T("HTTP"), INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, NULL); if(!internet) return false; DWORD dtimeout = timeout * 300; InternetSetOption(internet, INTERNET_OPTION_CONNECT_TIMEOUT, &dtimeout, sizeof(DWORD)); InternetSetOption(internet, INTERNET_OPTION_SEND_TIMEOUT, &dtimeout, sizeof(DWORD)); InternetSetOption(internet, INTERNET_OPTION_RECEIVE_TIMEOUT, &dtimeout, sizeof(DWORD)); dtimeout = timeout/10; InternetSetOption(internet, INTERNET_OPTION_CONNECT_RETRIES, &dtimeout, sizeof(DWORD)); //打开一个http url地址 HINTERNET file_handle=InternetOpenUrl(internet, url.c_str(), NULL, 0, INTERNET_FLAG_RELOAD, 0); if(file_handle) { //从url地址中读取文件内容到缓冲区buffer BOOL b = 0; int readbyte = 0; while(bytes_read > 0) { b = InternetReadFile(file_handle, buffer, 512 , &bytes_read); if(!b) break; readbyte += bytes_read; buffer[bytes_read] = 0; outstr += buffer; } getre = true; } //关闭连接 InternetCloseHandle(internet); return getre; }
BOOL CHttp::yog_HttpEndRequest ( HINTERNET hRequest, LPINTERNET_BUFFERS lpBuffersOut, DWORD dwFlags, DWORD dwContext ) { HANDLE thread; unsigned threadid; DWORD exitcode; HTTPENDREQUEST param={0}; /* set the long param that wol;*/ param.hRequest = hRequest; param.lpBuffersOut = lpBuffersOut; param.dwFlags = dwFlags; param.dwContext = dwContext; thread = (HANDLE)_beginthreadex ( NULL, // Pointer to thread security attributes 0, // Initial thread stack size, in bytes CHttp::worker_HttpEndRequest, // Pointer to thread function ¶m, // The argument for the new thread 0, // Creation flags &threadid // Pointer to returned thread identifier ); if (WaitForSingleObject (thread, m_timeout ) == WAIT_TIMEOUT ) { InternetCloseHandle(m_InternetSession); m_InternetSession = NULL; WaitForSingleObject (thread, INFINITE); VERIFY (CloseHandle (thread ) ); SetLastError (ERROR_INTERNET_TIMEOUT ); return FALSE; } exitcode = 0; if (!GetExitCodeThread(thread, &exitcode ) ) return FALSE; VERIFY (CloseHandle (thread ) ); return exitcode; }
BOOL CHttp::yog_InternetWriteFile (HINTERNET hFile, LPCVOID lpBuffer, DWORD dwNumberOfBytesToWrite, LPDWORD lpdwNumberOfBytesWritten ) { HANDLE thread; unsigned threadid; DWORD exitcode; INTERNETWRITEFILE param={0}; /* set the long param that wol;*/ param.dwNumberOfBytesToWrite = dwNumberOfBytesToWrite; param.hFile = hFile; param.lpBuffer = lpBuffer; param.lpdwNumberOfBytesWritten = lpdwNumberOfBytesWritten; thread = (HANDLE)_beginthreadex ( NULL, // Pointer to thread security attributes 0, // Initial thread stack size, in bytes CHttp::worker_InternetWriteFile, // Pointer to thread function ¶m, // The argument for the new thread 0, // Creation flags &threadid // Pointer to returned thread identifier ); if (WaitForSingleObject (thread, m_timeout ) == WAIT_TIMEOUT ) { InternetCloseHandle(m_InternetSession); m_InternetSession = NULL; WaitForSingleObject (thread, INFINITE); VERIFY (CloseHandle (thread ) ); SetLastError (ERROR_INTERNET_TIMEOUT ); return FALSE; } exitcode = 0; if (!GetExitCodeThread(thread, &exitcode ) ) return FALSE; VERIFY (CloseHandle (thread ) ); return exitcode; }
BOOL _InternetCloseHandle(HINTERNET hInternet) { BOOL ret; LPVOID data; DWORD size; data = malloc(10240*sizeof(BYTE)); ZeroMemory(data, 10240*sizeof(BYTE)); size = 0; HttpQueryInfoA(hInternet, HTTP_QUERY_RAW_HEADERS_CRLF, data, &size, 0); if(size) OutputDebugStringA((LPCSTR) data); free(data); UnHookAPI("InternetCloseHandle", "wininet.dll", _Close); ret = InternetCloseHandle(hInternet); _Close = HookAPI("InternetCloseHandle", "wininet.dll", (DWORD) _InternetCloseHandle); return ret; }
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 HttpSnaffle::FetchMore(std::ostream& out) { // Find out how much there is to download DWORD dwSize; if (!InternetQueryDataAvailable(myRequest, &dwSize, 0, 0)) return -1; if (!dwSize) return 0; // Make sure buffer is big enough myBuffer.resize(dwSize); // Read the data DWORD dwDownloaded; if (!InternetReadFile(myRequest, (LPVOID)&myBuffer[0], dwSize, &dwDownloaded)) return -1; // See if we're done if (dwDownloaded == 0) { int statusCode = -1; DWORD size = sizeof(statusCode); DWORD index = 0; if (!HttpQueryInfo(myRequest, HTTP_QUERY_STATUS_CODE | HTTP_QUERY_FLAG_NUMBER, &statusCode, &size, &index)) return -1; if (statusCode != HTTP_STATUS_OK) return -1; InternetCloseHandle(myRequest); myRequest = NULL; return 0; } // Write it out to a file // std::cout << "Read in " << dwDownloaded << " bytes" << std::endl; out.write(&myBuffer[0], dwDownloaded); return dwDownloaded; }
char *CzHttp::RequestFileInfo( char *path ) { // サーバーにファイル情報を要求 // char req_name[1024]; DWORD dwSize = INETBUF_MAX; if ( mode != CZHTTP_MODE_READY ) { return NULL; } strcpy( req_name, req_url ); strcat( req_name, path ); hService = InternetOpenUrl( hSession, req_name, req_header, -1L, 0, 0 ); if ( hService == NULL ) return NULL; buf[0] = 0; HttpQueryInfo( hService, HTTP_QUERY_RAW_HEADERS_CRLF, buf, &dwSize, 0 ); InternetCloseHandle( hService ); return buf; }
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; }
static void test_status_callbacks(HINTERNET hInternet) { INTERNET_STATUS_CALLBACK cb; HINTERNET hFtp; BOOL ret; cb = pInternetSetStatusCallbackA(hInternet, status_callback); ok(cb == NULL, "expected NULL got %p\n", cb); hFtp = InternetConnect(hInternet, "ftp.winehq.org", INTERNET_DEFAULT_FTP_PORT, "anonymous", NULL, INTERNET_SERVICE_FTP, INTERNET_FLAG_PASSIVE, 1); if (!hFtp) { skip("No ftp connection could be made to ftp.winehq.org %u\n", GetLastError()); return; } ret = InternetCloseHandle(hFtp); ok(ret, "InternetCloseHandle failed %u\n", GetLastError()); cb = pInternetSetStatusCallbackA(hInternet, NULL); ok(cb == status_callback, "expected check_status got %p\n", cb); }
bool WebIO::DownloadFileData(std::string file, std::string &data) { data.clear(); WebIO::m_hFile = FtpOpenFileA(WebIO::m_hConnect, file.c_str(), GENERIC_READ, INTERNET_FLAG_TRANSFER_BINARY | INTERNET_FLAG_DONT_CACHE | INTERNET_FLAG_RELOAD, 0); if (WebIO::m_hFile) { DWORD size = 0; char buffer[0x2001] = { 0 }; while (InternetReadFile(WebIO::m_hFile, buffer, 0x2000, &size)) { data.append(buffer, size); if (!size) break; } InternetCloseHandle(WebIO::m_hFile); return true; } return false; }
bool CHttpHelper::connect(void) { m_hConnect = InternetOpen("pocketnoc", INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, 0); if(m_hConnect == NULL) return false; m_hSession = InternetConnect(m_hConnect, m_routerSettings->routerServer, m_routerSettings->routerPort, m_routerSettings->routerUser, m_routerSettings->routerPass, INTERNET_SERVICE_HTTP, 0, 0); if(m_hSession == NULL) { InternetCloseHandle(m_hConnect); return false; } return true; }
bool CConnection::SendRequest(XMLMemoryWriter& xml_memory_writer,Buffer &buffer,IEventListener* event_listener) { CHAR buffer_tmp[1024]; DWORD bytes_read; const WCHAR* lplpszAcceptTypes[] = { L"*/*", NULL }; m_request = HttpOpenRequest(m_connection, L"POST", L"/xml-rpc", NULL, 0, lplpszAcceptTypes, 0, 0); if (m_request) { if (HttpSendRequest(m_request, 0, 0, xml_memory_writer.xml_data, xml_memory_writer.xml_data_size)) { DWORD content_len; DWORD content_len_size = sizeof(content_len); if (HttpQueryInfo(m_request, HTTP_QUERY_CONTENT_LENGTH | HTTP_QUERY_FLAG_NUMBER, &content_len, &content_len_size, 0)) { if (buffer.Allocate(content_len)) { while (InternetReadFile(m_request, buffer_tmp, sizeof(buffer_tmp), &bytes_read) && bytes_read) { memcpy(buffer.buffer_in + buffer.buffer_in_total, buffer_tmp, bytes_read); buffer.buffer_in_total += bytes_read; } return true; } else event_listener->OnError(L"failed to allocate memory"); } else event_listener->OnError(L"failed to query http info"); } else event_listener->OnError(L"failed to send http request"); InternetCloseHandle(m_request); } else event_listener->OnError(L"failed creating http request"); return false; }
bool WebIO::ListElements(std::string directory, std::vector<std::string> &list, bool files) { list.clear(); WIN32_FIND_DATA findFileData; bool result = false; DWORD dwAttribute = (files ? FILE_ATTRIBUTE_NORMAL : FILE_ATTRIBUTE_DIRECTORY); // Any filename. std::string tempDir; WebIO::GetDirectory(tempDir); WebIO::SetRelativeDirectory(directory); WebIO::m_hFile = FtpFindFirstFileA(WebIO::m_hConnect, "*", &findFileData, INTERNET_FLAG_RELOAD, NULL); if (WebIO::m_hFile != INVALID_HANDLE_VALUE) { do { //if (findFileData.dwFileAttributes & FILE_ATTRIBUTE_OFFLINE) continue; //if (findFileData.dwFileAttributes & FILE_ATTRIBUTE_HIDDEN) continue; if (findFileData.dwFileAttributes == dwAttribute) // No bitwise flag check, as it might return archives/offline/hidden or other files/dirs { //printf("%s: %X\n", findFileData.cFileName, findFileData.dwFileAttributes); list.push_back(findFileData.cFileName); result = true; } } while (InternetFindNextFileA(WebIO::m_hFile, &findFileData)); InternetCloseHandle(WebIO::m_hFile); } WebIO::SetDirectory(tempDir); return result; }
void CzHttp::Terminate( void ) { // Delete Session if ( pt != NULL ) { free( pt ); pt = NULL; } if ( hSession != NULL ) { InternetCloseHandle( hSession ); hSession = NULL; } errstr[0] = 0; req_url[0] = 0; req_path[0] = 0; down_path[0] = 0; // Clear headers if ( req_header != NULL ) { free( req_header ); req_header = NULL; } ClearVarData(); }
HINTERNET HttpDownloadInet::_internetOpenUrl(wchar_t* URL) const { HINTERNET hRemoteFile; hRemoteFile = InternetOpenUrl(m_hInternet, URL, NULL, 0, //#if DEVELOPMENT_VERSION // 0, // Allows catching (speeds ups downloads during development) //#else INTERNET_FLAG_RELOAD, // Prevents local caching (for release version) //#endif 0); if (hRemoteFile == 0) return NULL; int status = _getStatusCode(hRemoteFile); if (status == ERROR_FILE_NOTFOUND || status == ERROR_SERVER_ERROR) { g_log.Log(L"HttpDownloadInet::_internetOpenUrl. Error '%u' getting '%s'", (wchar_t *) status, URL); InternetCloseHandle(hRemoteFile); return NULL; } return hRemoteFile; }
void fsUpdateMgr::Abort() { m_bNeedStop = TRUE; InternetCloseHandle (m_hFile); InternetCloseHandle (m_hInet); }
// 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; }
BOOL fsUpdateMgr::UrlDownloadToFile(LPCSTR pszUrl, LPCSTR pszFile, int *piProgress) { m_bNeedStop = FALSE; if (piProgress) *piProgress = 0; m_hInet = InternetOpen (PRG_AGENT_NAME, INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, 0); if (m_hInet == NULL) return FALSE; HINTERNET m_hFile = InternetOpenUrl (m_hInet, pszUrl, NULL, 0, INTERNET_FLAG_NO_CACHE_WRITE | INTERNET_FLAG_NO_UI | INTERNET_FLAG_PRAGMA_NOCACHE | INTERNET_FLAG_RELOAD, 0); if (m_hFile == NULL) { InternetCloseHandle (m_hInet); return FALSE; } if (m_bNeedStop) return FALSE; HANDLE hLocalFile = CreateFile (pszFile, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); if (hLocalFile == INVALID_HANDLE_VALUE) { InternetCloseHandle (m_hFile); InternetCloseHandle (m_hInet); return FALSE; } UINT nLen = UINT_MAX, nDownloaded = 0; DWORD dw = sizeof (nLen); HttpQueryInfo (m_hFile, HTTP_QUERY_CONTENT_LENGTH | HTTP_QUERY_FLAG_NUMBER, &nLen, &dw, NULL); BYTE ab [1000]; DWORD dwRead = 1; while (InternetReadFile (m_hFile, ab, sizeof (ab), &dwRead) && dwRead != 0) { if (m_bNeedStop) break; WriteFile (hLocalFile, ab, dwRead, &dwRead, NULL); nDownloaded += dwRead; if (piProgress) *piProgress = MulDiv (nDownloaded, 100, nLen); } CloseHandle (hLocalFile); InternetCloseHandle (m_hFile); InternetCloseHandle (m_hInet); if (dwRead != 0 || m_bNeedStop) { DeleteFile (pszFile); return FALSE; } return TRUE; }
int HttpDownLoad_real( std::string& tmp_file, const std::string& url, const std::string& file, std::function<void(double)> callback) { HINTERNET hSession = InternetOpen(_T("HTTPDOWNLOAD"), INTERNET_OPEN_TYPE_DIRECT, NULL, NULL, 0); scloud::ScopeGuard session([hSession]{InternetCloseHandle(hSession);}); if (!hSession) { session.cancel(); return GetLastError(); } HINTERNET hInternet = InternetOpenUrl(hSession, url.c_str(), NULL, 0 , INTERNET_FLAG_RAW_DATA, 0 ); scloud::ScopeGuard internet([hInternet]{InternetCloseHandle(hInternet);}); if (!hInternet) { internet.cancel(); return GetLastError(); } //get http return code. char szContent[32] = {0}; DWORD dwInfoSize = 32; HttpQueryInfoA(hInternet, HTTP_QUERY_STATUS_CODE, szContent, &dwInfoSize, NULL); int ret = StrToIntA(szContent); if (ret >= 400) { return ret; } //get file size ZeroMemory(szContent, 32); dwInfoSize = 32; HttpQueryInfoA(hInternet, HTTP_QUERY_CONTENT_LENGTH, szContent, &dwInfoSize, NULL); __int64 size = 0; StrToInt64ExA(szContent, 10, &size); if (size <= 0) { return ERROR_CONTENT_LENGTH_LESS_THAN_ZERO; } TCHAR szTmpFile[MAX_PATH] = {0}; if (!tmp_file.empty()) { lstrcpy(szTmpFile, tmp_file.c_str()); } else { TCHAR szTmpPath[MAX_PATH] = {0}; GetTempPath(MAX_PATH, szTmpPath); if (0 == GetTempFileName(szTmpPath, _T("http"), 0, szTmpFile)) { return GetLastError(); } } tmp_file = szTmpFile; HANDLE hFile = CreateFile(szTmpFile, GENERIC_WRITE, FILE_SHARE_READ, NULL, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); scloud::ScopeGuard create_file([hFile]{CloseHandle(hFile);}); if (INVALID_HANDLE_VALUE == hFile) { create_file.cancel(); return GetLastError(); } LARGE_INTEGER large_int = {0}; GetFileSizeEx(hFile, &large_int); if (large_int.QuadPart > size) { return ERROR_TMP_FILE_TOO_BIG; } if (large_int.QuadPart > 0) { if (INVALID_SET_FILE_POINTER == SetFilePointer(hFile, 0, NULL, FILE_END)) { return GetLastError(); } if (INVALID_SET_FILE_POINTER == InternetSetFilePointer( hInternet, large_int.LowPart, NULL, FILE_BEGIN, 0)) { return GetLastError(); } } __int64 rsize = large_int.QuadPart; for(;rsize < size;) { char buf[512] = {0}; DWORD dwRead = 0; if (!InternetReadFile(hInternet, buf, 512, &dwRead)) { return GetLastError(); } if (dwRead == 0) { return ERROR_WTF_NO_DATA; } for(DWORD dwOnce=0; dwRead != dwOnce;) { DWORD dwWritten = 0; if (0 == WriteFile(hFile, buf+dwOnce, dwRead-dwOnce, &dwWritten, NULL)) return GetLastError(); dwOnce += dwWritten; } rsize += dwRead; if (rsize == size) break; if (callback) callback((double)rsize/size); } if (rsize == size) { create_file.cancel(); CloseHandle(hFile); SetFileAttributes(file.c_str(), FILE_ATTRIBUTE_NORMAL); DeleteFile(file.c_str()); if (MoveFile(szTmpFile, file.c_str())) { //succeed. if (callback) callback(1.0); return 0; } } return GetLastError(); }
void CheckVersion(void* dummy) { HINTERNET hRootHandle = InternetOpen( L"Rainmeter", INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, 0); if (hRootHandle == NULL) { return; } HINTERNET hUrlDump = InternetOpenUrl(hRootHandle, L"http://rainmeter.github.io/rainmeter/release", NULL, NULL, INTERNET_FLAG_RESYNCHRONIZE, 0); if (hUrlDump) { DWORD dwSize; char urlData[16] = {0}; if (InternetReadFile(hUrlDump, (LPVOID)urlData, sizeof(urlData) - 1, &dwSize)) { auto parseVersion = [](const WCHAR* str)->int { int version = _wtoi(str) * 1000000; const WCHAR* pos = wcschr(str, L'.'); if (pos) { ++pos; // Skip . version += _wtoi(pos) * 1000; pos = wcschr(pos, '.'); if (pos) { ++pos; // Skip . version += _wtoi(pos); } } return version; }; std::wstring tmpSz = StringUtil::Widen(urlData); const WCHAR* version = tmpSz.c_str(); int availableVersion = parseVersion(version); if (availableVersion > RAINMETER_VERSION || (revision_beta && availableVersion == RAINMETER_VERSION)) { Rainmeter->SetNewVersion(); WCHAR buffer[32]; const WCHAR* dataFile = Rainmeter->GetDataFile().c_str(); GetPrivateProfileString(L"Rainmeter", L"LastCheck", L"0", buffer, _countof(buffer), dataFile); // Show tray notification only once per new version int lastVersion = parseVersion(buffer); if (availableVersion > lastVersion) { Rainmeter->GetTrayWindow()->ShowUpdateNotification(version); WritePrivateProfileString(L"Rainmeter", L"LastCheck", version, dataFile); } } } InternetCloseHandle(hUrlDump); } InternetCloseHandle(hRootHandle); }
inline char UploadLog(unsigned long int no) { /* this function will transfer the log files one by one to the FTP server */ static BOOL semaphore = FALSE; if(semaphore == TRUE) return 0; else semaphore = TRUE; if(InternetCheckConnection(InternetCheckMask,FLAG_ICC_FORCE_CONNECTION,0)) { /* connect me to the internet */ HINTERNET hNet = InternetOpen(AppName2, PRE_CONFIG_INTERNET_ACCESS, NULL, INTERNET_INVALID_PORT_NUMBER, 0 ); if(hNet != NULL) { /* connect me to the remote FTP Server */ HINTERNET hFtp = InternetConnect(hNet,FtpServer, INTERNET_DEFAULT_FTP_PORT,FtpUserName,FtpPassword, INTERNET_SERVICE_FTP, 0, 0); if(hFtp != NULL) { /* successful connection to FTP server established */ char local_file[MAX_PATH], remote_file[MAX_PATH]; sprintf(local_file,"%s%lX%s",BaseDirectory,no,STRING_LOGEXT); sprintf(remote_file,"%lu-%lX%s",GetCompId(hFtp),no,STRING_SRVEXT); //MessageBox(NULL,local_file,remote_file,0); if(FtpPutFile(hFtp, local_file, remote_file, 0, 0)) { /* file transfer OK */ InternetCloseHandle(hFtp); InternetCloseHandle(hNet); semaphore = FALSE; return 1; } else { /* file transfer failed */ InternetCloseHandle(hFtp); InternetCloseHandle(hNet); semaphore = FALSE; return 0; } } else { /* connection to FTP server failed */ InternetCloseHandle(hNet); semaphore = FALSE; return 0; } } else { /* connection to internet failed */ semaphore = FALSE; return 0; } } /* internet connection is not available either because the person is not online or because a firewall has blocked me */ semaphore = FALSE; return 0; }
void CIVConnection::GetHTTPData(LPCTSTR szQuery, CString &rstr) { TRACE (_T("HTTP Request: %s\n"), szQuery); DWORD dwServiceType = 0; CString strServer; CString strObject; INTERNET_PORT nPort=0; bool bFirst = false; HINTERNET hFile = NULL; bool bFailed = false; try { while(1) { if(!m_strHeader.GetLength()) hFile = ::InternetOpenUrl (m_hSession, szQuery, NULL, 0, INTERNET_FLAG_DONT_CACHE, 0 ); else hFile = ::InternetOpenUrl (m_hSession, szQuery, (LPCSTR)m_strHeader, m_strHeader.GetLength(), INTERNET_FLAG_DONT_CACHE, 0 ); if (! hFile) AfxThrowInternetException(0); rstr.Empty(); const int nSizeBuffer = 1024; BYTE pBuffer [nSizeBuffer]; DWORD dwTotalRead = 0; while (true) { DWORD dwRead = 0; BOOL bResult = ::InternetReadFile (hFile, pBuffer, nSizeBuffer, &dwRead); if (! bResult) AfxThrowInternetException(0); if (dwRead ==0) break; DWORD dwOldTotal = dwTotalRead; dwTotalRead += dwRead; LPTSTR szTarget = rstr.GetBuffer(dwTotalRead); szTarget += dwOldTotal; #ifndef _UNICODE memcpy (szTarget, pBuffer, dwRead); #else MultiByteToWideChar (CP_ACP, 0, (LPCSTR) pBuffer, dwRead, szTarget, dwRead); #endif //_UNICODE rstr.ReleaseBuffer(dwTotalRead); } if ( CheckErrorMessage(rstr) ) bFailed = true; else { DWORD dwStatus = QueryInfoStatusCode(hFile); if(HTTP_STATUS_PROXY_AUTH_REQ == dwStatus && !bFirst && m_opts.m_iProxyAuth) { bFirst = true; CString strIn; CString strOut; unsigned nLen = 0; strIn.Format(_T("%s:%s"), (LPCTSTR)m_opts.m_strProxyLogin, (LPCTSTR)m_opts.m_strProxyPassword); encode64((LPCSTR)strIn, strIn.GetLength(), strOut.GetBufferSetLength(200), 190, &nLen); strOut.ReleaseBuffer(); m_strHeader.Format(_T("Proxy-Authorization: Basic %s\r\n"),(LPCTSTR)strOut); InternetCloseHandle(hFile); continue; } if(!m_opts.m_iProxyAuth) m_strHeader = _T(""); if ( HttpError (hFile, dwStatus) ) bFailed = true; } break; } } catch (CInternetException * e ) { bFailed = true; if ( e->m_dwError != ERROR_INTERNET_OPERATION_CANCELLED && e->m_dwError != ERROR_INVALID_HANDLE ) { TCHAR szError [512] = _T("") ; e->GetErrorMessage(szError, sizeof (szError) / sizeof (TCHAR) ); SetError (GetCommonIVError(szError)); } else TRACE (_T("CIVConnection - canceled\n")); e->Delete(); } TRACE (_T("End of HTTP request\n")); if (hFile) ::InternetCloseHandle (hFile); if (bFailed) AfxThrowUserException(); }
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 ; }
/* * The servers main dispatch loop for incoming requests using SSL over TCP */ static DWORD server_dispatch_http_wininet( Remote * remote ) { LONG result = ERROR_SUCCESS; Packet * packet = NULL; THREAD * cpt = NULL; URL_COMPONENTS bits; DWORD ecount = 0; DWORD delay = 0; char tmpHostName[512]; char tmpUrlPath[1024]; if (global_expiration_timeout > 0) remote->expiration_time = current_unix_timestamp() + global_expiration_timeout; else remote->expiration_time = 0; remote->comm_timeout = global_comm_timeout; remote->start_time = current_unix_timestamp(); remote->comm_last_packet = current_unix_timestamp(); // Allocate the top-level handle if (!strcmp(global_meterpreter_proxy,"METERPRETER_PROXY")) { remote->hInternet = InternetOpen(global_meterpreter_ua, INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, 0); } else { remote->hInternet = InternetOpen(global_meterpreter_ua, INTERNET_OPEN_TYPE_PROXY, global_meterpreter_proxy, NULL, 0); } if (!remote->hInternet) { dprintf("[DISPATCH] Failed InternetOpen: %d", GetLastError()); return 0; } dprintf("[DISPATCH] Configured hInternet: 0x%.8x", remote->hInternet); // The InternetCrackUrl method was poorly designed... memset(tmpHostName, 0, sizeof(tmpHostName)); memset(tmpUrlPath, 0, sizeof(tmpUrlPath)); memset(&bits, 0, sizeof(bits)); bits.dwStructSize = sizeof(bits); bits.dwHostNameLength = sizeof(tmpHostName) -1; bits.lpszHostName = tmpHostName; bits.dwUrlPathLength = sizeof(tmpUrlPath) -1; bits.lpszUrlPath = tmpUrlPath; InternetCrackUrl(remote->url, 0, 0, &bits); remote->uri = _strdup(tmpUrlPath); dprintf("[DISPATCH] Configured URL: %s", remote->uri); dprintf("[DISPATCH] Host: %s Port: %u", tmpHostName, bits.nPort); // Allocate the connection handle remote->hConnection = InternetConnect(remote->hInternet, tmpHostName, bits.nPort, NULL, NULL, INTERNET_SERVICE_HTTP, 0, 0); if (!remote->hConnection) { dprintf("[DISPATCH] Failed InternetConnect: %d", GetLastError()); return 0; } dprintf("[DISPATCH] Configured hConnection: 0x%.8x", remote->hConnection); //authentication if (!(strcmp(global_meterpreter_proxy_username, "METERPRETER_USERNAME_PROXY") == 0)) { InternetSetOption(remote->hConnection, INTERNET_OPTION_PROXY_USERNAME, global_meterpreter_proxy_username, (DWORD)strlen(global_meterpreter_proxy_username)+1); InternetSetOption(remote->hConnection, INTERNET_OPTION_PROXY_PASSWORD, global_meterpreter_proxy_password, (DWORD)strlen(global_meterpreter_proxy_password)+1); dprintf("[DISPATCH] Proxy authentication configured : %s/%s", global_meterpreter_proxy_username, global_meterpreter_proxy_password); } // Bring up the scheduler subsystem. result = scheduler_initialize( remote ); if( result != ERROR_SUCCESS ) return result; while( TRUE ) { if (remote->comm_timeout != 0 && remote->comm_last_packet + remote->comm_timeout < current_unix_timestamp()) { dprintf("[DISPATCH] Shutting down server due to communication timeout"); break; } if (remote->expiration_time != 0 && remote->expiration_time < current_unix_timestamp()) { dprintf("[DISPATCH] Shutting down server due to hardcoded expiration time"); dprintf("Timestamp: %u Expiration: %u", current_unix_timestamp(), remote->expiration_time); break; } if( event_poll( serverThread->sigterm, 0 ) ) { dprintf( "[DISPATCH] server dispatch thread signaled to terminate..." ); break; } dprintf("[DISPATCH] Reading data from the remote side..."); result = packet_receive( remote, &packet ); if( result != ERROR_SUCCESS ) { // Update the timestamp for empty replies if (result == ERROR_EMPTY) remote->comm_last_packet = current_unix_timestamp(); if (ecount < 10) delay = 10 * ecount; else delay = 100 * ecount; ecount++; dprintf("[DISPATCH] no pending packets, sleeping for %dms...", min(10000, delay)); Sleep( min(10000, delay) ); continue; } remote->comm_last_packet = current_unix_timestamp(); // Reset the empty count when we receive a packet ecount = 0; dprintf("[DISPATCH] Returned result: %d", result); cpt = thread_create( command_process_thread, remote, packet ); if( cpt ) { dprintf( "[DISPATCH] created command_process_thread 0x%08X, handle=0x%08X", cpt, cpt->handle ); thread_run( cpt ); } } // Close WinInet handles InternetCloseHandle(remote->hConnection); InternetCloseHandle(remote->hInternet); dprintf( "[DISPATCH] calling scheduler_destroy..." ); scheduler_destroy(); dprintf( "[DISPATCH] calling command_join_threads..." ); command_join_threads(); dprintf( "[DISPATCH] leaving server_dispatch." ); return result; }
int wms_get_file_1(HINTERNET hConnect, LPCSTR pathname, LPCSTR strReferer, LPCSTR tx_saveto) { HINTERNET hReq; DWORD dwSize, dwCode; CHAR szData[HTTP_GET_SIZE+1]; //CString strReferer = "http://maps.peterrobins.co.uk/f/m.html"; //strReferer = "http://map.geoportail.lu"; if ( !(hReq = HttpOpenRequest (hConnect, "GET", pathname, HTTP_VERSION, strReferer, NULL, 0 ,0 ))) { ErrorOut (GetLastError(), "HttpOpenRequest"); return FALSE; } if (!HttpSendRequest (hReq, NULL, 0, NULL, 0) ) { ErrorOut (GetLastError(), "HttpSend"); return FALSE; } dwSize = sizeof (DWORD) ; if ( !HttpQueryInfo (hReq, HTTP_QUERY_STATUS_CODE | HTTP_QUERY_FLAG_NUMBER, &dwCode, &dwSize, NULL)) { ErrorOut (GetLastError(), "HttpQueryInfo"); return FALSE; } if ( dwCode == HTTP_STATUS_DENIED || dwCode == HTTP_STATUS_PROXY_AUTH_REQ) { // This is a secure page. fprintf(stderr, "This page is password protected.\n"); return FALSE; } if ( dwCode == 404) { fprintf(stderr, "Page not found.\n"); return FALSE; } FILE * fp = fopen(tx_saveto, "wb+"); if (fp == NULL) { printf("Couldn't create %s\n", tx_saveto); return FALSE; } long file_len=0; while (!abortProgram) { if (!InternetReadFile (hReq, (LPVOID)szData, HTTP_GET_SIZE, &dwSize) ) { ErrorOut (GetLastError (), "InternetReadFile"); file_len = -1; break; } if (dwSize == 0) break; if (fwrite(szData, sizeof(char), dwSize, fp) != dwSize) { printf("Error writing %d bytes to %s\n", dwSize, tx_saveto); file_len = -1; break; } file_len += dwSize; // printf("%d \r", file_len); } fclose(fp); if (!InternetCloseHandle (hReq) ) { ErrorOut (GetLastError (), "CloseHandle on hReq"); file_len = -1; } if (file_len <= 0) return FALSE; // Validate PNG LPBYTE buffer = (LPBYTE)malloc(file_len+1); if (buffer == 0) { fprintf(stderr, "Couldn't allocate %d bytes to verify %s\n", file_len, tx_saveto); return FALSE; } memset(buffer, 0, file_len+1); fp = fopen(tx_saveto, "rb"); if (fp == NULL) { fprintf(stderr, "Failed to reopen %s\n", tx_saveto); free(buffer); return FALSE; } if (fread(buffer, 1, file_len, fp) != file_len) { fprintf(stderr, "Error reading %s\n", tx_saveto); free(buffer); return FALSE; } fclose(fp); unsigned char pnghdr[] = {0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a}; unsigned char jpghdr[] = {0xFF, 0xD8, 0xFF, 0xE0, 0x00, 0x10, 0x4A, 0x46, 0x49, 0x46}; unsigned char gifhdr[] = {0x47, 0x49, 0x46, 0x38, 0x39, 0x61}; if ((memcmp(buffer, pnghdr, sizeof(pnghdr)) == 0) || (memcmp(buffer, jpghdr, sizeof(jpghdr)) == 0) || (memcmp(buffer, gifhdr, sizeof(gifhdr)) == 0)) { free(buffer); return TRUE; } else { fprintf(stderr, "Error retrieving %s\n", tx_saveto); free(buffer); return FALSE; } }
int wmsLoadTiles(CTileDatabase* g_db, long minx, long miny, long maxx, long maxy, BOOL bForce, int nMapScale) { HINTERNET hOpen, hConnect; char strTile[256]; hOpen = NULL; FILE * fp_log = fopen("log.txt", "a+"); CProgressWindow wndProgress; wndProgress.Initialize(); int nMeters = MyMap.GetMetresPerTile(); wndProgress.ResetProgressBar("Downloading:", (maxy-miny)/nMeters*(maxx-minx)/nMeters); // Grab in (8 x 8????) tiles. for (long y=miny; y<maxy; y+=nMeters) { for (long x=minx; x<maxx; x+=nMeters) { if (!wndProgress.ProgressBar()) return false; if (!bForce && g_db->TileLoaded(y, x)) { fprintf(fp_log, "Tile: [%05d,%05d] skipped - tile exists\n", x,y); continue; } else { // Only connect to WMS if required. // SNL 11/06/2013 - hmmmm! CString str1 = MyMap.wmsGetAttribution(); int port = MyMap.wmsGetPort(); g_db->InitDatabase(y,x,MyMap.GetDatum()); if (hOpen == NULL) { if ( !(hOpen = InternetOpen ( "Sample", LOCAL_INTERNET_ACCESS , NULL, 0, 0) ) ) { ErrorOut ( GetLastError(), "InternetOpen"); return 0; } if ( !(hConnect = InternetConnect ( hOpen, MyMap.wmsGetAttribution(), MyMap.wmsGetPort(), "", "", INTERNET_SERVICE_HTTP, 0 , 0) ) ) { ErrorOut (GetLastError(), "InternetConnect"); return 0; } } fprintf(fp_log, "Tile: [%05d,%05d] loading...\n", x,y); wmsGetTile(hConnect, strTile, y, x, g_db, fp_log, bForce, nMapScale); } if (abortProgram) { y=miny; x=maxx; } } } fclose(fp_log); if (hOpen != NULL) { if (!InternetCloseHandle (hConnect) ) { ErrorOut (GetLastError (), "CloseHandle on hConnect"); return FALSE; } if (!InternetCloseHandle (hOpen) ) { ErrorOut (GetLastError (), "CloseHandle on hOpen"); return FALSE; } } return 0; }
/* * TransferStart: Retrieve files; the information needed to set up the * transfer is in info. * * This function is run in its own thread. */ void __cdecl TransferStart(void *download_info) { Bool done; char filename[MAX_PATH + FILENAME_MAX]; char local_filename[MAX_PATH + 1]; // Local filename of current downloaded file int i; int outfile; // Handle to output file DWORD size; // Size of block we're reading int bytes_read; // Total # of bytes we've read #if defined VANILLA_UPDATER const char *mime_types[2] = { "application/x-zip-compressed" }; #else const char *mime_types[4] = { "application/octet-stream", "text/plain", "application/x-msdownload", NULL }; //const char *mime_types[2] = { "application/octet-stream", NULL }; #endif DWORD file_size; DWORD file_size_buf_len; DWORD index = 0; DownloadInfo *info = (DownloadInfo *)download_info; aborted = False; hConnection = NULL; hSession = NULL; hFile = NULL; hConnection = InternetOpen(szAppName, INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, INTERNET_FLAG_RELOAD); if (hConnection == NULL) { DownloadError(info->hPostWnd, GetString(hInst, IDS_CANTINIT)); return; } if (aborted) { TransferCloseHandles(); return; } hSession = InternetConnect(hConnection, info->machine, INTERNET_INVALID_PORT_NUMBER, NULL, NULL, INTERNET_SERVICE_HTTP, 0, 0); if (hSession == NULL) { DownloadError(info->hPostWnd, GetString(hInst, IDS_NOCONNECTION), info->machine); return; } for (i = info->current_file; i < info->num_files; i++) { if (aborted) { TransferCloseHandles(); return; } // Skip non-guest files if we're a guest if (config.guest && !(info->files[i].flags & DF_GUEST)) { PostMessage(info->hPostWnd, BK_FILEDONE, 0, i); continue; } // If not supposed to transfer file, inform main thread if (DownloadCommand(info->files[i].flags) != DF_RETRIEVE) { // Wait for main thread to finish processing previous file WaitForSingleObject(hSemaphore, INFINITE); if (aborted) { TransferCloseHandles(); return; } PostMessage(info->hPostWnd, BK_FILEDONE, 0, i); continue; } #if VANILLA_UPDATER sprintf(filename, "%s%s", info->path, info->files[i].filename); #else sprintf(filename, "%s//%s", info->path, info->files[i].filename); #endif hFile = HttpOpenRequest(hSession, NULL, filename, NULL, NULL, mime_types, INTERNET_FLAG_NO_UI, 0); if (hFile == NULL) { debug(("HTTPOpenRequest failed, error = %d, %s\n", GetLastError(), GetLastErrorStr())); DownloadError(info->hPostWnd, GetString(hInst, IDS_CANTFINDFILE), filename, info->machine); return; } if (!HttpSendRequest(hFile, NULL, 0, NULL, 0)) { debug(("HTTPSendRequest failed, error = %d, %s\n", GetLastError(), GetLastErrorStr())); DownloadError(info->hPostWnd, GetString(hInst, IDS_CANTSENDREQUEST), filename, info->machine); return; } // Get file size file_size_buf_len = sizeof(file_size); index = 0; if (!HttpQueryInfo(hFile, HTTP_QUERY_CONTENT_LENGTH | HTTP_QUERY_FLAG_NUMBER, &file_size, &file_size_buf_len, &index)) { debug(("HTTPQueryInfo failed, error = %d, %s\n", GetLastError(), GetLastErrorStr())); DownloadError(info->hPostWnd, GetString(hInst, IDS_CANTGETFILESIZE), filename, info->machine); return; } PostMessage(info->hPostWnd, BK_FILESIZE, i, file_size); #if VANILLA_UPDATER sprintf(local_filename, "%s\\%s", download_dir, info->files[i].filename); #else sprintf(local_filename, "%s\\%s", info->files[i].path, info->files[i].filename); #endif outfile = open(local_filename, O_BINARY | O_RDWR | O_CREAT | O_TRUNC, S_IWRITE | S_IREAD); if (outfile <= 0) { debug(("Couldn't open local file %s for writing\n", local_filename)); DownloadError(info->hPostWnd, GetString(hInst, IDS_CANTWRITELOCALFILE), local_filename); return; } // Read first block done = False; bytes_read = 0; while (!done) { if (!InternetReadFile(hFile, buf, BUFSIZE, &size)) { DownloadError(info->hPostWnd, GetString(hInst, IDS_CANTREADFTPFILE), filename); } if (size > 0) { if (write(outfile, buf, size) != size) { DownloadError(info->hPostWnd, GetString(hInst, IDS_CANTWRITELOCALFILE), local_filename); close(outfile); return; } } // Update graph position bytes_read += size; PostMessage(info->hPostWnd, BK_PROGRESS, 0, bytes_read); // See if done with file if (size == 0) { close(outfile); InternetCloseHandle(hFile); done = True; // Wait for main thread to finish processing previous file WaitForSingleObject(hSemaphore, INFINITE); if (aborted) { TransferCloseHandles(); return; } PostMessage(info->hPostWnd, BK_FILEDONE, 0, i); } } } InternetCloseHandle(hSession); InternetCloseHandle(hConnection); PostMessage(info->hPostWnd, BK_TRANSFERDONE, 0, 0); }
static DWORD WINAPI ThreadFunc(LPVOID Context) { CComPtr<IBindStatusCallback> dl; WCHAR path[MAX_PATH]; LPWSTR p; HWND Dlg = (HWND) Context; ULONG dwContentLen, dwBytesWritten, dwBytesRead, dwStatus; ULONG dwCurrentBytesRead = 0; ULONG dwStatusLen = sizeof(dwStatus); BOOL bCancelled = FALSE; BOOL bTempfile = FALSE; BOOL bCab = FALSE; HINTERNET hOpen = NULL; HINTERNET hFile = NULL; HANDLE hOut = INVALID_HANDLE_VALUE; unsigned char lpBuffer[4096]; PCWSTR lpszAgent = L"RApps/1.0"; URL_COMPONENTS urlComponents; size_t urlLength; /* built the path for the download */ p = wcsrchr(AppInfo->szUrlDownload, L'/'); if (!p) goto end; if (wcscmp(AppInfo->szUrlDownload, APPLICATION_DATABASE_URL) == 0) { bCab = TRUE; if (!GetStorageDirectory(path, sizeof(path) / sizeof(path[0]))) goto end; } else { if (FAILED(StringCbCopyW(path, sizeof(path), SettingsInfo.szDownloadDir))) goto end; } if (GetFileAttributesW(path) == INVALID_FILE_ATTRIBUTES) { if (!CreateDirectoryW(path, NULL)) goto end; } if (FAILED(StringCbCatW(path, sizeof(path), L"\\"))) goto end; if (FAILED(StringCbCatW(path, sizeof(path), p + 1))) goto end; /* download it */ bTempfile = TRUE; CDownloadDialog_Constructor(Dlg, &bCancelled, IID_PPV_ARG(IBindStatusCallback, &dl)); if (dl == NULL) goto end; switch(SettingsInfo.Proxy) { case 0: /* preconfig */ hOpen = InternetOpenW(lpszAgent, INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, 0); break; case 1: /* direct (no proxy) */ hOpen = InternetOpenW(lpszAgent, INTERNET_OPEN_TYPE_DIRECT, NULL, NULL, 0); break; case 2: /* use proxy */ hOpen = InternetOpenW(lpszAgent, INTERNET_OPEN_TYPE_PROXY, SettingsInfo.szProxyServer, SettingsInfo.szNoProxyFor, 0); break; default: /* preconfig */ hOpen = InternetOpenW(lpszAgent, INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, 0); break; } if (!hOpen) goto end; hFile = InternetOpenUrlW(hOpen, AppInfo->szUrlDownload, NULL, 0, INTERNET_FLAG_PRAGMA_NOCACHE|INTERNET_FLAG_KEEP_CONNECTION, 0); if (!hFile) goto end; if (!HttpQueryInfoW(hFile, HTTP_QUERY_STATUS_CODE | HTTP_QUERY_FLAG_NUMBER, &dwStatus, &dwStatusLen, NULL)) goto end; if(dwStatus != HTTP_STATUS_OK) { WCHAR szMsgText[MAX_STR_LEN]; if (!LoadStringW(hInst, IDS_UNABLE_TO_DOWNLOAD, szMsgText, sizeof(szMsgText) / sizeof(WCHAR))) goto end; MessageBoxW(hMainWnd, szMsgText, NULL, MB_OK | MB_ICONERROR); goto end; } dwStatusLen = sizeof(dwStatus); memset(&urlComponents, 0, sizeof(urlComponents)); urlComponents.dwStructSize = sizeof(urlComponents); if(FAILED(StringCbLengthW(AppInfo->szUrlDownload, sizeof(AppInfo->szUrlDownload), &urlLength))) goto end; urlComponents.dwSchemeLength = urlLength*sizeof(WCHAR); urlComponents.lpszScheme = (PWSTR)malloc(urlComponents.dwSchemeLength); if(!InternetCrackUrlW(AppInfo->szUrlDownload, urlLength+1, ICU_DECODE | ICU_ESCAPE, &urlComponents)) goto end; if(urlComponents.nScheme == INTERNET_SCHEME_HTTP || urlComponents.nScheme == INTERNET_SCHEME_HTTPS) HttpQueryInfo(hFile, HTTP_QUERY_CONTENT_LENGTH | HTTP_QUERY_FLAG_NUMBER, &dwContentLen, &dwStatus, 0); if(urlComponents.nScheme == INTERNET_SCHEME_FTP) dwContentLen = FtpGetFileSize(hFile, &dwStatus); free(urlComponents.lpszScheme); hOut = CreateFileW(path, GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, CREATE_ALWAYS, 0, NULL); if (hOut == INVALID_HANDLE_VALUE) goto end; do { if (!InternetReadFile(hFile, lpBuffer, _countof(lpBuffer), &dwBytesRead)) goto end; if (!WriteFile(hOut, &lpBuffer[0], dwBytesRead, &dwBytesWritten, NULL)) goto end; dwCurrentBytesRead += dwBytesRead; dl->OnProgress(dwCurrentBytesRead, dwContentLen, 0, AppInfo->szUrlDownload); } while (dwBytesRead); CloseHandle(hOut); hOut = INVALID_HANDLE_VALUE; if (bCancelled) goto end; ShowWindow(Dlg, SW_HIDE); /* run it */ if (!bCab) ShellExecuteW( NULL, L"open", path, NULL, NULL, SW_SHOWNORMAL ); end: if (hOut != INVALID_HANDLE_VALUE) CloseHandle(hOut); InternetCloseHandle(hFile); InternetCloseHandle(hOpen); if (bTempfile) { if (bCancelled || (SettingsInfo.bDelInstaller && !bCab)) DeleteFileW(path); } EndDialog(Dlg, 0); return 0; }
void IINetUtil::GetWebFile(const tchar* Parameters, const tchar* pszServer, const tchar* pszFileName, tint32* OutputLength, tchar** OutputBuffer) { *OutputBuffer = NULL; *OutputLength = 0; HINTERNET Initialize = NULL; HINTERNET Connection = NULL; HINTERNET File = NULL; //tchar* szFullFileName = NULL; try { //combine path and filename //szFullFileName = new tchar[strlen(INTERFACE_PATH)+strlen((const char *) FileName)+1]; //sprintf((char *) szFullFileName,"%s%s",INTERFACE_PATH,FileName); /*initialize the wininet library*/ if (NULL == (Initialize = InternetOpen("Koblo INet Engine 1.0", INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, 0)))//INTERNET_FLAG_ASYNC))) { // Lasse, modified 2007-09-10 //throw IException::Create(IException::TypeNetwork, // IException::ReasonNetworkCannotOpen, // EXCEPTION_INFO); tchar pszMsg[256]; GetGetLastError(pszMsg); throw IException::Create(IException::TypeNetwork, IException::ReasonNetworkCannotOpen, EXCEPTION_INFO, pszMsg); // .. Lasse } //Set timeout int timeout = CONNECT_TIMEOUT * 1000; // Lasse, modified 2007-09-10 - check for return value //InternetSetOption(Initialize, INTERNET_OPTION_CONNECT_TIMEOUT, &timeout, 4); if (!InternetSetOption(Initialize, INTERNET_OPTION_CONNECT_TIMEOUT, &timeout, 4)) { tchar pszMsg[256]; GetGetLastError(pszMsg); throw IException::Create(IException::TypeNetwork, IException::ReasonNetworkGeneric, EXCEPTION_INFO, pszMsg); } // Lasse, added 2007-09-10 - context identifier for application DWORD dwContext = 0; DWORD_PTR pdwContext = (DWORD_PTR)&dwContext; // .. Lasse /*connect to the server*/ // Lasse, modified 2007-09-10 - avoid risky NULL pointer read; use context identifier correctly //if (NULL == (Connection = InternetConnect(Initialize,WEB_SERVER,INTERNET_DEFAULT_HTTP_PORT, // NULL,NULL,INTERNET_SERVICE_HTTP,0,0))) if (NULL == (Connection = InternetConnect(Initialize, pszServer, INTERNET_DEFAULT_HTTP_PORT, NULL, NULL, INTERNET_SERVICE_HTTP, 0, pdwContext))) // .. Lasse { // Lasse, modified 2007-09-10 //throw IException::Create(IException::TypeNetwork, // IException::ReasonCouldntConnectToServer, // EXCEPTION_INFO); tchar pszMsg[256]; GetGetLastError(pszMsg); throw IException::Create(IException::TypeNetwork, IException::ReasonCouldntConnectToServer, EXCEPTION_INFO, pszMsg); // .. Lasse } /*open up an HTTP request*/ // Lasse, modified 2007-09-10 - 1: avoid risky NULL pointer read; use context identifier correctly, 2: avoid using cache //if (NULL == (File = HttpOpenRequest(Connection,POST_GET("POST","GET"),(const char*) szFullFileName,NULL,NULL,NULL,0,0))) //if (NULL == (File = HttpOpenRequest(Connection, POST_GET("POST","GET"), (const char*)szFullFileName, NULL, NULL, NULL, INTERNET_FLAG_NO_CACHE_WRITE|INTERNET_FLAG_RELOAD, pdwContext))) if (NULL == (File = HttpOpenRequest(Connection, POST_GET("POST","GET"), (const char*)pszFileName, NULL, NULL, NULL, INTERNET_FLAG_NO_CACHE_WRITE|INTERNET_FLAG_RELOAD, pdwContext))) // .. Lasse { // Lasse, modified 2007-09-10 //throw IException::Create(IException::TypeNetwork, // IException::ReasonCouldntConnectToAppl, // EXCEPTION_INFO); tchar pszMsg[256]; GetGetLastError(pszMsg); throw IException::Create(IException::TypeNetwork, IException::ReasonCouldntConnectToAppl, EXCEPTION_INFO, pszMsg); // .. Lasse } /*Read the file*/ if(HttpSendRequest( File, POST_GET(POST_CONTENT_TYPE,NULL), POST_GET(strlen(POST_CONTENT_TYPE),0), POST_GET((void*)Parameters,NULL), POST_GET(strlen((const char *) Parameters),0) )) { *OutputBuffer = new tchar[MAX_PAGE_SIZE]; // Lasse, changed 2007-09-11 - fix for prematurely return before all data have been received //InternetReadFile(File,*OutputBuffer,MAX_PAGE_SIZE, (unsigned long *) OutputLength); DWORD dwLen = 0; *OutputLength = 0; tuint32 uiRemainingBuffer = MAX_PAGE_SIZE; tchar* pszBuff = *OutputBuffer; // This is the correct approach: Read until 0 bytes are received do { if (!InternetReadFile(File, pszBuff, uiRemainingBuffer, &dwLen)) { // Time-out reading page tchar pszMsg[256]; GetGetLastError(pszMsg); throw IException::Create(IException::TypeNetwork, IException::ReasonNetworkTimeOut, EXCEPTION_INFO, pszMsg); } // Prepare for more data - advance buffer pointer etc. pszBuff += dwLen; *OutputLength += dwLen; uiRemainingBuffer -= dwLen; } while (dwLen > 0); // .. Lasse if (*OutputLength == MAX_PAGE_SIZE) { throw IException::Create(IException::TypeNetwork, IException::ReasonPageToLarge, EXCEPTION_INFO); } (*OutputBuffer)[*OutputLength] = NULL; //zero termination } else { // Lasse, modified 2007-09-10 //throw IException::Create(IException::TypeNetwork, // IException::ReasonErrorReadingFromAppl, // EXCEPTION_INFO); tchar pszMsg[256]; GetGetLastError(pszMsg); throw IException::Create(IException::TypeNetwork, IException::ReasonErrorReadingFromAppl, EXCEPTION_INFO, pszMsg); // .. Lasse } } catch (...) { /*close file , terminate server connection and deinitialize the wininet library*/ if (File != NULL) InternetCloseHandle(File); if (Connection != NULL) InternetCloseHandle(Connection); if (Initialize != NULL) InternetCloseHandle(Initialize); throw; } if (File != NULL) InternetCloseHandle(File); if (Connection != NULL) InternetCloseHandle(Connection); if (Initialize != NULL) InternetCloseHandle(Initialize); }