bool ResourceFile::write (const File& cppFile, OutputStream& cpp, OutputStream& header) { String comment; comment << newLine << newLine << " This is an auto-generated file, created by " << JUCEApplication::getInstance()->getApplicationName() << newLine << " Do not edit anything in this file!" << newLine << newLine << "*/" << newLine << newLine; header << "/* =========================================================================================" << comment; cpp << "/* ==================================== " << resourceFileIdentifierString << " ====================================" << comment; if (juceHeader.exists()) header << CodeHelpers::createIncludeStatement (juceHeader, cppFile) << newLine; const String namespaceName (className); StringArray returnCodes; int i; for (i = 0; i < files.size(); ++i) returnCodes.add ("numBytes = " + namespaceName + "::" + variableNames[i] + "Size; return " + namespaceName + "::" + variableNames[i] + ";"); cpp << CodeHelpers::createIncludeStatement (cppFile.withFileExtension (".h"), cppFile) << newLine << newLine << newLine << "const char* " << namespaceName << "::getNamedResource (const char* resourceNameUTF8, int& numBytes) throw()" << newLine << "{" << newLine; CodeHelpers::createStringMatcher (cpp, "resourceNameUTF8", variableNames, returnCodes, 4); cpp << " numBytes = 0;" << newLine << " return 0;" << newLine << "}" << newLine << newLine; header << "namespace " << namespaceName << newLine << "{" << newLine; for (i = 0; i < files.size(); ++i) { const File& file = files.getReference(i); const int64 dataSize = file.getSize(); ScopedPointer <InputStream> fileStream (file.createInputStream()); jassert (fileStream != nullptr); if (fileStream != nullptr) { const String variableName (variableNames[i]); const String tempVariable ("temp_" + String::toHexString (file.hashCode())); header << " extern const char* " << variableName << ";" << newLine; header << " const int " << variableName << "Size = " << (int) dataSize << ";" << newLine << newLine; cpp << newLine << "//================== " << file.getFileName() << " ==================" << newLine << "static const unsigned char " << tempVariable << "[] =" << newLine; { MemoryBlock data; fileStream->readIntoMemoryBlock (data); CodeHelpers::writeDataAsCppLiteral (data, cpp); } cpp << newLine << newLine << "const char* " << namespaceName << "::" << variableName << " = (const char*) " << tempVariable << ";" << newLine; } } header << " // If you provide the name of one of the binary resource variables above, this function will" << newLine << " // return the corresponding data and its size (or a null pointer if the name isn't found)." << newLine << " const char* getNamedResource (const char* resourceNameUTF8, int& dataSizeInBytes) throw();" << newLine << "}" << newLine; return true; }
void Image::createFromEmbed(File& file, const ubyte_t* palette) { std::string err; png_structp png_ptr = nullptr; png_infop info_ptr = nullptr; png_bytep* row_pointers = nullptr; int channels; int png_format; //Stream png_size_t size = file.readDword(); png_Stream stream = {(png_size_t)file.tell(), size, &file}; ubyte_t* data = nullptr; int width; int height; int format; //Check the header png_byte header[8]; file.read(header, 8); if(png_sig_cmp(header, 0, 8) != 0) { err = "Embedded image not a valid PNG file."; goto end; } //Create png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, nullptr, nullptr, nullptr); info_ptr = png_create_info_struct(png_ptr); if(!info_ptr) { goto error; } if(setjmp(png_jmpbuf(png_ptr))) { goto error; } png_set_read_fn(png_ptr, &stream, vio_read); png_set_sig_bytes(png_ptr, 8); png_read_png(png_ptr, info_ptr, PNG_TRANSFORM_STRIP_16 | PNG_TRANSFORM_EXPAND, nullptr); //Basic info width = png_get_image_width(png_ptr, info_ptr); height = png_get_image_height(png_ptr, info_ptr); channels = png_get_channels(png_ptr, info_ptr); png_format = png_get_color_type(png_ptr, info_ptr); //Check the colortype switch(png_format) { case PNG_COLOR_TYPE_GRAY: format = COLORTYPE_GRAYSCALE; break; case PNG_COLOR_TYPE_GRAY_ALPHA: format = COLORTYPE_GRAYSCALE_ALPHA; break; case PNG_COLOR_TYPE_RGB: format = COLORTYPE_RGB; break; case PNG_COLOR_TYPE_RGBA: format = COLORTYPE_RGBA; break; default: err = "Embedded image not a grayscale, indexed, RGB, or RGBA PNG."; goto end; } //Allocate the image buffer and copy data into it data = (ubyte_t*)malloc(width * height * channels); row_pointers = png_get_rows(png_ptr, info_ptr); for(int j = 0; j < height; j++) for(int i = 0; i < width * channels; i++) { data[j * (width * channels) + i] = row_pointers[j][i]; } //Turn this data into textures! createFromMemory(data, width, height, format, palette); goto end; error: err = "Unknown error while reading PNG file."; end: if(png_ptr || info_ptr) { png_free_data(png_ptr, info_ptr, PNG_FREE_ALL, -1); png_destroy_read_struct(&png_ptr, &info_ptr, nullptr); } if(data) { free(data); } //Move cursor back in place file.seek(stream.origin + stream.size); if(!err.empty()) { die(err); } }
int main ( int argc , char *argv[] ) { // let's ensure our core file can dump struct rlimit lim; lim.rlim_cur = lim.rlim_max = RLIM_INFINITY; if ( setrlimit(RLIMIT_CORE,&lim) ) log("blaster::setrlimit: %s", mstrerror(errno) ); g_conf.m_maxMem = 500000000; // init our table for doing zobrist hashing if ( ! hashinit() ) { log("blaster::hashinit failed" ); return 1; } // init the memory class after conf since it gets maxMem from Conf //if ( ! g_mem.init ( 20000000 ) ) { // log("blaster::Mem init failed" ); return 1; } g_mem.m_maxMem = 200000000; // start up log file if ( ! g_log.init( "/tmp/blasterLog" ) ) { log("blaster::Log open /tmp/blasterLog failed" ); return 1; } // get dns ip from /etc/resolv.conf g_conf.m_dnsIps[0] = 0; FILE *fd = fopen ( "/etc/resolv.conf" , "r" ); if ( ! fd ) { log("blaster::fopen: /etc/resolve.conf %s", mstrerror(errno)); return 1; } char tmp[1024]; while ( fgets ( tmp , 1024 , fd ) ) { // tmp buf ptr char *p = tmp; // skip comments if ( *p == '#' ) continue; // skip nameserver name if ( ! isdigit(*p) ) while ( ! isspace ( *p ) ) p++ ; // skip spaces while ( isspace ( *p ) ) p++; // if this is not a digit, continue if ( ! isdigit(*p) ) continue; // get ip g_conf.m_dnsIps[0] = atoip ( p , gbstrlen(p) ); // done break; } fclose ( fd ); // if no dns server found, bail if ( g_conf.m_dnsIps[0] == 0 ) { log("blaster:: no dns ip found in /etc/resolv.conf");return 1;} // hack # of dns servers g_conf.m_numDns = 1; g_conf.m_dnsPorts[0] = 53; //g_conf.m_dnsIps [0] = atoip ( "192.168.0.1", 11 ); //g_conf.m_dnsClientPort = 9909; g_conf.m_dnsMaxCacheMem = 1024*10; // hack http server port to -1 (none) //g_conf.m_httpPort = 0; g_conf.m_httpMaxSockets = 200; //g_conf.m_httpMaxReadBufSize = 102*1024*1024; g_conf.m_httpMaxSendBufSize = 16*1024; //g_conf.m_httpMaxDownloadSockets = 200; if ( argc != 4 && argc != 5 && argc !=6 ) { printUsage: log("USAGE: blaster [fileOfUrls | -r<num random words><server>] [maxNumThreads] [wait in ms] " "<lines to skip> <string to append>"); log("USAGE: examples:"); log("USAGE: ./blaster queries.fromlog 10 1"); log("USAGE: ./blaster -r3http://www.gigablast.com/index.php?q= 1 100\n"); return 1; } // init the loop if ( ! g_loop.init() ) { log("blaster::Loop init failed" ); return 1; } // . then dns client // . server should listen to a socket and register with g_loop if ( ! g_dns.init(6000) ) { log("blaster::Dns client init failed" ); return 1; } // . then webserver // . server should listen to a socket and register with g_loop for(long i = 0; i < 50; i++) { if ( ! g_httpServer.init( 8333 + i, 9334+i ) ) { log("blaster::HttpServer init failed" ); //return 1; } else break; } // set File class char *fname = argv[1]; long fnameLen = gbstrlen(fname); long fileSize = 0; long bufSize = 0; char *buf = NULL; long n = 0; //should we generate random queries? if(fnameLen > 2 && fname[0] == '-' && fname[1] == 'r') { char *p = fname + 2; s_numRandWords = atoi( p ); while(is_digit(*p)) p++; getWords(); if(*p == '\0') goto printUsage; s_server = p; log("blaster server is %s", s_server); // char x[1024]; // while(1) { // long l = getRandomWords(x, x + 1024, s_numRandWords); // *(x + l) = '\0'; // log("blaster: %s", x); // } // exit(1); } else { //it is a real file File f; f.set ( fname ); // open file if ( ! f.open ( O_RDONLY ) ) { log("blaster::open: %s %s",fname,mstrerror(g_errno)); return 1; } // get file size fileSize = f.getFileSize() ; // store a \0 at the end bufSize = fileSize + 1; // make buffer to hold all buf = (char *) mmalloc ( bufSize , "blaster" ); if ( ! buf) {log("blaster::mmalloc: %s",mstrerror(errno));return 1;} //char *bufEnd = buf + bufSize; // set s_p s_p = buf; s_pend = buf + bufSize - 1; // read em all in if ( ! f.read ( buf , fileSize , 0 ) ) { log("blaster::read: %s %s",fname,mstrerror(g_errno));return 1;} // change \n to \0 //char *p = buf; for ( long i = 0 ; i < bufSize ; i++ ) { if ( buf[i] != '\n' ) continue; buf[i] = '\0'; n++; } f.close(); } // log a msg log(LOG_INIT,"blaster: read %li urls into memory", n ); long linesToSkip = 0; if ( argc >= 5 ) { linesToSkip = atoi ( argv[4] ); log (LOG_INIT,"blaster: skipping %li urls",linesToSkip); } for ( long i = 0; i < linesToSkip && s_p < s_pend; i++ ) s_p += gbstrlen(s_p) + 1; if ( argc == 6 ) { long len = gbstrlen ( argv[5] ); if ( len > 512 ) len = 512; strncpy ( s_append , argv[5] , gbstrlen (argv[5]) ); } else s_append[0] = '\0'; // get min time bewteen each spider in milliseconds s_wait = atoi( argv[3] ); // # of threads s_maxNumThreads = 1; s_maxNumThreads = atoi ( argv[2] ); s_portSwitch = 0; //if ( argc == 4 ) s_portSwitch = 1; //else s_portSwitch = 0; // start our spider loop //startSpidering( ); // wakeup wrapper every X ms g_loop.registerSleepCallback ( s_wait , NULL , sleepWrapper ); //msg10.addUrls ( uu , gbstrlen(uu)+1, NULL,0,time(0),4,true,NULL,NULL); // . now start g_loops main interrupt handling loop // . it should block forever // . when it gets a signal it dispatches to a server or db to handle it if ( ! g_loop.runLoop() ) { log("blaster::runLoop failed" ); return 1; } // dummy return (0-->normal exit status for the shell) return 0; }
friend bool operator < (const File &a, const File &b) { return a.fqp() < b.fqp(); }
bool Scope::execFile(const string& filename, bool printResult, bool reportError, int timeoutMs) { #ifdef _WIN32 boost::filesystem::path p(toWideString(filename.c_str())); #else boost::filesystem::path p(filename); #endif if (!exists(p)) { log() << "file [" << filename << "] doesn't exist" << endl; return false; } // iterate directories and recurse using all *.js files in the directory if (boost::filesystem::is_directory(p)) { boost::filesystem::directory_iterator end; bool empty = true; for (boost::filesystem::directory_iterator it (p); it != end; it++) { empty = false; boost::filesystem::path sub(*it); if (!endsWith(sub.string().c_str(), ".js")) continue; if (!execFile(sub.string(), printResult, reportError, timeoutMs)) return false; } if (empty) { log() << "directory [" << filename << "] doesn't have any *.js files" << endl; return false; } return true; } File f; f.open(filename.c_str(), true); if (!f.is_open() || f.bad()) return false; fileofs fo = f.len(); if (fo > kMaxJsFileLength) { warning() << "attempted to execute javascript file larger than 2GB" << endl; return false; } unsigned len = static_cast<unsigned>(fo); boost::scoped_array<char> data (new char[len+1]); data[len] = 0; f.read(0, data.get(), len); int offset = 0; if (data[0] == '#' && data[1] == '!') { const char* newline = strchr(data.get(), '\n'); if (!newline) return true; // file of just shebang treated same as empty file offset = newline - data.get(); } StringData code(data.get() + offset, len - offset); return exec(code, filename, printResult, reportError, timeoutMs); }
void swap(File& a, File& b) { a.swap(b); }
bool CmdExtract::ExtractCurrentFile(Archive &Arc,size_t HeaderSize,bool &Repeat) { // We can get negative sizes in corrupt archive and it is unacceptable // for size comparisons in CmdExtract::UnstoreFile and ComprDataIO::UnpRead, // where we cast sizes to size_t and can exceed another read or available // size. We could fix it when reading an archive. But we prefer to do it // here, because this function is called directly in unrar.dll, so we fix // bad parameters passed to dll. Also we want to see real negative sizes // in the listing of corrupt archive. if (Arc.FileHead.PackSize<0) Arc.FileHead.PackSize=0; if (Arc.FileHead.UnpSize<0) Arc.FileHead.UnpSize=0; 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 && PrevProcessed) SetExtraInfo20(Cmd,Arc,DestFileName); #endif if (HeaderType==HEAD_SERVICE && PrevProcessed) 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; } PrevProcessed=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); #ifdef _WIN_ALL if (!Cmd->AllowIncompatNames) MakeNameCompatible(ArcFileName); #endif 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) { // Stop archive extracting if user cancelled a password prompt. #ifdef RARDLL if (!ExtrDllGetPassword()) { Cmd->DllError=ERAR_MISSING_PASSWORD; return false; } #else if (!ExtrGetPassword(Arc,ArcFileName)) { PasswordCancelled=true; return false; } #endif // Skip only the current encrypted file if empty password is entered. // Actually our "cancel" code above intercepts empty passwords too now, // so we keep the code below just in case we'll decide process empty // and cancelled passwords differently sometimes. 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)) { ErrHandler.SetErrorCode(RARX_FATAL); #ifdef RARDLL Cmd->DllError=ERAR_UNKNOWN_FORMAT; #endif Arc.SeekToNext(); return !Arc.Solid; // Can try extracting next file only in non-solid archive. } // Set a password before creating the file, so we can skip creating // in case of wrong password. 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, Arc.FileHead.HashKey,PswCheck); // 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); ExtrFile=false; #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_PASSWORD; #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) { // Set it in test mode, so we also test subheaders such as NTFS streams // after tested file. if (Cmd->Test) PrevProcessed=true; 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 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 && !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 && !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; } PrevProcessed=FileCreateMode && LinkSuccess; } else if (!Arc.FileHead.SplitBefore) 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 (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 (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 // or ERAR_BAD_PASSWORD for RAR5 wrong password, // we should not replace it with less precise ERAR_BAD_DATA. if (Cmd->DllError!=ERAR_EOPEN && Cmd->DllError!=ERAR_BAD_PASSWORD) Cmd->DllError=ERAR_BAD_DATA; #endif } } #ifndef GUI else mprintf(L"\b\b\b\b\b "); #endif if (!TestMode && (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); PrevProcessed=true; } } } if (MatchFound) MatchedArgs++; if (DataIO.NextVolumeMissing) return false; if (!ExtrFile) if (!Arc.Solid) Arc.SeekToNext(); else if (!SkipSolid) return false; return true; }
static int64 calculateFileHashCode (const File& file) { ScopedPointer <FileInputStream> stream (file.createInputStream()); return stream != 0 ? calculateStreamHashCode (*stream) : 0; }
//============================================================================== static bool parseFile (const File& rootFolder, const File& newTargetFile, OutputStream& dest, const File& file, StringArray& alreadyIncludedFiles, const StringArray& includesToIgnore, const StringArray& wildcards, bool isOuterFile, bool stripCommentBlocks) { if (! file.exists()) { std::cout << "!! ERROR - file doesn't exist!"; return false; } StringArray lines; lines.addLines (file.loadFileAsString()); if (lines.size() == 0) { std::cout << "!! ERROR - input file was empty: " << file.getFullPathName(); return false; } bool lastLineWasBlank = true; for (int i = 0; i < lines.size(); ++i) { String line (lines[i]); String trimmed (line.trimStart()); if ((! isOuterFile) && trimmed.startsWith ("//================================================================")) line = String::empty; if (trimmed.startsWithChar ('#') && trimmed.removeCharacters (" \t").startsWithIgnoreCase ("#include\"")) { const int endOfInclude = line.indexOfChar (line.indexOfChar ('\"') + 1, '\"') + 1; const String lineUpToEndOfInclude (line.substring (0, endOfInclude)); const String lineAfterInclude (line.substring (endOfInclude)); const String filename (line.fromFirstOccurrenceOf ("\"", false, false) .upToLastOccurrenceOf ("\"", false, false)); const File targetFile (file.getSiblingFile (filename)); if (targetFile.exists() && targetFile.isAChildOf (rootFolder)) { if (matchesWildcard (filename.replaceCharacter ('\\', '/'), wildcards) && ! includesToIgnore.contains (targetFile.getFileName())) { if (line.containsIgnoreCase ("FORCE_AMALGAMATOR_INCLUDE") || ! alreadyIncludedFiles.contains (targetFile.getFullPathName())) { if (! canFileBeReincluded (targetFile)) alreadyIncludedFiles.add (targetFile.getFullPathName()); dest << newLine << "/*** Start of inlined file: " << targetFile.getFileName() << " ***/" << newLine; if (! parseFile (rootFolder, newTargetFile, dest, targetFile, alreadyIncludedFiles, includesToIgnore, wildcards, false, stripCommentBlocks)) { return false; } dest << "/*** End of inlined file: " << targetFile.getFileName() << " ***/" << newLine << newLine; line = lineAfterInclude; } else { line = String::empty; } } else { line = lineUpToEndOfInclude.upToFirstOccurrenceOf ("\"", true, false) + targetFile.getRelativePathFrom (newTargetFile.getParentDirectory()) .replaceCharacter ('\\', '/') + "\"" + lineAfterInclude; } } } if ((stripCommentBlocks || i == 0) && trimmed.startsWith ("/*") && (i > 10 || ! isOuterFile)) { int originalI = i; String originalLine = line; for (;;) { int end = line.indexOf ("*/"); if (end >= 0) { line = line.substring (end + 2); // If our comment appeared just before an assertion, leave it in, as it // might be useful.. if (lines [i + 1].contains ("assert") || lines [i + 2].contains ("assert")) { i = originalI; line = originalLine; } break; } line = lines [++i]; if (i >= lines.size()) break; } line = line.trimEnd(); if (line.isEmpty()) continue; } line = line.trimEnd(); { // Turn initial spaces into tabs.. int numIntialSpaces = 0; int len = line.length(); while (numIntialSpaces < len && line [numIntialSpaces] == ' ') ++numIntialSpaces; if (numIntialSpaces > 0) { int tabSize = 4; int numTabs = numIntialSpaces / tabSize; line = String::repeatedString ("\t", numTabs) + line.substring (numTabs * tabSize); } if (! line.containsChar ('"')) { // turn large areas of spaces into tabs - this will mess up alignment a bit, but // it's only the amalgamated file, so doesn't matter... line = line.replace (" ", "\t", false); line = line.replace (" ", "\t", false); } } if (line.isNotEmpty() || ! lastLineWasBlank) dest << line << newLine; lastLineWasBlank = line.isEmpty(); } return true; }
MainMenu::MainMenu () { File *file; time_t currentTime; // Load the OpenJazz logo try { file = new File(LOGO_FILE, false); } catch (int e) { throw e; } logo = file->loadSurface(64, 40); delete file; // Load the menu graphics try { file = new File(F_MENU, false); } catch (int e) { SDL_FreeSurface(logo); throw e; } if (file->getSize() > 200000) { time(¤tTime); // In December, load the Christmas menu graphics if (localtime(¤tTime)->tm_mon == 11) { file->skipRLE(); file->skipRLE(); file->skipRLE(); file->loadPalette(palette); background = file->loadSurface(SW, SH); highlight = file->loadSurface(SW, SH); } else { file->loadPalette(palette); background = file->loadSurface(SW, SH); highlight = file->loadSurface(SW, SH); file->skipRLE(); file->skipRLE(); file->skipRLE(); } } else { file->loadPalette(palette); background = file->loadSurface(SW, SH); highlight = file->loadSurface(SW, SH); } SDL_SetColorKey(background, SDL_SRCCOLORKEY, 0); SDL_SetColorKey(highlight, SDL_SRCCOLORKEY, 0); SDL_SetColorKey(logo, SDL_SRCCOLORKEY, 28); gameMenu = new GameMenu(file); delete file; return; }
bool PNGImageFormat::usesFileExtension (const File& f) { return f.hasFileExtension ("png"); }
bool YSE::SOUND::implementationObject::create(const std::string &fileName, CHANNEL::interfaceObject * ch, Bool loop, Flt volume, Bool streaming) { File ioFile; parent = ch->pimpl; looping = loop; fader.set(volume); this->streaming = streaming; if (!IO().getActive()) { ioFile = File::getCurrentWorkingDirectory().getChildFile(juce::String(fileName)); if (!ioFile.existsAsFile()) { INTERNAL::LogImpl().emit(E_FILE_ERROR, "file not found for " + ioFile.getFullPathName().toStdString()); goto release; } } else { if (!INTERNAL::CALLBACK::fileExists(fileName.c_str())) { INTERNAL::LogImpl().emit(E_FILE_ERROR, "file not found for " + fileName); goto release; } } if (!streaming) { if (IO().getActive()) { file = SOUND::Manager().addFile(fileName.c_str()); } else { file = SOUND::Manager().addFile(ioFile); } status_dsp = SS_STOPPED; status_upd = SS_STOPPED; if (file == nullptr) { goto release; } else { file->attach(this); objectStatus = OBJECT_CREATED; return true; } } else { // streams have their own soundfile streaming = true; status_dsp = SS_STOPPED; status_upd = SS_STOPPED; if (IO().getActive()) { file = new INTERNAL::soundFile(fileName.c_str()); } else { file = new INTERNAL::soundFile(ioFile); } if(file->create(true)) { filebuffer.resize(file->channels()); buffer = &filebuffer; return true; } else { delete file; file = nullptr; goto release; } } release: head = nullptr; return false; }
bool MonsterManager::LoadMonster(UINT mapId) { char xmlfile[260] = {0}; sprintf(xmlfile, "moninfo%u.xml", mapId); m_mapId = mapId; m_pListCtrl->DeleteAllItems(); Release(); char szFile[260] = {0}; sprintf(szFile, "%s/%s", EditorConfig::Instance()->makeServerResPath(MONINFO_PATH), xmlfile); xml_document doc; File file; if (!file.open(szFile)) return false; doc.load_buffer(file.getBufferPtr(), file.getLength()); ushort count = 0; ushort index = 0; for (pugi::xml_node node1=doc.child("moninfo").child("mon"); node1; node1=node1.next_sibling()) { MONINFO info; info.mapId = mapId; int baseId = node1.attribute("BaseId").as_int(); int num = node1.attribute("Num").as_int(); index++; info.race = baseId; info.num = num; info.ai = node1.attribute("AI").as_int(); info.speed = node1.attribute("Speed").as_int(); info.view = node1.attribute("View").as_int(); info.dropInfo[0].dropId = node1.attribute("DropId").as_int(); info.dropInfo[0].dropProb = node1.attribute("DropProb").as_int(); info.dropInfo[0].dropType = node1.attribute("DropType").as_int(); info.dropInfo[1].dropId = node1.attribute("DropId2").as_int(); info.dropInfo[1].dropProb = node1.attribute("DropProb2").as_int(); info.dropInfo[1].dropType = node1.attribute("DropType2").as_int(); info.dropInfo[2].dropId = node1.attribute("DropId3").as_int(); info.dropInfo[2].dropProb = node1.attribute("DropProb3").as_int(); info.dropInfo[2].dropType = node1.attribute("DropType3").as_int(); info.reviveTime = node1.attribute("ReviveTime").as_int(); info.isSiegeWar = node1.attribute("SiegeWar").as_int(); info.isEventMon = node1.attribute("EventMon").as_int(); info.birthRect.x = node1.attribute("BirthX").as_int(); info.birthRect.y = node1.attribute("BirthY").as_int(); info.birthRect.cx = node1.attribute("BirthWidth").as_int(); info.birthRect.cy = node1.attribute("BirthHeight").as_int(); const stMonBase* base = GameTable::getMonBase(baseId); if (!base) { LOGE("¶ÁÈ¡¹ÖÎï·Ö²¼³ö´í£¬²»´æÔڵĹÖÎïÀàÐÍ, file=%s, race=%u", szFile, baseId); continue; } Monster* pMon = new Monster; pMon->SetName(base->name); pMon->SetNum(num); pMon->FillInfo(info); pMon->Load(base->id); pMon->SetGridPos(info.birthRect.x, info.birthRect.y); if (!this->AddMonster(pMon)) { SAFE_DELETE(pMon); TRACE("²åÈë¹ÖÎïʧ°Ü, file=%s, race=%u", szFile, info.race); continue; } } return true; }
void FileReaderSync::ReadAsText(File& aBlob, const Optional<nsAString>& aEncoding, nsAString& aResult, ErrorResult& aRv) { nsCOMPtr<nsIInputStream> stream; nsresult rv = aBlob.GetInternalStream(getter_AddRefs(stream)); if (NS_FAILED(rv)) { aRv.Throw(rv); return; } nsAutoCString encoding; unsigned char sniffBuf[3] = { 0, 0, 0 }; uint32_t numRead; rv = stream->Read(reinterpret_cast<char*>(sniffBuf), sizeof(sniffBuf), &numRead); if (NS_FAILED(rv)) { aRv.Throw(rv); return; } // The BOM sniffing is baked into the "decode" part of the Encoding // Standard, which the File API references. if (!nsContentUtils::CheckForBOM(sniffBuf, numRead, encoding)) { // BOM sniffing failed. Try the API argument. if (!aEncoding.WasPassed() || !EncodingUtils::FindEncodingForLabel(aEncoding.Value(), encoding)) { // API argument failed. Try the type property of the blob. nsAutoString type16; aBlob.GetType(type16); NS_ConvertUTF16toUTF8 type(type16); nsAutoCString specifiedCharset; bool haveCharset; int32_t charsetStart, charsetEnd; NS_ExtractCharsetFromContentType(type, specifiedCharset, &haveCharset, &charsetStart, &charsetEnd); if (!EncodingUtils::FindEncodingForLabel(specifiedCharset, encoding)) { // Type property failed. Use UTF-8. encoding.AssignLiteral("UTF-8"); } } } nsCOMPtr<nsISeekableStream> seekable = do_QueryInterface(stream); if (!seekable) { aRv.Throw(NS_ERROR_FAILURE); return; } // Seek to 0 because to undo the BOM sniffing advance. UTF-8 and UTF-16 // decoders will swallow the BOM. rv = seekable->Seek(nsISeekableStream::NS_SEEK_SET, 0); if (NS_FAILED(rv)) { aRv.Throw(rv); return; } rv = ConvertStream(stream, encoding.get(), aResult); if (NS_FAILED(rv)) { aRv.Throw(rv); return; } }
void PNG_write(png_structp png_ptr, png_bytep data, png_size_t length) { File* file = (File*)png_get_io_ptr(png_ptr); if (file->write(data, length) != int(length)) { png_error(png_ptr, "Write error"); } }
String resolveRelativePath(String relativePath) { // We need to use a cached version of the working directory, // since plugin initialization is done in a non-threadsafe way at the moment. return cwd.getChildFile(relativePath).getFullPathName(); }
/** * Determine linux distro and version */ static void getLinuxDistro( string& name, string& version ) { char buf[4096] = { 0 }; // try lsb file first if ( boost::filesystem::exists( "/etc/lsb-release" ) ) { File f; f.open( "/etc/lsb-release", true ); if ( ! f.is_open() || f.bad() ) return; f.read( 0, buf, f.len() > 4095 ? 4095 : f.len() ); // find the distribution name and version in the contents. // format: KEY=VAL\n string contents = buf; unsigned lineCnt = 0; try { while ( lineCnt < contents.length() - 1 && contents.substr( lineCnt ).find( '\n' ) != string::npos ) { // until we hit the last newline or eof string line = contents.substr( lineCnt, contents.substr( lineCnt ).find( '\n' ) ); lineCnt += contents.substr( lineCnt ).find( '\n' ) + 1; size_t delim = line.find( '=' ); string key = line.substr( 0, delim ); string val = line.substr( delim + 1 ); // 0-based offset of delim if ( key.compare( "DISTRIB_ID" ) == 0 ) name = val; if ( string(key).compare( "DISTRIB_RELEASE" ) == 0 ) version = val; } } catch (const std::out_of_range &e) { // attempted to get invalid substr } return; // return with lsb-relase data } // try known flat-text file locations // format: Slackware-x86_64 13.0, Red Hat Enterprise Linux Server release 5.6 (Tikanga), etc. typedef vector <string> pathvec; pathvec paths; pathvec::const_iterator i; bool found = false; paths.push_back( "/etc/system-release" ); paths.push_back( "/etc/redhat-release" ); paths.push_back( "/etc/gentoo-release" ); paths.push_back( "/etc/novell-release" ); paths.push_back( "/etc/gentoo-release" ); paths.push_back( "/etc/SuSE-release" ); paths.push_back( "/etc/SUSE-release" ); paths.push_back( "/etc/sles-release" ); paths.push_back( "/etc/debian_release" ); paths.push_back( "/etc/slackware-version" ); for ( i = paths.begin(); i != paths.end(); ++i ) { // for each path if ( boost::filesystem::exists( *i ) ) { // if the file exists, break found = true; break; } } if ( found ) { // found a file File f; f.open( i->c_str(), true ); if ( ! f.is_open() || f.bad() ) // file exists but can't be opened return; // read up to 512 bytes int len = f.len() > 512 ? 512 : f.len(); f.read( 0, buf, len ); buf[ len ] = '\0'; name = buf; size_t nl = 0; if ( ( nl = name.find( '\n', nl ) ) != string::npos ) // stop at first newline name.erase( nl ); // no standard format for name and version. use kernel version version = "Kernel "; version += LinuxSysHelper::readLineFromFile("/proc/sys/kernel/osrelease"); } }
int main (int argc, const char** argv) { int status = 0; // Create a vector of args. std::vector <std::string> args; for (int i = 1; i < argc; ++i) args.push_back (argv[i]); Config config; config.set ("verbose", "1"); // Some options are hard-coded. if (args.size ()) { if (args[0] == "-h" || closeEnough ("--help", args[0], 3)) command_help (args); else if (args[0] == "-v" || closeEnough ("--version", args[0], 3)) { Color bold ("bold"); std::cout << "\n" << bold.colorize (PACKAGE_STRING) #ifdef HAVE_COMMIT << " " << COMMIT #endif << " built for " #if defined (DARWIN) << "darwin" #elif defined (SOLARIS) << "solaris" #elif defined (CYGWIN) << "cygwin" #elif defined (HAIKU) << "haiku" #elif defined (OPENBSD) << "openbsd" #elif defined (FREEBSD) << "freebsd" #elif defined (NETBSD) << "netbsd" #elif defined (LINUX) << "linux" #elif defined (KFREEBSD) << "GNU/kFreeBSD" #elif defined (GNUHURD) << "GNU/Hurd" #else << "unknown" #endif << "\n" << "Copyright (C) 2010 - 2014 Göteborg Bit Factory." << "\n" << "\n" << "Taskd may be copied only under the terms of the MIT license, " << "which may be found in the taskd source kit." << "\n" << "Documentation for taskd can be found using 'man taskd' or at " << "http://taskwarrior.org" << "\n" << "\n"; } else { try { // Some defaults come from the environment. char* root_env = getenv ("TASKDDATA"); if (root_env) config.set ("root", root_env); // Process all the options. std::vector <std::string> positionals; std::vector <std::string>::iterator arg; for (arg = args.begin (); arg != args.end (); ++arg) { if (closeEnough ("--data", *arg, 3)) config.set ("root", *(++arg)); else if (closeEnough ("--quiet", *arg, 3)) config.set ("verbose", 0); else if (closeEnough ("--debug", *arg, 3)) config.set ("debug", 1); else if (closeEnough ("--force", *arg, 3)) config.set ("confirmation", 0); else if (closeEnough ("--debug", *arg, 3)) config.set ("debug", 1); else if (closeEnough ("--daemon", *arg, 3)) config.set ("daemon", 1); else if (taskd_applyOverride (config, *arg)) ; else positionals.push_back (*arg); } // A database object interfaces to the data. Database db (&config); // The highest-level commands are hard-coded: if (closeEnough ("init", args[0], 3)) command_init (db, positionals); else if (closeEnough ("config", args[0], 3)) command_config (db, positionals); else if (closeEnough ("status", args[0], 3)) command_status (db, positionals); else if (closeEnough ("help", args[0], 3)) command_help ( positionals); else if (closeEnough ("diagnostics", args[0], 3)) command_diag (db, positionals); else if (closeEnough ("server", args[0], 3)) command_server (db, positionals); else if (closeEnough ("add", args[0], 3)) command_add (db, positionals); else if (closeEnough ("remove", args[0], 3)) command_remove (db, positionals); else if (closeEnough ("suspend", args[0], 3)) command_suspend (db, positionals); else if (closeEnough ("resume", args[0], 3)) command_resume (db, positionals); else if (closeEnough ("client", args[0], 3)) command_client (db, positionals); else { File subcommand (std::string (TASKD_EXTDIR) + "/taskd_" + args[0]); if (subcommand.exists () && subcommand.executable ()) { std::string command; join (command, " ", args); command = std::string (TASKD_EXTDIR) + "/taskd_" + command; std::string output; status = taskd_execute (command, output); std::cout << output; } else throw std::string ("ERROR: Did not recognize command '") + args[0] + "'."; } } catch (std::string& error) { if (error == "usage") { std::vector <std::string> no_args; command_help (no_args); } else std::cout << error << "\n"; status = -1; } catch (...) { std::cerr << "Unknown error.\n"; status = -2; } } } else command_help (args); return status; }
bool RecVolumes::Restore(RAROptions *Cmd,const char *Name, const wchar *NameW,bool Silent) { char ArcName[NM]; wchar ArcNameW[NM]; strcpy(ArcName,Name); strcpyw(ArcNameW,NameW); char *Ext=GetExt(ArcName); bool NewStyle=false; bool RevName=Ext!=NULL && stricomp(Ext,".rev")==0; if (RevName) { for (int DigitGroup=0;Ext>ArcName && DigitGroup<3;Ext--) if (!isdigit(*Ext)) if (isdigit(*(Ext-1)) && (*Ext=='_' || DigitGroup<2)) DigitGroup++; else if (DigitGroup<2) { NewStyle=true; break; } while (isdigit(*Ext) && Ext>ArcName+1) Ext--; strcpy(Ext,"*.*"); FindFile Find; Find.SetMask(ArcName); struct FindData FD; while (Find.Next(&FD)) { Archive Arc(Cmd); if (Arc.WOpen(FD.Name,FD.NameW) && Arc.IsArchive(true)) { strcpy(ArcName,FD.Name); *ArcNameW=0; break; } } } Archive Arc(Cmd); if (!Arc.WCheckOpen(ArcName,ArcNameW)) return(false); if (!Arc.Volume) { #ifndef SILENT Log(ArcName,St(MNotVolume),ArcName); #endif return(false); } bool NewNumbering=(Arc.NewMhd.Flags & MHD_NEWNUMBERING); Arc.Close(); char *VolNumStart=VolNameToFirstName(ArcName,ArcName,NewNumbering); char RecVolMask[NM]; strcpy(RecVolMask,ArcName); int BaseNamePartLength=VolNumStart-ArcName; strcpy(RecVolMask+BaseNamePartLength,"*.rev"); #ifndef SILENT Int64 RecFileSize=0; #endif FindFile Find; Find.SetMask(RecVolMask); struct FindData RecData; int FileNumber=0,RecVolNumber=0,FoundRecVolumes=0,MissingVolumes=0; char PrevName[NM]; while (Find.Next(&RecData)) { char *Name=RecData.Name; int P[3]; if (!RevName && !NewStyle) { NewStyle=true; char *Dot=GetExt(Name); if (Dot!=NULL) { int LineCount=0; Dot--; while (Dot>Name && *Dot!='.') { if (*Dot=='_') LineCount++; Dot--; } if (LineCount==2) NewStyle=false; } } if (NewStyle) { File CurFile; CurFile.TOpen(Name); CurFile.Seek(0,SEEK_END); Int64 Length=CurFile.Tell(); CurFile.Seek(Length-7,SEEK_SET); for (int I=0;I<3;I++) P[2-I]=CurFile.GetByte()+1; uint FileCRC=0; for (int I=0;I<4;I++) FileCRC|=CurFile.GetByte()<<(I*8); if (FileCRC!=CalcFileCRC(&CurFile,Length-4)) { #ifndef SILENT mprintf(St(MCRCFailed),Name); #endif continue; } } else { char *Dot=GetExt(Name); if (Dot==NULL) continue; bool WrongParam=false; for (int I=0;I<sizeof(P)/sizeof(P[0]);I++) { do { Dot--; } while (isdigit(*Dot) && Dot>=Name+BaseNamePartLength); P[I]=atoi(Dot+1); if (P[I]==0 || P[I]>255) WrongParam=true; } if (WrongParam) continue; } if (P[1]+P[2]>255) continue; if (RecVolNumber!=0 && RecVolNumber!=P[1] || FileNumber!=0 && FileNumber!=P[2]) { #ifndef SILENT Log(NULL,St(MRecVolDiffSets),Name,PrevName); #endif return(false); } RecVolNumber=P[1]; FileNumber=P[2]; strcpy(PrevName,Name); File *NewFile=new File; NewFile->TOpen(Name); SrcFile[FileNumber+P[0]-1]=NewFile; FoundRecVolumes++; #ifndef SILENT if (RecFileSize==0) RecFileSize=NewFile->FileLength(); #endif } #ifndef SILENT if (!Silent || FoundRecVolumes!=0) { mprintf(St(MRecVolFound),FoundRecVolumes); } #endif if (FoundRecVolumes==0) return(false); bool WriteFlags[256]; memset(WriteFlags,0,sizeof(WriteFlags)); char LastVolName[NM]; *LastVolName=0; for (int CurArcNum=0;CurArcNum<FileNumber;CurArcNum++) { Archive *NewFile=new Archive; bool ValidVolume=FileExist(ArcName); if (ValidVolume) { NewFile->TOpen(ArcName); ValidVolume=NewFile->IsArchive(false); if (ValidVolume) { bool EndFound=false,EndBlockRequired=false; while (!EndFound && NewFile->ReadHeader()!=0) { if (NewFile->GetHeaderType()==FILE_HEAD) { if (NewFile->NewLhd.UnpVer>=29) EndBlockRequired=true; if (!EndBlockRequired && (NewFile->NewLhd.Flags & LHD_SPLIT_AFTER)) EndFound=true; } if (NewFile->GetHeaderType()==ENDARC_HEAD) { if ((NewFile->EndArcHead.Flags&EARC_DATACRC)!=0 && NewFile->EndArcHead.ArcDataCRC!=CalcFileCRC(NewFile,NewFile->CurBlockPos)) { ValidVolume=false; #ifndef SILENT mprintf(St(MCRCFailed),ArcName); #endif } EndFound=true; } NewFile->SeekToNext(); } if (!EndFound) ValidVolume=false; } if (!ValidVolume) { NewFile->Close(); char NewName[NM]; strcpy(NewName,ArcName); strcat(NewName,".bad"); #ifndef SILENT mprintf(St(MBadArc),ArcName); mprintf(St(MRenaming),ArcName,NewName); #endif rename(ArcName,NewName); } NewFile->Seek(0,SEEK_SET); } if (!ValidVolume) { NewFile->TCreate(ArcName); WriteFlags[CurArcNum]=true; MissingVolumes++; if (CurArcNum==FileNumber-1) strcpy(LastVolName,ArcName); #ifndef SILENT mprintf(St(MAbsNextVol),ArcName); #endif } SrcFile[CurArcNum]=(File*)NewFile; NextVolumeName(ArcName,!NewNumbering); } #ifndef SILENT mprintf(St(MRecVolMissing),MissingVolumes); #endif if (MissingVolumes==0) { #ifndef SILENT mprintf(St(MRecVolAllExist)); #endif return(false); } if (MissingVolumes>FoundRecVolumes) { #ifndef SILENT mprintf(St(MRecVolCannotFix)); #endif return(false); } #ifndef SILENT mprintf(St(MReconstructing)); #endif RSCoder RSC(RecVolNumber); int TotalFiles=FileNumber+RecVolNumber; int Erasures[256],EraSize=0; for (int I=0;I<TotalFiles;I++) if (WriteFlags[I] || SrcFile[I]==NULL) Erasures[EraSize++]=I; #ifndef SILENT Int64 ProcessedSize=0; #ifndef GUI int LastPercent=-1; mprintf(" "); #endif #endif int RecCount=0; while (true) { if ((++RecCount & 15)==0) Wait(); int MaxRead=0; for (int I=0;I<TotalFiles;I++) if (WriteFlags[I] || SrcFile[I]==NULL) memset(&Buf[I*RECVOL_BUFSIZE],0,RECVOL_BUFSIZE); else { int ReadSize=SrcFile[I]->Read(&Buf[I*RECVOL_BUFSIZE],RECVOL_BUFSIZE); if (ReadSize!=RECVOL_BUFSIZE) memset(&Buf[I*RECVOL_BUFSIZE+ReadSize],0,RECVOL_BUFSIZE-ReadSize); if (ReadSize>MaxRead) MaxRead=ReadSize; } if (MaxRead==0) break; #ifndef SILENT int CurPercent=ToPercent(ProcessedSize,RecFileSize); if (!Cmd->DisablePercentage && CurPercent!=LastPercent) { mprintf("\b\b\b\b%3d%%",CurPercent); LastPercent=CurPercent; } ProcessedSize+=MaxRead; #endif for (int BufPos=0;BufPos<MaxRead;BufPos++) { byte Data[256]; for (int I=0;I<TotalFiles;I++) Data[I]=Buf[I*RECVOL_BUFSIZE+BufPos]; RSC.Decode(Data,TotalFiles,Erasures,EraSize); for (int I=0;I<EraSize;I++) Buf[Erasures[I]*RECVOL_BUFSIZE+BufPos]=Data[Erasures[I]]; /* for (int I=0;I<FileNumber;I++) Buf[I*RECVOL_BUFSIZE+BufPos]=Data[I]; */ } for (int I=0;I<FileNumber;I++) if (WriteFlags[I]) SrcFile[I]->Write(&Buf[I*RECVOL_BUFSIZE],MaxRead); } for (int I=0;I<RecVolNumber+FileNumber;I++) if (SrcFile[I]!=NULL) { File *CurFile=SrcFile[I]; if (NewStyle && WriteFlags[I]) { Int64 Length=CurFile->Tell(); CurFile->Seek(Length-7,SEEK_SET); for (int J=0;J<7;J++) CurFile->PutByte(0); } CurFile->Close(); SrcFile[I]=NULL; } if (*LastVolName) { Archive Arc(Cmd); if (Arc.Open(LastVolName,NULL,false,true) && Arc.IsArchive(true) && Arc.SearchBlock(ENDARC_HEAD)) { Arc.Seek(Arc.NextBlockPos,SEEK_SET); char Buf[8192]; int ReadSize=Arc.Read(Buf,sizeof(Buf)); int ZeroCount=0; while (ZeroCount<ReadSize && Buf[ZeroCount]==0) ZeroCount++; if (ZeroCount==ReadSize) { Arc.Seek(Arc.NextBlockPos,SEEK_SET); Arc.Truncate(); } } } #if !defined(GUI) && !defined(SILENT) if (!Cmd->DisablePercentage) mprintf("\b\b\b\b100%%"); if (!Silent && !Cmd->DisableDone) mprintf(St(MDone)); #endif return(true); }
bool UploadManager::prepareFile(UserConnection& aSource, const string& aType, const string& aFile, int64_t aStartPos, int64_t aBytes, bool listRecursive) { if(aFile.empty() || aStartPos < 0 || aBytes < -1 || aBytes == 0) { aSource.fileNotAvail("Invalid request"); return false; } InputStream* is = 0; int64_t start = 0; int64_t bytesLeft = 0; int64_t size = 0; bool userlist = (aFile == Transfer::USER_LIST_NAME_BZ || aFile == Transfer::USER_LIST_NAME); bool free = userlist; bool leaves = false; bool partList = false; string sourceFile; try { if(aType == Transfer::TYPE_FILE) { sourceFile = ShareManager::getInstance()->toReal(aFile); if(aFile == Transfer::USER_LIST_NAME) { // Unpack before sending... string bz2 = File(sourceFile, File::READ, File::OPEN).read(); string xml; CryptoManager::getInstance()->decodeBZ2(reinterpret_cast<const uint8_t*>(bz2.data()), bz2.size(), xml); // Clear to save some memory... string().swap(bz2); is = new MemoryInputStream(xml); start = 0; bytesLeft = size = xml.size(); } else { File* f = new File(sourceFile, File::READ, File::OPEN); start = aStartPos; size = f->getSize(); bytesLeft = (aBytes == -1) ? size : aBytes; if(size < (start + bytesLeft)) { aSource.fileNotAvail(); delete f; return false; } free = free || (size <= (int64_t)(SETTING(SET_MINISLOT_SIZE) * 1024) ); f->setPos(start); is = f; if((start + bytesLeft) < size) { is = new LimitedInputStream<true>(is, aBytes); } } } else if(aType == Transfer::TYPE_TTHL) { sourceFile = ShareManager::getInstance()->toReal(aFile); MemoryInputStream* mis = ShareManager::getInstance()->getTree(aFile); if(!mis) { aSource.fileNotAvail(); return false; } start = 0; bytesLeft = size = mis->getSize(); is = mis; leaves = true; free = true; } else if(aType == Transfer::TYPE_LIST) { // Partial file list MemoryInputStream* mis = ShareManager::getInstance()->generatePartialList(aFile, listRecursive); if(mis == NULL) { aSource.fileNotAvail(); return false; } // Some old dc++ clients err here... aBytes = -1; start = 0; bytesLeft = size = mis->getSize(); is = mis; free = true; partList = true; } else { aSource.fileNotAvail("Unknown file type"); return false; } } catch(const ShareException& e) { aSource.fileNotAvail(e.getError()); return false; } catch(const Exception& e) { LogManager::getInstance()->message(STRING(UNABLE_TO_SEND_FILE) + sourceFile + ": " + e.getError()); aSource.fileNotAvail(); return false; } Lock l(cs); bool extraSlot = false; if(!aSource.isSet(UserConnection::FLAG_HASSLOT)) { bool hasReserved = (reservedSlots.find(aSource.getUser()) != reservedSlots.end()); bool isFavorite = FavoriteManager::getInstance()->hasSlot(aSource.getUser()); if(!(hasReserved || isFavorite || getFreeSlots() > 0 || getAutoSlot())) { bool supportsFree = aSource.isSet(UserConnection::FLAG_SUPPORTS_MINISLOTS); bool allowedFree = aSource.isSet(UserConnection::FLAG_HASEXTRASLOT) || aSource.isSet(UserConnection::FLAG_OP) || getFreeExtraSlots() > 0; if(free && supportsFree && allowedFree) { extraSlot = true; } else { delete is; aSource.maxedOut(); // Check for tth root identifier string tFile = aFile; if (tFile.compare(0, 4, "TTH/") == 0) tFile = ShareManager::getInstance()->toVirtual(TTHValue(aFile.substr(4))); addFailedUpload(aSource, tFile + " (" + Util::toString((aStartPos*1000/(size+10))/10.0)+"% of " + Util::formatBytes(size) + " done)"); aSource.disconnect(); return false; } } else { clearUserFiles(aSource.getUser()); // this user is using a full slot, nix them. } setLastGrant(GET_TICK()); } Upload* u = new Upload(aSource); u->setStream(is); if(aBytes == -1) u->setSize(size); else u->setSize(start + bytesLeft); u->setStartPos(start); u->setSourceFile(sourceFile); if(userlist) u->setFlag(Upload::FLAG_USER_LIST); if(leaves) u->setFlag(Upload::FLAG_TTH_LEAVES); if(partList) u->setFlag(Upload::FLAG_PARTIAL_LIST); uploads.push_back(u); if(!aSource.isSet(UserConnection::FLAG_HASSLOT)) { if(extraSlot) { if(!aSource.isSet(UserConnection::FLAG_HASEXTRASLOT)) { aSource.setFlag(UserConnection::FLAG_HASEXTRASLOT); extra++; } } else { if(aSource.isSet(UserConnection::FLAG_HASEXTRASLOT)) { aSource.unsetFlag(UserConnection::FLAG_HASEXTRASLOT); extra--; } aSource.setFlag(UserConnection::FLAG_HASSLOT); running++; } reservedSlots.erase(aSource.getUser()); } return true; }
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); }
void RWSection::write(const File& file) { ostream* stream = file.openOutputStream(ostream::binary); write(stream); delete stream; }
friend bool operator == (const File &a, const File &b) { return a.fqp() == b.fqp(); }
int main (int argc, char* argv[]) { // This object makes sure that Juce is initialised and shut down correctly // for the scope of this function call. Make sure this declaration is the // first statement of this function. const ScopedJuceInitialiser_NonGUI juceSystemInitialiser; printf ("\n\n--------------------------------\n Font Serialiser by Niall Moody\n--------------------------------\n\n"); if (argc != 3) { printf (" Usage: FontSerialiser <filename> <fontname>\n\n"); printf (" FontSerialiser will turn a font into a compressed binary file.\n\n\n"); return 1; } // because we're not using the proper application startup procedure, we need to call // this explicitly here to initialise some of the time-related stuff.. initialiseJuce_GUI(); // get file and font name from command line arguments const File destFile (File::getCurrentWorkingDirectory().getChildFile (argv[1])); String fontName(argv[2]); // make sure the destination file can be written to OutputStream *destStream = destFile.createOutputStream(); if (destStream == 0) { String error; error << "\nError : Couldn't open " << destFile.getFullPathName() << " for writing.\n\n"; std::cout << error; destFile.deleteFile(); shutdownSequence(destStream); return 2; } // make sure the font is installed on the current system StringArray fontNames = Font::findAllTypefaceNames(); // for (int n = 0; n < fontNames.size(); n++) // { // std::cout << fontNames[n] << std::endl; // } if(!fontNames.contains(fontName)) { String error ("\nError: The font " + fontName + " does not exist in the system\n"); std::cout << error; destFile.deleteFile(); shutdownSequence(destStream); return 3; } // load the font as a system-Typeface Font font(fontName, 10, 0); if(!Typeface::createSystemTypefaceFor (font)) { String error ("\nError : Where's the font?\n\n"); std::cout << error; destFile.deleteFile(); shutdownSequence(destStream); return 4; } // copy the font-properties to a CustomTypeface CustomTypeface customTypeface; customTypeface.setCharacteristics(font.getTypefaceName(), font.getAscent(), font.isBold(), font.isItalic(), ' '); // Here's the important part: copy all glyphs to a new instance of CustomTypeface customTypeface.addGlyphsFromOtherTypeface( *font.getTypeface(), 0, 256); // finally write the typeface into the destination file customTypeface.writeToStream(*destStream); String op; op << "\nWrote font " << fontName << " to file " << destFile.getFullPathName() << " successfully.\n\n"; std::cout << op; std::cout << "\n(You might want to use Binary Builder to turn this file into a c++ file now)\n\n "; shutdownSequence(destStream); return 0; }
void FileChooser::showPlatformDialog (Array<File>& results, const String& title, const File& file, const String& filters, bool isDirectory, bool /* selectsFiles */, bool isSave, bool /* warnAboutOverwritingExistingFiles */, bool selectMultipleFiles, FilePreviewComponent* /* previewComponent */) { String separator; StringArray args; const File previousWorkingDirectory (File::getCurrentWorkingDirectory()); const bool isKdeFullSession = SystemStats::getEnvironmentVariable ("KDE_FULL_SESSION", String::empty) .equalsIgnoreCase ("true"); if (exeIsAvailable ("kdialog") && (isKdeFullSession || ! exeIsAvailable ("zenity"))) { // use kdialog for KDE sessions or if zenity is missing args.add ("kdialog"); if (title.isNotEmpty()) args.add ("--title=" + title); if (selectMultipleFiles) { separator = "\n"; args.add ("--multiple"); args.add ("--separate-output"); args.add ("--getopenfilename"); } else { if (isSave) args.add ("--getsavefilename"); else if (isDirectory) args.add ("--getexistingdirectory"); else args.add ("--getopenfilename"); } String startPath; if (file.exists()) { startPath = file.getFullPathName(); } else if (file.getParentDirectory().exists()) { startPath = file.getParentDirectory().getFullPathName(); } else { startPath = File::getSpecialLocation (File::userHomeDirectory).getFullPathName(); if (isSave) startPath += "/" + file.getFileName(); } args.add (startPath); args.add (filters.replaceCharacter (';', ' ')); args.add ("2>/dev/null"); } else { // zenity args.add ("zenity"); args.add ("--file-selection"); if (title.isNotEmpty()) args.add ("--title=" + title); if (selectMultipleFiles) { separator = ":"; args.add ("--multiple"); args.add ("--separator=" + separator); } else { if (isDirectory) args.add ("--directory"); if (isSave) args.add ("--save"); } if (file.isDirectory()) file.setAsCurrentWorkingDirectory(); else if (file.getParentDirectory().exists()) file.getParentDirectory().setAsCurrentWorkingDirectory(); else File::getSpecialLocation (File::userHomeDirectory).setAsCurrentWorkingDirectory(); if (! file.getFileName().isEmpty()) args.add ("--filename=" + file.getFileName()); } ChildProcess child; if (child.start (args, ChildProcess::wantStdOut)) { const String result (child.readAllProcessOutput().trim()); if (result.isNotEmpty()) { StringArray tokens; if (selectMultipleFiles) tokens.addTokens (result, separator, "\""); else tokens.add (result); for (int i = 0; i < tokens.size(); ++i) results.add (File::getCurrentWorkingDirectory().getChildFile (tokens[i])); } child.waitForProcessToFinish (60 * 1000); } previousWorkingDirectory.setAsCurrentWorkingDirectory(); }
void Typeface::scanFolderForFonts (const File& folder) { FTTypefaceList::getInstance()->scanFontPaths (StringArray (folder.getFullPathName())); }
bool RecVolumes3::Restore(RAROptions *Cmd,const wchar *Name,bool Silent) { wchar ArcName[NM]; wcscpy(ArcName,Name); wchar *Ext=GetExt(ArcName); bool NewStyle=false; bool RevName=Ext!=NULL && wcsicomp(Ext,L".rev")==0; if (RevName) { for (int DigitGroup=0;Ext>ArcName && DigitGroup<3;Ext--) if (!IsDigit(*Ext)) if (IsDigit(*(Ext-1)) && (*Ext=='_' || DigitGroup<2)) DigitGroup++; else if (DigitGroup<2) { NewStyle=true; break; } while (IsDigit(*Ext) && Ext>ArcName+1) Ext--; wcscpy(Ext,L"*.*"); FindFile Find; Find.SetMask(ArcName); FindData fd; while (Find.Next(&fd)) { Archive Arc(Cmd); if (Arc.WOpen(fd.Name) && Arc.IsArchive(true)) { wcscpy(ArcName,fd.Name); break; } } } Archive Arc(Cmd); if (!Arc.WCheckOpen(ArcName)) return false; if (!Arc.Volume) { #ifndef SILENT Log(ArcName,St(MNotVolume),ArcName); #endif return false; } bool NewNumbering=Arc.NewNumbering; Arc.Close(); wchar *VolNumStart=VolNameToFirstName(ArcName,ArcName,NewNumbering); wchar RecVolMask[NM]; wcscpy(RecVolMask,ArcName); size_t BaseNamePartLength=VolNumStart-ArcName; wcscpy(RecVolMask+BaseNamePartLength,L"*.rev"); #ifndef SILENT int64 RecFileSize=0; #endif // We cannot display "Calculating CRC..." message here, because we do not // know if we'll find any recovery volumes. We'll display it after finding // the first recovery volume. bool CalcCRCMessageDone=false; FindFile Find; Find.SetMask(RecVolMask); FindData RecData; int FileNumber=0,RecVolNumber=0,FoundRecVolumes=0,MissingVolumes=0; wchar PrevName[NM]; while (Find.Next(&RecData)) { wchar *CurName=RecData.Name; int P[3]; if (!RevName && !NewStyle) { NewStyle=true; wchar *Dot=GetExt(CurName); if (Dot!=NULL) { int LineCount=0; Dot--; while (Dot>CurName && *Dot!='.') { if (*Dot=='_') LineCount++; Dot--; } if (LineCount==2) NewStyle=false; } } if (NewStyle) { if (!CalcCRCMessageDone) { #ifndef SILENT mprintf(St(MCalcCRCAllVol)); #endif CalcCRCMessageDone=true; } #ifndef SILENT mprintf(L"\n%s",CurName); #endif File CurFile; CurFile.TOpen(CurName); CurFile.Seek(0,SEEK_END); int64 Length=CurFile.Tell(); CurFile.Seek(Length-7,SEEK_SET); for (int I=0;I<3;I++) P[2-I]=CurFile.GetByte()+1; uint FileCRC=0; for (int I=0;I<4;I++) FileCRC|=CurFile.GetByte()<<(I*8); uint CalcCRC; CalcFileSum(&CurFile,&CalcCRC,NULL,Cmd->Threads,Length-4); if (FileCRC!=CalcCRC) { #ifndef SILENT mprintf(St(MCRCFailed),CurName); #endif continue; } } else { wchar *Dot=GetExt(CurName); if (Dot==NULL) continue; bool WrongParam=false; for (size_t I=0;I<ASIZE(P);I++) { do { Dot--; } while (IsDigit(*Dot) && Dot>=CurName+BaseNamePartLength); P[I]=atoiw(Dot+1); if (P[I]==0 || P[I]>255) WrongParam=true; } if (WrongParam) continue; } if (P[1]+P[2]>255) continue; if (RecVolNumber!=0 && RecVolNumber!=P[1] || FileNumber!=0 && FileNumber!=P[2]) { #ifndef SILENT Log(NULL,St(MRecVolDiffSets),CurName,PrevName); #endif return(false); } RecVolNumber=P[1]; FileNumber=P[2]; wcscpy(PrevName,CurName); File *NewFile=new File; NewFile->TOpen(CurName); SrcFile[FileNumber+P[0]-1]=NewFile; FoundRecVolumes++; #ifndef SILENT if (RecFileSize==0) RecFileSize=NewFile->FileLength(); #endif } #ifndef SILENT if (!Silent || FoundRecVolumes!=0) { mprintf(St(MRecVolFound),FoundRecVolumes); } #endif if (FoundRecVolumes==0) return(false); bool WriteFlags[256]; memset(WriteFlags,0,sizeof(WriteFlags)); wchar LastVolName[NM]; *LastVolName=0; for (int CurArcNum=0;CurArcNum<FileNumber;CurArcNum++) { Archive *NewFile=new Archive(Cmd); bool ValidVolume=FileExist(ArcName); if (ValidVolume) { NewFile->TOpen(ArcName); ValidVolume=NewFile->IsArchive(false); if (ValidVolume) { while (NewFile->ReadHeader()!=0) { if (NewFile->GetHeaderType()==HEAD_ENDARC) { #ifndef SILENT mprintf(L"\n%s",ArcName); #endif if (NewFile->EndArcHead.DataCRC) { uint CalcCRC; CalcFileSum(NewFile,&CalcCRC,NULL,Cmd->Threads,NewFile->CurBlockPos); if (NewFile->EndArcHead.ArcDataCRC!=CalcCRC) { ValidVolume=false; #ifndef SILENT mprintf(St(MCRCFailed),ArcName); #endif } } break; } NewFile->SeekToNext(); } } if (!ValidVolume) { NewFile->Close(); wchar NewName[NM]; wcscpy(NewName,ArcName); wcscat(NewName,L".bad"); #ifndef SILENT mprintf(St(MBadArc),ArcName); mprintf(St(MRenaming),ArcName,NewName); #endif RenameFile(ArcName,NewName); } NewFile->Seek(0,SEEK_SET); } if (!ValidVolume) { // It is important to return 'false' instead of aborting here, // so if we are called from extraction, we will be able to continue // extracting. It may happen if .rar and .rev are on read-only disks // like CDs. if (!NewFile->Create(ArcName)) { // We need to display the title of operation before the error message, // to make clear for user that create error is related to recovery // volumes. This is why we cannot use WCreate call here. Title must be // before create error, not after that. #ifndef SILENT mprintf(St(MReconstructing)); #endif ErrHandler.CreateErrorMsg(NULL,ArcName); return false; } WriteFlags[CurArcNum]=true; MissingVolumes++; if (CurArcNum==FileNumber-1) wcscpy(LastVolName,ArcName); #ifndef SILENT mprintf(St(MAbsNextVol),ArcName); #endif } SrcFile[CurArcNum]=(File*)NewFile; NextVolumeName(ArcName,ASIZE(ArcName),!NewNumbering); } #ifndef SILENT mprintf(St(MRecVolMissing),MissingVolumes); #endif if (MissingVolumes==0) { #ifndef SILENT mprintf(St(MRecVolAllExist)); #endif return false; } if (MissingVolumes>FoundRecVolumes) { #ifndef SILENT mprintf(St(MRecVolCannotFix)); #endif return false; } #ifndef SILENT mprintf(St(MReconstructing)); #endif int TotalFiles=FileNumber+RecVolNumber; int Erasures[256],EraSize=0; for (int I=0;I<TotalFiles;I++) if (WriteFlags[I] || SrcFile[I]==NULL) Erasures[EraSize++]=I; #ifndef SILENT int64 ProcessedSize=0; #ifndef GUI int LastPercent=-1; mprintf(L" "); #endif #endif // Size of per file buffer. size_t RecBufferSize=TotalBufferSize/TotalFiles; #ifdef RAR_SMP uint ThreadNumber=Cmd->Threads; RSEncode rse[MaxPoolThreads]; #else uint ThreadNumber=1; RSEncode rse[1]; #endif for (uint I=0;I<ThreadNumber;I++) rse[I].Init(RecVolNumber); while (true) { Wait(); int MaxRead=0; for (int I=0;I<TotalFiles;I++) if (WriteFlags[I] || SrcFile[I]==NULL) memset(&Buf[I*RecBufferSize],0,RecBufferSize); else { int ReadSize=SrcFile[I]->Read(&Buf[I*RecBufferSize],RecBufferSize); if ((size_t)ReadSize!=RecBufferSize) memset(&Buf[I*RecBufferSize+ReadSize],0,RecBufferSize-ReadSize); if (ReadSize>MaxRead) MaxRead=ReadSize; } if (MaxRead==0) break; #ifndef SILENT int CurPercent=ToPercent(ProcessedSize,RecFileSize); if (!Cmd->DisablePercentage && CurPercent!=LastPercent) { mprintf(L"\b\b\b\b%3d%%",CurPercent); LastPercent=CurPercent; } ProcessedSize+=MaxRead; #endif int BlockStart=0; int BlockSize=MaxRead/ThreadNumber; if (BlockSize<0x100) BlockSize=MaxRead; for (uint CurThread=0;BlockStart<MaxRead;CurThread++) { // Last thread processes all left data including increasement // from rounding error. if (CurThread==ThreadNumber-1) BlockSize=MaxRead-BlockStart; RSEncode *curenc=rse+CurThread; curenc->Buf=&Buf[0]; curenc->BufStart=BlockStart; curenc->BufEnd=BlockStart+BlockSize; curenc->FileNumber=TotalFiles; curenc->RecBufferSize=RecBufferSize; curenc->Erasures=Erasures; curenc->EraSize=EraSize; #ifdef RAR_SMP if (ThreadNumber>1) RSThreadPool->AddTask(RSDecodeThread,(void*)curenc); else curenc->DecodeBuf(); #else curenc->DecodeBuf(); #endif BlockStart+=BlockSize; } #ifdef RAR_SMP RSThreadPool->WaitDone(); #endif // RAR_SMP for (int I=0;I<FileNumber;I++) if (WriteFlags[I]) SrcFile[I]->Write(&Buf[I*RecBufferSize],MaxRead); } for (int I=0;I<RecVolNumber+FileNumber;I++) if (SrcFile[I]!=NULL) { File *CurFile=SrcFile[I]; if (NewStyle && WriteFlags[I]) { int64 Length=CurFile->Tell(); CurFile->Seek(Length-7,SEEK_SET); for (int J=0;J<7;J++) CurFile->PutByte(0); } CurFile->Close(); SrcFile[I]=NULL; } if (*LastVolName!=0) { // Truncate the last volume to its real size. Archive Arc(Cmd); if (Arc.Open(LastVolName,FMF_UPDATE) && Arc.IsArchive(true) && Arc.SearchBlock(HEAD_ENDARC)) { Arc.Seek(Arc.NextBlockPos,SEEK_SET); char Buf[8192]; int ReadSize=Arc.Read(Buf,sizeof(Buf)); int ZeroCount=0; while (ZeroCount<ReadSize && Buf[ZeroCount]==0) ZeroCount++; if (ZeroCount==ReadSize) { Arc.Seek(Arc.NextBlockPos,SEEK_SET); Arc.Truncate(); } } } #if !defined(GUI) && !defined(SILENT) if (!Cmd->DisablePercentage) mprintf(L"\b\b\b\b100%%"); if (!Silent && !Cmd->DisableDone) mprintf(St(MDone)); #endif return true; }
FileWithTime (const File& f) : file (f), time (f.getLastModificationTime()) {}
ControlPanel::ControlPanel(ProcessorGraph* graph_, AudioComponent* audio_) : graph(graph_), audio(audio_), initialize(true), open(false), lastEngineIndex(-1) { if (1) { font = Font("Paragraph", 13, Font::plain); // MemoryInputStream mis(BinaryData::misoserialized, BinaryData::misoserializedSize, false); // Typeface::Ptr typeface = new CustomTypeface(mis); // font = Font(typeface); // font.setHeight(15); } audioEditor = (AudioEditor*) graph->getAudioNode()->createEditor(); addAndMakeVisible(audioEditor); playButton = new PlayButton(); playButton->addListener(this); addAndMakeVisible(playButton); recordButton = new RecordButton(); recordButton->addListener(this); addAndMakeVisible(recordButton); masterClock = new Clock(); addAndMakeVisible(masterClock); cpuMeter = new CPUMeter(); addAndMakeVisible(cpuMeter); diskMeter = new DiskSpaceMeter(); addAndMakeVisible(diskMeter); cpb = new ControlPanelButton(this); addAndMakeVisible(cpb); recordSelector = new ComboBox(); recordSelector->addListener(this); for (int i =0; i < RecordEngineManager::getNumOfBuiltInEngines(); i++) { RecordEngineManager* rem = RecordEngineManager::createBuiltInEngineManager(i); recordSelector->addItem(rem->getName(),i+1); recordEngines.add(rem); } addChildComponent(recordSelector); recordOptionsButton = new UtilityButton("R",Font("Small Text", 15, Font::plain)); recordOptionsButton->setEnabledState(true); recordOptionsButton->addListener(this); recordOptionsButton->setTooltip("Configure options for selected record engine"); addChildComponent(recordOptionsButton); newDirectoryButton = new UtilityButton("+", Font("Small Text", 15, Font::plain)); newDirectoryButton->setEnabledState(false); newDirectoryButton->addListener(this); newDirectoryButton->setTooltip("Start a new data directory"); addChildComponent(newDirectoryButton); File executable = File::getSpecialLocation(File::currentExecutableFile); #if defined(__APPLE__) const String executableDirectory = executable.getParentDirectory().getParentDirectory().getParentDirectory().getParentDirectory().getFullPathName(); #else const String executableDirectory = executable.getParentDirectory().getFullPathName(); #endif filenameComponent = new FilenameComponent("folder selector", executableDirectory, true, true, true, "*", "", ""); addChildComponent(filenameComponent); prependText = new Label("Prepend",""); prependText->setEditable(true); prependText->addListener(this); prependText->setColour(Label::backgroundColourId, Colours::lightgrey); prependText->setTooltip("Prepend to name of data directory"); addChildComponent(prependText); dateText = new Label("Date","YYYY-MM-DD_HH-MM-SS"); dateText->setColour(Label::backgroundColourId, Colours::lightgrey); dateText->setColour(Label::textColourId, Colours::grey); addChildComponent(dateText); appendText = new Label("Append",""); appendText->setEditable(true); appendText->addListener(this); appendText->setColour(Label::backgroundColourId, Colours::lightgrey); addChildComponent(appendText); appendText->setTooltip("Append to name of data directory"); //diskMeter->updateDiskSpace(graph->getRecordNode()->getFreeSpace()); //diskMeter->repaint(); //refreshMeters(); startTimer(10); setWantsKeyboardFocus(true); backgroundColour = Colour(58,58,58); }
int main(int argc, char* argv[]) { Logger* log = Logger::getCurrentLogger(); String text("The quick brown fox jumps over the lazy dog."); File root(File::getSpecialLocation(File::userDesktopDirectory).getParentDirectory().getChildFile("./chapter03_03_tests")); File dir1(root.getChildFile ("1")); File dir2(root.getChildFile("2")); File dir1a(dir1.getChildFile("a")); File dir2b(dir2.getChildFile("b")); Result result(Result::ok()); result = dir1a.createDirectory(); if (!result.wasOk()) { log->writeToLog("Creating dir 1/a failed"); return -1; } result = dir2b.createDirectory(); if (!result.wasOk()) { log->writeToLog ("Creating dir 2/b failed"); return -1; } File rel = dir1a.getChildFile ("../../2/b"); File file(File::getSpecialLocation(File::currentExecutableFile).getParentDirectory().getChildFile("./chapter03_03_test.txt")); bool fileExists = file.exists(); if (!fileExists) { log->writeToLog("file " + file.getFileName() + " does not exist"); return -1; } Time creationTime = file.getCreationTime(); Time modTime = file.getLastModificationTime(); int64 size = file.getSize(); file.replaceWithText(text); String fileText = file.loadFileAsString(); log->writeToLog("fileText: " + fileText); log->writeToLog ("file " + file.getFileName() + " info:"); log->writeToLog ("created: " + creationTime.toString(true, true, true, true)); log->writeToLog ("modified:" + modTime.toString(true, true, true, true)); log->writeToLog ("size:" + String(size) + " bytes"); log->writeToLog ("file path: " + file.getFullPathName()); log->writeToLog ("folder path: " + root.getFullPathName()); log->writeToLog ("dir1: " + dir1.getRelativePathFrom (root)); log->writeToLog ("dir2: " + dir2.getRelativePathFrom (root)); log->writeToLog ("dir1a: " + dir1a.getRelativePathFrom (root)); log->writeToLog ("dir2b: " + dir2b.getRelativePathFrom (root)); log->writeToLog ("rel: " + rel.getRelativePathFrom (root)); File usrfile = File::getSpecialLocation (File::userDocumentsDirectory); Array<File> childFiles; bool searchRecursively = false; usrfile.findChildFiles(childFiles, File::findFilesAndDirectories, searchRecursively); for (int i=0; i<childFiles.size(); ++i) { log->writeToLog (childFiles[i].getFullPathName()); } StringArray strings; bool preserveQuoted = true; strings.addTokens("one two three four five six", preserveQuoted); for (int i=0; i<strings.size(); ++i) { log->writeToLog("strings[" + String(i) + "]=" + strings[i]); } return 0; }