void move_log_file(std::string const& logpath, std::string const& new_name, int instance) { mutex::scoped_lock l(file_mutex); if (open_filename == m_filename) { log_file.close(); open_filename.clear(); } char log_name[512]; snprintf(log_name, sizeof(log_name), "libtorrent_logs%d", instance); std::string dir(combine_path(combine_path(complete(logpath), log_name), new_name) + ".log"); error_code ec; create_directories(parent_path(dir), ec); if (ec) fprintf(stderr, "Failed to create logfile directory %s: %s\n" , parent_path(dir).c_str(), ec.message().c_str()); ec.clear(); rename(m_filename, dir, ec); if (ec) fprintf(stderr, "Failed to move logfile %s: %s\n" , parent_path(dir).c_str(), ec.message().c_str()); m_filename = dir; }
void add_files_impl(file_storage& fs, std::string const& p , std::string const& l, boost::function<bool(std::string)> pred, boost::uint32_t flags) { std::string f = combine_path(p, l); if (!pred(f)) return; error_code ec; file_status s; stat_file(f, &s, ec, (flags & create_torrent::symlinks) ? dont_follow_links : 0); if (ec) return; // recurse into directories bool recurse = (s.mode & file_status::directory) != 0; // if the file is not a link or we're following links, and it's a directory // only then should we recurse #ifndef TORRENT_WINDOWS if ((s.mode & file_status::link) && (flags & create_torrent::symlinks)) recurse = false; #endif if (recurse) { fs.add_path(parent_path(combine_path(l, "x")), s.mode & 0777); for (directory i(f, ec); !i.done(); i.next(ec)) { std::string leaf = i.file(); if (ignore_subdir(leaf)) continue; add_files_impl(fs, p, combine_path(l, leaf), pred, flags); } } else if (s.mode & (file_status::regular_file | file_status::link)) { // #error use the fields from s int file_flags = get_file_attributes(f, (flags & create_torrent::symlinks) ? dont_follow_links : 0); // mask all bits to check if the file is a symlink if ((file_flags & file_storage::attribute_symlink) && (flags & create_torrent::symlinks)) { std::string sym_path = get_symlink_path(f); fs.add_file(l, 0, file_flags, s.mtime, sym_path, s.mode & 0777); } else { fs.add_file(l, s.file_size, file_flags, s.mtime, "", s.mode & 0777); } } if (fs.num_files() == 0) fs.set_name(l); }
logger(std::string const& logpath, std::string const& filename , int instance, bool append) { char log_name[512]; snprintf(log_name, sizeof(log_name), "libtorrent_logs%d", instance); std::string dir(complete(combine_path(logpath, log_name))); error_code ec; if (!exists(dir)) create_directories(dir, ec); m_filename = combine_path(dir, filename); mutex::scoped_lock l(file_mutex); open(!append); log_file << "\n\n\n*** starting log ***\n"; }
void xfilepath::chg_workdir(const char *reldir) { if(!reldir || reldir[0]==0) return; char *iter, *end=m_path+FILENAME_MAX; iter=combine_path(m_wpos,m_path,end,reldir,&m_wpos); if(iter==end) { wyc_warn("path is too long: %s",reldir); goto RESET_PATH; } if(iter!=m_wpos) { *iter++=ms_splitter; if(iter==end) { wyc_warn("path is too long: %s",reldir); goto RESET_PATH; } m_wpos=iter; } *iter=0; m_size=iter-m_path; return; RESET_PATH: m_wpos=m_path; *m_wpos=0; m_size=0; }
bool file_utils::full_path(dynamic_string &path) { #if defined(PLATFORM_WINDOWS) char buf[1024]; char *p = _fullpath(buf, path.get_ptr(), sizeof(buf)); if (!p) return false; #else char buf[PATH_MAX]; char *p; dynamic_string pn, fn; split_path(path.get_ptr(), pn, fn); if ((fn == ".") || (fn == "..")) { p = realpath(path.get_ptr(), buf); if (!p) return false; path.set(buf); } else { if (pn.is_empty()) pn = "./"; p = realpath(pn.get_ptr(), buf); if (!p) return false; combine_path(path, buf, fn.get_ptr()); } #endif return true; }
//----------------------------------------------------------------------------- bool find_file( std::string& path_to_file, const std::string& file_to_find, const std::string& search_path, bool recursive ) { if( !path_exists( search_path ) ) return false; // search_path doesn't exist if( !is_directory( search_path ) ) return false;// search_path not a directory // search_path exists and is a directory // check the current path for the file std::string path = combine_path( search_path, file_to_find ); if( file_exists( path ) ) { path_to_file = path; return true; } // if not recursive, then failed to find file. if( !recursive ) return false; // otherwise enumerate all the subdirectories in the directory and search // within those locations. std::vector<std::string> child_dirs = get_subdirectories( search_path ); for( std::vector<std::string>::iterator it = child_dirs.begin(); it != child_dirs.end(); it++ ) { std::string sub_path = *it; try { bool result = find_file( path_to_file, file_to_find, sub_path, true ); if( result ) return result; } catch( std::exception ex ) { } } // otherwise failed to find file. return false; }
std::string file_storage::file_path(int index) const { TORRENT_ASSERT(index >= 0 && index < int(m_files.size())); internal_file_entry const& fe = m_files[index]; TORRENT_ASSERT(fe.path_index >= -1 && fe.path_index < int(m_paths.size())); if (fe.path_index == -1) return fe.filename(); return combine_path(m_paths[fe.path_index], fe.filename()); }
bool file_utils::get_pathname(const char *p, dynamic_string &path) { dynamic_string temp_drive, temp_path; if (!split_path(p, &temp_drive, &temp_path, NULL, NULL)) return false; combine_path(path, temp_drive.get_ptr(), temp_path.get_ptr()); return true; }
void file_utils::combine_path_and_extension(dynamic_string &dst, const char *pA, const char *pB, const char *pC, const char *pExt) { combine_path(dst, pA, pB, pC); if ((!dst.ends_with(".")) && (pExt[0]) && (pExt[0] != '.')) dst.append_char('.'); dst.append(pExt); }
bool file_utils::split_path(const char *p, dynamic_string &path, dynamic_string &filename) { dynamic_string temp_drive, temp_path, temp_ext; if (!split_path(p, &temp_drive, &temp_path, &filename, &temp_ext)) return false; filename += temp_ext; combine_path(path, temp_drive.get_ptr(), temp_path.get_ptr()); return true; }
//----------------------------------------------------------------------------- bool worker_c::load( boost::shared_ptr<Reveal::Analytics::module_c>& module, Reveal::Core::analyzer_ptr analyzer ) { Reveal::Core::system_c system( Reveal::Core::system_c::SERVER ); if( !system.open() ) { std::string errmsg = "ERROR: Failed to open system. Make sure the Reveal environment is properly configured"; Reveal::Core::console_c::error( errmsg ); return false; } std::string pkg_path = system.packages_path(); system.close(); Reveal::Analytics::error_e error; if( analyzer->type == Reveal::Core::analyzer_c::PLUGIN ) { // load analyzer as plugin boost::shared_ptr<Reveal::Analytics::plugin_c> plugin = boost::shared_ptr<Reveal::Analytics::plugin_c>( new Reveal::Analytics::plugin_c() ); module = boost::dynamic_pointer_cast<Reveal::Analytics::module_c>( plugin ); } else if( analyzer->type == Reveal::Core::analyzer_c::SCRIPT ) { // load analyzer as script boost::shared_ptr<Reveal::Analytics::script_c> script = boost::shared_ptr<Reveal::Analytics::script_c>( new Reveal::Analytics::script_c() ); module = boost::dynamic_pointer_cast<Reveal::Analytics::module_c>( script ); } else { return false; } // compose the filename of the module std::string path = combine_path( pkg_path, analyzer->build_path); path = combine_path( path, analyzer->build_target ); // load the module error = module->load( path ); if( error != Reveal::Analytics::ERROR_NONE ) { printf( "failed to load requested analyzer\n" ); return false; } return true; }
bool create_test_file( std::string directory, std::string file ) { std::stringstream ss; std::string path = combine_path( directory, file ); std::ofstream f( path.c_str() ); ss << "0123456789" << std::endl; std::string s = ss.str(); f.write( s.c_str(), s.size() ); f.close(); return true; }
static char *make_path(const char *dir, const char *filepath) { char buf[1024]; char *path; snprintf(buf, ARRAY_LENGTH(buf), "%s", dir); combine_path(buf, ARRAY_LENGTH(buf), filepath); path = (char*)malloc(strlen(buf) + 1); if (!path) return NULL; strcpy(path, buf); return path; }
void posix_storage::rename_file(file_index_t const index, std::string const& new_filename, storage_error& ec) { if (index < file_index_t(0) || index >= files().end_file()) return; std::string const old_name = files().file_path(index, m_save_path); if (exists(old_name, ec.ec)) { std::string new_path; if (is_complete(new_filename)) new_path = new_filename; else new_path = combine_path(m_save_path, new_filename); std::string new_dir = parent_path(new_path); // create any missing directories that the new filename // lands in create_directories(new_dir, ec.ec); if (ec.ec) { ec.file(index); ec.operation = operation_t::file_rename; return; } rename(old_name, new_path, ec.ec); if (ec.ec == boost::system::errc::no_such_file_or_directory) ec.ec.clear(); if (ec) { ec.file(index); ec.operation = operation_t::file_rename; return; } } else if (ec.ec) { // if exists fails, report that error ec.file(index); ec.operation = operation_t::file_rename; return; } if (!m_mapped_files) { m_mapped_files.reset(new file_storage(files())); } m_mapped_files->rename_file(index, new_filename); }
svector *search_text_file(const char *dir, const char *filename) { char *text_file; svector *vec; if(dir == NULL) // Possible if environment variable not set return NULL; text_file = combine_path(dir, filename); if(fexists(text_file)) { vec = do_load_text_file(text_file); delete[] text_file; return vec; } delete[] text_file; return NULL; }
void xfilepath::chg_fpath(const char *relpath) { if(!relpath || relpath[0]==0) return; char *iter, *end=m_path+FILENAME_MAX; iter=combine_path(m_wpos,m_path,end,relpath,&m_wpos); if(iter==end) { wyc_warn("path is too long: %s",relpath); goto RESET_PATH; } *iter=0; m_size=iter-m_path; return; RESET_PATH: m_wpos=m_path; *m_wpos=0; m_size=0; }
void remove_all(std::string const& f, error_code& ec) { ec.clear(); file_status s; stat_file(f, &s, ec); if (ec) return; if (s.mode & file_status::directory) { for (directory i(f, ec); !i.done(); i.next(ec)) { if (ec) return; std::string p = i.file(); if (p == "." || p == "..") continue; remove_all(combine_path(f, p), ec); if (ec) return; } } remove(f, ec); }
static void start_handler(void *data, const XML_Char *tagname, const XML_Char **attributes) { const char *title; const char *name; const char *filepath; const char *srcpath; const char *destpath; const char *datfile_foldername; struct system_info *sysinfo_array; int sys_count; char buf[512]; const char *sysname; char sysfilename[512]; char *datfile_path = NULL; char *s; FILE *datfile = NULL; FILE *sysfile = NULL; int lineno = 0; int i; int ul = FALSE; struct messdocs_state *state = (struct messdocs_state *) data; if (state->m_depth == 0) { /* help tag */ if (strcmp(tagname, "help")) { process_error(state, NULL, "Expected tag 'help'"); return; } title = find_attribute(attributes, "title"); if (title) state->m_title = pool_strdup_lib(state->m_pool, title); } else if (!strcmp(tagname, "topic")) { /* topic tag */ name = find_attribute(attributes, "text"); filepath = find_attribute(attributes, "filepath"); /* output TOC info */ fprintf(state->m_chm_toc, "\t<LI> <OBJECT type=\"text/sitemap\">\n"); fprintf(state->m_chm_toc, "\t\t<param name=\"Name\" value=\"%s\">\n", name); fprintf(state->m_chm_toc, "\t\t<param name=\"Local\" value=\"%s\">\n", filepath); fprintf(state->m_chm_toc, "\t\t</OBJECT>\n"); /* copy file */ copy_file_to_dest(state->m_dest_dir, state->m_toc_dir, filepath); if (!state->m_default_topic) state->m_default_topic = pool_strdup_lib(state->m_pool, filepath); } else if (!strcmp(tagname, "folder")) { /* folder tag */ name = find_attribute(attributes, "text"); fprintf(state->m_chm_toc, "\t<LI> <OBJECT type=\"text/sitemap\">\n"); fprintf(state->m_chm_toc, "\t\t<param name=\"Name\" value=\"%s\">\n", name); fprintf(state->m_chm_toc, "\t\t</OBJECT>\n"); fprintf(state->m_chm_toc, "\t\t<UL>\n"); } else if (!strcmp(tagname, "file")) { /* file tag */ filepath = find_attribute(attributes, "filepath"); copy_file_to_dest(state->m_dest_dir, state->m_toc_dir, filepath); } else if (!strcmp(tagname, "datfile")) { /* datfile tag */ srcpath = find_attribute(attributes, "srcpath"); destpath = find_attribute(attributes, "destpath"); datfile_foldername = find_attribute(attributes, "text"); datfile_path = make_path(state->m_toc_dir, srcpath); datfile = fopen(datfile_path, "r"); if (!datfile) { process_error(state, NULL, "Cannot open datfile '%s'\n", datfile_path); return; } snprintf(buf, ARRAY_LENGTH(buf), "%s", state->m_dest_dir); combine_path(buf, ARRAY_LENGTH(buf), destpath); osd_mkdir(buf); sysinfo_array = NULL; sys_count = 0; sysname = NULL; while(!feof(datfile)) { fgets(buf, ARRAY_LENGTH(buf), datfile); s = strchr(buf, '\n'); if (s) *s = '\0'; rtrim(buf); switch(buf[0]) { case '$': if (!strncmp(buf, "$info", 5)) { /* $info */ s = strchr(buf, '='); s = s ? s + 1 : &buf[strlen(buf)]; sysinfo_array = (system_info*)pool_realloc_lib(state->m_pool, sysinfo_array, sizeof(*sysinfo_array) * (sys_count + 1)); if (!sysinfo_array) goto outofmemory; sysinfo_array[sys_count].name = pool_strdup_lib(state->m_pool, s); sysinfo_array[sys_count].desc = NULL; sysname = sysinfo_array[sys_count].name; sys_count++; snprintf(sysfilename, sizeof(sysfilename), "%s%s%s%s%s.htm", state->m_dest_dir, PATH_SEPARATOR, destpath, PATH_SEPARATOR, s); if (sysfile) fclose(sysfile); sysfile = fopen(sysfilename, "w"); lineno = 0; } else if (!strncmp(buf, "$bio", 4)) { /* $bio */ } else if (!strncmp(buf, "$end", 4)) { /* $end */ } break; case '#': case '\0': /* comments */ break; default: /* normal line */ if (!sysfile) break; html_encode(buf, ARRAY_LENGTH(buf)); if (!strncmp(buf, "======", 6) && lineno == 0) { char *heading = (char*)malloc(strlen(buf) + 1); memset(heading, 0, strlen(buf) + 1); strncpy(heading, buf + 6, strlen(buf) - 12); fprintf(sysfile, "<h1>%s</h1>\n", heading); fprintf(sysfile, "<p><i>(directory: %s)</i></p>\n", sysname); if (!sysinfo_array[sys_count-1].desc) sysinfo_array[sys_count-1].desc = pool_strdup_lib(state->m_pool, heading); free(heading); } else if (buf[0] == '=') { int count; char *heading = (char*)malloc(strlen(buf) + 1); memset(heading, 0, strlen(buf) + 1); if (ul) { fprintf(sysfile, "</ul>"); ul = FALSE; } for (count = 0; buf[count] == '='; count++); strncpy(heading, buf + count, strlen(buf) - count*2); fprintf(sysfile, "<h%d>%s</h%d>\n", 7-count, heading, 7-count); free(heading); } else if (!strncmp(buf, " * ", 4)) { if (!ul) { fprintf(sysfile, "<ul>"); } ul = TRUE; fprintf(sysfile, "<li>%s</li>", buf + 4); } else { if (ul) { fprintf(sysfile, "</ul>"); ul = FALSE; } fprintf(sysfile, "%s\n", buf); } lineno++; break; } } /* now write out all toc */ qsort(sysinfo_array, sys_count, sizeof(*sysinfo_array), str_compare); fprintf(state->m_chm_toc, "\t<LI> <OBJECT type=\"text/sitemap\">\n"); fprintf(state->m_chm_toc, "\t\t<param name=\"Name\" value=\"%s\">\n", datfile_foldername); fprintf(state->m_chm_toc, "\t\t</OBJECT>\n"); fprintf(state->m_chm_toc, "\t\t<UL>\n"); for (i = 0; i < sys_count; i++) { fprintf(state->m_chm_toc, "\t<LI> <OBJECT type=\"text/sitemap\">\n"); fprintf(state->m_chm_toc, "\t\t<param name=\"Name\" value=\"%s\">\n", sysinfo_array[i].desc); fprintf(state->m_chm_toc, "\t\t<param name=\"Local\" value=\"%s%s%s.htm\">\n", destpath, PATH_SEPARATOR, sysinfo_array[i].name); fprintf(state->m_chm_toc, "\t\t</OBJECT>\n"); } fprintf(state->m_chm_toc, "\t\t</UL>\n"); } state->m_depth++; outofmemory: if (datfile_path) free(datfile_path); if (datfile) fclose(datfile); if (sysfile) fclose(sysfile); }
int main(int argc, char *argv[]) { int k; short sample_buffer[1024*MAX_CHANNELS]; int writeToStdio = 0, out_dir_set = 0; int def_sr_set = 0, use_ltp = 0; int def_srate; int showHelp = 0; char *fnp; int result; int first_time = 1; char out_dir[255]; char aacFileName[255]; char audioFileName[255]; FILE *sndfile; FILE *infile; faacDecHandle hDecoder; faacDecConfigurationPtr config; char percent[200]; long buffercount; unsigned long bytesconsumed, samples, fileread, bytecount; unsigned char *buffer; unsigned long samplerate, channels, tagsize; /* System dependant types */ #ifdef _WIN32 long begin, end; #else clock_t begin; #endif fprintf(stderr, "FAAD (Freeware AAC Decoder) Compiled on: " __DATE__ "\n"); fprintf(stderr, "FAAD homepage: %s\n", "http://www.audiocoding.com"); /* begin process command line */ progName = argv[0]; while (1) { int c = -1; int option_index = 0; static struct option long_options[] = { { "outputdir", 0, 0, 'o' }, { "samplerate", 0, 0, 's' }, { "ltp", 0, 0, 'l' }, { "stdio", 0, 0, 'w' }, { "help", 0, 0, 'h' } }; c = getopt_long(argc, argv, "o:s:whl", long_options, &option_index); if (c == -1) break; switch (c) { case 'o': { if (optarg) { char dr[255]; if (sscanf(optarg, "%s", dr) < 1) { out_dir_set = 0; } else { out_dir_set = 1; strcpy(out_dir, dr); } } else { out_dir_set = 0; } break; } case 's': { if (optarg) { char dr[255]; if (sscanf(optarg, "%s", dr) < 1) { def_sr_set = 0; } else { def_sr_set = 1; def_srate = atoi(dr); } } else { out_dir_set = 0; } break; } case 'w': { writeToStdio = 1; break; } case 'l': { use_ltp = 1; break; } case 'h': { showHelp = 1; break; } default: break; } } /* check that we have at least two non-option arguments */ /* Print help if requested */ if (((argc - optind) < 1) || showHelp) { usage(); return 1; } /* point to the specified file name */ strcpy(aacFileName, argv[optind]); #ifdef _WIN32 begin = GetTickCount(); #else begin = clock(); #endif buffer = (unsigned char*)malloc(768*MAX_CHANNELS); memset(buffer, 0, 768*MAX_CHANNELS); infile = fopen(aacFileName, "rb"); if (infile == NULL) { /* unable to open file */ fprintf(stderr, "Error opening file: %s\n", aacFileName); return 1; } fseek(infile, 0, SEEK_END); fileread = ftell(infile); fseek(infile, 0, SEEK_SET); buffercount = bytecount = 0; fread(buffer, 1, 768*MAX_CHANNELS, infile); tagsize = id3v2_tag(buffer); if (tagsize) { fseek(infile, tagsize, SEEK_SET); bytecount = tagsize; buffercount = 0; fread(buffer, 1, 768*MAX_CHANNELS, infile); } hDecoder = faacDecOpen(); /* Set the default object type and samplerate */ /* This is useful for RAW AAC files */ config = faacDecGetCurrentConfiguration(hDecoder); if (def_sr_set) config->defSampleRate = def_srate; if (use_ltp) config->defObjectType = LTP; faacDecSetConfiguration(hDecoder, config); if((buffercount = faacDecInit(hDecoder, buffer, &samplerate, &channels)) < 0) { /* If some error initializing occured, skip the file */ fprintf(stderr, "Error initializing decoder library.\n"); return 1; } if (buffercount > 0) { bytecount += buffercount; for (k = 0; k < (768*MAX_CHANNELS - buffercount); k++) buffer[k] = buffer[k + buffercount]; fread(buffer + (768*MAX_CHANNELS) - buffercount, 1, buffercount, infile); buffercount = 0; } fprintf(stderr, "Busy decoding %s", aacFileName); if (tagsize) fprintf(stderr, " (has ID3v2)\n"); else fprintf(stderr, "\n"); /* Only calculate the path and open the file for writing if we are not writing to stdout. */ if(!writeToStdio) { if (out_dir_set) combine_path(audioFileName, out_dir, aacFileName); else strcpy(audioFileName, aacFileName); fnp = (char *)strrchr(audioFileName,'.'); if (fnp) fnp[0] = '\0'; strcat(audioFileName, ".wav"); } first_time = 1; do { if (buffercount > 0) { for (k = 0; k < (768*MAX_CHANNELS - buffercount); k++) buffer[k] = buffer[k + buffercount]; fread(buffer + (768*MAX_CHANNELS) - buffercount, 1, buffercount, infile); buffercount = 0; } result = faacDecDecode(hDecoder, buffer, &bytesconsumed, sample_buffer, &samples); if (result == FAAD_FATAL_ERROR) fprintf(stderr, "Fatal error decoding file\n"); if (result == FAAD_ERROR) fprintf(stderr, "Error decoding frame\n"); buffercount += bytesconsumed; bytecount += bytesconsumed; if (bytecount >= fileread) result = 9999; /* to make sure it stops now */ sprintf(percent, "%.2f decoding %s.", min((double)(bytecount*100)/fileread,100), aacFileName); fprintf(stderr, "%s\r", percent); #ifdef _WIN32 SetConsoleTitle(percent); #endif if ((result == FAAD_OK) && (samples > 0)) { if(first_time) { first_time = 0; if(!writeToStdio) { sndfile = fopen(audioFileName, "w+b"); if (sndfile==NULL) { fprintf(stderr, "Unable to create the file << %s >>.\n", audioFileName); continue; } CreateWavHeader(sndfile, channels, samplerate, 16); } else { sndfile = stdout; } } fwrite(sample_buffer, sizeof(short), 1024*channels, sndfile); } } while (result <= FAAD_OK_CHUPDATE); faacDecClose(hDecoder); fclose(infile); if(!writeToStdio) UpdateWavHeader(sndfile); /* Only close if we are not writing to stdout */ if(!writeToStdio) if(sndfile) fclose(sndfile); #ifdef _WIN32 end = GetTickCount(); fprintf(stderr, "Decoding %s took: %d sec.\n", aacFileName, (end-begin)/1000); SetConsoleTitle("FAAD"); #else /* clock() grabs time since the start of the app but when we decode multiple files, each file has its own starttime (begin). */ fprintf(stderr, "Decoding %s took: %5.2f sec.\n", aacFileName, (float)(clock() - begin)/(float)CLOCKS_PER_SEC); #endif if (buffer) free(buffer); return 0; }
// 'top_level' is extracting the file for a single-file torrent. The // distinction is that the filename is found in "name" rather than // "path" // root_dir is the name of the torrent, unless this is a single file // torrent, in which case it's empty. bool extract_single_file(bdecode_node const& dict, file_storage& files , std::string const& root_dir, ptrdiff_t info_ptr_diff, bool top_level , int& pad_file_cnt, error_code& ec) { if (dict.type() != bdecode_node::dict_t) return false; boost::uint32_t file_flags = get_file_attributes(dict); // symlinks have an implied "size" of zero. i.e. they use up 0 bytes of // the torrent payload space boost::int64_t const file_size = (file_flags & file_storage::flag_symlink) ? 0 : dict.dict_find_int_value("length", -1); if (file_size < 0 ) { ec = errors::torrent_invalid_length; return false; } boost::int64_t const mtime = dict.dict_find_int_value("mtime", 0); std::string path = root_dir; std::string path_element; char const* filename = NULL; int filename_len = 0; if (top_level) { // prefer the name.utf-8 because if it exists, it is more likely to be // correctly encoded bdecode_node p = dict.dict_find_string("name.utf-8"); if (!p) p = dict.dict_find_string("name"); if (!p || p.string_length() == 0) { ec = errors::torrent_missing_name; return false; } filename = p.string_ptr() + info_ptr_diff; filename_len = p.string_length(); while (filename_len > 0 && filename[0] == TORRENT_SEPARATOR) { filename += 1; filename_len -= 1; } sanitize_append_path_element(path, p.string_ptr(), p.string_length()); } else { bdecode_node p = dict.dict_find_list("path.utf-8"); if (!p) p = dict.dict_find_list("path"); if (p && p.list_size() > 0) { std::size_t const orig_path_len = path.size(); int const preallocate = path.size() + path_length(p, ec); if (ec) return false; path.reserve(preallocate); for (int i = 0, end(p.list_size()); i < end; ++i) { bdecode_node e = p.list_at(i); if (i == end - 1) { filename = e.string_ptr() + info_ptr_diff; filename_len = e.string_length(); } while (filename_len > 0 && filename[0] == TORRENT_SEPARATOR) { filename += 1; filename_len -= 1; } sanitize_append_path_element(path, e.string_ptr(), e.string_length()); } // if all path elements were sanitized away, we need to use another // name instead if (path.size() == orig_path_len) { path += TORRENT_SEPARATOR; path += "_"; } } else if (file_flags & file_storage::flag_pad_file) { // pad files don't need a path element, we'll just store them // under the .pad directory char cnt[10]; snprintf(cnt, sizeof(cnt), "%d", pad_file_cnt); path = combine_path(".pad", cnt); ++pad_file_cnt; } else { ec = errors::torrent_missing_name; return false; } } // bitcomet pad file if (path.find("_____padding_file_") != std::string::npos) file_flags = file_storage::flag_pad_file; bdecode_node fh = dict.dict_find_string("sha1"); char const* filehash = NULL; if (fh && fh.string_length() == 20) filehash = fh.string_ptr() + info_ptr_diff; std::string symlink_path; if (file_flags & file_storage::flag_symlink) { if (bdecode_node s_p = dict.dict_find_list("symlink path")) { int const preallocate = path_length(s_p, ec); if (ec) return false; symlink_path.reserve(preallocate); for (int i = 0, end(s_p.list_size()); i < end; ++i) { bdecode_node const& n = s_p.list_at(i); sanitize_append_path_element(symlink_path, n.string_ptr() , n.string_length()); } } } else { file_flags &= ~file_storage::flag_symlink; } if (filename_len > path.length() || path.compare(path.size() - filename_len, filename_len, filename , filename_len) != 0) { // if the filename was sanitized and differ, clear it to just use path filename = NULL; filename_len = 0; } files.add_file_borrow(filename, filename_len, path, file_size, file_flags, filehash , mtime, symlink_path); return true; }
Config *init_paths(const char *talk_ref) { Config *config = new Config(); const char *sys_prefix = "/usr/local/share"; config->talk_path = replace_extension(talk_ref, "talk"); config->graph_path = replace_extension(talk_ref, "graph"); config->project_dir = get_path(talk_ref); config->latex_dir = replace_extension(talk_ref, "latex"); config->html_dir = replace_extension(talk_ref, "html"); config->sys_dir = combine_path(sys_prefix, "multitalk"); config->sys_image_dir = combine_path(config->sys_dir, "gfx"); config->sys_style_dir = combine_path(config->sys_dir, "styles"); config->sys_font_dir = combine_path(config->sys_dir, "fonts"); config->proj_style_dir = combine_path(config->project_dir, "styles"); config->proj_font_dir = combine_path(config->project_dir, "fonts"); config->sys_rc_dir = sdup("/etc"); config->caption = new char[strlen(config->talk_path) + 20]; sprintf(config->caption, "Multitalk - %s", config->talk_path); char *e = getenv("MULTITALK_DIR"); if(e == NULL) { config->env_dir = NULL; config->env_style_dir = NULL; config->env_font_dir = NULL; config->env_image_dir = NULL; } else { config->env_dir = sdup(e); config->env_style_dir = combine_path(config->env_dir, "styles"); config->env_font_dir = combine_path(config->env_dir, "fonts"); config->env_image_dir = combine_path(config->env_dir, "gfx"); } uid_t id; struct passwd *pw; id = getuid(); pw = getpwuid(id); if(pw == NULL) error("Can't lookup home directory"); config->home_dir = sdup(pw->pw_dir); config->home_style_dir = combine_path(config->home_dir, ".multitalk/styles"); config->home_font_dir = combine_path(config->home_dir, ".multitalk/fonts"); config->home_image_dir = combine_path(config->home_dir, ".multitalk/gfx"); config->home_rc_dir = combine_path(config->home_dir, ".multitalk"); if(debug & DEBUG_PATHS) { printf("=== Directories ===\n"); printf("talk_path = %s\n", config->talk_path); printf("project_dir = %s\n", config->project_dir); printf("latex_dir = %s\n", config->latex_dir); printf("html_dir = %s\n", config->html_dir); printf("sys_style_dir = %s\n", config->sys_style_dir); printf("home_style_dir = %s\n", config->home_style_dir); printf("===================\n"); } return config; }
void file_storage::optimize(int pad_file_limit, int alignment) { // it doesn't make any sense to pad files that // are smaller than one block if (pad_file_limit >= 0 && pad_file_limit < 0x4000) pad_file_limit = 0x4000; // also, it doesn't make any sense to pad files // that are smaller than the alignment, since they // won't get aligned anyway; they are used as padding if (pad_file_limit >= 0 && pad_file_limit < alignment) pad_file_limit = alignment; size_type off = 0; int padding_file = 0; for (std::vector<internal_file_entry>::iterator i = m_files.begin(); i != m_files.end(); ++i) { if ((off & (alignment-1)) == 0) { // this file position is aligned, pick the largest // available file to put here std::vector<internal_file_entry>::iterator best_match = std::max_element(i, m_files.end() , &compare_file_entry_size); if (best_match != i) { int index = file_index(*best_match); int cur_index = file_index(*i); reorder_file(index, cur_index); i = m_files.begin() + cur_index; } } else if (pad_file_limit >= 0 && i->size > pad_file_limit && i->pad_file == false) { // if we have pad files enabled, and this file is // not piece-aligned and the file size exceeds the // limit, and it's not a padding file itself. // so add a padding file in front of it int pad_size = alignment - (off & (alignment-1)); // find the largest file that fits in pad_size std::vector<internal_file_entry>::iterator best_match = m_files.end(); for (std::vector<internal_file_entry>::iterator j = i+1; j < m_files.end(); ++j) { if (j->size > pad_size) continue; if (best_match == m_files.end() || j->size > best_match->size) best_match = j; } if (best_match != m_files.end()) { // we found one // We cannot have found i, because i->size > pad_file_limit // which is forced to be no less than alignment. We only // look for files <= pad_size, which never is greater than // alignment TORRENT_ASSERT(best_match != i); int index = file_index(*best_match); int cur_index = file_index(*i); reorder_file(index, cur_index); i = m_files.begin() + cur_index; i->offset = off; off += i->size; continue; } // we could not find a file that fits in pad_size // add a padding file // note that i will be set to point to the // new pad file. Once we're done adding it, we need // to increment i to point to the current file again // first add the pad file to the end of the file list // then swap it in place. This minimizes the amount // of copying of internal_file_entry, which is somewhat // expensive (until we have move semantics) int cur_index = file_index(*i); int index = m_files.size(); m_files.push_back(internal_file_entry()); internal_file_entry& e = m_files.back(); // i may have been invalidated, refresh it i = m_files.begin() + cur_index; e.size = pad_size; e.offset = off; char name[30]; snprintf(name, sizeof(name), ".____padding_file/%d", padding_file); std::string path = combine_path(m_name, name); e.set_name(path.c_str()); e.pad_file = true; off += pad_size; ++padding_file; if (!m_mtime.empty()) m_mtime.resize(index + 1, 0); if (!m_file_hashes.empty()) m_file_hashes.resize(index + 1, NULL); if (!m_file_base.empty()) m_file_base.resize(index + 1, 0); reorder_file(index, cur_index); TORRENT_ASSERT((off & (alignment-1)) == 0); continue; } i->offset = off; off += i->size; } m_total_size = off; }
void file_utils::combine_path(dynamic_string &dst, const char *pA, const char *pB, const char *pC) { combine_path(dst, pA, pB); combine_path(dst, dst.get_ptr(), pC); }
void file_storage::optimize(int pad_file_limit) { // the main purpuse of padding is to optimize disk // I/O. This is a conservative memory page size assumption int alignment = 8*1024; // it doesn't make any sense to pad files that // are smaller than one piece if (pad_file_limit >= 0 && pad_file_limit < alignment) pad_file_limit = alignment; size_type off = 0; int padding_file = 0; for (std::vector<internal_file_entry>::iterator i = m_files.begin(); i != m_files.end(); ++i) { if ((off & (alignment-1)) == 0) { // this file position is aligned, pick the largest // available file to put here std::vector<internal_file_entry>::iterator best_match = std::max_element(i, m_files.end() , &compare_file_entry_size); if (best_match != i) { int index = file_index(*best_match); int cur_index = file_index(*i); reorder_file(index, cur_index); i = m_files.begin() + cur_index; } } else if (pad_file_limit >= 0 && (off & (alignment-1)) != 0 && i->size > pad_file_limit && i->pad_file == false) { // if we have pad files enabled, and this file is // not piece-aligned and the file size exceeds the // limit, and it's not a padding file itself. // so add a padding file in front of it int pad_size = alignment - (off & (alignment-1)); // find the largest file that fits in pad_size std::vector<internal_file_entry>::iterator best_match = m_files.end(); for (std::vector<internal_file_entry>::iterator j = i+1; j < m_files.end(); ++j) { if (j->size > pad_size) continue; if (best_match == m_files.end() || j->size > best_match->size) best_match = j; } if (best_match != m_files.end()) { // we found one // We cannot have found i, because i->size > pad_file_limit // which is forced to be no less than alignment. We only // look for files <= pad_size, which never is greater than // alignment TORRENT_ASSERT(best_match != i); int index = file_index(*best_match); int cur_index = file_index(*i); reorder_file(index, cur_index); i = m_files.begin() + cur_index; i->offset = off; off += i->size; continue; } // we could not find a file that fits in pad_size // add a padding file // note that i will be set to point to the // new pad file. Once we're done adding it, we need // to increment i to point to the current file again internal_file_entry e; i = m_files.insert(i, e); i->size = pad_size; i->offset = off; char name[30]; snprintf(name, sizeof(name), ".____padding_file/%d", padding_file); std::string path = combine_path(m_name, name); i->set_name(path.c_str()); i->pad_file = true; off += pad_size; ++padding_file; // skip the pad file we just added and point // at the current file again ++i; } i->offset = off; off += i->size; } m_total_size = off; }
std::string complete(std::string const& f) { if (is_complete(f)) return f; return combine_path(current_working_directory(), f); }
//----------------------------------------------------------------------------- int main( int argc, char* argv[] ) { std::string path; std::string temp_path, root_path; // names of files and directories std::string test_file = "test.txt"; std::string subdir1_name = "subdir1"; std::string subdir2_name = "subdir2"; std::string subsubdir1_name = "subsubdir1"; std::string subdir_test_file = "subtest.txt"; // get the current working path from the system std::string working_path = get_current_path(); // attempt to create a temporary directory if( !get_temp_directory( temp_path ) ) return 5; // temp path just reported to be successfully created. test existence method if( !path_exists( temp_path ) ) return 1; // temp path is a path to a directory, so test is_directory if( !is_directory( temp_path ) ) return 2; // create a file in the temp path if( !create_test_file( temp_path, test_file ) ) return 8; // already know temp path is not a file, so test is_file for negative case if( is_file( temp_path ) ) return 3; // test whether the is file method reports the test file correctly path = combine_path( temp_path, test_file ); if( !is_file( path ) ) return 3; // attempt to remove the temporary directory if( !remove_directory( temp_path ) ) return 6; //-- // get another temporary directory this time call it the root path if( !get_temp_directory( root_path ) ) return 7; // create a file in the root path if( !create_test_file( root_path, test_file ) ) return 8; // create a directory in the root path std::string subdir1_path = combine_path( root_path, subdir1_name ); if( !get_directory( subdir1_path ) ) return 9; // create another directory in the root path std::string subdir2_path = combine_path( root_path, subdir2_name ); if( !get_directory( subdir2_path ) ) return 9; // create a directory in the first child directory of the root path std::string subsubdir1_path = combine_path( subdir1_path, subsubdir1_name ); if( !get_directory( subsubdir1_path ) ) return 9; // create a file in the child of the child directory if( !create_test_file( subsubdir1_path, subdir_test_file ) ) return 8; /* // get the subdirectories of the root std::vector<std::string> dirs = get_subdirectories( root_path ); for( std::vector<std::string>::iterator it = dirs.begin(); it != dirs.end(); it++ ) { printf( "dir: %s\n", it->c_str() ); } */ // test find file without recursion. search for the test file in the root if( !find_file( path, test_file, root_path ) ) return 1; // validate the path returned from find file temp_path = combine_path( root_path, test_file ); if( temp_path != path ) return 1; // test find file with recursion. search for the subtest file in the dirs if( !find_file( path, subdir_test_file, root_path, true ) ) return 1; temp_path = combine_path( subsubdir1_path, subdir_test_file ); if( temp_path != path ) return 1; // clean up the root path if( !remove_directory( root_path ) ) return 6; if( find_file( path, "gzserver", "/usr/local", true ) ) { printf( "path: %s\n", path.c_str() ); } return 0; }
//----------------------------------------------------------------------------- bool service_c::init( void ) { // open the system Reveal::Core::system_c system( Reveal::Core::system_c::SERVER ); if( !system.open() ) { std::string errmsg = "ERROR: Failed to open system. Make sure the Reveal environment is properly configured"; Reveal::Core::console_c::error( errmsg ); return false; } // get system environmental parameters unsigned port = system.samples_port(); std::string pkg_path = system.packages_path(); // close the system system.close(); // open the database boost::shared_ptr<Reveal::DB::database_c> db( new Reveal::DB::database_c() ); if( !db->open() ) { std::string errmsg = "ERROR: Failed to open database."; Reveal::Core::console_c::error( errmsg ); return false; } // fetch the list of analyzer plugins std::vector<Reveal::Core::analyzer_ptr> analyzers; db->fetch( analyzers ); // compile all analyzer plugins for( unsigned i = 0; i < analyzers.size(); i++ ) { // if not a plugin, then skip compiling if( analyzers[i]->type != Reveal::Core::analyzer_c::PLUGIN ) continue; std::string rel_src_path = analyzers[i]->source_path; std::string rel_build_path = analyzers[i]->build_path; std::string file_name = analyzers[i]->build_target; std::string rel_library_path = combine_path( rel_build_path, file_name ); std::string src_path = combine_path( pkg_path, rel_src_path ); std::string build_path = combine_path( pkg_path, rel_build_path ); std::string library_path = combine_path( pkg_path, rel_library_path ); printf( "src_path[%s], build_path[%s], library_path[%s]\n", src_path.c_str(), build_path.c_str(), library_path.c_str() ); std::vector<std::string> build_products; build_products.push_back( file_name ); if( !path_exists( src_path ) ) { std::cerr << "ERROR: Unable to locate the analyzer path." << std::endl; continue; } if( !get_directory( build_path ) ) { std::cerr << "ERROR: Unable to open the analyzer build path." << std::endl; continue; } Reveal::Core::package_ptr package( new Reveal::Core::package_c( src_path, build_path ) ); // configure package bool cmake_result = package->configure(); if( !cmake_result ) { printf( "ERROR: Failed to configure make for analyzer plugin\nExiting\n" ); continue; } else { printf( "Package configuration succeeded\n" ); } // build package bool make_result = package->make( build_products ); if( !make_result ) { printf( "ERROR: Failed to build analyzer plugin\nExiting\n" ); continue; } else { printf( "Built package\n" ); } } // open IPC Reveal::Samples::exchange_c exchange; exchange.open(); _clientconnection = Reveal::Core::connection_c( port ); if( _clientconnection.open() != Reveal::Core::connection_c::ERROR_NONE ) { printf( "Failed to open clientconnection\n" ); return false; } _workerconnection = Reveal::Core::connection_c( Reveal::Core::connection_c::DEALER, _clientconnection.context() ); if( _workerconnection.open() != Reveal::Core::connection_c::ERROR_NONE ) { printf( "Failed to open workerconnection\n" ); return false; } // spawn worker threads and set them to work void* context = _clientconnection.context(); for( unsigned i = 0; i < MAX_CLIENT_WORKERS; i++ ) { pthread_t workerthread; pthread_create( &workerthread, NULL, service_c::worker_thread, context ); workers.push_back( workerthread ); } printf( "Server is listening...\n" ); return true; }
boost::intrusive_ptr<file> file_pool::open_file(void* st, std::string const& p , file_storage::iterator fe, file_storage const& fs, int m, error_code& ec) { TORRENT_ASSERT(st != 0); TORRENT_ASSERT(is_complete(p)); TORRENT_ASSERT((m & file::rw_mask) == file::read_only || (m & file::rw_mask) == file::read_write); mutex::scoped_lock l(m_mutex); file_set::iterator i = m_files.find(std::make_pair(st, fs.file_index(*fe))); if (i != m_files.end()) { lru_file_entry& e = i->second; e.last_use = time_now(); if (e.key != st && ((e.mode & file::rw_mask) != file::read_only || (m & file::rw_mask) != file::read_only)) { // this means that another instance of the storage // is using the exact same file. #if BOOST_VERSION >= 103500 ec = errors::file_collision; #endif return boost::intrusive_ptr<file>(); } e.key = st; // if we asked for a file in write mode, // and the cached file is is not opened in // write mode, re-open it if ((((e.mode & file::rw_mask) != file::read_write) && ((m & file::rw_mask) == file::read_write)) || (e.mode & file::no_buffer) != (m & file::no_buffer) || (e.mode & file::random_access) != (m & file::random_access)) { // close the file before we open it with // the new read/write privilages TORRENT_ASSERT(e.file_ptr->refcount() == 1); #if TORRENT_CLOSE_MAY_BLOCK mutex::scoped_lock l(m_closer_mutex); m_queued_for_close.push_back(e.file_ptr); l.unlock(); e.file_ptr = new file; #else e.file_ptr->close(); #endif std::string full_path = combine_path(p, fs.file_path(*fe)); if (!e.file_ptr->open(full_path, m, ec)) { m_files.erase(i); return boost::intrusive_ptr<file>(); } #ifdef TORRENT_WINDOWS // file prio is supported on vista and up #if _WIN32_WINNT >= 0x0600 if (m_low_prio_io) { // TODO: load this function dynamically from Kernel32.dll FILE_IO_PRIORITY_HINT_INFO priorityHint; priorityHint.PriorityHint = IoPriorityHintLow; SetFileInformationByHandle(e.file_ptr->native_handle(), FileIoPriorityHintInfo, &priorityHint, sizeof(PriorityHint)); } #endif #endif TORRENT_ASSERT(e.file_ptr->is_open()); e.mode = m; } TORRENT_ASSERT((e.mode & file::no_buffer) == (m & file::no_buffer)); return e.file_ptr; } // the file is not in our cache if ((int)m_files.size() >= m_size) { // the file cache is at its maximum size, close // the least recently used (lru) file from it remove_oldest(); } lru_file_entry e; e.file_ptr.reset(new (std::nothrow)file); if (!e.file_ptr) { ec = error_code(ENOMEM, get_posix_category()); return e.file_ptr; } std::string full_path = combine_path(p, fs.file_path(*fe)); if (!e.file_ptr->open(full_path, m, ec)) return boost::intrusive_ptr<file>(); e.mode = m; e.key = st; m_files.insert(std::make_pair(std::make_pair(st, fs.file_index(*fe)), e)); TORRENT_ASSERT(e.file_ptr->is_open()); return e.file_ptr; }