void log_to_file(const IQuotesProvider* pProvider, MCONTACT hContact, const tstring& rsLogFileName, const tstring& rsFormat) { std::string sPath = quotes_t2a(rsLogFileName.c_str()); std::string::size_type n = sPath.find_last_of("\\/"); if (std::string::npos != n) sPath.erase(n); DWORD dwAttributes = ::GetFileAttributesA(sPath.c_str()); if ((0xffffffff == dwAttributes) || (0 == (dwAttributes&FILE_ATTRIBUTE_DIRECTORY))) CreateDirectoryTree(sPath.c_str()); tofstream file(rsLogFileName.c_str(), std::ios::app | std::ios::out); file.imbue(GetSystemLocale()); if (file.good()) { tstring s = format_rate(pProvider, hContact, rsFormat); file << s; } }
/* Writes a line into the log. */ void FileWrite(HANDLE hcontact) { HANDLE fhout; DWORD byteswritten; char szout[1024],sznl[3]="\r\n"; DBVARIANT dbv; DBGetContactSetting(NULL,S_MOD,"PathToFile",&dbv); strcpy(szout,ParseString(dbv.pszVal,hcontact,1)); fhout=CreateFile(szout,GENERIC_WRITE,0,NULL,OPEN_ALWAYS,0,NULL); if (fhout==INVALID_HANDLE_VALUE){ CreateDirectoryTree(szout); fhout=CreateFile(szout,GENERIC_WRITE,0,NULL,OPEN_ALWAYS,0,NULL); if (fhout==INVALID_HANDLE_VALUE) return; } DBFreeVariant(&dbv); SetFilePointer(fhout,0,0,FILE_END); strcpy(szout,ParseString(!DBGetContactSetting(NULL,S_MOD,"FileStamp",&dbv)?dbv.pszVal:DEFAULT_FILESTAMP,hcontact,1)); DBFreeVariant(&dbv); WriteFile(fhout,szout,strlen(szout),&byteswritten,NULL); WriteFile(fhout,sznl,strlen(sznl),&byteswritten,NULL); CloseHandle(fhout); }
int OpenBayes() { char bayesdb_fullpath[MAX_PATH]; char *bayesdb_fullpath_utf8; char *errmsg, *tmp; sqlite3_stmt *stmt; if (hBayesFolder) { FoldersGetCustomPath(hBayesFolder, bayesdb_fullpath, MAX_PATH, ""); } else { tmp = Utils_ReplaceVars("%miranda_userdata%"); if (tmp[mir_strlen(tmp)-1] == '\\') tmp[mir_strlen(tmp)-1] = 0; mir_strcpy(bayesdb_fullpath, tmp); mir_strcat(bayesdb_fullpath, "\\" BAYESDB_PATH); mir_free(tmp); } CreateDirectoryTree(bayesdb_fullpath); mir_strcat(bayesdb_fullpath, "\\" BAYESDB_FILENAME); bayesdb_fullpath_utf8 = mir_utf8encode(bayesdb_fullpath); if (sqlite3_open(bayesdb_fullpath_utf8, &bayesdb) == SQLITE_OK) { sqlite3_exec(bayesdb, "CREATE TABLE IF NOT EXISTS spam (token blob(16), num int)", NULL, NULL, &errmsg); sqlite3_exec(bayesdb, "CREATE TABLE IF NOT EXISTS ham (token blob(16), num int)", NULL, NULL, &errmsg); sqlite3_exec(bayesdb, "CREATE TABLE IF NOT EXISTS stats (key varchar(32), value int)", NULL, NULL, &errmsg); sqlite3_exec(bayesdb, "CREATE TABLE IF NOT EXISTS queue (contact int, msgtime int, message text)", NULL, NULL, &errmsg); sqlite3_prepare_v2(bayesdb, "SELECT count(1) FROM stats WHERE key='spam_msgcount' OR key='ham_msgcount'", -1, &stmt, NULL); if (sqlite3_step(stmt) == SQLITE_ROW) if (sqlite3_column_int(stmt, 0) != 2) { sqlite3_exec(bayesdb, "INSERT INTO stats VALUES ('spam_msgcount', 0)", NULL, NULL, NULL); sqlite3_exec(bayesdb, "INSERT INTO stats VALUES ('ham_msgcount', 0)", NULL, NULL, NULL); } } else { MessageBoxA(NULL, bayesdb_fullpath_utf8, "Can't open database", MB_OK); } mir_free(bayesdb_fullpath_utf8); #ifdef _DEBUG tmp = Utils_ReplaceVars("%miranda_userdata%"); if (tmp[mir_strlen(tmp)-1] == '\\') tmp[mir_strlen(tmp)-1] = 0; mir_snprintf(bayesdb_fullpath, "%s\\%s\\%s", tmp, BAYESDB_PATH, BAYESDBG_FILENAME); mir_free(tmp); bayesdb_fullpath_utf8 = mir_utf8encode(bayesdb_fullpath); if (sqlite3_open(bayesdb_fullpath_utf8, &bayesdbg) == SQLITE_OK) { sqlite3_exec(bayesdbg, "CREATE TABLE spam (token varchar(50), num int)", NULL, NULL, &errmsg); sqlite3_exec(bayesdbg, "CREATE TABLE ham (token varchar(50), num int)", NULL, NULL, &errmsg); } mir_free(bayesdb_fullpath_utf8); #endif return 0; }
void myfilterWorker(PEXCEPTION_POINTERS exc_ptr, bool notify) { TCHAR path[MAX_PATH]; SYSTEMTIME st; HANDLE hDumpFile = NULL; GetLocalTime(&st); CreateDirectoryTree(CrashLogFolder); __try { if (dtsubfldr) { mir_sntprintf(path, MAX_PATH, TEXT("%s\\%02d.%02d.%02d"), CrashLogFolder, st.wYear, st.wMonth, st.wDay); CreateDirectory(path, NULL); mir_sntprintf(path, MAX_PATH, TEXT("%s\\%02d.%02d.%02d\\crash%02d%02d%02d%02d%02d%02d.mdmp"), CrashLogFolder, st.wYear, st.wMonth, st.wDay, st.wYear, st.wMonth, st.wDay, st.wHour, st.wMinute, st.wSecond); } else mir_sntprintf(path, MAX_PATH, TEXT("%s\\crash%02d%02d%02d%02d%02d%02d.mdmp"), CrashLogFolder, st.wYear, st.wMonth, st.wDay, st.wYear, st.wMonth, st.wDay, st.wHour, st.wMinute, st.wSecond); hDumpFile = CreateFile(path, GENERIC_WRITE, FILE_SHARE_READ, NULL, CREATE_NEW, FILE_ATTRIBUTE_NORMAL, NULL); if (hDumpFile != INVALID_HANDLE_VALUE) CreateMiniDump(hDumpFile, exc_ptr); else if (GetLastError() != ERROR_ALREADY_EXISTS) MessageBox(NULL, TranslateT("Crash Report write location is inaccesible"), TEXT("Miranda Crash Dumper"), MB_OK | MB_ICONERROR | MB_TASKMODAL | MB_TOPMOST); } __except(EXCEPTION_EXECUTE_HANDLER) {} bool empty = GetFileSize(hDumpFile, NULL) == 0; CloseHandle(hDumpFile); if (empty) DeleteFile(path); __try { if (dtsubfldr) { mir_sntprintf(path, MAX_PATH, TEXT("%s\\%02d.%02d.%02d"), CrashLogFolder, st.wYear, st.wMonth, st.wDay); CreateDirectory(path, NULL); mir_sntprintf(path, MAX_PATH, TEXT("%s\\%02d.%02d.%02d\\crash%02d%02d%02d%02d%02d%02d.txt"), CrashLogFolder, st.wYear, st.wMonth, st.wDay, st.wYear, st.wMonth, st.wDay, st.wHour, st.wMinute, st.wSecond); } else mir_sntprintf(path, MAX_PATH, TEXT("%s\\crash%02d%02d%02d%02d%02d%02d.txt"), CrashLogFolder, st.wYear, st.wMonth, st.wDay, st.wYear, st.wMonth, st.wDay, st.wHour, st.wMinute, st.wSecond); hDumpFile = CreateFile(path, GENERIC_WRITE, FILE_SHARE_READ, NULL, CREATE_NEW, FILE_ATTRIBUTE_NORMAL, NULL); mir_sntprintf(path, MAX_PATH, TranslateT("Miranda crashed. Crash report stored in the folder:\n %s\n\n Would you like store it in the clipboard as well?"), CrashLogFolder); if (hDumpFile != INVALID_HANDLE_VALUE) CreateCrashReport(hDumpFile, exc_ptr, notify ? path : NULL); } __except(myDebugFilter(GetExceptionCode(), GetExceptionInformation())) {} bool empty1 = GetFileSize(hDumpFile, NULL) == 0; CloseHandle(hDumpFile); if (empty1) DeleteFile(path); }
//borrowed from netliblog.c static void CreateDirectoryTree(char *szDir) { DWORD dwAttributes; char *pszLastBackslash,szTestDir[MAX_PATH]; lstrcpynA(szTestDir,szDir,sizeof(szTestDir)); if((dwAttributes=GetFileAttributesA(szTestDir))!=0xffffffff && dwAttributes&FILE_ATTRIBUTE_DIRECTORY) return; pszLastBackslash=strrchr(szTestDir,'\\'); if(pszLastBackslash==NULL) return; *pszLastBackslash='\0'; CreateDirectoryTree(szTestDir); CreateDirectoryA(szTestDir,NULL); }
MIR_CORE_DLL(void) CreatePathToFile(char *szFilePath) { if (szFilePath == NULL) return; char *pszLastBackslash = strrchr(szFilePath, '\\'); if (pszLastBackslash == NULL) return; *pszLastBackslash = '\0'; CreateDirectoryTree(szFilePath); *pszLastBackslash = '\\'; }
INT_PTR StoreVersionInfoToFile(WPARAM, LPARAM lParam) { CreateDirectoryTree(VersionInfoFolder); TCHAR path[MAX_PATH]; mir_sntprintf(path, TEXT("%s\\VersionInfo.txt"), VersionInfoFolder); HANDLE hDumpFile = CreateFile(path, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); if (hDumpFile != INVALID_HANDLE_VALUE) { CMString buffer; PrintVersionInfo(buffer, (unsigned int)lParam | VI_FLAG_PRNVAR); WriteUtfFile(hDumpFile, T2Utf(buffer.c_str())); CloseHandle(hDumpFile); ShowMessage(3, TranslateT("Version Info stored into file %s"), path); } else ShowMessage(2, TranslateT("Version Info file %s is inaccessible"), path); return 0; }
MIR_CORE_DLL(int) CreateDirectoryTree(const char *szDir) { if (szDir == NULL) return 1; char szTestDir[MAX_PATH]; mir_strncpy(szTestDir, szDir, _countof(szTestDir)); DWORD dwAttributes = GetFileAttributesA(szTestDir); if (dwAttributes != INVALID_FILE_ATTRIBUTES && (dwAttributes & FILE_ATTRIBUTE_DIRECTORY)) return 0; char *pszLastBackslash = strrchr(szTestDir, '\\'); if (pszLastBackslash == NULL) return 0; *pszLastBackslash = '\0'; CreateDirectoryTree(szTestDir); *pszLastBackslash = '\\'; return (CreateDirectoryA(szTestDir, NULL) == 0) ? GetLastError() : 0; }
bool InternetDownloadFile(const char *szUrl, char* szDest, HANDLE &hHttpDwnl) { int result = 0xBADBAD; char *szRedirUrl = NULL; NETLIBHTTPREQUEST nlhr = {0}; // initialize the netlib request nlhr.cbSize = sizeof(nlhr); nlhr.requestType = REQUEST_GET; nlhr.flags = NLHRF_NODUMP | NLHRF_HTTP11 | NLHRF_PERSISTENT | NLHRF_REDIRECT; nlhr.szUrl = (char*)szUrl; nlhr.nlc = hHttpDwnl; // change the header so the plugin is pretended to be IE 6 + WinXP nlhr.headersCount = 2; nlhr.headers=(NETLIBHTTPHEADER*)alloca(sizeof(NETLIBHTTPHEADER)*nlhr.headersCount); nlhr.headers[0].szName = "User-Agent"; nlhr.headers[0].szValue = NETLIB_USER_AGENT; nlhr.headers[1].szName = "Connection"; nlhr.headers[1].szValue = "close"; while (result == 0xBADBAD) { // download the page NETLIBHTTPREQUEST *nlhrReply = (NETLIBHTTPREQUEST*)CallService(MS_NETLIB_HTTPTRANSACTION, (WPARAM)hNetlibUser,(LPARAM)&nlhr); if (nlhrReply) { hHttpDwnl = nlhrReply->nlc; // if the recieved code is 200 OK if (nlhrReply->resultCode == 200) { char *delim = strrchr(szDest, '\\'); if (delim) *delim = '\0'; CreateDirectoryTree(szDest); if (delim) *delim = '\\'; int res = -1; int fh = _open(szDest, _O_BINARY | _O_WRONLY | _O_CREAT, _S_IREAD | _S_IWRITE); if (fh != -1) { res = _write(fh, nlhrReply->pData, nlhrReply->dataLength); _close(fh); } if (res < 0) remove(szDest); else result = 0; } // if the recieved code is 302 Moved, Found, etc // workaround for url forwarding else if (nlhrReply->resultCode == 302 || nlhrReply->resultCode == 301 || nlhrReply->resultCode == 307) { // page moved // get the url for the new location and save it to szInfo // look for the reply header "Location" for (int i=0; i<nlhrReply->headersCount; i++) { if (!mir_strcmp(nlhrReply->headers[i].szName, "Location")) { size_t rlen = 0; if (nlhrReply->headers[i].szValue[0] == '/') { const char* szPath; const char* szPref = strstr(szUrl, "://"); szPref = szPref ? szPref + 3 : szUrl; szPath = strchr(szPref, '/'); rlen = szPath != NULL ? szPath - szUrl : mir_strlen(szUrl); } szRedirUrl = (char*)mir_realloc(szRedirUrl, rlen + mir_strlen(nlhrReply->headers[i].szValue)*3 + 1); strncpy(szRedirUrl, szUrl, rlen); mir_strcpy(szRedirUrl+rlen, nlhrReply->headers[i].szValue); nlhr.szUrl = szRedirUrl; break; } } } else result = 1; } else { hHttpDwnl = NULL; result = 1; } CallService(MS_NETLIB_FREEHTTPREQUESTSTRUCT,0,(LPARAM)nlhrReply); } mir_free(szRedirUrl); return result == 0; }
void TlenProcessPic(XmlNode *node, TlenProtocol *proto) { TLEN_LIST_ITEM *item = NULL; char *crc, *crc_c, *idt, *size, *from, *fromRaw, *rt; from = TlenXmlGetAttrValue(node, "from"); fromRaw = TlenLoginFromJID(from); idt = TlenXmlGetAttrValue(node, "idt"); size = TlenXmlGetAttrValue(node, "size"); crc_c = TlenXmlGetAttrValue(node, "crc_c"); crc = TlenXmlGetAttrValue(node, "crc"); rt = TlenXmlGetAttrValue(node, "rt"); if (idt != NULL) { item = TlenListGetItemPtr(proto, LIST_PICTURE, idt); } if (item != NULL) { if (!strcmp(from, "ps")) { char *st = TlenXmlGetAttrValue(node, "st"); if (st != NULL) { item->ft->iqId = mir_strdup(st); item->ft->id2 = mir_strdup(rt); if (item->ft->hFileEvent != NULL) { SetEvent(item->ft->hFileEvent); item->ft->hFileEvent = NULL; } } } else if (!strcmp(item->ft->jid, fromRaw)) { if (crc_c != NULL) { if (!strcmp(crc_c, "n")) { /* crc_c = n, picture transfer accepted */ TlenPsPost(proto, item); } else if (!strcmp(crc_c, "f")) { /* crc_c = f, picture cached, no need to transfer again */ LogPictureMessage(proto, item->ft->jid, item->ft->files[0], TRUE); TlenP2PFreeFileTransfer(item->ft); TlenListRemove(proto, LIST_PICTURE, idt); } } else if (rt != NULL) { item->ft->id2 = mir_strdup(rt); TlenPsGet(proto, item); } } } else if (crc != NULL) { BOOL bAccept = proto->tlenOptions.imagePolicy == TLEN_IMAGES_ACCEPT_ALL || (proto->tlenOptions.imagePolicy == TLEN_IMAGES_IGNORE_NIR && IsAuthorized(proto, from)); if (bAccept) { FILE* fp; char fileName[MAX_PATH]; char *ext = TlenXmlGetAttrValue(node, "ext"); char *tmpPath = Utils_ReplaceVars( "%miranda_userdata%" ); int tPathLen = mir_snprintf(fileName, MAX_PATH, "%s\\Images\\Tlen", tmpPath); long oldSize = 0, lSize = atol(size); DWORD dwAttributes = GetFileAttributesA( fileName ); if ( dwAttributes == 0xffffffff || ( dwAttributes & FILE_ATTRIBUTE_DIRECTORY ) == 0 ) CreateDirectoryTree(fileName); mir_free(tmpPath); fileName[ tPathLen++ ] = '\\'; mir_snprintf( fileName + tPathLen, MAX_PATH - tPathLen, "%s.%s", crc, ext ); fp = fopen( fileName, "rb" ); if (fp) { fseek(fp, 0, SEEK_END); oldSize = ftell(fp); fclose(fp); } if (oldSize != lSize) { item = TlenListAdd(proto, LIST_PICTURE, idt); item->ft = TlenFileCreateFT(proto, from); item->ft->files = (char **) mir_alloc(sizeof(char *)); item->ft->filesSize = (long *) mir_alloc(sizeof(long)); item->ft->files[0] = mir_strdup(fileName); item->ft->filesSize[0] = lSize; item->ft->fileTotalSize = item->ft->filesSize[0]; TlenSend(proto, "<message type='pic' to='%s' crc_c='n' idt='%s'/>", from, idt); } else { TlenSend(proto, "<message type='pic' to='%s' crc_c='f' idt='%s'/>", from, idt); LogPictureMessage(proto, from, fileName, FALSE); } } } mir_free(fromRaw); }
extern "C" __declspec(dllexport) int Load() { mir_getLP(&pluginInfo); InitializeCriticalSection(&csFileShareListAccess); hHttpAcceptConnectionsService = CreateServiceFunction(MS_HTTP_ACCEPT_CONNECTIONS, nToggelAcceptConnections); if (! hHttpAcceptConnectionsService) { MessageBox(NULL, _T("Failed to CreateServiceFunction MS_HTTP_ACCEPT_CONNECTIONS"), MSG_BOX_TITEL, MB_OK); return 1; } hHttpAddChangeRemoveService = CreateServiceFunction(MS_HTTP_ADD_CHANGE_REMOVE, nAddChangeRemoveShare); if (! hHttpAddChangeRemoveService) { MessageBox(NULL, _T("Failed to CreateServiceFunction MS_HTTP_ADD_CHANGE_REMOVE"), MSG_BOX_TITEL, MB_OK); return 1; } hHttpGetShareService = CreateServiceFunction(MS_HTTP_GET_SHARE, nGetShare); if (! hHttpGetShareService) { MessageBox(NULL, _T("Failed to CreateServiceFunction MS_HTTP_GET_SHARE"), MSG_BOX_TITEL, MB_OK); return 1; } hHttpGetAllShares = CreateServiceFunction(MS_HTTP_GET_ALL_SHARES, nHttpGetAllShares); if (! hHttpGetAllShares) { MessageBox(NULL, _T("Failed to CreateServiceFunction MS_HTTP_GET_ALL_SHARES"), MSG_BOX_TITEL, MB_OK); return 1; } hEventSystemInit = HookEvent(ME_SYSTEM_MODULESLOADED, MainInit); if (!hEventSystemInit) { MessageBox(NULL, _T("Failed to HookEvent ME_SYSTEM_MODULESLOADED"), MSG_BOX_TITEL, MB_OK); return 1; } hPreShutdown = HookEvent(ME_SYSTEM_PRESHUTDOWN, PreShutdown); if (!hPreShutdown) { MessageBox(NULL, _T("Failed to HookEvent ME_SYSTEM_PRESHUTDOWN"), MSG_BOX_TITEL, MB_OK); return 1; } if(CallService(MS_DB_GETPROFILEPATH,MAX_PATH,(LPARAM)szPluginPath)) { MessageBox(NULL, _T("Failed to retrieve plugin path."), MSG_BOX_TITEL, MB_OK); return 1; } _tcsncat(szPluginPath,_T("\\HTTPServer\\"), MAX_PATH); int err = CreateDirectoryTree(szPluginPath); if((err != 0) && (err != ERROR_ALREADY_EXISTS)) { MessageBox(NULL, _T("Failed to create HTTPServer directory."), MSG_BOX_TITEL, MB_OK); return 1; } nPluginPathLen = (int)strlen(szPluginPath); sLogFilePath = szPluginPath; sLogFilePath += "HTTPServer.log"; if (! bInitMimeHandling()) { MessageBox(NULL, "Failed to read configuration file : " szMimeTypeConfigFile, MSG_BOX_TITEL, MB_OK); } nMaxUploadSpeed = db_get_dw(NULL, MODULE, "MaxUploadSpeed", nMaxUploadSpeed); nMaxConnectionsTotal = db_get_dw(NULL, MODULE, "MaxConnectionsTotal", nMaxConnectionsTotal); nMaxConnectionsPerUser = db_get_dw(NULL, MODULE, "MaxConnectionsPerUser", nMaxConnectionsPerUser); bLimitOnlyWhenOnline = db_get_b(NULL, MODULE, "LimitOnlyWhenOnline", bLimitOnlyWhenOnline) != 0; indexCreationMode = (eIndexCreationMode) db_get_b(NULL, MODULE, "IndexCreationMode", 2); if (db_get_b(NULL, MODULE, "AddAcceptConMenuItem", 1)) { CLISTMENUITEM mi = { sizeof(mi) }; mi.flags = CMIF_TCHAR; mi.pszContactOwner = NULL; //all contacts mi.hIcon = LoadIcon(hInstance, MAKEINTRESOURCE(IDI_SHARE_NEW_FILE)); mi.position = 1000085000; mi.pszName = LPGENT("Enable HTTP server"); mi.pszService = MS_HTTP_ACCEPT_CONNECTIONS; hAcceptConnectionsMenuItem = Menu_AddMainMenuItem(&mi); } if (indexCreationMode == INDEX_CREATION_HTML || indexCreationMode == INDEX_CREATION_DETECT) if (!LoadIndexHTMLTemplate()) { indexCreationMode = INDEX_CREATION_DISABLE; db_set_b(NULL, MODULE, "IndexCreationMode", (BYTE)indexCreationMode); } hEventProtoAck = HookEvent(ME_PROTO_ACK, nProtoAck); return 0; }
int Backup(TCHAR* backup_filename) { TCHAR source_file[MAX_PATH] = {0}, dest_file[MAX_PATH] = {0}; TCHAR* backupfolder,* pathtmp,* puText; HWND progress_dialog; DWORD start_time = GetTickCount64(); int i; size_t dest_file_len; CallService(MS_DB_GETPROFILENAMET, MAX_PATH, (LPARAM)dbname); if (backup_filename == NULL) { int err = 0; SYSTEMTIME st; TCHAR buffer[MAX_COMPUTERNAME_LENGTH + 1 ]; //GetComputerName (buffer , & size); DWORD size = sizeof(buffer); /* Buffer size is chosen large enough to contain any DNS name, not just MAX_COMPUTERNAME_LENGTH + 1 */ /* characters. MAX_COMPUTERNAME_LENGTH is usually less than 32, but it varies among systems, so we */ /* cannot use the constant in a precompiled Windows agent, which is expected to work on any system. */ backupfolder = Utils_ReplaceVarsT(options.folder); // ensure the backup folder exists (either create it or return non-zero signifying error) err = CreateDirectoryTree(backupfolder); if(err != ERROR_ALREADY_EXISTS && err != 0) { return 1; } GetLocalTime(&st); GetComputerName(buffer, &size); mir_sntprintf(dest_file, MAX_PATH, _T("%s\\%s_%02d.%02d.%02d@%02d-%02d-%02d_%s.bak"), backupfolder, dbname, st.wYear, st.wMonth, st.wDay, st.wHour, st.wMinute, st.wSecond, buffer); mir_free(backupfolder); } else lstrcpyn(dest_file, backup_filename, MAX_PATH); if(!options.disable_popups) ShowPopup(dbname, TranslateT("Backup in Progress")); if(!options.disable_progress) { progress_dialog = CreateDialog(hInst, MAKEINTRESOURCE(IDD_COPYPROGRESS), 0, (DLGPROC)DlgProcProgress); SetDlgItemText(progress_dialog, IDC_PROGRESSMESSAGE, TranslateT("Rotating backup files...")); } RotateBackups(progress_dialog, start_time); SetDlgItemText(progress_dialog, 0xDAED, TranslateT("Copying database file...")); SendMessage(progress_dialog, PBM_SETPOS, (WPARAM)(int)(0), 0); UpdateWindow(progress_dialog); mir_sntprintf(source_file, MAX_PATH, _T("%s\\%s"), profilePath, dbname); pathtmp = Utils_ReplaceVarsT(source_file); if (CopyFile(pathtmp, dest_file, 0)) { SendMessage(progress_dialog, PBM_SETPOS, (WPARAM)(int)(100), 0); UpdateWindow(progress_dialog); DBWriteContactSettingDword(0, "AutoBackups", "LastBackupTimestamp", (DWORD)time(0)); if(!options.disable_popups) { dest_file_len = lstrlen(dest_file); if(dest_file_len > 50) { puText = mir_alloc(sizeof(TCHAR) * (dest_file_len + 2)); for(i = (int)dest_file_len - 1; dest_file[i] != _T('\\'); i--); lstrcpyn(puText, dest_file, i + 2); lstrcat(puText, _T("\n")); lstrcat(puText, dest_file + i + 1); } else puText = mir_tstrdup(dest_file); ShowPopup(puText, TranslateT("Database backuped")); mir_free(puText); } } else DeleteFile(dest_file); mir_free(pathtmp); DestroyWindow(progress_dialog); return 0; }
int __stdcall isCopyFile( FileCopyCallback_t callback, wchar_t *PathOut, wchar_t *PathIn, BOOL bInnerFolders ) { wchar_t TempDir[ _MAX_PATH ] = {0}; __int64 mCopySize = 0; FILE *mFileOut; // Из FILE *mFileIn; // В int PolKilo = 1024 * 512; wchar_t *TempBuf; size_t result; mCopy = TRUE; FileList = ( FileList_t * )FileList_Init(); TempBuf = ( wchar_t * )malloc( PolKilo ); SizePathOut = wcslen( PathOut ); mbInnerFolders = bInnerFolders; wcscpy( mPathOut, PathOut ); // Ищем файлы SECURITY_ATTRIBUTES sa; ZeroMemory (&sa, sizeof(sa)); sa.nLength = sizeof(sa); sa.bInheritHandle = TRUE; sa.lpSecurityDescriptor = NULL; hEvent = CreateEvent (&sa, false, false, NULL); hThread = CreateThread (&sa, NULL, SearchThread, NULL, NULL, &thID); WaitWithMessageLoop( &hEvent ); CloseHandle( hEvent ); CloseHandle( hThread ); if( !mCopy ) { free( TempBuf ); FileList_Free( FileList ); return 0; } FileList->AllSize = FileList->AllSize / 1024 ; callback( "allsize", ( int )FileList->AllSize, "" ); // Создаем папку CreateDirectoryTree( PathIn ); // Создаем подпапки for( int i = 0; i < FileList->NumDir; ++i ) { wsprintf( TempDir, L"%s\\%s", PathIn, FileList->mPath[ i ] ); CreateDirectoryTree( TempDir ); } for( int z = 0; z < FileList->NumFiles; ++z ) { if( !mCopy ) break; // Создаем файл в "конечной" папке if( bInnerFolders ) wsprintf( TempDir, L"%s\\%s", PathIn, FileList->Files[ z ] + SizePathOut - 1 ); else wsprintf( TempDir, L"%s\\%s", PathIn, GetFileName( FileList->Files[ z ] ) ); mFileIn = _wfopen( TempDir, L"wb" ); if( mFileIn == NULL ) break; callback( "filename", 0, convertUnicode( FileList->Files[ z ] ) ); // Открываем исходный файл mFileOut = _wfopen( FileList->Files[ z ], L"rb" ); if( mFileIn == NULL ) break; while( !feof( mFileOut ) && mCopy ) { result = fread( TempBuf, 1, PolKilo, mFileOut ); if( ferror( mFileOut ) ) { ErrorExit( L"fread" ); fclose( mFileOut ); fclose( mFileIn ); continue; } mCopySize += result; fwrite( TempBuf, 1, result, mFileIn ); if( ferror( mFileIn ) ) { ErrorExit( L"fread" ); fclose( mFileOut ); fclose( mFileIn ); continue; } callback( "write", mCopySize / 1024, "" ); } fclose( mFileOut ); fclose( mFileIn ); } free( TempBuf ); FileList_Free( FileList ); return 1; }
int ExtractCurrentFile(HZIP hZip,bool bSkipPath) { int r=-1; char filename_inzip[256]; unz_file_info64 file_info; ZIPDECOMPRESSION *p=(ZIPDECOMPRESSION*)hZip; int err=unzGetCurrentFileInfo64(p->hZip,&file_info,filename_inzip,sizeof(filename_inzip),NULL,0,NULL,0); if (err == UNZ_OK) { bool bEncrypted=((file_info.flag & 1) != 0); if ((bEncrypted) && (!p->bEncrypted)) { ArchSetLastError(ARCH_ZIP_IS_ENCRYPTED); return -1; } char *lpPassword=((bEncrypted) && (p->bEncrypted)) ? p->szPassword : 0; int err=unzOpenCurrentFilePassword(p->hZip,lpPassword); if (err == UNZ_OK) { void *buf=_alloc(INT_BUF_SIZE); if (buf) { if (p->bExctractToMem) { p->lpMem=VirtualAlloc(NULL,file_info.uncompressed_size,MEM_COMMIT,PAGE_READWRITE); p->dwSize=file_info.uncompressed_size; byte *pMem=(byte*)p->lpMem; if (p->lpMem) { do { err=unzReadCurrentFile(p->hZip,pMem,INT_BUF_SIZE); if (err < 0) { VirtualFree(p->lpMem,file_info.uncompressed_size,MEM_DECOMMIT); break; } pMem+=err; } while (err > 0); } else ArchSetLastError(ARCH_NO_MEM); if (!err) r=1; } else { WCHAR *unicode_filename_inzip=OemToUnicodeEx(filename_inzip,-1), file_to_store[MAX_PATH], destPath[MAX_PATH], *filename=unicode_filename_inzip; if (bSkipPath) { WCHAR *p,*filename_withoutpath; p=filename_withoutpath=unicode_filename_inzip; while ((*p) != '\0') { if ((*p == '/') || (*p == '\\')) filename_withoutpath=p+1; p++; } filename=filename_withoutpath; } int dwLen=wsprintfW(destPath,L"%s\\%s",p->strOutputDir,filename); for (int i=0; i < dwLen; i++) { if (destPath[i] == '/') destPath[i]='\\'; } lstrcpyW(file_to_store,destPath); if (PathRemoveFileSpecW(destPath) != FALSE) CreateDirectoryTree(destPath); MemFree(unicode_filename_inzip); HANDLE fout=CreateFileW(file_to_store,GENERIC_WRITE,0,NULL,CREATE_ALWAYS,0,NULL); do { DWORD dwSize; err=unzReadCurrentFile(p->hZip,buf,INT_BUF_SIZE); if (err < 0) break; if (!WriteFile(fout,buf,err,&dwSize,0)) { err=-1; break; } } while (err > 0); SysCloseHandle(fout); if (!err) { change_file_date(file_to_store,file_info.dosDate,file_info.tmu_date); r=1; } else DeleteFileW(file_to_store); } MemFree(buf); } unzCloseCurrentFile(p->hZip); } } return r; }