bool CmdExtract::ExtrCreateFile(Archive &Arc,File &CurFile) { return true; // OPENMPT ADDITION bool Success=true; wchar Command=Cmd->Command[0]; #if !defined(GUI) && !defined(SFX_MODULE) if (Command=='P') CurFile.SetHandleType(FILE_HANDLESTD); #endif if ((Command=='E' || Command=='X') && !Cmd->Test) { bool UserReject; // Specify "write only" mode to avoid OpenIndiana NAS problems // with SetFileTime and read+write files. if (!FileCreate(Cmd,&CurFile,DestFileName,ASIZE(DestFileName),&UserReject,Arc.FileHead.UnpSize,&Arc.FileHead.mtime,true)) { Success=false; if (!UserReject) { ErrHandler.CreateErrorMsg(Arc.FileName,DestFileName); #ifdef RARDLL Cmd->DllError=ERAR_ECREATE; #endif if (!IsNameUsable(DestFileName)) { uiMsg(UIMSG_CORRECTINGNAME,Arc.FileName); wchar OrigName[ASIZE(DestFileName)]; wcsncpyz(OrigName,DestFileName,ASIZE(OrigName)); MakeNameUsable(DestFileName,true); CreatePath(DestFileName,true); if (FileCreate(Cmd,&CurFile,DestFileName,ASIZE(DestFileName),&UserReject,Arc.FileHead.UnpSize,&Arc.FileHead.mtime,true)) { #ifndef SFX_MODULE uiMsg(UIERROR_RENAMING,Arc.FileName,OrigName,DestFileName); #endif Success=true; } else ErrHandler.CreateErrorMsg(Arc.FileName,DestFileName); } } } } return Success; }
static Int2 LIBCALLBACK VSMGenericAsnSave (OMProcControlPtr ompcp, CharPtr mode ) { Char filename[255]; SelStructPtr ssp, sel; #ifdef WIN_MAC FILE * fp; #endif ValNodePtr entity_list = NULL, vnp; SelectedSaveData ssd; ssp = ObjMgrGetSelected(); if (ssp == NULL) { return OM_MSG_RET_ERROR; } for (sel = ssp; sel != NULL; sel = sel->next) { for (vnp = entity_list; vnp != NULL && vnp->data.intvalue != sel->entityID; vnp = vnp->next) {} if (vnp == NULL) { ValNodeAddInt (&entity_list, 0, sel->entityID); } } ssd.omp = ObjMgrGet(); /* get file name to use */ filename[0] = '\0'; if (GetOutputFileName(filename, (size_t)254, NULL)) { WatchCursor(); #ifdef WIN_MAC fp = FileOpen (filename, "r"); if (fp != NULL) { FileClose (fp); } else { FileCreate (filename, "TEXT", "ttxt"); } #endif ssd.aip = AsnIoOpen(filename, mode); ssd.ssp = ssp; for (vnp = entity_list; vnp != NULL; vnp = vnp->next) { SaveSeqLocEntity (vnp->data.intvalue, &ssd); GatherObjectsInEntity (vnp->data.intvalue, 0, NULL, SaveOneSelectedItem, (Pointer) &ssd, NULL); } ValNodeFree (entity_list); AsnIoClose(ssd.aip); ArrowCursor(); } return OM_MSG_RET_DONE; }
//--------------------------------------------------------------------------- void __fastcall TCPRecib1::PHDS1BeforePost( TObject* Sender ) { if( !FileExists( String( PHDS1->GV( RECIB_ARQUIVO ) ) ) ) { FileClose( FileCreate( String( PHDS1->GV( RECIB_ARQUIVO ) ) ) ); } if( PHDS1->State == phEdit ) { if(W1->Documents->Count) { for(int f = 1; f <= W1->Documents->Count; f++) { if((String)W1->Documents->Item((OleVariant)f)->Name == ExtractFileName(PHDS1->GV(RECIB_ARQUIVO))) { /*quando o usuário deixou o word aberto e não salvou as alterações nele, salva automaticamente e fecha o word*/ if(WordDocument1->Saved == false) WordDocument1->Save(); W1->Disconnect(); break; } } } } }
bool CmdExtract::ExtrCreateFile(CommandData *Cmd,Archive &Arc,File &CurFile) { bool Success=true; wchar Command=Cmd->Command[0]; #if !defined(GUI) && !defined(SFX_MODULE) if (Command=='P') CurFile.SetHandleType(FILE_HANDLESTD); #endif if ((Command=='E' || Command=='X') && !Cmd->Test) { bool UserReject; // Specify "write only" mode to avoid OpenIndiana NAS problems // with SetFileTime and read+write files. if (!FileCreate(Cmd,&CurFile,DestFileName,ASIZE(DestFileName),Cmd->Overwrite,&UserReject,Arc.FileHead.UnpSize,&Arc.FileHead.mtime,true)) { Success=false; if (!UserReject) { ErrHandler.CreateErrorMsg(Arc.FileName,DestFileName); ErrHandler.SetErrorCode(RARX_CREATE); #ifdef RARDLL Cmd->DllError=ERAR_ECREATE; #endif if (!IsNameUsable(DestFileName)) { Log(Arc.FileName,St(MCorrectingName)); wchar OrigName[ASIZE(DestFileName)]; wcsncpyz(OrigName,DestFileName,ASIZE(OrigName)); MakeNameUsable(DestFileName,true); CreatePath(DestFileName,true); if (FileCreate(Cmd,&CurFile,DestFileName,ASIZE(DestFileName),Cmd->Overwrite,&UserReject,Arc.FileHead.UnpSize,&Arc.FileHead.mtime,true)) { #ifndef SFX_MODULE Log(Arc.FileName,St(MRenaming),OrigName,DestFileName); #endif Success=true; } else ErrHandler.CreateErrorMsg(Arc.FileName,DestFileName); } } } } return Success; }
Int2 LIBCALLBACK VSMFastaSortedProtSave (Pointer data) { OMProcControlPtr ompcp; Char filename[255]; FILE * fp; ValNode vn; SeqEntryPtr sep = NULL; ompcp = (OMProcControlPtr)data; if (ompcp == NULL) return OM_MSG_RET_ERROR; switch(ompcp->input_itemtype) { case OBJ_SEQENTRY: case OBJ_BIOSEQ: case OBJ_BIOSEQSET: break; default: ErrPostEx(SEV_ERROR, 0,0,"ToFasta: Can only write Seq-entry, Bioseq, or Bioseq-set"); return OM_MSG_RET_ERROR; } if (ompcp->input_choicetype == OBJ_SEQENTRY) sep = (SeqEntryPtr)(ompcp->input_choice); else { vn.next = NULL; vn.data.ptrvalue = ompcp->input_data; if (ompcp->input_itemtype == OBJ_BIOSEQ) vn.choice = 1; else vn.choice = 2; sep = &vn; } filename[0] = '\0'; if (GetOutputFileName(filename, (size_t)254, NULL)) { WatchCursor(); #ifdef WIN_MAC fp = FileOpen (filename, "r"); if (fp != NULL) { FileClose (fp); } else { FileCreate (filename, "TEXT", "ttxt"); } #endif fp = FileOpen(filename, "w"); WriteSortedProteinsToFile (fp, sep); FileClose(fp); ArrowCursor(); } return OM_MSG_RET_DONE; }
static void Cn3D_ExportPDBNow(ButtoN b) { Char path[256]; FILE *pFile; Int2 iTest; Int4 iCount = 0; PDNMS pdnmsMain = NULL; Int2Ptr i2Vec = NULL; i2Vec = PickedModels(&iCount); if (iCount == 0) { ErrClear(); ErrPostEx(SEV_INFO, 0, 0, "Nothing to save!"); ErrShow(); Disable(Cn3D_bPDBOk); return; } GetTitle(Cn3D_tPDBSave, path, sizeof(path)); pdnmsMain = GetSelectedModelstruc(); #ifdef WIN_MAC FileCreate(path, "TEXT", "ttxt"); #endif WatchCursor(); pFile = FileOpen(path, "w"); if (pFile) { iTest = WritePDBModelList(pdnmsMain, pFile, iCount, i2Vec); I2VectorFree(i2Vec, 0); if (!iTest) { ErrClear(); ErrPostEx(SEV_FATAL, 0, 0, "Unable to Export\nPossibly Corrupt Data in Memory!\n"); ErrShow(); } fflush(pFile); fclose(pFile); } else { ErrClear(); ErrPostEx(SEV_INFO, 0, 0, "Sorry, Unable to Open File:\n %s", path); ErrShow(); Disable(Cn3D_bPDBOk); I2VectorFree(i2Vec, 0); SetTitle(Cn3D_tPDBSave, "\0"); ArrowCursor(); return; } Remove(Cn3D_wPDBSave); Cn3D_EnableFileOps(); Cn3D_Export_InUse = FALSE; ArrowCursor(); return; }
INIFile::INIFile( const std::string &name ) : fileLoaded( false ), /*invalid( true ),*/ fileDirty( false ) { memset( &statbuf, 0, sizeof( struct stat ) ); loadedFileName = ExpandFileName( trim( name ).c_str() ).c_str() ; if ( !FileExists( loadedFileName.c_str() ) ) { ForceDirectories( ExtractFilePath( loadedFileName.c_str() ).c_str() ); int fh = FileCreate( loadedFileName.c_str() ); if ( fh != -1 ) FileClose( fh ); } }
static Boolean SaveSetsInOneSelectedSet (GatherObjectPtr gop) { SetSavePtr ssp; SelStructPtr sel; BioseqSetPtr bssp; CharPtr filename, file_fmt = "%s_%d.sqn"; SeqEntryPtr sep; AsnIoPtr aip; #ifdef WIN_MAC FILE *fp; #endif if (gop == NULL || gop->dataptr == NULL || gop->itemtype != OBJ_BIOSEQSET) return TRUE; ssp = (SetSavePtr) gop->userdata; if (ssp == NULL || StringHasNoText (ssp->file_base)) return TRUE; sel = ssp->sel; while (sel != NULL && (sel->entityID != gop->entityID || sel->itemtype != gop->itemtype || sel->itemID != gop->itemID)) { sel = sel->next; } if (sel == NULL) return TRUE; bssp = gop->dataptr; filename = (CharPtr) MemNew (sizeof (Char) + (StringLen (ssp->file_base) + StringLen (file_fmt) + 15)); for (sep = bssp->seq_set; sep != NULL; sep = sep->next) { sprintf (filename, file_fmt, ssp->file_base, ssp->file_num); ssp->file_num++; #ifdef WIN_MAC fp = FileOpen (filename, "r"); if (fp != NULL) { FileClose (fp); } else { FileCreate (filename, "TEXT", "ttxt"); } #endif aip = AsnIoOpen(filename, "w"); SeqEntryAsnWrite (sep, aip, NULL); AsnIoClose (aip); } filename = MemFree (filename); return TRUE; }
void __fastcall TPointersViewBox::WritePointersToFile(TObject*) { if(FList) if(FList->size()>0) { TSaveDialog* dialog=new TSaveDialog(NULL); if(dialog->Execute()) { FileClose(FileCreate(dialog->FileName)); std::ofstream file(dialog->FileName.c_str()); WriteTListToStream(*FList,file); } delete dialog; } }
bool CEncoder::Init(const char* strFile, int iInChannels, int iInRate, int iInBits) { if (strFile == NULL) return false; m_dwWriteBufferPointer = 0; m_strFile = strFile; m_iInChannels = iInChannels; m_iInSampleRate = iInRate; m_iInBitsPerSample = iInBits; if (!FileCreate(strFile)) { CLog::Log(LOGERROR, "Error: Cannot open file: %s", strFile); return false; } return true; }
// Initialize tiny log TINY_LOG *NewTinyLog() { char name[MAX_PATH]; SYSTEMTIME st; TINY_LOG *t; LocalTime(&st); MakeDir(TINY_LOG_DIRNAME); Format(name, sizeof(name), TINY_LOG_FILENAME, st.wYear, st.wMonth, st.wDay, st.wHour, st.wMinute, st.wSecond); t = ZeroMalloc(sizeof(TINY_LOG)); StrCpy(t->FileName, sizeof(t->FileName), name); t->io = FileCreate(name); t->Lock = NewLock(); return t; }
int mtFile::runWrite( mtThreadWork::DataUser* pkDataUser ) { char* pcFile = getFileName(pkDataUser->pcAccount); if (NULL == pcFile) { return mtProtocol::E_RESULT_FALT_FILE_INVALIDE_PATH; } if (FileOpen(&pkDataUser->hFile, pcFile)) { pkDataUser->iFileOffset = getFileOffset(pkDataUser->pcAccount); pkDataUser->ulTransferBytes = getDataFileBytes(); pkDataUser->iFileRunType = E_FILE_RUN_WRITE_FILE; } else { /// ╢╢╫╗нд╪Ч if (FileCreate(&pkDataUser->hFile, pcFile, getFolderBytes())) { pkDataUser->iFileOffset = 0; pkDataUser->ulTransferBytes = getCreateFileBytes(); pkDataUser->iFileRunType = E_FILE_RUN_WRITE_FILE_CREATE; } else { return mtProtocol::E_RESULT_FALT_FILE_CREATE_FUNCTION; } } pkDataUser->kOverlapped.Offset = pkDataUser->iFileOffset; pkDataUser->eOverlappedType = mtThread::E_OLT_LOCKFILEEx; if (0 == FileLock(pkDataUser->hFile, pkDataUser->ulTransferBytes, &pkDataUser->kOverlapped, LOCKFILE_EXCLUSIVE_LOCK)) { FileClose(&pkDataUser->hFile); return mtProtocol::E_RESULT_FALT_FILE_LOCK; } return mtProtocol::E_RESULT_SUCCESS; }
/** * Create path recursively if parts of the path * do not exist. */ static bool FileCreatePath(const String& path) { // Get parent directory and check if it exists. String parentPath = FileGetParentDirectory(path); if (0 == parentPath.size()) { return false; } if (!FileExists(parentPath)) { // It does not exist, create it recursively. bool success = FileCreatePath(parentPath); if (!success) { return false; } } // Create the path. return FileCreate(path); }
//--------------------------------------------------------------------------- bool __fastcall TFileCmd::CreateFile() { AnsiString name = FDestinationName, path = FDestinationPath; if(FType == fstDirectory) { ForceDirectories(path + name); if(!DirectoryExists(path + name)) throw EInOutError("Couldn't create the directory " + FDestinationName); } else { if(FAddFile && FileExists(path + name)) { if((FDestinationHandle = FileOpen(path + name,fmOpenWrite|fmShareDenyWrite)) == -1) throw EFOpenError("Couldn't open the file " + FDestinationName); FileSeek(FDestinationHandle,0,2); } FDestinationHandle = FileCreate(path + name); if(FDestinationHandle == -1) return false; Position = 0; } return true; }
Value cairo_5c_gui_open_event (cairo_5c_surface_t *c5s) { ENTER (); cairo_5c_gui_t *gui = c5s->u.window.gui; int fd[2]; Value read; int err; if (pipe (fd) < 0) { err = errno; RaiseStandardException (exception_open_error, 3, FileGetErrorMessage (err), FileGetError (err), NewStrString ("event")); RETURN (Void); } read = FileCreate (fd[0], FileReadable); if (aborting) RETURN(Void); gui->send_events = fdopen (fd[1], "w"); RETURN(read); }
// щелчок на кнопке "Добавить" void __fastcall TForm1::Button1Click(TObject *Sender) { AnsiString st; /* файл можно открыть в режиме fmCreate, тогда, если файл существует, он будет открыт для записи, если файла нет, то он будет создан */ st = MonthCalendar1->Date.DateString() + " " + Edit1->Text + "\r\n"; /* открыть для записи или создать файл meteo.txt */ if ( FileExists("meteo.txt") ) f = FileOpen("meteo.txt",fmOpenWrite); else f = FileCreate("meteo.txt"); if ( f != -1 ) { // файл открыт для записи FileSeek(f,0,2); // установить указатель на конец файла FileWrite(f,st.c_str(),st.Length()); FileClose(f); Button1->Enabled = false; } else { /* ошибка доступа к файлу: ни открыть, ни создать не получилось */ ShowMessage("Oшибка доступа к файлу: ни открыть," "ни создать не получилось"); } }
bool CmdExtract::ExtractCurrentFile(Archive &Arc,size_t HeaderSize,bool &Repeat) { wchar Command=Cmd->Command[0]; if (HeaderSize==0) { if (DataIO.UnpVolume) { #ifdef NOVOLUME return false; #else // Supposing we unpack an old RAR volume without end of archive record // and last file is not split between volumes. if (!MergeArchive(Arc,&DataIO,false,Command)) { ErrHandler.SetErrorCode(RARX_WARNING); return false; } #endif } else return false; } HEADER_TYPE HeaderType=Arc.GetHeaderType(); if (HeaderType!=HEAD_FILE) { #ifndef SFX_MODULE if (HeaderType==HEAD3_OLDSERVICE && PrevExtracted) SetExtraInfo20(Cmd,Arc,DestFileName); #endif if (HeaderType==HEAD_SERVICE && PrevExtracted) SetExtraInfo(Cmd,Arc,DestFileName); if (HeaderType==HEAD_ENDARC) { if (Arc.EndArcHead.NextVolume) { #ifndef NOVOLUME if (!MergeArchive(Arc,&DataIO,false,Command)) { ErrHandler.SetErrorCode(RARX_WARNING); return false; } #endif Arc.Seek(Arc.CurBlockPos,SEEK_SET); return true; } else return false; } Arc.SeekToNext(); return true; } PrevExtracted=false; if (!Cmd->Recurse && MatchedArgs>=Cmd->FileArgs.ItemsCount() && AllMatchesExact) return false; int MatchType=MATCH_WILDSUBPATH; bool EqualNames=false; wchar MatchedArg[NM]; int MatchNumber=Cmd->IsProcessFile(Arc.FileHead,&EqualNames,MatchType,MatchedArg,ASIZE(MatchedArg)); bool MatchFound=MatchNumber!=0; #ifndef SFX_MODULE if (Cmd->ExclPath==EXCL_BASEPATH) { wcsncpyz(Cmd->ArcPath,MatchedArg,ASIZE(Cmd->ArcPath)); *PointToName(Cmd->ArcPath)=0; if (IsWildcard(Cmd->ArcPath)) // Cannot correctly process path*\* masks here. *Cmd->ArcPath=0; } #endif if (MatchFound && !EqualNames) AllMatchesExact=false; Arc.ConvertAttributes(); #if !defined(SFX_MODULE) && !defined(RARDLL) if (Arc.FileHead.SplitBefore && FirstFile) { wchar CurVolName[NM]; wcsncpyz(CurVolName,ArcName,ASIZE(CurVolName)); VolNameToFirstName(ArcName,ArcName,ASIZE(ArcName),Arc.NewNumbering); if (wcsicomp(ArcName,CurVolName)!=0 && FileExist(ArcName)) { // If first volume name does not match the current name and if such // volume name really exists, let's unpack from this first volume. Repeat=true; return false; } #ifndef RARDLL if (!ReconstructDone) { ReconstructDone=true; if (RecVolumesRestore(Cmd,Arc.FileName,true)) { Repeat=true; return false; } } #endif wcsncpyz(ArcName,CurVolName,ASIZE(ArcName)); } #endif wchar ArcFileName[NM]; ConvertPath(Arc.FileHead.FileName,ArcFileName); if (Arc.FileHead.Version) { if (Cmd->VersionControl!=1 && !EqualNames) { if (Cmd->VersionControl==0) MatchFound=false; int Version=ParseVersionFileName(ArcFileName,false); if (Cmd->VersionControl-1==Version) ParseVersionFileName(ArcFileName,true); else MatchFound=false; } } else if (!Arc.IsArcDir() && Cmd->VersionControl>1) MatchFound=false; DataIO.UnpVolume=Arc.FileHead.SplitAfter; DataIO.NextVolumeMissing=false; Arc.Seek(Arc.NextBlockPos-Arc.FileHead.PackSize,SEEK_SET); bool ExtrFile=false; bool SkipSolid=false; #ifndef SFX_MODULE if (FirstFile && (MatchFound || Arc.Solid) && Arc.FileHead.SplitBefore) { if (MatchFound) { uiMsg(UIERROR_NEEDPREVVOL,Arc.FileName,ArcFileName); #ifdef RARDLL Cmd->DllError=ERAR_BAD_DATA; #endif ErrHandler.SetErrorCode(RARX_OPEN); } MatchFound=false; } FirstFile=false; #endif if (MatchFound || (SkipSolid=Arc.Solid)!=0) { // First common call of uiStartFileExtract. It is done before overwrite // prompts, so if SkipSolid state is changed below, we'll need to make // additional uiStartFileExtract calls with updated parameters. if (!uiStartFileExtract(ArcFileName,!Cmd->Test,Cmd->Test && Command!='I',SkipSolid)) return false; ExtrPrepareName(Arc,ArcFileName,DestFileName,ASIZE(DestFileName)); // DestFileName can be set empty in case of excessive -ap switch. ExtrFile=!SkipSolid && *DestFileName!=0 && !Arc.FileHead.SplitBefore; if ((Cmd->FreshFiles || Cmd->UpdateFiles) && (Command=='E' || Command=='X')) { FindData FD; if (FindFile::FastFind(DestFileName,&FD)) { if (FD.mtime >= Arc.FileHead.mtime) { // If directory already exists and its modification time is newer // than start of extraction, it is likely it was created // when creating a path to one of already extracted items. // In such case we'll better update its time even if archived // directory is older. if (!FD.IsDir || FD.mtime<StartTime) ExtrFile=false; } } else if (Cmd->FreshFiles) ExtrFile=false; } if (Arc.FileHead.Encrypted) { #ifdef RARDLL if (!ExtrDllGetPassword()) return false; #else if (!ExtrGetPassword(Arc,ArcFileName)) { PasswordCancelled=true; return false; } #endif // Skip only the current encrypted file if empty password is entered. if (!Cmd->Password.IsSet()) { ErrHandler.SetErrorCode(RARX_WARNING); #ifdef RARDLL Cmd->DllError=ERAR_MISSING_PASSWORD; #endif ExtrFile=false; } } #ifdef RARDLL if (*Cmd->DllDestName!=0) wcsncpyz(DestFileName,Cmd->DllDestName,ASIZE(DestFileName)); #endif if (!CheckUnpVer(Arc,ArcFileName)) { ExtrFile=false; ErrHandler.SetErrorCode(RARX_FATAL); #ifdef RARDLL Cmd->DllError=ERAR_UNKNOWN_FORMAT; #endif } File CurFile; bool LinkEntry=Arc.FileHead.RedirType!=FSREDIR_NONE; if (LinkEntry && Arc.FileHead.RedirType!=FSREDIR_FILECOPY) { if (ExtrFile && Command!='P' && !Cmd->Test) { // Overwrite prompt for symbolic and hard links. bool UserReject=false; if (FileExist(DestFileName) && !UserReject) FileCreate(Cmd,NULL,DestFileName,ASIZE(DestFileName),&UserReject,Arc.FileHead.UnpSize,&Arc.FileHead.mtime); if (UserReject) ExtrFile=false; } } else if (Arc.IsArcDir()) { if (!ExtrFile || Command=='P' || Command=='I' || Command=='E' || Cmd->ExclPath==EXCL_SKIPWHOLEPATH) return true; TotalFileCount++; ExtrCreateDir(Arc,ArcFileName); return true; } else if (ExtrFile) // Create files and file copies (FSREDIR_FILECOPY). ExtrFile=ExtrCreateFile(Arc,CurFile); if (!ExtrFile && Arc.Solid) { SkipSolid=true; ExtrFile=true; // We changed SkipSolid, so we need to call uiStartFileExtract // with "Skip" parameter to change the operation status // from "extracting" to "skipping". For example, it can be necessary // if user answered "No" to overwrite prompt when unpacking // a solid archive. if (!uiStartFileExtract(ArcFileName,false,false,true)) return false; } if (ExtrFile) { bool TestMode=Cmd->Test || SkipSolid; // Unpack to memory, not to disk. if (!SkipSolid) { if (!TestMode && Command!='P' && CurFile.IsDevice()) { uiMsg(UIERROR_INVALIDNAME,Arc.FileName,DestFileName); ErrHandler.WriteError(Arc.FileName,DestFileName); } TotalFileCount++; } FileCount++; #ifndef GUI if (Command!='I') { if (SkipSolid) mprintf(St(MExtrSkipFile),ArcFileName); else switch(Cmd->Test ? 'T':Command) // "Test" can be also enabled by -t switch. { case 'T': mprintf(St(MExtrTestFile),ArcFileName); break; #ifndef SFX_MODULE case 'P': mprintf(St(MExtrPrinting),ArcFileName); break; #endif case 'X': case 'E': mprintf(St(MExtrFile),DestFileName); break; } } if (!Cmd->DisablePercentage) mprintf(L" "); #endif SecPassword FilePassword=Cmd->Password; #if defined(_WIN_ALL) && !defined(SFX_MODULE) ConvertDosPassword(Arc,FilePassword); #endif byte PswCheck[SIZE_PSWCHECK]; DataIO.SetEncryption(false,Arc.FileHead.CryptMethod,&FilePassword, Arc.FileHead.SaltSet ? Arc.FileHead.Salt:NULL, Arc.FileHead.InitV,Arc.FileHead.Lg2Count, PswCheck,Arc.FileHead.HashKey); bool WrongPassword=false; // If header is damaged, we cannot rely on password check value, // because it can be damaged too. if (Arc.FileHead.Encrypted && Arc.FileHead.UsePswCheck && memcmp(Arc.FileHead.PswCheck,PswCheck,SIZE_PSWCHECK)!=0 && !Arc.BrokenHeader) { uiMsg(UIERROR_BADPSW,Arc.FileName); ErrHandler.SetErrorCode(RARX_BADPWD); WrongPassword=true; } DataIO.CurUnpRead=0; DataIO.CurUnpWrite=0; DataIO.UnpHash.Init(Arc.FileHead.FileHash.Type,Cmd->Threads); DataIO.PackedDataHash.Init(Arc.FileHead.FileHash.Type,Cmd->Threads); DataIO.SetPackedSizeToRead(Arc.FileHead.PackSize); DataIO.SetFiles(&Arc,&CurFile); DataIO.SetTestMode(TestMode); DataIO.SetSkipUnpCRC(SkipSolid); #if defined(_WIN_ALL) && !defined(SFX_MODULE) && !defined(SILENT) if (!TestMode && !WrongPassword && !Arc.BrokenHeader && Arc.FileHead.UnpSize>0xffffffff && (Fat32 || !NotFat32)) { if (!Fat32) // Not detected yet. NotFat32=!(Fat32=IsFAT(Cmd->ExtrPath)); if (Fat32) uiMsg(UIMSG_FAT32SIZE); // Inform user about FAT32 size limit. } #endif if (!TestMode && !WrongPassword && !Arc.BrokenHeader && (Arc.FileHead.PackSize<<11)>Arc.FileHead.UnpSize && (Arc.FileHead.UnpSize<100000000 || Arc.FileLength()>Arc.FileHead.PackSize)) CurFile.Prealloc(Arc.FileHead.UnpSize); CurFile.SetAllowDelete(!Cmd->KeepBroken); bool FileCreateMode=!TestMode && !SkipSolid && Command!='P'; bool ShowChecksum=true; // Display checksum verification result. bool LinkSuccess=true; // Assume success for test mode. if (LinkEntry) { FILE_SYSTEM_REDIRECT Type=Arc.FileHead.RedirType; if (Type==FSREDIR_HARDLINK || Type==FSREDIR_FILECOPY) { wchar NameExisting[NM]; ExtrPrepareName(Arc,Arc.FileHead.RedirName,NameExisting,ASIZE(NameExisting)); if (FileCreateMode && *NameExisting!=0) // *NameExisting can be 0 in case of excessive -ap switch. { if (Type==FSREDIR_HARDLINK) LinkSuccess=ExtractHardlink(DestFileName,NameExisting,ASIZE(NameExisting)); else LinkSuccess=ExtractFileCopy(CurFile,Arc.FileName,DestFileName,NameExisting,ASIZE(NameExisting)); } } else if (Type==FSREDIR_UNIXSYMLINK || Type==FSREDIR_WINSYMLINK || Type==FSREDIR_JUNCTION) { if (FileCreateMode) LinkSuccess=ExtractSymlink(Cmd,DataIO,Arc,DestFileName); } else { uiMsg(UIERROR_UNKNOWNEXTRA, Arc.FileName, DestFileName); LinkSuccess=false; } if (!LinkSuccess || (Arc.Format==RARFMT15 && !FileCreateMode)) { // RAR 5.x links have a valid data checksum even in case of // failure, because they do not store any data. // We do not want to display "OK" in this case. // For 4.x symlinks we verify the checksum only when extracting, // but not when testing an archive. ShowChecksum=false; } PrevExtracted=FileCreateMode && LinkSuccess; } else if (!Arc.FileHead.SplitBefore && !WrongPassword) { if (Arc.FileHead.Method==0) UnstoreFile(DataIO,Arc.FileHead.UnpSize); else { #ifdef _ANDROID // malloc and new do not report memory allocation errors // in Android, so if free memory is set, check it here // trying to prevent crash. if (Cmd->FreeMem!=0 && Cmd->FreeMem < Arc.FileHead.WinSize) throw std::bad_alloc(); #endif Unp->Init(Arc.FileHead.WinSize,Arc.FileHead.Solid); Unp->SetDestSize(Arc.FileHead.UnpSize); #ifndef SFX_MODULE if (Arc.Format!=RARFMT50 && Arc.FileHead.UnpVer<=15) Unp->DoUnpack(15,FileCount>1 && Arc.Solid); else #endif Unp->DoUnpack(Arc.FileHead.UnpVer,Arc.FileHead.Solid); } } Arc.SeekToNext(); // We check for "split after" flag to detect partially extracted files // from incomplete volume sets. For them file header contains packed // data hash, which must not be compared against unpacked data hash // to prevent accidental match. Moreover, for -m0 volumes packed data // hash would match truncated unpacked data hash and lead to fake "OK" // in incomplete volume set. bool ValidCRC=!Arc.FileHead.SplitAfter && DataIO.UnpHash.Cmp(&Arc.FileHead.FileHash,Arc.FileHead.UseHashKey ? Arc.FileHead.HashKey:NULL); // We set AnySolidDataUnpackedWell to true if we found at least one // valid non-zero solid file in preceding solid stream. If it is true // and if current encrypted file is broken, we do not need to hint // about a wrong password and can report CRC error only. if (!Arc.FileHead.Solid) AnySolidDataUnpackedWell=false; // Reset the flag, because non-solid file is found. else if (Arc.FileHead.Method!=0 && Arc.FileHead.UnpSize>0 && ValidCRC) AnySolidDataUnpackedWell=true; bool BrokenFile=false; // Checksum is not calculated in skip solid mode for performance reason. if (!SkipSolid && ShowChecksum) { if (!WrongPassword && ValidCRC) { #ifndef GUI if (Command!='P' && Command!='I') mprintf(L"%s%s ",Cmd->DisablePercentage ? L" ":L"\b\b\b\b\b ", Arc.FileHead.FileHash.Type==HASH_NONE ? L" ?":St(MOk)); #endif } else { if (!WrongPassword) { if (Arc.FileHead.Encrypted && (!Arc.FileHead.UsePswCheck || Arc.BrokenHeader) && !AnySolidDataUnpackedWell) uiMsg(UIERROR_CHECKSUMENC,Arc.FileName,ArcFileName); else uiMsg(UIERROR_CHECKSUM,Arc.FileName,ArcFileName); } BrokenFile=true; ErrHandler.SetErrorCode(RARX_CRC); #ifdef RARDLL // If we already have ERAR_EOPEN as result of missing volume, // we should not replace it with less precise ERAR_BAD_DATA. if (Cmd->DllError!=ERAR_EOPEN) Cmd->DllError=WrongPassword ? ERAR_BAD_PASSWORD : ERAR_BAD_DATA; #endif } } #ifndef GUI else mprintf(L"\b\b\b\b\b "); #endif if (!TestMode && !WrongPassword && (Command=='X' || Command=='E') && (!LinkEntry || (Arc.FileHead.RedirType==FSREDIR_FILECOPY && LinkSuccess)) && (!BrokenFile || Cmd->KeepBroken)) { // We could preallocate more space that really written to broken file. if (BrokenFile) CurFile.Truncate(); #if defined(_WIN_ALL) || defined(_EMX) if (Cmd->ClearArc) Arc.FileHead.FileAttr&=~FILE_ATTRIBUTE_ARCHIVE; #endif CurFile.SetOpenFileTime( Cmd->xmtime==EXTTIME_NONE ? NULL:&Arc.FileHead.mtime, Cmd->xctime==EXTTIME_NONE ? NULL:&Arc.FileHead.ctime, Cmd->xatime==EXTTIME_NONE ? NULL:&Arc.FileHead.atime); CurFile.Close(); #if defined(_WIN_ALL) && !defined(SFX_MODULE) if (Cmd->SetCompressedAttr && (Arc.FileHead.FileAttr & FILE_ATTRIBUTE_COMPRESSED)!=0) SetFileCompression(CurFile.FileName,true); #endif #ifdef _UNIX if (Cmd->ProcessOwners && Arc.Format==RARFMT50 && Arc.FileHead.UnixOwnerSet) SetUnixOwner(Arc,CurFile.FileName); #endif CurFile.SetCloseFileTime( Cmd->xmtime==EXTTIME_NONE ? NULL:&Arc.FileHead.mtime, Cmd->xatime==EXTTIME_NONE ? NULL:&Arc.FileHead.atime); if (!Cmd->IgnoreGeneralAttr && !SetFileAttr(CurFile.FileName,Arc.FileHead.FileAttr)) uiMsg(UIERROR_FILEATTR,Arc.FileName,CurFile.FileName); PrevExtracted=true; } } } if (MatchFound) MatchedArgs++; if (DataIO.NextVolumeMissing) return false; if (!ExtrFile) { if (!Arc.Solid) Arc.SeekToNext(); else if (!SkipSolid) return false; } return true; }
bool RecVolumes5::Restore(RAROptions *Cmd,const wchar *Name,bool Silent) { wchar ArcName[NM]; wcscpy(ArcName,Name); wchar *Num=GetVolNumPart(ArcName); while (Num>ArcName && IsDigit(*(Num-1))) Num--; wcsncpyz(Num,L"*.*",ASIZE(ArcName)-(Num-ArcName)); wchar FirstVolName[NM]; *FirstVolName=0; int64 RecFileSize=0; FindFile VolFind; VolFind.SetMask(ArcName); FindData fd; uint FoundRecVolumes=0; while (VolFind.Next(&fd)) { Wait(); Archive *Vol=new Archive(Cmd); int ItemPos=-1; if (Vol->WOpen(fd.Name)) { if (CmpExt(fd.Name,L"rev")) { uint RecNum=ReadHeader(Vol,FoundRecVolumes==0); if (RecNum!=0) { if (FoundRecVolumes==0) RecFileSize=Vol->FileLength(); ItemPos=RecNum; FoundRecVolumes++; } } else if (Vol->IsArchive(true) && (Vol->SFXSize>0 || CmpExt(fd.Name,L"rar"))) { if (!Vol->Volume && !Vol->BrokenHeader) { uiMsg(UIERROR_NOTVOLUME,ArcName); return false; } // We work with archive as with raw data file, so we do not want // to spend time to QOpen I/O redirection. Vol->QOpenUnload(); Vol->Seek(0,SEEK_SET); // RAR volume found. Get its number, store the handle in appropriate // array slot, clean slots in between if we had to grow the array. wchar *Num=GetVolNumPart(fd.Name); uint VolNum=0; for (uint K=1;Num>=fd.Name && IsDigit(*Num);K*=10,Num--) VolNum+=(*Num-'0')*K; if (VolNum==0 || VolNum>MaxVolumes) continue; size_t CurSize=RecItems.Size(); if (VolNum>CurSize) { RecItems.Alloc(VolNum); for (size_t I=CurSize;I<VolNum;I++) RecItems[I].f=NULL; } ItemPos=VolNum-1; if (*FirstVolName==0) VolNameToFirstName(fd.Name,FirstVolName,ASIZE(FirstVolName),true); } } if (ItemPos==-1) delete Vol; // Skip found file, it is not RAR or REV volume. else if ((uint)ItemPos<RecItems.Size()) // Check if found more REV than needed. { // Store found RAR or REV volume. RecVolItem *Item=RecItems+ItemPos; Item->f=Vol; Item->New=false; wcsncpyz(Item->Name,fd.Name,ASIZE(Item->Name)); } } if (!Silent || FoundRecVolumes!=0) uiMsg(UIMSG_RECVOLFOUND,FoundRecVolumes); if (FoundRecVolumes==0) return false; uiMsg(UIMSG_RECVOLCALCCHECKSUM); MissingVolumes=0; for (uint I=0;I<TotalCount;I++) { RecVolItem *Item=&RecItems[I]; if (Item->f!=NULL) { uiMsg(UIMSG_STRING,Item->Name); uint RevCRC; CalcFileSum(Item->f,&RevCRC,NULL,Cmd->Threads,INT64NDF,CALCFSUM_CURPOS); Item->Valid=RevCRC==Item->CRC; if (!Item->Valid) { uiMsg(UIMSG_CHECKSUM,Item->Name); // Close only corrupt REV volumes here. We'll close and rename corrupt // RAR volumes later, if we'll know that recovery is possible. if (I>=DataCount) { Item->f->Close(); Item->f=NULL; FoundRecVolumes--; } } } if (I<DataCount && (Item->f==NULL || !Item->Valid)) MissingVolumes++; } uiMsg(UIMSG_RECVOLMISSING,MissingVolumes); if (MissingVolumes==0) { uiMsg(UIERROR_RECVOLALLEXIST); return false; } if (MissingVolumes>FoundRecVolumes) { uiMsg(UIERROR_RECVOLFOUND,FoundRecVolumes); // Intentionally not displayed in console mode. uiMsg(UIERROR_RECVOLCANNOTFIX); return false; } uiMsg(UIMSG_RECONSTRUCTING); // Create missing and rename bad volumes. uint64 MaxVolSize=0; for (uint I=0;I<DataCount;I++) { RecVolItem *Item=&RecItems[I]; if (Item->FileSize>MaxVolSize) MaxVolSize=Item->FileSize; if (Item->f!=NULL && !Item->Valid) { Item->f->Close(); wchar NewName[NM]; wcscpy(NewName,Item->Name); wcscat(NewName,L".bad"); uiMsg(UIMSG_BADARCHIVE,Item->Name); uiMsg(UIMSG_RENAMING,Item->Name,NewName); RenameFile(Item->Name,NewName); delete Item->f; Item->f=NULL; } if (Item->New=(Item->f==NULL)) { wcsncpyz(Item->Name,FirstVolName,ASIZE(Item->Name)); uiMsg(UIMSG_CREATING,Item->Name); uiMsg(UIEVENT_NEWARCHIVE,Item->Name); File *NewVol=new File; bool UserReject; if (!FileCreate(Cmd,NewVol,Item->Name,ASIZE(Item->Name),&UserReject)) { if (!UserReject) ErrHandler.CreateErrorMsg(Item->Name); ErrHandler.Exit(UserReject ? RARX_USERBREAK:RARX_CREATE); } NewVol->Prealloc(Item->FileSize); Item->f=NewVol; Item->New=true; } NextVolumeName(FirstVolName,ASIZE(FirstVolName),false); } int64 ProcessedSize=0; #ifndef GUI int LastPercent=-1; mprintf(L" "); #endif // Even though we already preliminary calculated missing volume number, // let's do it again now, when we have the final and exact information. MissingVolumes=0; ValidFlags=new bool[TotalCount]; for (uint I=0;I<TotalCount;I++) { ValidFlags[I]=RecItems[I].f!=NULL && !RecItems[I].New; if (I<DataCount && !ValidFlags[I]) MissingVolumes++; } // Size of per file buffer. RecBufferSize=TotalBufferSize/MissingVolumes; if ((RecBufferSize&1)==1) // Must be even for our RS16 codec. RecBufferSize--; #ifdef USE_SSE RecBufferSize&=~(SSE_ALIGNMENT-1); // Align for SSE. #endif uint *Data=new uint[TotalCount]; RSCoder16 RS; if (!RS.Init(DataCount,RecCount,ValidFlags)) return false; // Should not happen, we check parameter validity above. RealReadBuffer=new byte[RecBufferSize+SSE_ALIGNMENT]; byte *ReadBuf=(byte *)ALIGN_VALUE(RealReadBuffer,SSE_ALIGNMENT); while (true) { Wait(); int MaxRead=0; for (uint I=0,J=DataCount;I<DataCount;I++) { uint VolNum=I; if (!ValidFlags[I]) // If next RAR volume is missing or invalid. { while (!ValidFlags[J]) // Find next valid REV volume. J++; VolNum=J++; // Use next valid REV volume data instead of RAR. } RecVolItem *Item=RecItems+VolNum; byte *B=&ReadBuf[0]; int ReadSize=0; if (Item->f!=NULL && !Item->New) ReadSize=Item->f->Read(B,RecBufferSize); if (ReadSize!=RecBufferSize) memset(B+ReadSize,0,RecBufferSize-ReadSize); if (ReadSize>MaxRead) MaxRead=ReadSize; // We can have volumes of different size. Let's use data chunk // for largest volume size. uint DataToProcess=(uint)Min(RecBufferSize,MaxVolSize-ProcessedSize); ProcessRS(Cmd,I,B,DataToProcess,false); } if (MaxRead==0) break; for (uint I=0,J=0;I<DataCount;I++) if (!ValidFlags[I]) { RecVolItem *Item=RecItems+I; size_t WriteSize=(size_t)Min(MaxRead,Item->FileSize); Item->f->Write(Buf+(J++)*RecBufferSize,WriteSize); Item->FileSize-=WriteSize; } int CurPercent=ToPercent(ProcessedSize,RecFileSize); if (!Cmd->DisablePercentage && CurPercent!=LastPercent) { uiProcessProgress("RV",ProcessedSize,RecFileSize); LastPercent=CurPercent; } ProcessedSize+=MaxRead; } for (uint I=0;I<TotalCount;I++) if (RecItems[I].f!=NULL) RecItems[I].f->Close(); delete[] ValidFlags; delete[] Data; #if !defined(GUI) && !defined(SILENT) if (!Cmd->DisablePercentage) mprintf(L"\b\b\b\b100%%"); if (!Silent && !Cmd->DisableDone) mprintf(St(MDone)); #endif return true; }
Int2 LIBCALLBACK VSMFastaProtSaveWithProduct ( Pointer data ) { Char filename[255]; FastaExportOptionsData fe; ValNode vn; SeqEntryPtr sep = NULL; SeqFeatPtr sfp; SeqLocPtr slp; Uint1 code; BioseqPtr bsp; OMProcControlPtr ompcp; if ((ompcp = (OMProcControlPtr) data) == NULL) { return OM_MSG_RET_ERROR; } sfp = NULL; switch(ompcp->input_itemtype) { case OBJ_SEQENTRY: case OBJ_BIOSEQ: case OBJ_BIOSEQSET: break; case OBJ_SEQFEAT: sfp = (SeqFeatPtr) ompcp->input_data; if (sfp == NULL || (sfp->data.choice != SEQFEAT_CDREGION && sfp->data.choice != SEQFEAT_PROT)) return OM_MSG_RET_ERROR; break; default: ErrPostEx(SEV_ERROR, 0,0,"ToFasta: Can only write Seq-entry, Bioseq, or Bioseq-set"); return OM_MSG_RET_ERROR; } if (sfp != NULL) { } else if (ompcp->input_choicetype == OBJ_SEQENTRY) sep = (SeqEntryPtr)(ompcp->input_choice); else { vn.next = NULL; vn.data.ptrvalue = ompcp->input_data; if (ompcp->input_itemtype == OBJ_BIOSEQ) vn.choice = 1; else vn.choice = 2; sep = &vn; } filename[0] = '\0'; if (GetOutputFileName(filename, (size_t)254, NULL)) { WatchCursor(); #ifdef WIN_MAC fe.fp = FileOpen (filename, "r"); if (fe.fp != NULL) { FileClose (fe.fp); } else { FileCreate (filename, "TEXT", "ttxt"); } #endif fe.fp = FileOpen(filename, "w"); if (sfp != NULL) { code = Seq_code_ncbieaa; slp = sfp->location; if (sfp->data.choice == SEQFEAT_CDREGION) { slp = sfp->product; } bsp = GetBioseqGivenSeqLoc (slp, ompcp->input_entityID); if (slp != NULL && bsp != NULL) { SeqLocFastaStream (slp, fe.fp, STREAM_EXPAND_GAPS | STREAM_CORRECT_INVAL, 70, 0, 0); } } else { fe.flags = STREAM_EXPAND_GAPS | STREAM_CORRECT_INVAL; fe.linelen = 70; fe.blocklen = 0; fe.grouplen = 0; VisitBioseqsInSep (sep, &fe, WriteOneProteinWithProduct); } FileClose(fe.fp); ArrowCursor(); } return OM_MSG_RET_DONE; }
bool CmdExtract::ExtractCurrentFile(CommandData *Cmd,Archive &Arc,size_t HeaderSize,bool &Repeat) { char Command=*Cmd->Command; if (HeaderSize==0) if (DataIO.UnpVolume) { #ifdef NOVOLUME return(false); #else if (!MergeArchive(Arc,&DataIO,false,Command)) { ErrHandler.SetErrorCode(WARNING); return(false); } SignatureFound=false; #endif } else return(false); int HeadType=Arc.GetHeaderType(); if (HeadType!=FILE_HEAD) { if (HeadType==AV_HEAD || HeadType==SIGN_HEAD) SignatureFound=true; #if !defined(SFX_MODULE) && !defined(_WIN_CE) if (HeadType==SUB_HEAD && PrevExtracted) SetExtraInfo(Cmd,Arc,DestFileName,*DestFileNameW ? DestFileNameW:NULL); #endif if (HeadType==NEWSUB_HEAD) { if (Arc.SubHead.CmpName(SUBHEAD_TYPE_AV)) SignatureFound=true; #if !defined(NOSUBBLOCKS) && !defined(_WIN_CE) if (PrevExtracted) SetExtraInfoNew(Cmd,Arc,DestFileName,*DestFileNameW ? DestFileNameW:NULL); #endif } if (HeadType==ENDARC_HEAD) if (Arc.EndArcHead.Flags & EARC_NEXT_VOLUME) { #ifndef NOVOLUME if (!MergeArchive(Arc,&DataIO,false,Command)) { ErrHandler.SetErrorCode(WARNING); return(false); } SignatureFound=false; #endif Arc.Seek(Arc.CurBlockPos,SEEK_SET); return(true); } else return(false); Arc.SeekToNext(); return(true); } PrevExtracted=false; if (SignatureFound || !Cmd->Recurse && MatchedArgs>=Cmd->FileArgs->ItemsCount() && AllMatchesExact) return(false); char ArcFileName[NM]; IntToExt(Arc.NewLhd.FileName,Arc.NewLhd.FileName); strcpy(ArcFileName,Arc.NewLhd.FileName); wchar ArcFileNameW[NM]; *ArcFileNameW=0; int MatchType=MATCH_WILDSUBPATH; bool EqualNames=false; int MatchNumber=Cmd->IsProcessFile(Arc.NewLhd,&EqualNames,MatchType); bool ExactMatch=MatchNumber!=0; #if !defined(SFX_MODULE) && !defined(_WIN_CE) if (Cmd->ExclPath==EXCL_BASEPATH) { *Cmd->ArcPath=0; if (ExactMatch) { Cmd->FileArgs->Rewind(); if (Cmd->FileArgs->GetString(Cmd->ArcPath,NULL,sizeof(Cmd->ArcPath),MatchNumber-1)) *PointToName(Cmd->ArcPath)=0; } } #endif if (ExactMatch && !EqualNames) AllMatchesExact=false; #ifdef UNICODE_SUPPORTED bool WideName=(Arc.NewLhd.Flags & LHD_UNICODE) && UnicodeEnabled(); #else bool WideName=false; #endif #ifdef _APPLE if (WideName) { WideToUtf(Arc.NewLhd.FileNameW,ArcFileName,sizeof(ArcFileName)); WideName=false; } #endif wchar *DestNameW=WideName ? DestFileNameW:NULL; #ifdef UNICODE_SUPPORTED if (WideName) { ConvertPath(Arc.NewLhd.FileNameW,ArcFileNameW); char Name[NM]; if (WideToChar(ArcFileNameW,Name) && IsNameUsable(Name)) strcpy(ArcFileName,Name); } #endif ConvertPath(ArcFileName,ArcFileName); if (Arc.IsArcLabel()) return(true); if (Arc.NewLhd.Flags & LHD_VERSION) { if (Cmd->VersionControl!=1 && !EqualNames) { if (Cmd->VersionControl==0) ExactMatch=false; int Version=ParseVersionFileName(ArcFileName,ArcFileNameW,false); if (Cmd->VersionControl-1==Version) ParseVersionFileName(ArcFileName,ArcFileNameW,true); else ExactMatch=false; } } else if (!Arc.IsArcDir() && Cmd->VersionControl>1) ExactMatch=false; Arc.ConvertAttributes(); #ifndef SFX_MODULE if ((Arc.NewLhd.Flags & (LHD_SPLIT_BEFORE/*|LHD_SOLID*/)) && FirstFile) { char CurVolName[NM]; strcpy(CurVolName,ArcName); VolNameToFirstName(ArcName,ArcName,(Arc.NewMhd.Flags & MHD_NEWNUMBERING)!=0); if (stricomp(ArcName,CurVolName)!=0 && FileExist(ArcName)) { *ArcNameW=0; Repeat=true; return(false); } #if !defined(RARDLL) && !defined(_WIN_CE) if (!ReconstructDone) { ReconstructDone=true; RecVolumes RecVol; if (RecVol.Restore(Cmd,Arc.FileName,Arc.FileNameW,true)) { Repeat=true; return(false); } } #endif strcpy(ArcName,CurVolName); } #endif DataIO.UnpVolume=(Arc.NewLhd.Flags & LHD_SPLIT_AFTER)!=0; DataIO.NextVolumeMissing=false; Arc.Seek(Arc.NextBlockPos-Arc.NewLhd.FullPackSize,SEEK_SET); bool TestMode=false; bool ExtrFile=false; bool SkipSolid=false; #ifndef SFX_MODULE if (FirstFile && (ExactMatch || Arc.Solid) && (Arc.NewLhd.Flags & (LHD_SPLIT_BEFORE/*|LHD_SOLID*/))!=0) { if (ExactMatch) { Log(Arc.FileName,St(MUnpCannotMerge),ArcFileName); #ifdef RARDLL Cmd->DllError=ERAR_BAD_DATA; #endif ErrHandler.SetErrorCode(OPEN_ERROR); } ExactMatch=false; } FirstFile=false; #endif if (ExactMatch || (SkipSolid=Arc.Solid)!=0) { if ((Arc.NewLhd.Flags & LHD_PASSWORD)!=0) #ifndef RARDLL if (*Password==0) #endif { #ifdef RARDLL if (*Cmd->Password==0) if (Cmd->Callback==NULL || Cmd->Callback(UCM_NEEDPASSWORD,Cmd->UserData,(LPARAM)Cmd->Password,sizeof(Cmd->Password))==-1) return(false); strcpy(Password,Cmd->Password); #else if (!GetPassword(PASSWORD_FILE,ArcFileName,Password,sizeof(Password))) { PasswordCancelled=true; return(false); } #endif } #if !defined(GUI) && !defined(SILENT) else if (!PasswordAll && (!Arc.Solid || Arc.NewLhd.UnpVer>=20 && (Arc.NewLhd.Flags & LHD_SOLID)==0)) { eprintf(St(MUseCurPsw),ArcFileName); switch(Cmd->AllYes ? 1:Ask(St(MYesNoAll))) { case -1: ErrHandler.Exit(USER_BREAK); case 2: if (!GetPassword(PASSWORD_FILE,ArcFileName,Password,sizeof(Password))) { return(false); } break; case 3: PasswordAll=true; break; } } #endif #ifndef SFX_MODULE if (*Cmd->ExtrPath==0 && *Cmd->ExtrPathW!=0) WideToChar(Cmd->ExtrPathW,DestFileName); else #endif strcpy(DestFileName,Cmd->ExtrPath); #ifndef SFX_MODULE if (Cmd->AppendArcNameToPath) { strcat(DestFileName,PointToName(Arc.FirstVolumeName)); SetExt(DestFileName,NULL); AddEndSlash(DestFileName); } #endif char *ExtrName=ArcFileName; bool EmptyName=false; #ifndef SFX_MODULE size_t Length=strlen(Cmd->ArcPath); if (Length>1 && IsPathDiv(Cmd->ArcPath[Length-1]) && strlen(ArcFileName)==Length-1) Length--; if (Length>0 && strnicomp(Cmd->ArcPath,ArcFileName,Length)==0) { ExtrName+=Length; while (*ExtrName==CPATHDIVIDER) ExtrName++; if (*ExtrName==0) EmptyName=true; } #endif bool AbsPaths=Cmd->ExclPath==EXCL_ABSPATH && Command=='X' && IsDriveDiv(':'); if (AbsPaths) *DestFileName=0; if (Command=='E' || Cmd->ExclPath==EXCL_SKIPWHOLEPATH) strcat(DestFileName,PointToName(ExtrName)); else strcat(DestFileName,ExtrName); char DiskLetter=etoupper(DestFileName[0]); if (AbsPaths && DestFileName[1]=='_' && IsPathDiv(DestFileName[2]) && DiskLetter>='A' && DiskLetter<='Z') DestFileName[1]=':'; #ifndef SFX_MODULE if (!WideName && *Cmd->ExtrPathW!=0) { DestNameW=DestFileNameW; WideName=true; CharToWide(ArcFileName,ArcFileNameW); } #endif if (WideName) { if (*Cmd->ExtrPathW!=0) strcpyw(DestFileNameW,Cmd->ExtrPathW); else CharToWide(Cmd->ExtrPath,DestFileNameW); #ifndef SFX_MODULE if (Cmd->AppendArcNameToPath) { wchar FileNameW[NM]; if (*Arc.FirstVolumeNameW!=0) strcpyw(FileNameW,Arc.FirstVolumeNameW); else CharToWide(Arc.FirstVolumeName,FileNameW); strcatw(DestFileNameW,PointToName(FileNameW)); SetExt(DestFileNameW,NULL); AddEndSlash(DestFileNameW); } #endif wchar *ExtrNameW=ArcFileNameW; #ifndef SFX_MODULE if (Length>0) { wchar ArcPathW[NM]; GetWideName(Cmd->ArcPath,Cmd->ArcPathW,ArcPathW); Length=strlenw(ArcPathW); } ExtrNameW+=Length; while (*ExtrNameW==CPATHDIVIDER) ExtrNameW++; #endif if (AbsPaths) *DestFileNameW=0; if (Command=='E' || Cmd->ExclPath==EXCL_SKIPWHOLEPATH) strcatw(DestFileNameW,PointToName(ExtrNameW)); else strcatw(DestFileNameW,ExtrNameW); if (AbsPaths && DestFileNameW[1]=='_' && IsPathDiv(DestFileNameW[2])) DestFileNameW[1]=':'; } else *DestFileNameW=0; ExtrFile=!SkipSolid && !EmptyName && (Arc.NewLhd.Flags & LHD_SPLIT_BEFORE)==0; if ((Cmd->FreshFiles || Cmd->UpdateFiles) && (Command=='E' || Command=='X')) { struct FindData FD; if (FindFile::FastFind(DestFileName,DestNameW,&FD)) { if (FD.mtime >= Arc.NewLhd.mtime) { // If directory already exists and its modification time is newer // than start of extraction, it is likely it was created // when creating a path to one of already extracted items. // In such case we'll better update its time even if archived // directory is older. if (!FD.IsDir || FD.mtime<StartTime) ExtrFile=false; } } else if (Cmd->FreshFiles) ExtrFile=false; } // Skip encrypted file if no password is specified. if ((Arc.NewLhd.Flags & LHD_PASSWORD)!=0 && *Password==0) { ErrHandler.SetErrorCode(WARNING); #ifdef RARDLL Cmd->DllError=ERAR_MISSING_PASSWORD; #endif ExtrFile=false; } #ifdef RARDLL if (*Cmd->DllDestName) { strncpyz(DestFileName,Cmd->DllDestName,ASIZE(DestFileName)); *DestFileNameW=0; if (Cmd->DllOpMode!=RAR_EXTRACT) ExtrFile=false; } if (*Cmd->DllDestNameW) { strncpyzw(DestFileNameW,Cmd->DllDestNameW,ASIZE(DestFileNameW)); DestNameW=DestFileNameW; if (Cmd->DllOpMode!=RAR_EXTRACT) ExtrFile=false; } #endif #ifdef SFX_MODULE if ((Arc.NewLhd.UnpVer!=UNP_VER && Arc.NewLhd.UnpVer!=29) && Arc.NewLhd.Method!=0x30) #else if (Arc.NewLhd.UnpVer<13 || Arc.NewLhd.UnpVer>UNP_VER) #endif { #ifndef SILENT Log(Arc.FileName,St(MUnknownMeth),ArcFileName); #ifndef SFX_MODULE Log(Arc.FileName,St(MVerRequired),Arc.NewLhd.UnpVer/10,Arc.NewLhd.UnpVer%10); #endif #endif ExtrFile=false; ErrHandler.SetErrorCode(WARNING); #ifdef RARDLL Cmd->DllError=ERAR_UNKNOWN_FORMAT; #endif } File CurFile; if (!IsLink(Arc.NewLhd.FileAttr)) if (Arc.IsArcDir()) { if (!ExtrFile || Command=='P' || Command=='E' || Cmd->ExclPath==EXCL_SKIPWHOLEPATH) return(true); if (SkipSolid) { #ifndef GUI mprintf(St(MExtrSkipFile),ArcFileName); #endif return(true); } TotalFileCount++; if (Cmd->Test) { #ifndef GUI mprintf(St(MExtrTestFile),ArcFileName); mprintf(" %s",St(MOk)); #endif return(true); } MKDIR_CODE MDCode=MakeDir(DestFileName,DestNameW,!Cmd->IgnoreGeneralAttr,Arc.NewLhd.FileAttr); bool DirExist=false; if (MDCode!=MKDIR_SUCCESS) { DirExist=FileExist(DestFileName,DestNameW); if (DirExist && !IsDir(GetFileAttr(DestFileName,DestNameW))) { bool UserReject; FileCreate(Cmd,NULL,DestFileName,DestNameW,Cmd->Overwrite,&UserReject,Arc.NewLhd.FullUnpSize,Arc.NewLhd.FileTime); DirExist=false; } CreatePath(DestFileName,DestNameW,true); MDCode=MakeDir(DestFileName,DestNameW,!Cmd->IgnoreGeneralAttr,Arc.NewLhd.FileAttr); } if (MDCode==MKDIR_SUCCESS) { #ifndef GUI mprintf(St(MCreatDir),DestFileName); mprintf(" %s",St(MOk)); #endif PrevExtracted=true; } else if (DirExist) { if (!Cmd->IgnoreGeneralAttr) SetFileAttr(DestFileName,DestNameW,Arc.NewLhd.FileAttr); PrevExtracted=true; } else { Log(Arc.FileName,St(MExtrErrMkDir),DestFileName); ErrHandler.SysErrMsg(); #ifdef RARDLL Cmd->DllError=ERAR_ECREATE; #endif ErrHandler.SetErrorCode(CREATE_ERROR); } if (PrevExtracted) { #if defined(_WIN_32) && !defined(_WIN_CE) && !defined(SFX_MODULE) if (Cmd->SetCompressedAttr && (Arc.NewLhd.FileAttr & FILE_ATTRIBUTE_COMPRESSED)!=0 && WinNT()) SetFileCompression(DestFileName,DestNameW,true); #endif SetDirTime(DestFileName,DestNameW, Cmd->xmtime==EXTTIME_NONE ? NULL:&Arc.NewLhd.mtime, Cmd->xctime==EXTTIME_NONE ? NULL:&Arc.NewLhd.ctime, Cmd->xatime==EXTTIME_NONE ? NULL:&Arc.NewLhd.atime); } return(true); } else { if (Cmd->Test && ExtrFile) TestMode=true; #if !defined(GUI) && !defined(SFX_MODULE) if (Command=='P' && ExtrFile) CurFile.SetHandleType(FILE_HANDLESTD); #endif if ((Command=='E' || Command=='X') && ExtrFile && !Cmd->Test) { bool UserReject; if (!FileCreate(Cmd,&CurFile,DestFileName,DestNameW,Cmd->Overwrite,&UserReject,Arc.NewLhd.FullUnpSize,Arc.NewLhd.FileTime)) { ExtrFile=false; if (!UserReject) { ErrHandler.CreateErrorMsg(Arc.FileName,DestFileName); ErrHandler.SetErrorCode(CREATE_ERROR); #ifdef RARDLL Cmd->DllError=ERAR_ECREATE; #endif if (!IsNameUsable(DestFileName)) { Log(Arc.FileName,St(MCorrectingName)); char OrigName[sizeof(DestFileName)]; strncpyz(OrigName,DestFileName,ASIZE(OrigName)); MakeNameUsable(DestFileName,true); CreatePath(DestFileName,NULL,true); if (FileCreate(Cmd,&CurFile,DestFileName,NULL,Cmd->Overwrite,&UserReject,Arc.NewLhd.FullUnpSize,Arc.NewLhd.FileTime)) { #ifndef SFX_MODULE Log(Arc.FileName,St(MRenaming),OrigName,DestFileName); #endif ExtrFile=true; } else ErrHandler.CreateErrorMsg(Arc.FileName,DestFileName); } } } } } if (!ExtrFile && Arc.Solid) { SkipSolid=true; TestMode=true; ExtrFile=true; } if (ExtrFile) { if (!SkipSolid) { if (!TestMode && Command!='P' && CurFile.IsDevice()) { Log(Arc.FileName,St(MInvalidName),DestFileName); ErrHandler.WriteError(Arc.FileName,DestFileName); } TotalFileCount++; } FileCount++; #ifndef GUI if (Command!='I') if (SkipSolid) mprintf(St(MExtrSkipFile),ArcFileName); else switch(Cmd->Test ? 'T':Command) { case 'T': mprintf(St(MExtrTestFile),ArcFileName); break; #ifndef SFX_MODULE case 'P': mprintf(St(MExtrPrinting),ArcFileName); break; #endif case 'X': case 'E': mprintf(St(MExtrFile),DestFileName); break; } if (!Cmd->DisablePercentage) mprintf(" "); #endif DataIO.CurUnpRead=0; DataIO.CurUnpWrite=0; DataIO.UnpFileCRC=Arc.OldFormat ? 0 : 0xffffffff; DataIO.PackedCRC=0xffffffff; DataIO.SetEncryption( (Arc.NewLhd.Flags & LHD_PASSWORD) ? Arc.NewLhd.UnpVer:0,Password, (Arc.NewLhd.Flags & LHD_SALT) ? Arc.NewLhd.Salt:NULL,false, Arc.NewLhd.UnpVer>=36); DataIO.SetPackedSizeToRead(Arc.NewLhd.FullPackSize); DataIO.SetFiles(&Arc,&CurFile); DataIO.SetTestMode(TestMode); DataIO.SetSkipUnpCRC(SkipSolid); #ifndef _WIN_CE if (!TestMode && !Arc.BrokenFileHeader && (Arc.NewLhd.FullPackSize<<11)>Arc.NewLhd.FullUnpSize && (Arc.NewLhd.FullUnpSize<100000000 || Arc.FileLength()>Arc.NewLhd.FullPackSize)) CurFile.Prealloc(Arc.NewLhd.FullUnpSize); #endif CurFile.SetAllowDelete(!Cmd->KeepBroken); bool LinkCreateMode=!Cmd->Test && !SkipSolid; if (ExtractLink(DataIO,Arc,DestFileName,DataIO.UnpFileCRC,LinkCreateMode)) PrevExtracted=LinkCreateMode; else if ((Arc.NewLhd.Flags & LHD_SPLIT_BEFORE)==0) if (Arc.NewLhd.Method==0x30) UnstoreFile(DataIO,Arc.NewLhd.FullUnpSize); else { Unp->SetDestSize(Arc.NewLhd.FullUnpSize); #ifndef SFX_MODULE if (Arc.NewLhd.UnpVer<=15) Unp->DoUnpack(15,FileCount>1 && Arc.Solid); else #endif Unp->DoUnpack(Arc.NewLhd.UnpVer,(Arc.NewLhd.Flags & LHD_SOLID)!=0); } if (Arc.IsOpened()) Arc.SeekToNext(); bool BrokenFile=false; if (!SkipSolid) { if (Arc.OldFormat && UINT32(DataIO.UnpFileCRC)==UINT32(Arc.NewLhd.FileCRC) || !Arc.OldFormat && UINT32(DataIO.UnpFileCRC)==UINT32(Arc.NewLhd.FileCRC^0xffffffff)) { #ifndef GUI if (Command!='P' && Command!='I') mprintf("%s%s ",Cmd->DisablePercentage ? " ":"\b\b\b\b\b ",St(MOk)); #endif } else { char *BadArcName=/*(Arc.NewLhd.Flags & LHD_SPLIT_BEFORE) ? NULL:*/Arc.FileName; if (Arc.NewLhd.Flags & LHD_PASSWORD) { Log(BadArcName,St(MEncrBadCRC),ArcFileName); } else { Log(BadArcName,St(MCRCFailed),ArcFileName); } BrokenFile=true; ErrHandler.SetErrorCode(CRC_ERROR); #ifdef RARDLL Cmd->DllError=ERAR_BAD_DATA; #endif Alarm(); } } #ifndef GUI else mprintf("\b\b\b\b\b "); #endif if (!TestMode && (Command=='X' || Command=='E') && !IsLink(Arc.NewLhd.FileAttr)) { #if defined(_WIN_32) || defined(_EMX) if (Cmd->ClearArc) Arc.NewLhd.FileAttr&=~FA_ARCH; /* else Arc.NewLhd.FileAttr|=FA_ARCH; //set archive bit for unpacked files (file is not backed up) */ #endif if (!BrokenFile || Cmd->KeepBroken) { if (BrokenFile) CurFile.Truncate(); CurFile.SetOpenFileTime( Cmd->xmtime==EXTTIME_NONE ? NULL:&Arc.NewLhd.mtime, Cmd->xctime==EXTTIME_NONE ? NULL:&Arc.NewLhd.ctime, Cmd->xatime==EXTTIME_NONE ? NULL:&Arc.NewLhd.atime); CurFile.Close(); #if defined(_WIN_32) && !defined(_WIN_CE) && !defined(SFX_MODULE) if (Cmd->SetCompressedAttr && (Arc.NewLhd.FileAttr & FILE_ATTRIBUTE_COMPRESSED)!=0 && WinNT()) SetFileCompression(CurFile.FileName,CurFile.FileNameW,true); #endif CurFile.SetCloseFileTime( Cmd->xmtime==EXTTIME_NONE ? NULL:&Arc.NewLhd.mtime, Cmd->xatime==EXTTIME_NONE ? NULL:&Arc.NewLhd.atime); if (!Cmd->IgnoreGeneralAttr) SetFileAttr(CurFile.FileName,CurFile.FileNameW,Arc.NewLhd.FileAttr); PrevExtracted=true; } } } } if (ExactMatch) MatchedArgs++; if (DataIO.NextVolumeMissing || !Arc.IsOpened()) return(false); if (!ExtrFile) if (!Arc.Solid) Arc.SeekToNext(); else if (!SkipSolid) return(false); return(true); }
main(int argc, char *argv[]) { CDReader *cdreaderP; FILEHANDLE image_file; UWORD audio_blklen, mode1_blklen, mode2_blklen; TCHAR image_filnam[_MAX_PATH + 1]; TCHAR cue_filnam[_MAX_PATH + 1]; TCHAR cdtext_filnam[_MAX_PATH + 1]; TCHAR *image_filnamP = NULL, *cue_filnamP = NULL, *cdtext_filnamP = NULL; // Enable exception handling. EXCEPTION_HANDLER_START // Initialize and check the protection. ProtInitialize (NULL, FALSE); // Get the environment variables. GetEnvironmentVariables(); // Parse the command line arguments. ParseCommandLine (argc, argv); // Register the event callback function. EventRegisterCallback (ConsoleEventCallback); // Startup the ASPI manager. ASPIAdapter::StartupManager (FALSE, FALSE, TRUE); // Find a CDROM device... if (cdreader_id_specified) { if ((cdreaderP = (CDReader *)ASPIAdapter::FindDeviceObject ( ASPI_M_DEVTYPE_CDROM | ASPI_M_DEVTYPE_WORM, cdreader_adapter, cdreader_id, cdreader_lun)) == NULL) { fprintf (stderr, "\nError: Specified device (%u:%u:%u) is not a CDROM!\n", cdreader_adapter, cdreader_id, cdreader_lun); exit (1); } } else { if ((cdreaderP = (CDReader *)ASPIAdapter::FindDeviceObject ( ASPI_M_DEVTYPE_CDROM | ASPI_M_DEVTYPE_WORM)) == NULL) { fprintf (stderr, "\nError: Unable to find a known CDROM device!\n"); exit (1); } } if (log_flag) { printf ("CDROM device found...\n"); printf (" HA #%u - ASPI ID #%u - %-8s %-16s %-4s\n\n", cdreaderP->GetAdapter(), cdreaderP->GetId(), cdreaderP->GetVendorId(), cdreaderP->GetProductId(), cdreaderP->GetFirmwareLevel()); } if (cdreaderP->GetModel() == GENERIC_CDROM_SCSI) { fprintf (stderr, "Warning: CDROM device model is unknown to this program!\n"); fprintf (stderr, "The generic CDROM device driver will be used...\n\n"); } // If necessary, check that this device supports the reading of SUBCODEs. if ((scan_subcode_mode == SCAN_SUBCODE_QUICK) || (scan_subcode_mode == SCAN_SUBCODE_FULL)) { if (! cdreaderP->IsFlagSet(CDReader::crfReadSUBQ)) { fprintf (stderr, "Error: CDROM device does not support the reading of subcodes!\n"); exit (1); } } // If necessary, check that this device supports the reading of CD+G discs. if (cdg_flag && (! cdreaderP->IsFlagSet(CDReader::crfReadCDG))) { fprintf (stderr, "Error: CDROM device does not support the reading of CD+G discs!\n"); exit (1); } // Analyze the disc layout. auto_ptr<DiscLayout> disclayoutP(new DiscLayout ( cdreaderP, read_speed, scan_subcode_mode, mcn_isrc_flag, cdtext_flag, log_flag)); if (log_flag) { printf ("\nDisc Statistics:\n"); printf (" Audio track count - %u\n", disclayoutP->m_nAudioTrackCount); printf (" Mode1 data track count - %u\n", disclayoutP->m_nMode1TrackCount); printf (" Mode2 data track count - %u\n", disclayoutP->m_nMode2TrackCount); } // Is the disc too long? if (disclayoutP->m_nLastLBA > CDROM_80MIN_BLKCNT) fprintf (stderr, "\nWARNING: Disc is longer than 80 minutes!\n"); // Check the disc layout. if (! disclayoutP->Check()) { fprintf (stderr, "\nWARNING: Disc contains one or more tracks that are shorter than \n"); fprintf (stderr, "four seconds. This is a violation of the CDROM specification.\n"); } // Determine the block lengths. audio_blklen = (cdg_flag ? SECTOR_CDDA_SUBPW_BLKLEN : SECTOR_CDDA_BLKLEN); if (cooked_flag) {mode1_blklen = SECTOR_MODE1_BLKLEN; mode2_blklen = SECTOR_MODE2_BLKLEN;} else {mode1_blklen = SECTOR_RAW_BLKLEN; mode2_blklen = SECTOR_RAW_BLKLEN;} // Set the block length for each track. DiscInfo *discinfoP = disclayoutP->m_pDiscInfo; for (int i = 0; i < discinfoP->m_nTrackCount; i++) { TRACKINFO *trackinfoP = &discinfoP->m_TrackInfo[i]; switch (trackinfoP->datatype) { case DATATYPE_CDDA: trackinfoP->blklen = audio_blklen; break; case DATATYPE_CDROM: trackinfoP->blklen = mode1_blklen; break; case DATATYPE_CDROMXA: case DATATYPE_CDI: trackinfoP->blklen = mode2_blklen; break; } } // Build the cuesheet filename. StringCopy (cue_filnam, base_filnamP); FileAddExtension (cue_filnam, ".cue", (! cueonly_flag)); cue_filnamP = cue_filnam; // If we're not just writing a cuesheet, then build the image and CD-TEXT filenames. if (! cueonly_flag) { StringCopy (image_filnam, base_filnamP); FileAddExtension (image_filnam, ".bin", FALSE); image_filnamP = image_filnam; if (cdtext_flag && (discinfoP->m_pCDTextPackVec != NULL)) { StringCopy (cdtext_filnam, base_filnamP); FileAddExtension (cdtext_filnam, ".cdt", TRUE); cdtext_filnamP = cdtext_filnam; } // Display image file stats? if (log_flag) { // Compute the amount of disc space required. ULONG blkcnt = disclayoutP->m_nLastLBA + 1; printf ("\nImage file will require approximately %luMb of disk space.\n", CDIV (blkcnt * SECTOR_RAW_BLKLEN, 0x100000)); } // Prompt to begin copy? if (confirm_flag) { printf ("\nHit <ENTER> to copy disc (or CTRL/C to exit)..."); getchar (); printf ("\n"); } } // Generate the CUE SHEET file. disclayoutP->GenerateCuesheetFile (cue_filnamP, image_filnamP, cdtext_filnamP); // Generate the CD-TEXT data file? if (cdtext_filnamP != NULL) { FILEHANDLE handle; ULONG null = 0; if ((handle = FileCreate (cdtext_filnamP)) == NULL) SignalException (E_CreateFile, 1, 0, 0, HeapString(cdtext_filnamP)); FileWrite ( handle, discinfoP->m_pCDTextPackVec, discinfoP->m_nCDTextPackCount * sizeof(CDTEXTPACK)); FileWrite (handle, &null, 1); FileClose (handle); } // Generate the image file? if (image_filnamP != NULL) { // Make sure the device is ready. cdreaderP->LoadDisc (TRUE); // Create the output image file. if ((image_file = FileCreate (image_filnamP)) == NULL) { fprintf (stderr, "\nError creating image file \"%s\"\n", image_filnamP); exit (1); } // Loop through the "copy instructions"... for (int i = 0; i < disclayoutP->m_nCopyInstrCount; i++) { COPYINSTR *copyinstrP = &disclayoutP->m_CopyInstr[i]; // Set the block length. UWORD blklen = ((copyinstrP->datatype == DATATYPE_CDDA) ? audio_blklen : ((copyinstrP->datatype == DATATYPE_CDROM) ? mode1_blklen : mode2_blklen)); // Select operation... switch (copyinstrP->opcode) { // Read a range of audio/data sectors. case CI_READ_SECTORS: { if (copyinstrP->datatype == DATATYPE_CDDA) { // Set the reading speed. cdreaderP->SetSpindleSpeed (read_speed, FALSE, FALSE); // Extract the audio sectors. cdreaderP->ExtractSectorsToFile ( image_file, DATATYPE_CDDA, blklen, copyinstrP->lba, copyinstrP->blkcnt, jitter_mode, 0, error_mode, FALSE, log_flag); } else { // Set the reading speed to maximum. cdreaderP->SetSpindleSpeed (SPEED_MAX, TRUE, FALSE); // Extract the data sectors. cdreaderP->ExtractSectorsToFile ( image_file, copyinstrP->datatype, blklen, copyinstrP->lba, copyinstrP->blkcnt, JITTER_MODE_DISABLE, 0, error_mode, FALSE, log_flag); } break; } // Generate replacements for unreadable blocks at the end of a track. case CI_GENERATE_SECTORS: { WriteEmptySectors ( image_file, copyinstrP->datatype, blklen, copyinstrP->lba, copyinstrP->blkcnt); break; } // Ignore PREGAP instructions. case CI_GENERATE_PREGAP: case CI_GENERATE_PREGAP2: break; default: SignalException (E_BugCheck); } } // Reset the reading speed. cdreaderP->SetSpindleSpeed (SPEED_MAX, FALSE, FALSE); // Close the image file. FileClose (image_file); // Success! if (log_flag) printf ("\nCopy completed successfully!\n"); // Notify user of completion? if (beep_flag) BeepUser(); } // Shutdown the ASPI manager. ASPIAdapter::ShutdownManager(); // End exception handling. EXCEPTION_HANDLER_EXIT return (0); }
bool CmdExtract::ExtractCurrentFile(CommandData *Cmd,Archive &Arc,size_t HeaderSize,bool &Repeat) { wchar Command=Cmd->Command[0]; if (HeaderSize==0) if (DataIO.UnpVolume) { #ifdef NOVOLUME return false; #else if (!MergeArchive(Arc,&DataIO,false,Command)) { ErrHandler.SetErrorCode(RARX_WARNING); return false; } #endif } else return false; HEADER_TYPE HeaderType=Arc.GetHeaderType(); if (HeaderType!=HEAD_FILE) { #ifndef SFX_MODULE if (HeaderType==HEAD3_OLDSERVICE && PrevExtracted) SetExtraInfo20(Cmd,Arc,DestFileName); #endif if (HeaderType==HEAD_SERVICE && PrevExtracted) SetExtraInfo(Cmd,Arc,DestFileName); if (HeaderType==HEAD_ENDARC) if (Arc.EndArcHead.NextVolume) { #ifndef NOVOLUME if (!MergeArchive(Arc,&DataIO,false,Command)) { ErrHandler.SetErrorCode(RARX_WARNING); return false; } #endif Arc.Seek(Arc.CurBlockPos,SEEK_SET); return true; } else return false; Arc.SeekToNext(); return true; } PrevExtracted=false; if (!Cmd->Recurse && MatchedArgs>=Cmd->FileArgs.ItemsCount() && AllMatchesExact) return false; int MatchType=MATCH_WILDSUBPATH; bool EqualNames=false; int MatchNumber=Cmd->IsProcessFile(Arc.FileHead,&EqualNames,MatchType); bool ExactMatch=MatchNumber!=0; #ifndef SFX_MODULE if (Cmd->ExclPath==EXCL_BASEPATH) { *Cmd->ArcPath=0; if (ExactMatch) { Cmd->FileArgs.Rewind(); if (Cmd->FileArgs.GetString(Cmd->ArcPath,ASIZE(Cmd->ArcPath),MatchNumber-1)) *PointToName(Cmd->ArcPath)=0; } } #endif if (ExactMatch && !EqualNames) AllMatchesExact=false; Arc.ConvertAttributes(); #if !defined(SFX_MODULE) && !defined(RARDLL) if (Arc.FileHead.SplitBefore && FirstFile) { wchar CurVolName[NM]; wcsncpyz(CurVolName,ArcName,ASIZE(CurVolName)); VolNameToFirstName(ArcName,ArcName,Arc.NewNumbering); if (wcsicomp(ArcName,CurVolName)!=0 && FileExist(ArcName)) { // If first volume name does not match the current name and if such // volume name really exists, let's unpack from this first volume. Repeat=true; return false; } #ifndef RARDLL if (!ReconstructDone) { ReconstructDone=true; if (RecVolumesRestore(Cmd,Arc.FileName,true)) { Repeat=true; return false; } } #endif wcsncpyz(ArcName,CurVolName,ASIZE(ArcName)); } #endif wchar ArcFileName[NM]; ConvertPath(Arc.FileHead.FileName,ArcFileName); if (Arc.FileHead.Version) { if (Cmd->VersionControl!=1 && !EqualNames) { if (Cmd->VersionControl==0) ExactMatch=false; int Version=ParseVersionFileName(ArcFileName,false); if (Cmd->VersionControl-1==Version) ParseVersionFileName(ArcFileName,true); else ExactMatch=false; } } else if (!Arc.IsArcDir() && Cmd->VersionControl>1) ExactMatch=false; DataIO.UnpVolume=Arc.FileHead.SplitAfter; DataIO.NextVolumeMissing=false; Arc.Seek(Arc.NextBlockPos-Arc.FileHead.PackSize,SEEK_SET); bool ExtrFile=false; bool SkipSolid=false; #ifndef SFX_MODULE if (FirstFile && (ExactMatch || Arc.Solid) && Arc.FileHead.SplitBefore) { if (ExactMatch) { Log(Arc.FileName,St(MUnpCannotMerge),ArcFileName); #ifdef RARDLL Cmd->DllError=ERAR_BAD_DATA; #endif ErrHandler.SetErrorCode(RARX_OPEN); } ExactMatch=false; } FirstFile=false; #endif if (ExactMatch || (SkipSolid=Arc.Solid)!=0) { ExtrPrepareName(Cmd,Arc,ArcFileName,DestFileName,ASIZE(DestFileName)); // DestFileName can be set empty in case of excessive -ap switch. ExtrFile=!SkipSolid && *DestFileName!=0 && !Arc.FileHead.SplitBefore; if ((Cmd->FreshFiles || Cmd->UpdateFiles) && (Command=='E' || Command=='X')) { FindData FD; if (FindFile::FastFind(DestFileName,&FD)) { if (FD.mtime >= Arc.FileHead.mtime) { // If directory already exists and its modification time is newer // than start of extraction, it is likely it was created // when creating a path to one of already extracted items. // In such case we'll better update its time even if archived // directory is older. if (!FD.IsDir || FD.mtime<StartTime) ExtrFile=false; } } else if (Cmd->FreshFiles) ExtrFile=false; } if (Arc.FileHead.Encrypted) { #ifdef RARDLL if (!ExtrDllGetPassword(Cmd)) return false; #else if (!ExtrGetPassword(Cmd,Arc,ArcFileName)) { PasswordCancelled=true; return false; } #endif // Skip only the current encrypted file if empty password is entered. if (!Password.IsSet()) { ErrHandler.SetErrorCode(RARX_WARNING); #ifdef RARDLL Cmd->DllError=ERAR_MISSING_PASSWORD; #endif ExtrFile=false; } } #ifdef RARDLL if (*Cmd->DllDestName!=0) { wcsncpyz(DestFileName,Cmd->DllDestName,ASIZE(DestFileName)); // Do we need this code? // if (Cmd->DllOpMode!=RAR_EXTRACT) // ExtrFile=false; } #endif if (!CheckUnpVer(Arc,ArcFileName)) { ExtrFile=false; ErrHandler.SetErrorCode(RARX_WARNING); #ifdef RARDLL Cmd->DllError=ERAR_UNKNOWN_FORMAT; #endif } File CurFile; bool LinkEntry=Arc.FileHead.RedirType!=FSREDIR_NONE; if (LinkEntry && Arc.FileHead.RedirType!=FSREDIR_FILECOPY) { if (ExtrFile && Command!='P' && !Cmd->Test) { // Overwrite prompt for symbolic and hard links. bool UserReject=false; if (FileExist(DestFileName) && !UserReject) FileCreate(Cmd,NULL,DestFileName,ASIZE(DestFileName),Cmd->Overwrite,&UserReject,Arc.FileHead.UnpSize,&Arc.FileHead.mtime); if (UserReject) ExtrFile=false; } } else if (Arc.IsArcDir()) { if (!ExtrFile || Command=='P' || Command=='I' || Command=='E' || Cmd->ExclPath==EXCL_SKIPWHOLEPATH) return true; TotalFileCount++; ExtrCreateDir(Cmd,Arc,ArcFileName); return true; } else if (ExtrFile) // Create files and file copies (FSREDIR_FILECOPY). ExtrFile=ExtrCreateFile(Cmd,Arc,CurFile); if (!ExtrFile && Arc.Solid) { SkipSolid=true; ExtrFile=true; } if (ExtrFile) { bool TestMode=Cmd->Test || SkipSolid; // Unpack to memory, not to disk. if (!SkipSolid) { if (!TestMode && Command!='P' && CurFile.IsDevice()) { Log(Arc.FileName,St(MInvalidName),DestFileName); ErrHandler.WriteError(Arc.FileName,DestFileName); } TotalFileCount++; } FileCount++; #ifndef GUI if (Command!='I') if (SkipSolid) mprintf(St(MExtrSkipFile),ArcFileName); else switch(Cmd->Test ? 'T':Command) // "Test" can be also enabled by -t switch. { case 'T': mprintf(St(MExtrTestFile),ArcFileName); break; #ifndef SFX_MODULE case 'P': mprintf(St(MExtrPrinting),ArcFileName); break; #endif case 'X': case 'E': mprintf(St(MExtrFile),DestFileName); break; } if (!Cmd->DisablePercentage) mprintf(L" "); #endif SecPassword FilePassword=Password; #if defined(_WIN_ALL) && !defined(SFX_MODULE) ConvertDosPassword(Arc,FilePassword); #endif byte PswCheck[SIZE_PSWCHECK]; DataIO.SetEncryption(false,Arc.FileHead.CryptMethod,&FilePassword, Arc.FileHead.SaltSet ? Arc.FileHead.Salt:NULL, Arc.FileHead.InitV,Arc.FileHead.Lg2Count, PswCheck,Arc.FileHead.HashKey); bool WrongPassword=false; // If header is damaged, we cannot rely on password check value, // because it can be damaged too. if (Arc.FileHead.Encrypted && Arc.FileHead.UsePswCheck && memcmp(Arc.FileHead.PswCheck,PswCheck,SIZE_PSWCHECK)!=0 && !Arc.BrokenHeader) { Log(Arc.FileName,St(MWrongPassword)); ErrHandler.SetErrorCode(RARX_BADPWD); WrongPassword=true; } DataIO.CurUnpRead=0; DataIO.CurUnpWrite=0; DataIO.UnpHash.Init(Arc.FileHead.FileHash.Type,Cmd->Threads); DataIO.PackedDataHash.Init(Arc.FileHead.FileHash.Type,Cmd->Threads); DataIO.SetPackedSizeToRead(Arc.FileHead.PackSize); DataIO.SetFiles(&Arc,&CurFile); DataIO.SetTestMode(TestMode); DataIO.SetSkipUnpCRC(SkipSolid); if (!TestMode && !WrongPassword && !Arc.BrokenHeader && (Arc.FileHead.PackSize<<11)>Arc.FileHead.UnpSize && (Arc.FileHead.UnpSize<100000000 || Arc.FileLength()>Arc.FileHead.PackSize)) CurFile.Prealloc(Arc.FileHead.UnpSize); CurFile.SetAllowDelete(!Cmd->KeepBroken); bool FileCreateMode=!TestMode && !SkipSolid && Command!='P'; bool ShowChecksum=true; // Display checksum verification result. bool LinkSuccess=true; // Assume success for test mode. if (LinkEntry) { FILE_SYSTEM_REDIRECT Type=Arc.FileHead.RedirType; if (Type==FSREDIR_HARDLINK || Type==FSREDIR_FILECOPY) { wchar NameExisting[NM]; ExtrPrepareName(Cmd,Arc,Arc.FileHead.RedirName,NameExisting,ASIZE(NameExisting)); if (FileCreateMode && *NameExisting!=0) // *NameExisting can be 0 in case of excessive -ap switch. if (Type==FSREDIR_HARDLINK) LinkSuccess=ExtractHardlink(DestFileName,NameExisting,ASIZE(NameExisting)); else LinkSuccess=ExtractFileCopy(Cmd,CurFile,Arc.FileName,DestFileName,NameExisting,ASIZE(NameExisting)); } else if (Type==FSREDIR_UNIXSYMLINK || Type==FSREDIR_WINSYMLINK || Type==FSREDIR_JUNCTION) { if (FileCreateMode) LinkSuccess=ExtractSymlink(Cmd,DataIO,Arc,DestFileName); } else { #ifndef SFX_MODULE Log(Arc.FileName,St(MUnknownExtra),DestFileName); #endif LinkSuccess=false; } if (!LinkSuccess || Arc.Format==RARFMT15 && !FileCreateMode) { // RAR 5.x links have a valid data checksum even in case of // failure, because they do not store any data. // We do not want to display "OK" in this case. // For 4.x symlinks we verify the checksum only when extracting, // but not when testing an archive. ShowChecksum=false; } PrevExtracted=FileCreateMode && LinkSuccess; } else if (!Arc.FileHead.SplitBefore && !WrongPassword) if (Arc.FileHead.Method==0) UnstoreFile(DataIO,Arc.FileHead.UnpSize); else { Unp->Init(Arc.FileHead.WinSize,Arc.FileHead.Solid); Unp->SetDestSize(Arc.FileHead.UnpSize); #ifndef SFX_MODULE if (Arc.Format!=RARFMT50 && Arc.FileHead.UnpVer<=15) Unp->DoUnpack(15,FileCount>1 && Arc.Solid); else #endif Unp->DoUnpack(Arc.FileHead.UnpVer,Arc.FileHead.Solid); } Arc.SeekToNext(); bool ValidCRC=DataIO.UnpHash.Cmp(&Arc.FileHead.FileHash,Arc.FileHead.UseHashKey ? Arc.FileHead.HashKey:NULL); // We set AnySolidDataUnpackedWell to true if we found at least one // valid non-zero solid file in preceding solid stream. If it is true // and if current encrypted file is broken, we do not need to hint // about a wrong password and can report CRC error only. if (!Arc.FileHead.Solid) AnySolidDataUnpackedWell=false; // Reset the flag, because non-solid file is found. else if (Arc.FileHead.Method!=0 && Arc.FileHead.UnpSize>0 && ValidCRC) AnySolidDataUnpackedWell=true; bool BrokenFile=false; // Checksum is not calculated in skip solid mode for performance reason. if (!SkipSolid && ShowChecksum) { if (!WrongPassword && ValidCRC) { #ifndef GUI if (Command!='P' && Command!='I') mprintf(L"%s%s ",Cmd->DisablePercentage ? L" ":L"\b\b\b\b\b ", Arc.FileHead.FileHash.Type==HASH_NONE ? L" ?":St(MOk)); #endif } else { if (!WrongPassword) if (Arc.FileHead.Encrypted && (!Arc.FileHead.UsePswCheck || Arc.BrokenHeader) && !AnySolidDataUnpackedWell) { Log(Arc.FileName,St(MEncrBadCRC),ArcFileName); } else { Log(Arc.FileName,St(MCRCFailed),ArcFileName); } BrokenFile=true; ErrHandler.SetErrorCode(RARX_CRC); #ifdef RARDLL // If we already have ERAR_EOPEN as result of missing volume, // we should not replace it with less precise ERAR_BAD_DATA. if (Cmd->DllError!=ERAR_EOPEN) Cmd->DllError=ERAR_BAD_DATA; #endif } } #ifndef GUI else mprintf(L"\b\b\b\b\b "); #endif if (!TestMode && !WrongPassword && (Command=='X' || Command=='E') && (!LinkEntry || Arc.FileHead.RedirType==FSREDIR_FILECOPY && LinkSuccess) && (!BrokenFile || Cmd->KeepBroken)) { // We could preallocate more space that really written to broken file. if (BrokenFile) CurFile.Truncate(); #if defined(_WIN_ALL) || defined(_EMX) if (Cmd->ClearArc) Arc.FileHead.FileAttr&=~FILE_ATTRIBUTE_ARCHIVE; #endif CurFile.SetOpenFileTime( Cmd->xmtime==EXTTIME_NONE ? NULL:&Arc.FileHead.mtime, Cmd->xctime==EXTTIME_NONE ? NULL:&Arc.FileHead.ctime, Cmd->xatime==EXTTIME_NONE ? NULL:&Arc.FileHead.atime); CurFile.Close(); #if defined(_WIN_ALL) && !defined(SFX_MODULE) if (Cmd->SetCompressedAttr && (Arc.FileHead.FileAttr & FILE_ATTRIBUTE_COMPRESSED)!=0) SetFileCompression(CurFile.FileName,true); #endif #ifdef _UNIX if (Cmd->ProcessOwners && Arc.Format==RARFMT50 && Arc.FileHead.UnixOwnerSet) SetUnixOwner(Arc,CurFile.FileName); #endif CurFile.SetCloseFileTime( Cmd->xmtime==EXTTIME_NONE ? NULL:&Arc.FileHead.mtime, Cmd->xatime==EXTTIME_NONE ? NULL:&Arc.FileHead.atime); if (!Cmd->IgnoreGeneralAttr) SetFileAttr(CurFile.FileName,Arc.FileHead.FileAttr); PrevExtracted=true; } } } if (ExactMatch) MatchedArgs++; if (DataIO.NextVolumeMissing) return false; if (!ExtrFile) if (!Arc.Solid) Arc.SeekToNext(); else if (!SkipSolid) return false; return true; }
u32 NandPadgen() { u8* ctrStart = FindNandCtr(); if (ctrStart == NULL) return 1; u8 ctr[16] = {0x0}; u32 i = 0; for(i = 0; i < 16; i++) ctr[i] = *(ctrStart + (15 - i)); //The CTR is stored backwards in memory. add_ctr(ctr, 0xB93000); //The CTR stored in memory would theoretically be for NAND block 0, so we need to increment it some. u32 keyslot = 0x0; u32 nand_size = 0; switch (GetUnitPlatform()) { case PLATFORM_3DS: keyslot = 0x4; nand_size = 758; break; case PLATFORM_N3DS: keyslot = 0x5; nand_size = 1055; break; } Debug("Creating NAND FAT16 xorpad. Size (MB): %u", nand_size); Debug("Filename: nand.fat16.xorpad"); PadInfo padInfo = {.keyslot = keyslot, .setKeyY = 0, .size_mb = nand_size , .filename = "/nand.fat16.xorpad"}; memcpy(padInfo.CTR, ctr, 16); u32 result = CreatePad(&padInfo); if(result == 0) { Debug("Done!"); return 0; } else { return 1; } } u32 CreatePad(PadInfo *info) { static const uint8_t zero_buf[16] __attribute__((aligned(16))) = {0}; u8* buffer = BUFFER_ADDRESS; u32 result = 0; if (!FileCreate(info->filename, true)) // No DebugFileCreate() here - messages are already given return 1; if(info->setKeyY) setup_aeskey(info->keyslot, AES_BIG_INPUT | AES_NORMAL_INPUT, info->keyY); use_aeskey(info->keyslot); u8 ctr[16] __attribute__((aligned(32))); memcpy(ctr, info->CTR, 16); u32 size_bytes = info->size_mb * 1024*1024; for (u32 i = 0; i < size_bytes; i += BUFFER_MAX_SIZE) { u32 curr_block_size = min(BUFFER_MAX_SIZE, size_bytes - i); for (u32 j = 0; j < curr_block_size; j+= 16) { set_ctr(AES_BIG_INPUT | AES_NORMAL_INPUT, ctr); aes_decrypt((void*)zero_buf, (void*)buffer + j, ctr, 1, AES_CTR_MODE); add_ctr(ctr, 1); } ShowProgress(i, size_bytes); if (!DebugFileWrite((void*)buffer, curr_block_size, i)) { result = 1; break; } } ShowProgress(0, 0); FileClose(); return result; } u32 NandDumper() { u8* buffer = BUFFER_ADDRESS; u32 nand_size = (GetUnitPlatform() == PLATFORM_3DS) ? 0x3AF00000 : 0x4D800000; u32 result = 0; Debug("Dumping System NAND. Size (MB): %u", nand_size / (1024 * 1024)); if (!DebugFileCreate("/NAND.bin", true)) return 1; u32 n_sectors = nand_size / NAND_SECTOR_SIZE; for (u32 i = 0; i < n_sectors; i += SECTORS_PER_READ) { ShowProgress(i, n_sectors); sdmmc_nand_readsectors(i, SECTORS_PER_READ, buffer); if(!DebugFileWrite(buffer, NAND_SECTOR_SIZE * SECTORS_PER_READ, i * NAND_SECTOR_SIZE)) { result = 1; break; } } ShowProgress(0, 0); FileClose(); return result; } u32 NandPartitionsDumper() { u32 ctrnand_offset; u32 ctrnand_size; u32 keyslot; switch (GetUnitPlatform()) { case PLATFORM_3DS: ctrnand_offset = 0x0B95CA00; ctrnand_size = 0x2F3E3600; keyslot = 0x4; break; case PLATFORM_N3DS: ctrnand_offset = 0x0B95AE00; ctrnand_size = 0x41D2D200; keyslot = 0x5; break; } // see: http://3dbrew.org/wiki/Flash_Filesystem Debug("Dumping firm0.bin: %s!", DumpPartition("firm0.bin", 0x0B130000, 0x00400000, 0x6) == 0 ? "succeeded" : "failed"); Debug("Dumping firm1.bin: %s!", DumpPartition("firm1.bin", 0x0B530000, 0x00400000, 0x6) == 0 ? "succeeded" : "failed"); Debug("Dumping ctrnand.bin: %s!", DumpPartition("ctrnand.bin", ctrnand_offset, ctrnand_size, keyslot) == 0 ? "succeeded" : "failed"); return 0; }
// 抓拍数据 void CALLBACK VehicleDataCallbackFuc(void *pUserData, VehicleData *pData) { TForm1 *pThis = (TForm1 *)pUserData; if(pThis->tvConnectDev->Selected == NULL) return; String strIP; bool bFlag = false; PDevInfo pDev = NULL; TTreeNodes *nodes = pThis->tvConnectDev->Items; if(nodes != NULL) { for(int i = 0; i < nodes->Count; i++) { if(TreeView_GetCheckState(pThis->tvConnectDev->Handle,nodes->Item[i]->ItemId)) { String strViewIP = nodes->Item[i]->Text; // 只显示指定抓拍的设备数据 strIP.sprintf("%s", pData->ucDeviceIP); if(strIP == strViewIP) { bFlag = true; break; } } } } if(!bFlag) return; int nColor = pData->PlateColor; TDateTime dataTime = Now(); SYSTEMTIME tm; GetSystemTime(&tm); String strPlate = (char *)pData->ucPlate; String strPath; String strBigFile, strCifFile, strPlateFile, strPlateNoFile; int iFileHandle = 0; // 大图 if(pData->pucBigImage != NULL && pData->uiBigImageLen > 0) { strPath = pThis->strImagePath + strIP + "\\大图\\" + FormatDateTime("yyyymmdd", dataTime) + "\\"; pThis->CreateDirectoryRecurrent(strPath); strBigFile = Format("%s%s%03d(%s).jpg", ARRAYOFCONST((strPath, dataTime.FormatString("hhmmss"), tm.wMilliseconds, strPlate))); iFileHandle = FileCreate(strBigFile); if(iFileHandle != 0) { FileWrite(iFileHandle, pData->pucBigImage, pData->uiBigImageLen); FileClose(iFileHandle); if(FileExists(strBigFile)) { pThis->imgBigImg->Picture->LoadFromFile(strBigFile); } } } // CIF图 if(pData->pucCIFImage != NULL && pData->uiCIFImageLen > 0) { strPath = pThis->strImagePath + strIP + "\\CIF图\\" + dataTime.FormatString("yyyymmdd") + "\\"; pThis->CreateDirectoryRecurrent(strPath); strCifFile = Format("%s%s%03d(%s).jpg", ARRAYOFCONST((strPath, dataTime.FormatString("hhmmss"), tm.wMilliseconds, strPlate))); iFileHandle = FileCreate(strCifFile); if(iFileHandle != 0) { FileWrite(iFileHandle, pData->pucCIFImage, pData->uiCIFImageLen); FileClose(iFileHandle); if(FileExists(strCifFile)) { pThis->imgCIFImg->Picture->LoadFromFile(strCifFile); } } } // 车牌图 if(pData->pucPlateImage != NULL && pData->uiPlateImageLen > 0) { strPath = pThis->strImagePath + strIP + "\\车牌图\\" + dataTime.FormatString("yyyymmdd") + "\\"; pThis->CreateDirectoryRecurrent(strPath); strPlateFile = Format("%s%s%03d(%s).jpg", ARRAYOFCONST((strPath, dataTime.FormatString("hhmmss"), tm.wMilliseconds, strPlate))); iFileHandle = FileCreate(strPlateFile); if(iFileHandle != 0) { FileWrite(iFileHandle, pData->pucPlateImage, pData->uiPlateImageLen); FileClose(iFileHandle); } if(FileExists(strPlateFile)) { pThis->imgPlateImg->Picture->LoadFromFile(strPlateFile); } } // 车牌号码 pThis->ShowPlate(strPlate, nColor); }
void __fastcall TForm1::Button1Click(TObject *Sender) { //1.图像数组 Byte *data ; // data[] 处理一行数据 this->Image2->Picture->Bitmap->PixelFormat = pf8bit ; Graphics::TBitmap * bitmap = this->Image2->Picture->Bitmap ; //2.计算差值 DynamicArray< DynamicArray <int> > h ; TObjectList *positionXY = new TObjectList(true); TObjectList *map = new TObjectList(true); h.Length = height; for(int i = 0 ; i < height ; i++) { h[i].Length = width /2 ; data = static_cast<Byte *> (this->Image2->Picture->Bitmap->ScanLine[i]) ; for(int j = 0 ; j < width /2 ; j++) { //compute the difference h[i][j] = data[2*j] - data[2*j+1] ; //averate int average = (data[2*j] + data[2*j+1]) /2 ; //judge Expandable //3.把差值分类 统计可以差值的位置 if( ( h[i][j] < 2*(255-average) )&&( h[i][j] > -2*(255-average)) && ( h[i][j] < 2*average+1 )&& ( h[i][j] > -(2*average+1) ) ) { TPoint *p = new TPoint; p->x = i ; p->y = j ; //map the pair(a,b) a{x,y} //4.嵌入数据 if( embedCount <= embedSize ) { //expand difference if( embeddata.operator [](embedCount) == '1') { h[i][j] = 2*h[i][j]+ 1 ; } embedCount++ ; //recaculate x y data[2*j] = average + (h[i][j]+1)/2 ; data[2*j+1] = average - h[i][j]/2 ; map->Add((TObject *)p); TPoint *pair = new TPoint(data[2*j],data[2*j+1]); positionXY->Add((TObject *)pair); } else { //5.存储map if(this->SaveDialog1->Execute()) { //保存map AnsiString FileName = this->SaveDialog1->FileName; int handle = FileCreate(FileName); for(int a = 0 ; a < map->Count ; a++) { TPoint * p = (TPoint *)map->Items[a] ; FileWrite(handle,p,sizeof(TPoint)); } FileClose(handle); this->Image2->Canvas->Draw(0,0,bitmap) ; //保存h[i][j]; AnsiString strH = ""; for(int a = 0 ; a <= i ; a++) { for(int b = 0 ; b <= j ; b++) { strH +=AnsiString(h[a][b])+";"; } } AnsiString dirFileName = ExtractFilePath(FileName) +"difference.txt"; int difHandle = FileCreate(dirFileName); FileWrite(difHandle,strH.c_str(),strH.Length()); FileClose(difHandle); //保存修改坐标值 AnsiString valueFileName = ExtractFilePath(FileName) + "value.txt" ; int valueHandle = FileCreate(valueFileName); AnsiString pairStr = "" ; for(int x = 0 ; x < positionXY->Count ; x++) { TPoint *pair = (TPoint *)positionXY->Items[x] ; pairStr += AnsiString(pair->x) + "," + AnsiString(pair->y) + ";" ; } FileWrite(valueHandle,pairStr.c_str(),pairStr.Length()); FileClose(valueHandle) ; return ; } } } } } //6. 清理 delete map ; }
void CmdExtract::ExtrCreateDir(Archive &Arc,const wchar *ArcFileName) { if (Cmd->Test) { #ifndef GUI mprintf(St(MExtrTestFile),ArcFileName); mprintf(L" %s",St(MOk)); #endif return; } MKDIR_CODE MDCode=MakeDir(DestFileName,!Cmd->IgnoreGeneralAttr,Arc.FileHead.FileAttr); bool DirExist=false; if (MDCode!=MKDIR_SUCCESS) { DirExist=FileExist(DestFileName); if (DirExist && !IsDir(GetFileAttr(DestFileName))) { // File with name same as this directory exists. Propose user // to overwrite it. bool UserReject; FileCreate(Cmd,NULL,DestFileName,ASIZE(DestFileName),&UserReject,Arc.FileHead.UnpSize,&Arc.FileHead.mtime); DirExist=false; } if (!DirExist) { CreatePath(DestFileName,true); MDCode=MakeDir(DestFileName,!Cmd->IgnoreGeneralAttr,Arc.FileHead.FileAttr); if (MDCode!=MKDIR_SUCCESS) { wchar OrigName[ASIZE(DestFileName)]; wcsncpyz(OrigName,DestFileName,ASIZE(OrigName)); MakeNameUsable(DestFileName,true); CreatePath(DestFileName,true); MDCode=MakeDir(DestFileName,!Cmd->IgnoreGeneralAttr,Arc.FileHead.FileAttr); #ifndef SFX_MODULE if (MDCode==MKDIR_SUCCESS) uiMsg(UIERROR_RENAMING,Arc.FileName,OrigName,DestFileName); #endif } } } if (MDCode==MKDIR_SUCCESS) { #ifndef GUI mprintf(St(MCreatDir),DestFileName); mprintf(L" %s",St(MOk)); #endif PrevExtracted=true; } else if (DirExist) { if (!Cmd->IgnoreGeneralAttr) SetFileAttr(DestFileName,Arc.FileHead.FileAttr); PrevExtracted=true; } else { uiMsg(UIERROR_DIRCREATE,Arc.FileName,DestFileName); ErrHandler.SysErrMsg(); #ifdef RARDLL Cmd->DllError=ERAR_ECREATE; #endif ErrHandler.SetErrorCode(RARX_CREATE); } if (PrevExtracted) { #if defined(_WIN_ALL) && !defined(SFX_MODULE) if (Cmd->SetCompressedAttr && (Arc.FileHead.FileAttr & FILE_ATTRIBUTE_COMPRESSED)!=0 && WinNT()) SetFileCompression(DestFileName,true); #endif SetDirTime(DestFileName, Cmd->xmtime==EXTTIME_NONE ? NULL:&Arc.FileHead.mtime, Cmd->xctime==EXTTIME_NONE ? NULL:&Arc.FileHead.ctime, Cmd->xatime==EXTTIME_NONE ? NULL:&Arc.FileHead.atime); } }
FILE * fopen(const char *_name, const char *_type) { if(!strcmp(_type, "rb")) { FileOpen_typ FileOpen_0 = {0}; FileOpen_0.enable = 1; FileOpen_0.pDevice = (UDINT)PATH; FileOpen_0.pFile = (UDINT)_name; FileOpen_0.mode = fiREAD_ONLY; do { FileOpen(&FileOpen_0); }while (FileOpen_0.status == 65535); if (FileOpen_0.status) return NULL; FileInfo_typ FileInfo_0 = {0}; FileInfo_0.enable = 1; FileInfo_0.pDevice = (UDINT)PATH; FileInfo_0.pName = (UDINT)_name; fiFILE_INFO fiFILE_INFO_0 = {0}; FileInfo_0.pInfo = (UDINT)&fiFILE_INFO_0; do { FileInfo(&FileInfo_0); }while (FileInfo_0.status == 65535); if (FileInfo_0.status) return NULL; FileInfo1 *fi = new FileInfo1(); fi->size = fiFILE_INFO_0.size; fi->ident = FileOpen_0.ident; return (FILE*)fi; } if(!strcmp(_type, "wb")) { //try to delete the file FileDelete_typ FileDelete_0 = {0}; FileDelete_0.enable = 1; FileDelete_0.pDevice = (UDINT)PATH; FileDelete_0.pName = (UDINT)_name; do { FileDelete(&FileDelete_0); }while (FileDelete_0.status == 65535); //create the file FileCreate_typ FileCreate_0 = {0}; FileCreate_0.enable = 1; FileCreate_0.pDevice = (UDINT)PATH; FileCreate_0.pFile = (UDINT)_name; do { FileCreate(&FileCreate_0); }while (FileCreate_0.status == 65535); if (FileCreate_0.status) return NULL; FileInfo1 *fi = new FileInfo1(); fi->ident = FileCreate_0.ident; fi->writeAccess = 1; return (FILE*)fi; } return 0; }
static void Cn3D_ExportKinNow(ButtoN b) { Char path[256]; FILE *pFile; Int2 iTest; Int4 iCount = 0; PDNMS pdnmsMain = NULL; Int2 iColor = 0; Byte bRender = 0; Int2Ptr i2Vec = NULL; i2Vec = PickedModels(&iCount); if (iCount == 0) { ErrClear(); ErrPostEx(SEV_INFO, 0, 0, "Nothing to save!"); ErrShow(); Disable(Cn3D_bKinOk); return; } GetTitle(Cn3D_tKinSave, path, sizeof(path)); iColor = GetValue(Cn3D_gColorAtoms); bRender = KIN_DEFAULT; if (GetStatus(Cn3D_bRender[0]) == TRUE) bRender = bRender | (Byte) KIN_VIRTUAL; if (GetStatus(Cn3D_bRender[1]) == TRUE) bRender = bRender | (Byte) KIN_BACKBONE; if (GetStatus(Cn3D_bRender[2]) == TRUE) bRender = bRender | (Byte) KIN_RESIDUE; if (GetStatus(Cn3D_bRender[3]) == TRUE) bRender = bRender | (Byte) KIN_HET; if (GetStatus(Cn3D_bRender[4]) == TRUE) bRender = bRender | (Byte) KIN_ALTCONF; if (GetStatus(Cn3D_bRender[5]) == TRUE) bRender = bRender | (Byte) KIN_MULTANIM; pdnmsMain = GetSelectedModelstruc(); #ifdef WIN_MAC FileCreate(path, "TEXT", "ttxt"); #endif WatchCursor(); pFile = FileOpen(path, "w"); if (pFile) { iTest = WriteKinModelList(pdnmsMain, pFile, iColor, bRender, iCount, i2Vec); I2VectorFree(i2Vec, 0); if (!iTest) { ErrClear(); ErrPostEx(SEV_FATAL, 0, 0, "Unable to Export\nPossibly Corrupt Data in Memory!\n"); ErrShow(); } fflush(pFile); fclose(pFile); } else { ErrClear(); ErrPostEx(SEV_INFO, 0, 0, "Sorry, Unable to Open File:\n %s", path); ErrShow(); Disable(Cn3D_bKinOk); I2VectorFree(i2Vec, 0); SetTitle(Cn3D_tKinSave, "\0"); ArrowCursor(); return; } Remove(Cn3D_wKinSave); Cn3D_EnableFileOps(); Cn3D_Export_InUse = FALSE; ArrowCursor(); return; }
//--------------------------------------------------------------------------- void __fastcall TFormLog::ButtonLogClick(TObject *Sender) { if(EditQRZ->Text=="") return; int H; AnsiString LogName = ThePath + "\\stream.adi"; if(FileExists(LogName)) { H = FileOpen(LogName,fmOpenReadWrite); if(H<0) { Application->MessageBox("Cannot write to log","IZ8BLY PSK31 Lab",MB_OK | MB_ICONSTOP); return; } FileSeek(H,0,2); } else { H = FileCreate(LogName); if(H<0) { Application->MessageBox("Cannot write to log","IZ8BLY PSK31 Lab",MB_OK | MB_ICONSTOP); return; } FileWriteString(H,"Created by IZ8BLY PSK31 Lab\r\n<EOH>\r\n"); } AnsiString Linea; TDateTime TD; if(UTCTimeLog) { SYSTEMTIME SystemTime; GetSystemTime(&SystemTime); TD = SystemTimeToDateTime(SystemTime); } else { TD = TDateTime().CurrentDateTime(); } Linea = FormatAdif("CALL",EditQRZ->Text) + FormatAdif("NAME",EditName->Text)+ FormatAdif("QTH",EditQTH->Text)+ FormatAdif("RST_RCVD",EditRSTReceived->Text)+ FormatAdif("RST_SENT",EditRSTSent->Text)+ FormatAdif("FREQ",EditFrequency->Text)+ FormatAdif("MODE","STREAM")+ FormatAdif("QSO_DATE",TD.FormatString("yyyymmdd"))+ FormatAdif("TIME_ON",TD.FormatString("hhmm"))+ FormatAdif("COMMENT",EditComments->Text)+ "<EOR>\r\n"; FileWriteString(H,Linea); FileClose(H); char oldclip[2048]; Clipboard()->GetTextBuf(oldclip,2048); Clipboard()->SetTextBuf(Linea.c_str()); SendMessage(HWND_BROADCAST,IZ8BLY,0,0); Clipboard()->SetTextBuf(oldclip); ButtonLog->Enabled = false; }
u32 CreatePad(PadInfo *info) { u8* buffer = BUFFER_ADDRESS; u32 size_byte = (info->size_mb) ? info->size_mb * 1024*1024 : info->size_b; u32 result = 0; if (!DebugCheckFreeSpace(size_byte)) return 1; if (!FileCreate(info->filename, true)) // No DebugFileCreate() here - messages are already given return 1; CryptBufferInfo decryptInfo = {.keyslot = info->keyslot, .setKeyY = info->setKeyY, .mode = info->mode, .buffer = buffer}; memcpy(decryptInfo.ctr, info->ctr, 16); memcpy(decryptInfo.keyY, info->keyY, 16); for (u32 i = 0; i < size_byte; i += BUFFER_MAX_SIZE) { u32 curr_block_size = min(BUFFER_MAX_SIZE, size_byte - i); decryptInfo.size = curr_block_size; memset(buffer, 0x00, curr_block_size); ShowProgress(i, size_byte); CryptBuffer(&decryptInfo); if (!DebugFileWrite((void*)buffer, curr_block_size, i)) { result = 1; break; } } ShowProgress(0, 0); FileClose(); return result; } u32 SdInfoGen(SdInfo* info, const char* base_path) { char* filelist = (char*)0x20400000; // check the base path for validity if ((strncmp(base_path, "/Nintendo 3DS", 13) != 0 ) || (strncmp(base_path, "/Nintendo 3DS/Private/", 22) == 0) || (strnlen(base_path, 255) < 13 + 33 + 33)) { Debug("Invalid base path given"); return 1; } Debug("Generating SDinfo.bin in memory..."); if (!GetFileList(base_path, filelist, 0x100000, true, true, false)) { Debug("Failed retrieving the filelist"); return 1; } u32 n_entries = 0; SdInfoEntry* entries = info->entries; for (char* path = strtok(filelist, "\n"); path != NULL; path = strtok(NULL, "\n")) { u32 plen = strnlen(path, 255); // get size in MB if (!FileOpen(path)) continue; entries[n_entries].size_mb = (FileGetSize() + (1024 * 1024) - 1) / (1024 * 1024); FileClose(); // skip to relevant part of path path += 13 + 33 + 33; // length of ("/Nintendo 3DS" + "/<id0>" + "/<id1>") plen -= 13 + 33 + 33; if ((strncmp(path, "/dbs", 4) != 0) && (strncmp(path, "/extdata", 8) != 0) && (strncmp(path, "/title", 6) != 0)) continue; // get filename char* filename = entries[n_entries].filename; filename[0] = '/'; for (u32 i = 1; i < 180 && path[i] != 0; i++) filename[i] = (path[i] == '/') ? '.' : path[i]; strncpy(filename + plen, ".xorpad", (180 - 1) - plen); // get AES counter GetSdCtr(entries[n_entries].ctr, path); if (++n_entries >= MAX_ENTRIES) break; } info->n_entries = n_entries; return (n_entries > 0) ? 0 : 1; }