int LocalStrnicmp(const char *Str1,const char *Str2,int Length) { char AnsiStr1[8192],AnsiStr2[8192]; OemToChar(Str1,AnsiStr1); OemToChar(Str2,AnsiStr2); AnsiStr1[Length]=AnsiStr2[Length]=0; CharLower(AnsiStr1); CharLower(AnsiStr2); return lstrcmp(AnsiStr1,AnsiStr2); }
tstring GetContactUid(HANDLE hContact, tstring Protocol) { tstring Uid; TCHAR dUid[32]={0}; char aUid[32]={0}; char *szProto = mir_utf8encodeW(Protocol.c_str()); CONTACTINFO ci; ZeroMemory((void *)&ci, sizeof(ci)); ci.hContact = hContact; ci.szProto = szProto; ci.cbSize = sizeof(ci); ci.dwFlag = CNF_DISPLAYUID | CNF_TCHAR; if (!CallService(MS_CONTACT_GETCONTACTINFO, 0, (LPARAM) & ci)) { switch (ci.type) { case CNFT_ASCIIZ: Uid=ci.pszVal; mir_free((void *)ci.pszVal); break; case CNFT_DWORD: _itoa_s(ci.dVal,aUid,32,10); OemToChar(aUid, dUid); Uid=dUid; break; default: Uid=_T(""); break; }; } mir_free(szProto); return Uid; }
int GetFileOwner (const char *Computer, const char *Name, char *Owner) { SECURITY_INFORMATION si = OWNER_SECURITY_INFORMATION|GROUP_SECURITY_INFORMATION; SECURITY_DESCRIPTOR *sd; char sddata[500]; *Owner=0; sd=(SECURITY_DESCRIPTOR *)sddata; char AnsiName[NM]; OemToChar(Name,AnsiName); SetFileApisToANSI(); DWORD Needed; int GetCode=GetFileSecurity(AnsiName,si,sd,sizeof(sddata),&Needed); SetFileApisToOEM(); if (!GetCode || (Needed>sizeof(sddata))) return(FALSE); PSID pOwner; BOOL OwnerDefaulted; if (!GetSecurityDescriptorOwner(sd,&pOwner,&OwnerDefaulted)) return(FALSE); char AccountName[200],DomainName[200]; DWORD AccountLength=sizeof(AccountName),DomainLength=sizeof(DomainName); SID_NAME_USE snu; if (!LookupAccountSid(Computer,pOwner,AccountName,&AccountLength,DomainName,&DomainLength,&snu)) return(FALSE); CharToOem(AccountName,Owner); return(TRUE); }
void IntToExt(const char *Src,char *Dest) { #if defined(_WIN_32) OemToChar(Src,Dest); #else if (Dest!=Src) strcpy(Dest,Src); #endif }
//--------------------------------------------------------------------------- void __fastcall TMyRCVersion::initialise( void ) { delete[] FVData; FVData = 0; DWORD fvHandle; unsigned int vSize; #if defined (_UNICODE) wchar_t appFName[ 255 ]; wchar_t * subBlockName = new wchar_t[ 255 ]; #else char appFName[ 255 ]; char * subBlockName = new char[ 255 ]; #endif HINSTANCE hInstance = 0; // default to application switch ( FInfoFrom ) { case ifDLL: hInstance = FhInstance; break; case ifPackage: hInstance = HInstance; // DLL Module Instance for package break; } int nLen = ::GetModuleFileName( hInstance, appFName, 255 ); appFName[ nLen ] = '\0'; #if !defined (_UNICODE) OemToChar( appFName, appFName ); #endif DWORD dwSize = ::GetFileVersionInfoSize( appFName, &fvHandle ); if ( dwSize ) { FVData = ( void * ) new char[ dwSize ]; if ( ::GetFileVersionInfo( appFName, fvHandle, dwSize, FVData ) ) { // Copy string to buffer so if the -dc compiler switch(Put constant strings in code segments) // is on VerQueryValue will work under Win16. This works around a problem in Microsoft's ver.dll // which writes to the string pointed to by subBlockName. // #if defined (_UNICODE) wcscpy(subBlockName, _T("\\VarFileInfo\\Translation")); #else strcpy(subBlockName, _T("\\VarFileInfo\\Translation")); #endif if ( !::VerQueryValue( FVData, subBlockName, ( void * * ) & TransBlock, &vSize ) ) { delete[] FVData; FVData = 0; } else // Swap the words so sprintf will print the lang-charset in the correct format. // *TransBlock = MAKELONG( HIWORD( *TransBlock ), LOWORD( *TransBlock ) ); } } delete [] subBlockName; }
void ConvertNameToShort(const char *Src,char *Dest) { char ShortName[NM],AnsiName[NM]; SetFileApisToANSI(); OemToChar(Src,AnsiName); if (GetShortPathName(AnsiName,ShortName,sizeof(ShortName))) CharToOem(ShortName,Dest); else lstrcpy(Dest,Src); SetFileApisToOEM(); }
/*--------------------------------------------------------------------------*/ char *getCurrentLine(void) { char *line = NULL; reallocLineBuffer(); cur_line[max_pos + 1] = '\0'; line = strdup_windows(cur_line); if (line) OemToChar(cur_line, line); return line; }
/*--------------------------------------------------------------------------*/ int sci_oemtochar(char *fname, unsigned long l) { int l1 = 0, n1 = 0, m1 = 0; char *Output = NULL; if (getWarningMode()) { sciprint(_("%s: Feature %s is obsolete.\n"), _("Warning"), fname); sciprint(_("%s: This feature will be permanently removed in Scilab %s\n\n"), _("Warning"), "5.4.1"); } CheckRhs(1, 1); CheckLhs(0, 1); if (GetType(1) == sci_strings) { char *OEMstring = NULL; GetRhsVar(1, STRING_DATATYPE, &m1, &n1, &l1); OEMstring = cstk(l1); Output = (char*)MALLOC((strlen(OEMstring) + 1) * sizeof(char)); if (getScilabMode() == SCILAB_STD) { OemToChar(OEMstring, Output); } else { wsprintf(Output, "%s", OEMstring); } } else { Scierror(999, _("%s: Wrong type for input argument #%d: String expected.\n"), fname, 1); return 0; } n1 = 1; m1 = (int)strlen(Output); CreateVarFromPtr(Rhs + 1, STRING_DATATYPE, &m1, &n1, &Output); if (Output) { FREE(Output); Output = NULL; } LhsVar(1) = Rhs + 1; PutLhsVar(); return 0; }
/*--------------------------------------------------------------------------*/ char *getCurrentLine(void) { char *line = NULL; reallocLineBuffer(); cur_line[max_pos + 1] = '\0'; line = os_strdup(cur_line); if (line) { OemToChar(cur_line, line); } return line; }
int CopyToClipboard (const char *Data) { OSVERSIONINFO WinVer; WinVer.dwOSVersionInfoSize = sizeof (OSVERSIONINFO); GetVersionEx (&WinVer); long DataSize; if (Data!=NULL && (DataSize=strlen(Data))!=0) { HGLOBAL hData; void *GData; if (!OpenClipboard(NULL)) return(FALSE); EmptyClipboard(); int BufferSize=DataSize+1; if ((hData=GlobalAlloc(GMEM_MOVEABLE|GMEM_DDESHARE,BufferSize))!=NULL) if ((GData=GlobalLock(hData))!=NULL) { memcpy(GData,Data,DataSize+1); GlobalUnlock(hData); SetClipboardData(CF_OEMTEXT,(HANDLE)hData); } if ((hData=GlobalAlloc(GMEM_MOVEABLE|GMEM_DDESHARE,BufferSize))!=NULL) if ((GData=GlobalLock(hData))!=NULL) { memcpy(GData,Data,DataSize+1); OemToChar((LPCSTR)GData,(LPTSTR)GData); GlobalUnlock(hData); SetClipboardData(CF_TEXT,(HANDLE)hData); } if (WinVer.dwPlatformId==VER_PLATFORM_WIN32_NT) if ((hData=GlobalAlloc(GMEM_MOVEABLE|GMEM_DDESHARE,BufferSize*2))!=NULL) if ((GData=GlobalLock(hData))!=NULL) { MultiByteToWideChar(CP_OEMCP,0,Data,-1,(LPWSTR)GData,BufferSize); GlobalUnlock(hData); SetClipboardData(CF_UNICODETEXT,(HANDLE)hData); } CloseClipboard(); } return(TRUE); }
void GetPasswordText(char *Str,int MaxLength) { #ifdef _WIN_32 HANDLE hConIn=GetStdHandle(STD_INPUT_HANDLE); HANDLE hConOut=GetStdHandle(STD_OUTPUT_HANDLE); DWORD ConInMode,ConOutMode; DWORD Read=0; GetConsoleMode(hConIn,&ConInMode); GetConsoleMode(hConOut,&ConOutMode); SetConsoleMode(hConIn,ENABLE_LINE_INPUT); SetConsoleMode(hConOut,ENABLE_PROCESSED_OUTPUT|ENABLE_WRAP_AT_EOL_OUTPUT); ReadConsole(hConIn,Str,MaxLength-1,&Read,NULL); Str[Read]=0; OemToChar(Str,Str); SetConsoleMode(hConIn,ConInMode); SetConsoleMode(hConOut,ConOutMode); #elif defined(_EMX) || defined(_BEOS) fgets(Str,MaxLength-1,stdin); #else strncpy(Str,getpass(""),MaxLength-1); #endif RemoveLF(Str); }
int PASCAL RARReadHeaderEx(HANDLE hArcData,struct RARHeaderDataEx *D) { DataSet *Data=(DataSet *)hArcData; //try //{ if ((Data->HeaderSize=(int)Data->Arc.SearchBlock(FILE_HEAD))<=0) { if (Data->Arc.Volume && Data->Arc.GetHeaderType()==ENDARC_HEAD && (Data->Arc.EndArcHead.Flags & EARC_NEXT_VOLUME)) if (MergeArchive(Data->Arc,NULL,false,'L')) { Data->Extract.SignatureFound=false; Data->Arc.Seek(Data->Arc.CurBlockPos,SEEK_SET); return(RARReadHeaderEx(hArcData,D)); } else return(ERAR_EOPEN); return(Data->Arc.BrokenFileHeader ? ERAR_BAD_DATA:ERAR_END_ARCHIVE); } if (Data->OpenMode==RAR_OM_LIST && (Data->Arc.NewLhd.Flags & LHD_SPLIT_BEFORE)) { int Code=RARProcessFile(hArcData,RAR_SKIP,NULL,NULL); if (Code==0) return(RARReadHeaderEx(hArcData,D)); else return(Code); } strncpyz(D->ArcName,Data->Arc.FileName,ASIZE(D->ArcName)); if (*Data->Arc.FileNameW) strncpyw(D->ArcNameW,Data->Arc.FileNameW,sizeof(D->ArcNameW)); else CharToWide(Data->Arc.FileName,D->ArcNameW); strncpyz(D->FileName,Data->Arc.NewLhd.FileName,ASIZE(D->FileName)); if (*Data->Arc.NewLhd.FileNameW) strncpyw(D->FileNameW,Data->Arc.NewLhd.FileNameW,sizeof(D->FileNameW)); else { #ifdef _WIN_32 char AnsiName[NM]; OemToChar(Data->Arc.NewLhd.FileName,AnsiName); if (!CharToWide(AnsiName,D->FileNameW,ASIZE(D->FileNameW))) *D->FileNameW=0; #else if (!CharToWide(Data->Arc.NewLhd.FileName,D->FileNameW,ASIZE(D->FileNameW))) *D->FileNameW=0; #endif } D->Flags=Data->Arc.NewLhd.Flags; D->PackSize=Data->Arc.NewLhd.PackSize; D->PackSizeHigh=Data->Arc.NewLhd.HighPackSize; D->UnpSize=Data->Arc.NewLhd.UnpSize; D->UnpSizeHigh=Data->Arc.NewLhd.HighUnpSize; D->HostOS=Data->Arc.NewLhd.HostOS; D->FileCRC=Data->Arc.NewLhd.FileCRC; D->FileTime=Data->Arc.NewLhd.FileTime; D->UnpVer=Data->Arc.NewLhd.UnpVer; D->Method=Data->Arc.NewLhd.Method; D->FileAttr=Data->Arc.NewLhd.FileAttr; D->CmtSize=0; D->CmtState=0; // } // catch (int ErrCode) //{ // return(RarErrorToDll(ErrCode)); // } return(0); }
bool FileCreate(RAROptions *Cmd,File *NewFile,char *Name,wchar *NameW, OVERWRITE_MODE Mode,bool *UserReject,Int64 FileSize, uint FileTime) { if (UserReject!=NULL) *UserReject=false; while (FileExist(Name,NameW)) { if (Mode==OVERWRITE_NONE) { if (UserReject!=NULL) *UserReject=true; return(false); } #ifdef SILENT Mode=OVERWRITE_ALL; #endif if (Cmd->AllYes || Mode==OVERWRITE_ALL) break; if (Mode==OVERWRITE_ASK) { eprintf(St(MFileExists),Name); int Choice=Ask(St(MYesNoAllRenQ)); if (Choice==1) break; if (Choice==2) { if (UserReject!=NULL) *UserReject=true; return(false); } if (Choice==3) { Cmd->Overwrite=OVERWRITE_ALL; break; } if (Choice==4) { if (UserReject!=NULL) *UserReject=true; Cmd->Overwrite=OVERWRITE_NONE; return(false); } if (Choice==5) { mprintf(St(MAskNewName)); char NewName[NM]; #ifdef _WIN_32 File SrcFile; SrcFile.SetHandleType(FILE_HANDLESTD); int Size=SrcFile.Read(NewName,NM); NewName[Size]=0; OemToChar(NewName,NewName); #else fgets(NewName,sizeof(NewName),stdin); #endif RemoveLF(NewName); if (PointToName(NewName)==NewName) strcpy(PointToName(Name),NewName); else strcpy(Name,NewName); if (NameW!=NULL) *NameW=0; continue; } if (Choice==6) ErrHandler.Exit(USER_BREAK); } } if (NewFile!=NULL && NewFile->Create(Name,NameW)) return(true); PrepareToDelete(Name,NameW); CreatePath(Name,NameW,true); return(NewFile!=NULL ? NewFile->Create(Name,NameW):remove(Name)==0); }
/**************************************** Callback called from GetFiles and PutFiles each time whole buffer sended or received to refresh state of copy progress Can be called in any plugin state (quite, not show, etc) ****************************************/ BOOL TrafficInformation::Callback(int Size) { double tmDiff; DWORD tm; time_t tmt; char str[MAX_PATH]; double TotalPercent,db; GET_TIME(tm); tmDiff = Abs(CMP_TIME(tm,LastTime)); tmt = time(NULL); FileSize += Size; FullFileSize = Max(FileSize,FullFileSize); if(Size && FTP_Info->CheckForEsc(FALSE,FALSE)) { Log(("User cancel")); return FALSE; } if(Size && tmDiff*1000 < FTP_Info->GetOpt()->IdleShowPeriod) return TRUE; memmove(&LastTime,&tm,sizeof(LastTime)); TotalPercent = ToPercent(TotalSz(),TotalFullSize); //Avg if(tmDiff > 0) { AvCps[0] = AvCps[1]; AvCps[1] = AvCps[2]; AvCps[2] = (FileSize - LastSize) / tmDiff; } LastSize = FileSize; //Cur db = ((double)tmt-FileStartTime-FileWaitTime); if(db > 0) Cps = FileSize / db; else Cps = 0; //Total db = ((double)tmt-TotalStartTime-TotalWaitTime); if(db > 0) TotalCps = (TotalSize+FileSize) / db; else TotalCps = 0; //Show QUIET progressing if(!ShowStatus) { _snprintf(str,ARRAYSIZE(str), "{%2.1lf%%} %s: %.26s", TotalPercent, FTP_Info->GetMsg(TitleMsg), FTP_Info->PointToName(SrcFileName)); FTP_Info->IdleMessage(str,FTP_Info->GetOpt()->ProcessColor); return TRUE; } //Window caption if(FTP_Info->FtpGetRetryCount()) _snprintf(str,ARRAYSIZE(str),"%d: {%2.1lf%%} %s - Far", FTP_Info->FtpGetRetryCount(), TotalPercent, FTP_Info->GetMsg(TitleMsg)); else _snprintf(str,ARRAYSIZE(str),"{%2.1lf%%} %s - Far", TotalPercent,FTP_Info->GetMsg(TitleMsg)); if(StrCmp(str,ConsoleTitle,-1,TRUE) != 0) { if(FTP_Info->WinVer->dwPlatformId != VER_PLATFORM_WIN32_NT) OemToChar(str,str); SetConsoleTitle(str); StrCpy(ConsoleTitle,str,ARRAYSIZE(ConsoleTitle)); } //Mark CMD window invisible FTP_Info->FtpCmdBlock(TRUE); //Show message LPCSTR MsgItems[MAX_TRAF_LINES+1]; DrawInfos(tmt); if(FTP_Info->FtpGetRetryCount()) _snprintf(str,ARRAYSIZE(str),"%d: %s",FTP_Info->FtpGetRetryCount(),FTP_Info->GetMsg(TitleMsg)); else StrCpy(str,FTP_Info->GetMsg(TitleMsg),ARRAYSIZE(str)); MsgItems[0] = str; int n; for(n = 0; n < LineCount; n++) MsgItems[n+1] = Lines[n]; FTP_Info->FMessage(FMSG_LEFTALIGN, NULL, (LPCSTR *)MsgItems, LineCount+1, 0); return TRUE; }
int PASCAL ProcessFile(HANDLE hArcData,int Operation,char *DestPath,char *DestName,wchar *DestPathW,wchar *DestNameW, string sParfileName) { DataSet *Data=(DataSet *)hArcData; try { Data->Arc.m_sParfileName = sParfileName; if (Data->OpenMode==RAR_OM_LIST || Operation==RAR_SKIP && !Data->Arc.Solid) { if (/*Data->OpenMode==RAR_OM_LIST && */Data->Arc.Volume && Data->Arc.GetHeaderType()==FILE_HEAD && (Data->Arc.NewLhd.Flags & LHD_SPLIT_AFTER)!=0) if (MergeArchive(Data->Arc,NULL,false,'L')) { Data->Arc.Seek(Data->Arc.CurBlockPos,SEEK_SET); return(0); } else return(ERAR_EOPEN); Data->Arc.SeekToNext(); } else { if (DestPath!=NULL || DestName!=NULL) { OemToChar(NullToEmpty(DestPath),Data->Cmd.ExtrPath); OemToChar(NullToEmpty(DestName),Data->Cmd.ArcName); AddEndSlash(Data->Cmd.ExtrPath); } else { *Data->Cmd.ExtrPath=0; } if (DestPathW!=NULL || DestNameW!=NULL) { strncpyw(Data->Cmd.ExtrPathW,NullToEmpty(DestPathW),NM-2); AddEndSlash(Data->Cmd.ExtrPathW); } else { *Data->Cmd.ExtrPathW=0; } strcpy(Data->Cmd.Command,Operation==RAR_EXTRACT ? "X":"T"); Data->Cmd.Test=Operation!=RAR_EXTRACT; bool Repeat=false; Data->Extract.ExtractCurrentFile(&Data->Cmd,Data->Arc,Data->HeaderSize,Repeat); while (Data->Arc.ReadHeader()!=0 && Data->Arc.GetHeaderType()==NEWSUB_HEAD) { Data->Extract.ExtractCurrentFile(&Data->Cmd,Data->Arc,Data->HeaderSize,Repeat); Data->Arc.SeekToNext(); } Data->Arc.Seek(Data->Arc.CurBlockPos,SEEK_SET); } } catch (int ErrCode) { return(RarErrorToDll(ErrCode)); } catch(...) { return -1; } return 0; }
// listen for output and pass it to the parent object DWORD WINAPI CConsolePipe::ListenerThreadProc(LPVOID lpParameter) { CConsolePipe* pThis = (CConsolePipe*)lpParameter; assert(pThis && pThis->m_hChildProcess); // most of the time the child process will have already terminated, but that's no rule // Read the child's (ansi) output. char lpBuffer[CPBUF_SIZE+1]; DWORD nBytesRead; BOOL doOEM = !(pThis->m_dwFlags & CPF_NOCONVERTOEM); // keep on reading the child's stdout till the pipe is broken (child finishes) while(1) { if (!ReadFile(pThis->m_hOutputRead, lpBuffer, CPBUF_SIZE, &nBytesRead, NULL) || nBytesRead==0) { // the usual error is ERROR_BROKEN_PIPE but don't get fussy #ifdef _DEBUG DWORD err_ = GetLastError(); if ( err_ != ERROR_BROKEN_PIPE) ATLTRACE(_T("MINI-assert: Listener thread broken due to error %x"), err_); #endif break; } assert(nBytesRead <= CPBUF_SIZE); lpBuffer[nBytesRead] = 0; #ifdef UNICODE // USES_CONVERSION is very bad within loops, so go manually WCHAR wbuf[CPBUF_SIZE+1]; // can't rely on ES_OEMCONVERT to do the conversion as necessary MultiByteToWideChar( doOEM ? CP_OEMCP : CP_ACP, 0, lpBuffer, nBytesRead, wbuf, CPBUF_SIZE); wbuf[nBytesRead] = 0; pThis->OnReceivedOutput(wbuf); #else // this is a bit dodgy since a window is updated from a non-owner thread if(doOEM) OemToChar(lpBuffer, lpBuffer); // inplace ok pThis->OnReceivedOutput(lpBuffer); #endif } #ifdef _DEBUG if( CPF_NOAUTODELETE & pThis->m_dwFlags) ATLTRACE(_T("PIPE %x: Listener thread terminates\n"), pThis); else ATLTRACE(_T("PIPE %x: Listener thread terminates & self-destructs\n"), pThis); #endif // cleanup the thread early lest destructor forces our termination CloseHandle(pThis->m_hListenerThread); pThis->m_hListenerThread = NULL; // notify our parent that the child has (probably) finished pThis->OnReceivedOutput(NULL/*hint*/); if( CPF_NOAUTODELETE & pThis->m_dwFlags ) pThis->Cleanup(); else delete pThis; // hara-kiri return 1; }
/////////////////////////////////////////////////////////////// // // CResourceChecker::ReplaceFilesInZIP // // Based on example at http://www.winimage.com/zLibDll/minizip.html // by Ivan A. Krestinin // /////////////////////////////////////////////////////////////// int CResourceChecker::ReplaceFilesInZIP( const string& strOrigZip, const string& strTempZip, const vector < string >& pathInArchiveList, const vector < string >& m_upgradedFullPathList ) { // open source and destination file zlib_filefunc_def ffunc; #ifdef WIN32 fill_win32_filefunc(&ffunc); #else fill_fopen_filefunc(&ffunc); #endif zipFile szip = unzOpen2(strOrigZip.c_str(), &ffunc); if (szip==NULL) { /*free(tmp_name);*/ return 0; } zipFile dzip = zipOpen2(strTempZip.c_str(), APPEND_STATUS_CREATE, NULL, &ffunc); if (dzip==NULL) { unzClose(szip); /*free(tmp_name);*/ return 0; } // get global commentary unz_global_info glob_info; if (unzGetGlobalInfo(szip, &glob_info) != UNZ_OK) { zipClose(dzip, NULL); unzClose(szip); /*free(tmp_name);*/ return 0; } char* glob_comment = NULL; if (glob_info.size_comment > 0) { glob_comment = (char*)malloc(glob_info.size_comment+1); if ((glob_comment==NULL)&&(glob_info.size_comment!=0)) { zipClose(dzip, NULL); unzClose(szip); /*free(tmp_name);*/ return 0; } if ((unsigned int)unzGetGlobalComment(szip, glob_comment, glob_info.size_comment+1) != glob_info.size_comment) { zipClose(dzip, NULL); unzClose(szip); free(glob_comment); /*free(tmp_name);*/ return 0; } } // copying files int n_files = 0; int rv = unzGoToFirstFile(szip); while (rv == UNZ_OK) { // get zipped file info unz_file_info unzfi; char dos_fn[MAX_PATH]; if (unzGetCurrentFileInfo(szip, &unzfi, dos_fn, MAX_PATH, NULL, 0, NULL, 0) != UNZ_OK) break; char fn[MAX_PATH]; #ifdef WIN32 OemToChar(dos_fn, fn); #endif // See if file should be replaced string fullPathReplacement; for ( unsigned long i = 0 ; i < pathInArchiveList.size () ; i++ ) if ( stricmp ( fn, pathInArchiveList[i].c_str () ) == 0 ) fullPathReplacement = m_upgradedFullPathList[i]; // Replace file in zip if ( fullPathReplacement.length () ) { void* buf = NULL; unsigned long ulLength = 0; // Get new file into a buffer if ( FILE* pFile = File::Fopen ( fullPathReplacement.c_str (), "rb" ) ) { // Get the file size, fseek( pFile, 0, SEEK_END ); ulLength = ftell( pFile ); fseek( pFile, 0, SEEK_SET ); // Load file into a buffer buf = malloc( ulLength ); if ( fread ( buf, 1, ulLength, pFile ) != ulLength ) { free( buf ); buf = NULL; } // Clean up fclose ( pFile ); } if( !buf ) break; // open destination file zip_fileinfo zfi; memcpy (&zfi.tmz_date, &unzfi.tmu_date, sizeof(tm_unz)); zfi.dosDate = unzfi.dosDate; zfi.internal_fa = unzfi.internal_fa; zfi.external_fa = unzfi.external_fa; char* extrafield = NULL; char* commentary = NULL; int size_local_extra = 0; void* local_extra = NULL; int unzfi_size_file_extra = 0; int method = Z_DEFLATED; int level = Z_DEFAULT_COMPRESSION; if (zipOpenNewFileInZip(dzip, dos_fn, &zfi, local_extra, size_local_extra, extrafield, unzfi_size_file_extra, commentary, method, level )!=UNZ_OK) {free(extrafield); free(commentary); free(local_extra); free(buf); break;} // write file if (zipWriteInFileInZip(dzip, buf, ulLength)!=UNZ_OK) {free(extrafield); free(commentary); free(local_extra); free(buf); break;} if (zipCloseFileInZip(dzip/*, unzfi.uncompressed_size, unzfi.crc*/)!=UNZ_OK) {free(extrafield); free(commentary); free(local_extra); free(buf); break;} free( buf ); } // Copy file in zip if ( !fullPathReplacement.length () ) { char* extrafield = (char*)malloc(unzfi.size_file_extra); if ((extrafield==NULL)&&(unzfi.size_file_extra!=0)) break; char* commentary = (char*)malloc(unzfi.size_file_comment); if ((commentary==NULL)&&(unzfi.size_file_comment!=0)) {free(extrafield); break;} if (unzGetCurrentFileInfo(szip, &unzfi, dos_fn, MAX_PATH, extrafield, unzfi.size_file_extra, commentary, unzfi.size_file_comment) != UNZ_OK) {free(extrafield); free(commentary); break;} // open file for RAW reading int method; int level; if (unzOpenCurrentFile2(szip, &method, &level, 1)!=UNZ_OK) {free(extrafield); free(commentary); break;} int size_local_extra = unzGetLocalExtrafield(szip, NULL, 0); if (size_local_extra<0) {free(extrafield); free(commentary); break;} void* local_extra = malloc(size_local_extra); if ((local_extra==NULL)&&(size_local_extra!=0)) {free(extrafield); free(commentary); break;} if (unzGetLocalExtrafield(szip, local_extra, size_local_extra)<0) {free(extrafield); free(commentary); free(local_extra); break;} // this malloc may fail if file very large void* buf = malloc(unzfi.compressed_size); if ((buf==NULL)&&(unzfi.compressed_size!=0)) {free(extrafield); free(commentary); free(local_extra); break;} // read file int sz = unzReadCurrentFile(szip, buf, unzfi.compressed_size); if ((unsigned int)sz != unzfi.compressed_size) {free(extrafield); free(commentary); free(local_extra); free(buf); break;} // open destination file zip_fileinfo zfi; memcpy (&zfi.tmz_date, &unzfi.tmu_date, sizeof(tm_unz)); zfi.dosDate = unzfi.dosDate; zfi.internal_fa = unzfi.internal_fa; zfi.external_fa = unzfi.external_fa; if (zipOpenNewFileInZip2(dzip, dos_fn, &zfi, local_extra, size_local_extra, extrafield, unzfi.size_file_extra, commentary, method, level, 1)!=UNZ_OK) {free(extrafield); free(commentary); free(local_extra); free(buf); break;} // write file if (zipWriteInFileInZip(dzip, buf, unzfi.compressed_size)!=UNZ_OK) {free(extrafield); free(commentary); free(local_extra); free(buf); break;} if (zipCloseFileInZipRaw(dzip, unzfi.uncompressed_size, unzfi.crc)!=UNZ_OK) {free(extrafield); free(commentary); free(local_extra); free(buf); break;} if (unzCloseCurrentFile(szip)==UNZ_CRCERROR) {free(extrafield); free(commentary); free(local_extra); free(buf); break;} free(commentary); free(buf); free(extrafield); free(local_extra); n_files ++; } rv = unzGoToNextFile(szip); } zipClose(dzip, glob_comment); unzClose(szip); free(glob_comment); return rv==UNZ_END_OF_LIST_OF_FILE; }
bool ReadTextFile(char *Name,StringList *List,bool Config,bool AbortOnError, RAR_CHARSET SrcCharset,bool Unquote,bool SkipComments) { char FileName[NM]; if (Config) GetConfigName(Name,FileName,true); else strcpy(FileName,Name); File SrcFile; if (*FileName) { bool OpenCode=AbortOnError ? SrcFile.WOpen(FileName):SrcFile.Open(FileName); if (!OpenCode) { if (AbortOnError) ErrHandler.Exit(OPEN_ERROR); return(false); } } else SrcFile.SetHandleType(FILE_HANDLESTD); unsigned int DataSize=0,ReadSize; const int ReadBlock=1024; Array<char> Data(ReadBlock+5); while ((ReadSize=SrcFile.Read(&Data[DataSize],ReadBlock))!=0) { DataSize+=ReadSize; Data.Add(ReadSize); } memset(&Data[DataSize],0,5); if (SrcCharset==RCH_UNICODE || SrcCharset==RCH_DEFAULT && IsUnicode((byte *)&Data[0],DataSize)) { // Unicode in native system format, can be more than 2 bytes per character Array<wchar> DataW(Data.Size()/2+1); for (int I=2;I<Data.Size()-1;I+=2) DataW[(I-2)/2]=(wchar)Data[I]+(wchar)Data[I+1]*256; wchar *CurStr=&DataW[0]; Array<char> AnsiName; while (*CurStr!=0) { wchar *NextStr=CurStr,*CmtPtr=NULL; while (*NextStr!='\r' && *NextStr!='\n' && *NextStr!=0) { if (SkipComments && NextStr[0]=='/' && NextStr[1]=='/') { *NextStr=0; CmtPtr=NextStr; } NextStr++; } *NextStr=0; for (wchar *SpacePtr=(CmtPtr ? CmtPtr:NextStr)-1;SpacePtr>=CurStr;SpacePtr--) { if (*SpacePtr!=' ' && *SpacePtr!='\t') break; *SpacePtr=0; } if (*CurStr) { int Length=strlenw(CurStr); int AddSize=4*(Length-AnsiName.Size()+1); if (AddSize>0) AnsiName.Add(AddSize); if (Unquote && *CurStr=='\"' && CurStr[Length-1]=='\"') { CurStr[Length-1]=0; CurStr++; } WideToChar(CurStr,&AnsiName[0],AnsiName.Size()); List->AddString(&AnsiName[0],CurStr); } CurStr=NextStr+1; while (*CurStr=='\r' || *CurStr=='\n') CurStr++; } } else { char *CurStr=&Data[0]; while (*CurStr!=0) { char *NextStr=CurStr,*CmtPtr=NULL; while (*NextStr!='\r' && *NextStr!='\n' && *NextStr!=0) { if (SkipComments && NextStr[0]=='/' && NextStr[1]=='/') { *NextStr=0; CmtPtr=NextStr; } NextStr++; } *NextStr=0; for (char *SpacePtr=(CmtPtr ? CmtPtr:NextStr)-1;SpacePtr>=CurStr;SpacePtr--) { if (*SpacePtr!=' ' && *SpacePtr!='\t') break; *SpacePtr=0; } if (*CurStr) { if (Unquote && *CurStr=='\"') { int Length=strlen(CurStr); if (CurStr[Length-1]=='\"') { CurStr[Length-1]=0; CurStr++; } } #if defined(_WIN_32) if (SrcCharset==RCH_OEM) OemToChar(CurStr,CurStr); #endif List->AddString(CurStr); } CurStr=NextStr+1; while (*CurStr=='\r' || *CurStr=='\n') CurStr++; } } return(true); }
int ArcCommand::ReplaceVar(char *Command,int &Length) { char Chr=Command[2]&(~0x20); if (Command[0]!='%' || Command[1]!='%' || Chr < 'A' || Chr > 'Z') return FALSE; char SaveStr[MAX_COMMAND_LENGTH],LocalAllFilesMask[NM]; int QuoteName=0,UseSlash=FALSE,FolderMask=FALSE,FolderName=FALSE; int NameOnly=FALSE,PathOnly=FALSE,AnsiCode=FALSE; int MaxNamesLength=127; int VarLength=3; lstrcpy(LocalAllFilesMask,AllFilesMask); while (1) { int BreakScan=FALSE; Chr=Command[VarLength]; if (Command[2]=='F' && Chr >= '0' && Chr <= '9') { MaxNamesLength=FSF.atoi(&Command[VarLength]); while (Chr >= '0' && Chr <= '9') Chr=Command[++VarLength]; continue; } if (Command[2]=='E' && Chr >= '0' && Chr <= '9') { MaxAllowedExitCode=FSF.atoi(&Command[VarLength]); while (Chr >= '0' && Chr <= '9') Chr=Command[++VarLength]; continue; } switch(Command[VarLength]) { case 'A': AnsiCode=TRUE; break; case 'Q': QuoteName=1; break; case 'q': QuoteName=2; break; case 'S': UseSlash=TRUE; break; case 'M': FolderMask=TRUE; break; case 'N': FolderName=TRUE; break; case 'W': NameOnly=TRUE; break; case 'P': PathOnly=TRUE; break; case '*': lstrcpy(LocalAllFilesMask,"*"); break; default: BreakScan=TRUE; break; } if (BreakScan) break; VarLength++; } if ((MaxNamesLength-=Length)<=0) MaxNamesLength=1; if (MaxNamesLength>MAX_COMMAND_LENGTH-512) MaxNamesLength=MAX_COMMAND_LENGTH-512; if (FolderMask==FALSE && FolderName==FALSE) FolderName=TRUE; lstrcpy(SaveStr,Command+VarLength); switch(Command[2]) { case 'A': lstrcpy(Command,ArcName); if (AnsiCode) OemToChar(Command,Command); if (PathOnly) { char *NamePtr=(char *)FSF.PointToName(Command); if (NamePtr!=Command) *(NamePtr-1)=0; else lstrcpy(Command," "); } FSF.QuoteSpaceOnly(Command); break; case 'a': { int Dot=strchr(FSF.PointToName(ArcName),'.')!=NULL; ConvertNameToShort(ArcName,Command); char *Slash=strrchr(ArcName,'\\'); if (GetFileAttributes(ArcName)==0xFFFFFFFF && Slash!=NULL && Slash!=ArcName) { char Path[NM]; lstrcpy(Path,ArcName); Path[Slash-ArcName]=0; ConvertNameToShort(Path,Command); lstrcat(Command,Slash); } if (Dot && strchr(FSF.PointToName(Command),'.')==NULL) lstrcat(Command,"."); if (AnsiCode) OemToChar(Command,Command); if (PathOnly) { char *NamePtr=(char *)FSF.PointToName(Command); if (NamePtr!=Command) *(NamePtr-1)=0; else lstrcpy(Command," "); } } FSF.QuoteSpaceOnly(Command); break; case 'D': *Command=0; break; case 'E': *Command=0; break; case 'l': case 'L': if (!MakeListFile(ListFileName,Command[2]=='l',QuoteName,UseSlash, FolderName,NameOnly,PathOnly,FolderMask, LocalAllFilesMask,AnsiCode)) return -1; char QListName[NM+2]; FSF.QuoteSpaceOnly(lstrcpy(QListName,ListFileName)); lstrcpy(Command,QListName); break; case 'P': lstrcpy(Command,Password); break; case 'C': if(*CommentFileName) //второй раз сюда не лезем break; { *Command=0; HANDLE CommentFile; //char CommentFileName[MAX_PATH]; char Buf[512]; SECURITY_ATTRIBUTES sa; sa.nLength=sizeof(sa); sa.lpSecurityDescriptor=NULL; sa.bInheritHandle=TRUE; if(FSF.MkTemp(CommentFileName, "FAR") && (CommentFile=CreateFile(CommentFileName, GENERIC_WRITE, FILE_SHARE_READ|FILE_SHARE_WRITE, &sa, CREATE_ALWAYS, /*FILE_ATTRIBUTE_TEMPORARY|*//*FILE_FLAG_DELETE_ON_CLOSE*/0, NULL)) != INVALID_HANDLE_VALUE) { DWORD Count; if(Info.InputBox(GetMsg(MComment), GetMsg(MInputComment), NULL, "", Buf, sizeof(Buf), NULL, 0)) //??тут можно и заполнить строку комментарием, но надо знать, файловый //?? он или архивный. да и имя файла в архиве тоже надо знать... { WriteFile(CommentFile, Buf, lstrlen(Buf), &Count, NULL); lstrcpy(Command, CommentFileName); CloseHandle(CommentFile); } FlushConsoleInputBuffer(GetStdHandle(STD_INPUT_HANDLE)); } } break; case 'R': lstrcpy(Command,RealArcDir); if (UseSlash) { for (int I=0;Command[I];I++) if (Command[I]=='\\') // Command[I]='//'; /* $ 28.11.2000 AS */ Command[I]='/'; /* AS $*/ } FSF.QuoteSpaceOnly(Command); break; case 'W': lstrcpy(Command,TempPath); break; case 'f': case 'F': if (PanelItem!=NULL) { char CurArcDir[NM]; lstrcpy(CurArcDir,ArcDir); int Length=lstrlen(CurArcDir); if (Length>0 && CurArcDir[Length-1]!='\\') lstrcat(CurArcDir,"\\"); char Names[MAX_COMMAND_LENGTH]; *Names=0; if (NameNumber==-1) NameNumber=0; while (NameNumber<ItemsNumber || Command[2]=='f') { char Name[NM*2]; int IncreaseNumber=0,FileAttr; if (*NextFileName) { FSF.sprintf(Name,"%s%s%s",PrefixFileName,CurArcDir,NextFileName); *NextFileName=0; FileAttr=0; } else { int N; if (Command[2]=='f' && PrevFileNameNumber!=-1) N=PrevFileNameNumber; else { N=NameNumber; IncreaseNumber=1; } if (N>=ItemsNumber) break; *PrefixFileName=0; char *cFileName=PanelItem[N].FindData.cFileName; if(PanelItem[N].UserData && (PanelItem[N].Flags & PPIF_USERDATA)) { struct ArcItemUserData *aud=(struct ArcItemUserData*)PanelItem[N].UserData; if(aud->SizeStruct == sizeof(struct ArcItemUserData)) { if(aud->Prefix) lstrcpyn(PrefixFileName,aud->Prefix,sizeof(PrefixFileName)); if(aud->LinkName) cFileName=aud->LinkName; } } // CHECK for BUGS!! if(*cFileName == '\\' || *cFileName == '/') FSF.sprintf(Name,"%s%s",PrefixFileName,cFileName+1); else FSF.sprintf(Name,"%s%s%s",PrefixFileName,CurArcDir,cFileName); NormalizePath(Name,Name); FileAttr=PanelItem[N].FindData.dwFileAttributes; PrevFileNameNumber=N; } if (AnsiCode) OemToChar(Name,Name); if (NameOnly) { char NewName[NM]; lstrcpy(NewName,FSF.PointToName(Name)); lstrcpy(Name,NewName); } if (PathOnly) { char *NamePtr=(char *)FSF.PointToName(Name); if (NamePtr!=Name) *(NamePtr-1)=0; else lstrcpy(Name," "); } if (*Names==0 || (lstrlen(Names)+lstrlen(Name)<MaxNamesLength && Command[2]!='f')) { NameNumber+=IncreaseNumber; if (FileAttr & FILE_ATTRIBUTE_DIRECTORY) { char FolderMaskName[NM]; //lstrcpy(LocalAllFilesMask,PrefixFileName); FSF.sprintf(FolderMaskName,"%s\\%s",Name,LocalAllFilesMask); if (PathOnly) { lstrcpy(FolderMaskName,Name); char *NamePtr=(char *)FSF.PointToName(FolderMaskName); if (NamePtr!=FolderMaskName) *(NamePtr-1)=0; else lstrcpy(FolderMaskName," "); } if (FolderMask) { if (FolderName) lstrcpy(NextFileName,FolderMaskName); else lstrcpy(Name,FolderMaskName); } } if (QuoteName==1) FSF.QuoteSpaceOnly(Name); else if (QuoteName==2) QuoteText(Name); if (UseSlash) for (int I=0;Name[I];I++) if (Name[I]=='\\') // Name[I]='//'; /* $ 28.11.2000 AS */ Name[I]='/'; /* AS $*/ if (*Names) lstrcat(Names," "); lstrcat(Names,Name); } else break; } lstrcpy(Command,Names); } else *Command=0; break; default: return FALSE; } Length=lstrlen(Command); lstrcat(Command,SaveStr); return TRUE; }
bool FileCreate(RAROptions *Cmd,File *NewFile,char *Name,wchar *NameW, OVERWRITE_MODE Mode,bool *UserReject,int64 FileSize, uint FileTime) { if (UserReject!=NULL) *UserReject=false; #if defined(_WIN_32) && !defined(_WIN_CE) bool ShortNameChanged=false; #endif while (FileExist(Name,NameW)) { #if defined(_WIN_32) && !defined(_WIN_CE) if (!ShortNameChanged) { ShortNameChanged=true; if (UpdateExistingShortName(Name,NameW)) continue; } #endif if (Mode==OVERWRITE_NONE) { if (UserReject!=NULL) *UserReject=true; return(false); } #ifdef SILENT Mode=OVERWRITE_ALL; #endif if (Cmd->AllYes || Mode==OVERWRITE_ALL) break; if (Mode==OVERWRITE_DEFAULT || Mode==OVERWRITE_FORCE_ASK) { eprintf(St(MFileExists),Name); int Choice=Ask(St(MYesNoAllRenQ)); if (Choice==1) break; if (Choice==2) { if (UserReject!=NULL) *UserReject=true; return(false); } if (Choice==3) { Cmd->Overwrite=OVERWRITE_ALL; break; } if (Choice==4) { if (UserReject!=NULL) *UserReject=true; Cmd->Overwrite=OVERWRITE_NONE; return(false); } if (Choice==5) { mprintf(St(MAskNewName)); char NewName[NM]; #ifdef _WIN_32 File SrcFile; SrcFile.SetHandleType(FILE_HANDLESTD); int Size=SrcFile.Read(NewName,sizeof(NewName)-1); NewName[Size]=0; OemToChar(NewName,NewName); #else if (fgets(NewName,sizeof(NewName),stdin)==NULL) { // Process fgets failure as if user answered 'No'. if (UserReject!=NULL) *UserReject=true; return(false); } #endif RemoveLF(NewName); if (PointToName(NewName)==NewName) strcpy(PointToName(Name),NewName); else strcpy(Name,NewName); if (NameW!=NULL) *NameW=0; continue; } if (Choice==6) ErrHandler.Exit(USER_BREAK); } if (Mode==OVERWRITE_AUTORENAME) { if (GetAutoRenamedName(Name)) { if (NameW!=NULL) *NameW=0; } else Mode=OVERWRITE_DEFAULT; continue; } } if (NewFile!=NULL && NewFile->Create(Name,NameW)) return(true); PrepareToDelete(Name,NameW); CreatePath(Name,NameW,true); return(NewFile!=NULL ? NewFile->Create(Name,NameW):DelFile(Name,NameW)); }
int PASCAL ProcessFile(HANDLE hArcData,int Operation,char *DestPath,char *DestName,wchar *DestPathW,wchar *DestNameW) { DataSet *Data=(DataSet *)hArcData; //try //{ Data->Cmd.DllError=0; if (Data->OpenMode==RAR_OM_LIST || Data->OpenMode==RAR_OM_LIST_INCSPLIT || Operation==RAR_SKIP && !Data->Arc.Solid) { if (Data->Arc.Volume && Data->Arc.GetHeaderType()==FILE_HEAD && (Data->Arc.NewLhd.Flags & LHD_SPLIT_AFTER)!=0) if (MergeArchive(Data->Arc,NULL,false,'L')) { Data->Extract.SignatureFound=false; Data->Arc.Seek(Data->Arc.CurBlockPos,SEEK_SET); return(0); } else return(ERAR_EOPEN); Data->Arc.SeekToNext(); } else { Data->Cmd.DllOpMode=Operation; if (DestPath!=NULL || DestName!=NULL) { #ifdef _WIN_32 OemToChar(NullToEmpty(DestPath),Data->Cmd.ExtrPath); #else strcpy(Data->Cmd.ExtrPath,NullToEmpty(DestPath)); #endif AddEndSlash(Data->Cmd.ExtrPath); #ifdef _WIN_32 OemToChar(NullToEmpty(DestName),Data->Cmd.DllDestName); #else strcpy(Data->Cmd.DllDestName,NullToEmpty(DestName)); #endif } else { *Data->Cmd.ExtrPath=0; *Data->Cmd.DllDestName=0; } if (DestPathW!=NULL || DestNameW!=NULL) { strncpyw(Data->Cmd.ExtrPathW,NullToEmpty(DestPathW),NM-2); AddEndSlash(Data->Cmd.ExtrPathW); strncpyw(Data->Cmd.DllDestNameW,NullToEmpty(DestNameW),NM-1); if (*Data->Cmd.DllDestNameW!=0 && *Data->Cmd.DllDestName==0) WideToChar(Data->Cmd.DllDestNameW,Data->Cmd.DllDestName); } else { *Data->Cmd.ExtrPathW=0; *Data->Cmd.DllDestNameW=0; } strcpy(Data->Cmd.Command,Operation==RAR_EXTRACT ? "X":"T"); Data->Cmd.Test=Operation!=RAR_EXTRACT; bool Repeat=false; Data->Extract.ExtractCurrentFile(&Data->Cmd,Data->Arc,Data->HeaderSize,Repeat); while (Data->Arc.ReadHeader()!=0 && Data->Arc.GetHeaderType()==NEWSUB_HEAD) { Data->Extract.ExtractCurrentFile(&Data->Cmd,Data->Arc,Data->HeaderSize,Repeat); Data->Arc.SeekToNext(); } Data->Arc.Seek(Data->Arc.CurBlockPos,SEEK_SET); } //} //catch (int ErrCode) //{ // return(RarErrorToDll(ErrCode)); //} return(Data->Cmd.DllError); }
int ArcCommand::MakeListFile(char *ListFileName,int ShortNames,int QuoteName, int UseSlash,int FolderName,int NameOnly,int PathOnly, int FolderMask,char *LocalAllFilesMask,int AnsiCode) { // FILE *ListFile; HANDLE ListFile; DWORD WriteSize; SECURITY_ATTRIBUTES sa; sa.nLength=sizeof(sa); sa.lpSecurityDescriptor=NULL; sa.bInheritHandle=TRUE; if (FSF.MkTemp(ListFileName,"FAR")==NULL || (ListFile=CreateFile(ListFileName,GENERIC_WRITE, FILE_SHARE_READ|FILE_SHARE_WRITE, &sa,CREATE_ALWAYS, FILE_FLAG_SEQUENTIAL_SCAN,NULL)) == INVALID_HANDLE_VALUE) { if(!Silent) { char NameMsg[NM]; const char *MsgItems[]={GetMsg(MError),GetMsg(MCannotCreateListFile),NameMsg,GetMsg(MOk)}; FSF.TruncPathStr(lstrcpyn(NameMsg,ListFileName,sizeof(NameMsg)),MAX_WIDTH_MESSAGE); Info.Message(Info.ModuleNumber,FMSG_WARNING,NULL,MsgItems,ARRAYSIZE(MsgItems),1); } /* $ 25.07.2001 AA if(ListFile != INVALID_HANDLE_VALUE) CloseHandle(ListFile); 25.07.2001 AA $*/ return FALSE; } char CurArcDir[NM]; char Buf[3*NM]; if(NameOnly) *CurArcDir=0; else lstrcpy( CurArcDir, ArcDir ); int Length=lstrlen(CurArcDir); if (Length>0 && CurArcDir[Length-1]!='\\') lstrcat(CurArcDir,"\\"); if (UseSlash) for (int I=0;CurArcDir[I];I++) if (CurArcDir[I]=='\\') // CurArcDir[I]='//'; CurArcDir[I]='/'; for (int I=0;I<ItemsNumber;I++) { char FileName[NM]; if (ShortNames && *PanelItem[I].FindData.cAlternateFileName) lstrcpy(FileName,PanelItem[I].FindData.cAlternateFileName); else lstrcpy(FileName,PanelItem[I].FindData.cFileName); if (NameOnly) { char NewName[NM]; lstrcpy(NewName,FSF.PointToName(FileName)); lstrcpy(FileName,NewName); } if (PathOnly) { char *Ptr=(char*)FSF.PointToName(FileName); *Ptr=0; } int FileAttr=PanelItem[I].FindData.dwFileAttributes; *PrefixFileName=0; if(PanelItem[I].UserData && (PanelItem[I].Flags & PPIF_USERDATA)) { struct ArcItemUserData *aud=(struct ArcItemUserData*)PanelItem[I].UserData; if(aud->SizeStruct == sizeof(struct ArcItemUserData)) { if(aud->Prefix) lstrcpyn(PrefixFileName,aud->Prefix,sizeof(PrefixFileName)); if(aud->LinkName) lstrcpyn(FileName,aud->LinkName,sizeof(FileName)); } } int Error=FALSE; if (((FileAttr & FILE_ATTRIBUTE_DIRECTORY)==0 || FolderName)) { char OutName[NM]; // CHECK for BUGS!! if(*FileName == '\\' || *FileName == '/') FSF.sprintf(OutName,"%s%s",PrefixFileName,FileName+1); else FSF.sprintf(OutName,"%s%s%s",PrefixFileName,CurArcDir,FileName); NormalizePath(OutName,OutName); if (QuoteName==1) FSF.QuoteSpaceOnly(OutName); else if (QuoteName==2) QuoteText(OutName); if (AnsiCode) OemToChar(OutName,OutName); lstrcpy(Buf,OutName);lstrcat(Buf,"\r\n"); Error=WriteFile(ListFile,Buf,lstrlen(Buf),&WriteSize,NULL) == FALSE; //Error=fwrite(Buf,1,lstrlen(Buf),ListFile) != lstrlen(Buf); } if (!Error && (FileAttr & FILE_ATTRIBUTE_DIRECTORY) && FolderMask) { char OutName[NM]; FSF.sprintf(OutName,"%s%s%s%c%s",PrefixFileName,CurArcDir,FileName,UseSlash ? '/':'\\',LocalAllFilesMask); if (QuoteName==1) FSF.QuoteSpaceOnly(OutName); else if (QuoteName==2) QuoteText(OutName); if (AnsiCode) OemToChar(OutName,OutName); lstrcpy(Buf,OutName);lstrcat(Buf,"\r\n"); Error=WriteFile(ListFile,Buf,lstrlen(Buf),&WriteSize,NULL) == FALSE; //Error=fwrite(Buf,1,lstrlen(Buf),ListFile) != lstrlen(Buf); } if (Error) { CloseHandle(ListFile); DeleteFile(ListFileName); if(!Silent) { const char *MsgItems[]={GetMsg(MError),GetMsg(MCannotCreateListFile),GetMsg(MOk)}; Info.Message(Info.ModuleNumber,FMSG_WARNING,NULL,MsgItems,ARRAYSIZE(MsgItems),1); } return FALSE; } } CloseHandle(ListFile); /* if (!CloseHandle(ListFile)) { // clearerr(ListFile); CloseHandle(ListFile); DeleteFile(ListFileName); if(!Silent) { char *MsgItems[]={GetMsg(MError),GetMsg(MCannotCreateListFile),GetMsg(MOk)}; Info.Message(Info.ModuleNumber,FMSG_WARNING,NULL,MsgItems,ARRAYSIZE(MsgItems),1); } return FALSE; } */ return TRUE; }
bool ReadTextFile(char *Name,StringList *List,bool Config,bool AbortOnError, bool ConvertToAnsi,bool Unquote,bool SkipComments) { char FileName[NM]; if (Config) GetConfigName(Name,FileName,true); else strcpy(FileName,Name); File SrcFile; if (*FileName) { bool OpenCode=AbortOnError ? SrcFile.WOpen(FileName):SrcFile.Open(FileName); if (!OpenCode) { if (AbortOnError) ErrHandler.Exit(OPEN_ERROR); return(false); } } else SrcFile.SetHandleType(FILE_HANDLESTD); unsigned int DataSize=0,ReadSize; const int ReadBlock=1024; Array<char> Data(ReadBlock+5); while ((ReadSize=SrcFile.Read(&Data[DataSize],ReadBlock))!=0) { DataSize+=ReadSize; Data.Add(ReadSize); } memset(&Data[DataSize],0,5); if (IsUnicode((byte *)&Data[0],DataSize)) { wchar *CurStr=(wchar *)&Data[2]; Array<char> AnsiName; while (*CurStr!=0) { wchar *NextStr=CurStr,*CmtPtr=NULL; while (*NextStr!='\r' && *NextStr!='\n' && *NextStr!=0) { if (SkipComments && NextStr[0]=='/' && NextStr[1]=='/') { *NextStr=0; CmtPtr=NextStr; } NextStr++; } *NextStr=0; for (wchar *SpacePtr=(CmtPtr ? CmtPtr:NextStr)-1;SpacePtr>=CurStr;SpacePtr--) { if (*SpacePtr!=' ' && *SpacePtr!='\t') break; *SpacePtr=0; } if (*CurStr) { int Length=strlenw(CurStr); int AddSize=Length-AnsiName.Size()+1; if (AddSize>0) AnsiName.Add(AddSize); if (Unquote && *CurStr=='\"' && CurStr[Length-1]=='\"') { CurStr[Length-1]=0; CurStr++; } WideToChar(CurStr,&AnsiName[0]); List->AddString(&AnsiName[0],CurStr); } CurStr=NextStr+1; while (*CurStr=='\r' || *CurStr=='\n') CurStr++; } } else { char *CurStr=&Data[0]; while (*CurStr!=0) { char *NextStr=CurStr,*CmtPtr=NULL; while (*NextStr!='\r' && *NextStr!='\n' && *NextStr!=0) { if (SkipComments && NextStr[0]=='/' && NextStr[1]=='/') { *NextStr=0; CmtPtr=NextStr; } NextStr++; } *NextStr=0; for (char *SpacePtr=(CmtPtr ? CmtPtr:NextStr)-1;SpacePtr>=CurStr;SpacePtr--) { if (*SpacePtr!=' ' && *SpacePtr!='\t') break; *SpacePtr=0; } if (*CurStr) { if (Unquote && *CurStr=='\"') { int Length=strlen(CurStr); if (CurStr[Length-1]=='\"') { CurStr[Length-1]=0; CurStr++; } } #if defined(_WIN_32) && !defined(_XBOX) && !defined(_LINUX) if (ConvertToAnsi) OemToChar(CurStr,CurStr); #endif List->AddString(CurStr); } CurStr=NextStr+1; while (*CurStr=='\r' || *CurStr=='\n') CurStr++; } } return(true); }
int CLIB_ROUTINE main( int argc, char **argv) { /************************************** * * m a i n * ************************************** * * Functional description * Install or remove a Firebird service. * **************************************/ USHORT sw_command = COMMAND_NONE; bool sw_version = false; USHORT sw_startup = STARTUP_AUTO; USHORT sw_mode = DEFAULT_PRIORITY; USHORT sw_guardian = NO_GUARDIAN; USHORT sw_arch = ARCH_SS; bool sw_interactive = false; const TEXT* instance = FB_DEFAULT_INSTANCE; const TEXT* username = NULL; const TEXT* password = NULL; // Let's get the root directory from the instance path of this program. // argv[0] is only _mostly_ guaranteed to give this info, // so we GetModuleFileName() TEXT directory[MAXPATHLEN]; const USHORT len = GetModuleFileName(NULL, directory, sizeof(directory)); if (len == 0) return svc_error(GetLastError(), "GetModuleFileName", NULL); fb_assert(len <= sizeof(directory)); // Get to the last '\' (this one precedes the filename part). There is // always one after a call to GetModuleFileName(). TEXT* p = directory + len; while (p != directory) { --p; if ((*p) == '\\') break; } *p = '\0'; TEXT full_username[128]; TEXT oem_username[128]; TEXT keyb_password[64]; const TEXT* const* const end = argv + argc; while (++argv < end) { if (**argv != '-') { int i; const TEXT* cmd; for (i = 0; cmd = commands[i].name; i++) { const TEXT* q; for (p = *argv, q = cmd; *p && UPPER(*p) == *q; p++, q++) ; if (!*p && commands[i].abbrev <= (USHORT) (q - cmd)) break; } if (!cmd) { printf("Unknown command \"%s\"\n", *argv); usage_exit(); } sw_command = commands[i].code; } else { p = *argv + 1; switch (UPPER(*p)) { case 'A': sw_startup = STARTUP_AUTO; break; case 'D': sw_startup = STARTUP_DEMAND; break; /* case 'R': sw_mode = NORMAL_PRIORITY; break; */ case 'B': sw_mode = HIGH_PRIORITY; break; case 'Z': sw_version = true; break; case 'G': sw_guardian = USE_GUARDIAN; break; case 'L': if (++argv < end) username = *argv; if (++argv < end) { if (**argv == '-') // Next switch --argv; else password = *argv; } break; case 'I': sw_interactive = true; break; case 'N': if (++argv < end) instance = *argv; break; case '?': usage_exit(); default: printf("Unknown switch \"%s\"\n", p); usage_exit(); } } } if (sw_version) printf("instsvc version %s\n", FB_VERSION); if (sw_command == COMMAND_NONE || (username && sw_command != COMMAND_INSTALL)) { usage_exit(); } if (sw_command == COMMAND_INSTALL && username != 0) { if (sw_interactive) { printf("\"Interact with desktop\" mode can be set for LocalSystem account only"); exit(FINI_ERROR); } const char* limit = username; while (*limit != '\0' && *limit != '\\') ++limit; if (!*limit) { DWORD cnlen = sizeof(full_username) - 1; GetComputerName(full_username, &cnlen); strcat(full_username, "\\"); strncat(full_username, username, sizeof(full_username) - (cnlen + 1)); } else { strncpy(full_username, username, sizeof(full_username)); } full_username[sizeof(full_username) - 1] = '\0'; CharToOem(full_username, oem_username); username = full_username; if (password == 0) { printf("Enter %s user password : "******"\n"); OemToChar(keyb_password, keyb_password); password = keyb_password; } // Let's grant "Logon as a Service" right to the -login user switch (SERVICES_grant_privilege(full_username, svc_error, L"SeServiceLogonRight")) { case FB_PRIVILEGE_ALREADY_GRANTED: /* // OM - I think it is better not to bother the admin with this message. printf("The 'Logon as a Service' right was already granted to %s\n", oem_username); */ break; case FB_SUCCESS: printf("The 'Logon as a Service' right has been granted to %s\n", oem_username); break; case FB_FAILURE: default: printf("Failed granting the 'Logon as a Service' right to %s\n", oem_username); exit(FINI_ERROR); break; } // Let's grant "Adjust memory quotas for a process" right to the -login user switch (SERVICES_grant_privilege(full_username, svc_error, L"SeIncreaseQuotaPrivilege")) { case FB_PRIVILEGE_ALREADY_GRANTED: break; case FB_SUCCESS: printf("The 'Adjust memory quotas for a process' right has been granted to %s\n", oem_username); break; case FB_FAILURE: default: printf("Failed granting the 'Adjust memory quotas for a process' right to %s\n", oem_username); exit(FINI_ERROR); break; } } DWORD dwScmManagerAccess = SC_MANAGER_ALL_ACCESS; switch (sw_command) { case COMMAND_INSTALL: case COMMAND_REMOVE: dwScmManagerAccess = SC_MANAGER_CREATE_SERVICE; break; case COMMAND_START: case COMMAND_STOP: dwScmManagerAccess = SC_MANAGER_CONNECT; break; case COMMAND_QUERY: dwScmManagerAccess = SC_MANAGER_ENUMERATE_SERVICE; break; } const SC_HANDLE manager = OpenSCManager(NULL, NULL, dwScmManagerAccess); if (manager == NULL) { svc_error(GetLastError(), "OpenSCManager", NULL); exit(FINI_ERROR); } USHORT status, status2; SC_HANDLE service; Firebird::string guard_service_name, guard_display_name; guard_service_name.printf(ISCGUARD_SERVICE, instance); guard_display_name.printf(ISCGUARD_DISPLAY_NAME, instance); Firebird::string remote_service_name, remote_display_name; remote_service_name.printf(REMOTE_SERVICE, instance); remote_display_name.printf(REMOTE_DISPLAY_NAME, instance); Firebird::string switches; if (strchr(instance, ' ')) switches.printf("-s \"%s\"", instance); else switches.printf("-s %s", instance); switch (sw_command) { case COMMAND_INSTALL: // First, lets do the guardian, if it has been specified if (sw_guardian) { status = SERVICES_install(manager, guard_service_name.c_str(), guard_display_name.c_str(), ISCGUARD_DISPLAY_DESCR, ISCGUARD_EXECUTABLE, directory, switches.c_str(), NULL, sw_startup, username, password, false, // interactive_mode true, // auto_restart svc_error); status2 = FB_SUCCESS; if (username != 0) { status2 = SERVICES_grant_access_rights(guard_service_name.c_str(), username, svc_error); } if (status == FB_SUCCESS && status2 == FB_SUCCESS) { printf("Service \"%s\" successfully created.\n", guard_display_name.c_str()); } // Set sw_startup to manual in preparation for install the service sw_startup = STARTUP_DEMAND; } // do the install of the server status = SERVICES_install(manager, remote_service_name.c_str(), remote_display_name.c_str(), REMOTE_DISPLAY_DESCR, REMOTE_EXECUTABLE, directory, switches.c_str(), NULL, sw_startup, username, password, sw_interactive, !sw_guardian, svc_error); status2 = FB_SUCCESS; if (username != 0) { status2 = SERVICES_grant_access_rights(remote_service_name.c_str(), username, svc_error); } if (status == FB_SUCCESS && status2 == FB_SUCCESS) { printf("Service \"%s\" successfully created.\n", remote_display_name.c_str()); } break; case COMMAND_REMOVE: service = OpenService(manager, guard_service_name.c_str(), SERVICE_ALL_ACCESS); if (service) { CloseServiceHandle(service); status = SERVICES_remove(manager, guard_service_name.c_str(), /*guard_display_name.c_str(),*/ svc_error); if (status == FB_SUCCESS) { printf("Service \"%s\" successfully deleted.\n", guard_display_name.c_str()); } else if (status == IB_SERVICE_RUNNING) { printf("Service \"%s\" not deleted.\n", guard_display_name.c_str()); printf("You must stop it before attempting to delete it.\n\n"); } } else { status = (GetLastError() == ERROR_SERVICE_DOES_NOT_EXIST) ? FB_SUCCESS : FB_FAILURE; } service = OpenService(manager, remote_service_name.c_str(), SERVICE_ALL_ACCESS); if (service) { CloseServiceHandle(service); status2 = SERVICES_remove(manager, remote_service_name.c_str(), /*remote_display_name.c_str(),*/ svc_error); if (status2 == FB_SUCCESS) { printf("Service \"%s\" successfully deleted.\n", remote_display_name.c_str()); } else if (status2 == IB_SERVICE_RUNNING) { printf("Service \"%s\" not deleted.\n", remote_display_name.c_str()); printf("You must stop it before attempting to delete it.\n\n"); } } else { status2 = (GetLastError() == ERROR_SERVICE_DOES_NOT_EXIST) ? FB_SUCCESS : FB_FAILURE; } if (status != FB_SUCCESS && status2 != FB_SUCCESS) status = FB_FAILURE; break; case COMMAND_START: // Test for use of the guardian. If so, start the guardian else start the server service = OpenService(manager, guard_service_name.c_str(), SERVICE_START); if (service) { CloseServiceHandle(service); status = SERVICES_start(manager, guard_service_name.c_str(), /*guard_display_name.c_str(),*/ sw_mode, svc_error); if (status == FB_SUCCESS) { printf("Service \"%s\" successfully started.\n", guard_display_name.c_str()); } } else { CloseServiceHandle(service); status = SERVICES_start(manager, remote_service_name.c_str(), /*remote_display_name.c_str(),*/ sw_mode, svc_error); if (status == FB_SUCCESS) { printf("Service \"%s\" successfully started.\n", remote_display_name.c_str()); } } break; case COMMAND_STOP: // Test for use of the guardian. If so, stop the guardian else stop the server service = OpenService(manager, guard_service_name.c_str(), SERVICE_STOP); if (service) { CloseServiceHandle(service); status = SERVICES_stop(manager, guard_service_name.c_str(), /*guard_display_name.c_str(),*/ svc_error); if (status == FB_SUCCESS) { printf("Service \"%s\" successfully stopped.\n", guard_display_name.c_str()); } } else { CloseServiceHandle(service); status = SERVICES_stop(manager, remote_service_name.c_str(), /*remote_display_name.c_str(),*/ svc_error); if (status == FB_SUCCESS) { printf("Service \"%s\" successfully stopped.\n", remote_display_name.c_str()); } } break; case COMMAND_QUERY: if (svc_query_ex(manager) == FB_FAILURE) { svc_query(guard_service_name.c_str(), guard_display_name.c_str(), manager); svc_query(remote_service_name.c_str(), remote_display_name.c_str(), manager); } status = FB_SUCCESS; break; default: status = FB_SUCCESS; } CloseServiceHandle(manager); return (status == FB_SUCCESS) ? FINI_OK : FINI_ERROR; }