/** Function to create a directory path for a file. \param[in] path Path to create. The final part is the file name and is not created. \param[in] pathDepth This determines how much of the path to assume exists before attempting to create directories: pathDepth = 0 create no directories pathDepth = 1 create all directories needed (i.e. only assume root directory exists). pathDepth = 2 Assume 1 directory below the root directory exists pathDepth = -1 Assume all but one directory exists pathDepth = -2 Assume all but two directories exist. */ asynStatus asynNDArrayDriver::createFilePath(const char *path, int pathDepth) { asynStatus result = asynSuccess; char *parts[MAX_PATH_PARTS]; int num_parts; char directory[MAX_FILENAME_LEN]; // Initialise the directory to create char nextDir[MAX_FILENAME_LEN]; // Extract the next name from the directory char* saveptr; int i=0; // Check for trivial case. if (pathDepth == 0) return asynSuccess; // Check for Windows disk designator if (path[1] == ':') { nextDir[0]=path[0]; nextDir[1]=':'; i+=2; } // Skip over any more delimiters while ((path[i] == '/' || path[i] == '\\') && i < MAX_FILENAME_LEN) { nextDir[i] = path[i]; ++i; } nextDir[i] = 0; // Now, tokenise the path - first making a copy because strtok is destructive strcpy(directory, &path[i] ); num_parts = 0; parts[num_parts] = strtok_r( directory, "\\/", &saveptr); while ( parts[num_parts] != NULL ) { parts[++num_parts] = strtok_r(NULL, "\\/", &saveptr); } // Handle the case if the path depth is negative if (pathDepth < 0) { pathDepth = num_parts + pathDepth; if (pathDepth < 1) pathDepth = 1; } // Loop through parts creating directories for ( i = 0; i < num_parts && result != asynError; i++ ) { strcat(nextDir, parts[i]); if ( i >= pathDepth ) { if(MKDIR(nextDir, 0777) != 0 && errno != EEXIST) { result = asynError; } } strcat(nextDir, delim); } return result; }
void Unpup(const char* folder){ u32 i; char folder_2[200]; if(read_only!=1){ for(i=0;;i++){ sprintf(folder_2,"%s_%u",folder,i); MKDIR(folder_2, 0777); if (chdir(folder_2) != 0){ }else{ break; } } } const char *file_name; if(read_only!=0) printf("Read Only Mode!\n"); printf("Reading...\n"); u64 HDR = be64(pup); if(HDR!=PSV_HDR) fail("\nERROR! Not a PlayStation Vita Update File (%08x%08x)",HDR>>32,HDR); u32 pkg_version = le32(pup+0x08); u32 img_version = le32(pup+0x10); file_count = le32(pup+0x18); u32 hdr_lenght = le32(pup+0x20); u32 pkg_lenght = le32(pup+0x28); dmsg("HDR 0x%08x%08x\n",HDR>>32,HDR); dmsg("PKG VERSION 0x%08x\n",pkg_version); dmsg("IMG VERSION 0x%08x\n",img_version); printf("N of Files %u\n",file_count); dmsg("HDR Lenght 0x%08x\n",hdr_lenght); dmsg("PKG Lenght 0x%08x\n",pkg_lenght); dmsg("Table Lenght 0x%08x\n",0x80+(0x20*file_count)); u32 entry,offset,size; for(i=0;i<file_count;i+=0x1){ entry = le32(pup+0x80+0x20*i); offset = le32(pup+0x80+0x20*i+0x08); size = le32(pup+0x80+0x20*i+0x10); file_name = id2name(entry, t_names, NULL); if(file_name==NULL) fail("unknown entry id: 0x%08x | Offset: 0x%08x ",entry,offset); // dmsg("Offset: %08x ",offset); printf("Found: %20s | size: %10u Bytes\n",file_name,size); if(read_only!=1) memcpy_to_file(file_name, pup + offset, size); } if(read_only!=1){ dmsg("Writing security_1.."); Write("security_1",0x30,0x50); } printf("Done!\n"); }
char * ChangeToDir (const char *Dirname) { STRUCT_STAT st; if (STAT(Dirname, &st)) { // doen't exist; must create it MKDIR (Dirname); } if (S_ISDIR(st.st_mode) == 0) { // it's not a dir, must create a dir MKDIR (Dirname); } char *oldDirname = GetCurrDir (); CHDIR(Dirname); return oldDirname; }
/* make directories. make parent directories as needed, with no error if * the path already exists */ static int mkdir_p(const char *path, mode_t mode) { struct stat st; const char *e; char *p = NULL; char tmp[1024]; size_t len; int r; /* ensure the path is valid */ if (!(e = strrchr(path, '/'))) return -EINVAL; /* ensure path is a directory */ r = stat(path, &st); if (r == 0 && !S_ISDIR(st.st_mode)) return -ENOTDIR; /* copy the pathname */ snprintf(tmp, sizeof(tmp), "%s", path); len = strlen(tmp); if (tmp[len - 1] == '/') tmp[len - 1] = 0; /* iterate mkdir over the path */ for (p = tmp + 1; *p; p++) if (*p == '/') { *p = 0; r = MKDIR(tmp, mode); if (r < 0 && errno != EEXIST) return -errno; *p = '/'; } /* try to make the whole path */ r = MKDIR(tmp, mode); if (r < 0 && errno != EEXIST) return -errno; /* creation successful or the file already exists */ return EXIT_SUCCESS; }
int savegame_simple () { char home[MAX_PATH], path[MAX_PATH]; if (get_app_dir (home, MAX_PATH) < 0) { message_box ("Couldn't save game."); return err_BadFileOpen; } sprintf (path, "%s/" DATA_DIR "/", home); MKDIR (path, 0755); sprintf (path, "%s/" DATA_DIR "/%05X.%s/", home, game.crc, game.id); MKDIR (path, 0711); sprintf (path, "%s/" DATA_DIR "/%05X.%s/%08d.sav", home, game.crc, game.id, 0); save_game (path, "Default savegame"); return err_OK; }
jm_status_enu_t jm_mkdir(jm_callbacks* cb, const char* dir) { if(!cb) { cb = jm_get_default_callbacks(); } if(MKDIR(dir)) { jm_log_fatal(cb,module,"Could not create directory %s", dir); return jm_status_error; } else return jm_status_success; }
int trap_MakeDirectory(lua_State *s) { const char *dir; trap_args(s, "MakeDirectory", "s", &dir); dir = datapath(dir); if (MKDIR(dir)) { FATAL("Failed to make directory: %s", dir); } return 0; }
/* check if config directory exists; if not create it and set config_dir */ void config_check_dir() { char level_dir[512]; snprintf( config.dir_name, sizeof(config.dir_name)-1, "%s/%s", (getenv( "HOME" )?getenv( "HOME" ):"."), CONFIG_DIR_NAME ); /* test and create .lgames */ if ( opendir( config.dir_name ) == 0 ) { fprintf( stderr, "couldn't find/open config directory '%s'\n", config.dir_name ); fprintf( stderr, "attempting to create it... " ); MKDIR( config.dir_name, S_IRWXU ); if ( opendir( config.dir_name ) == 0 ) fprintf( stderr, "failed\n" ); else fprintf( stderr, "ok\n" ); } /* create levels directory */ sprintf( level_dir, "%s/lbreakout2-levels", config.dir_name ); MKDIR( level_dir, S_IRWXU ); /* create themes directory */ sprintf( level_dir, "%s/lbreakout2-themes", config.dir_name ); MKDIR( level_dir, S_IRWXU ); }
void mkdirs(int oklen, char* path) { if (strlen(path) <= oklen) return; char dir[PATH_MAX]; strcpy(dir, path); char* slash = strrchr(dir, '/'); if (slash == 0) return; *slash = 0; mkdirs(oklen, dir); MKDIR(dir); }
void test_app_manager::test1(void) { _START(); _INFO("Verify of internal class nnAppManager:load and display a draw"); _AUTHOR("Coppi Angelo n2draw library "); _STOP(); nnAppManager app; #ifdef _UNICODE STRING name(X("conf_utf16.xml")); #else STRING name(X("conf_utf8.xml")); #endif STRING path("./"); IChild *childs = app.createObjects(name,path); CA_ASSERT(childs != nullptr); bool res; nnPoint p=childs->getView()->getConstPhy(); CA_ASSERT(p.x != 0 ); CA_ASSERT(p.y != 0); res=childs->getImage()->loadImages(); CA_ASSERT(res == true); nnContactNO *v = new nnContactNO(); nnObjManager *mn = dynamic_cast<nnObjManager *>(childs->getManager()); res = mn->addContact(10, 0, v); CA_ASSERT(res == true); CA_ASSERT((int)mn->size() == (int)1); nnGenericCoil *u = new nnGenericCoil(); res = mn->addCoil(10, u); CA_ASSERT(res == true); CA_ASSERT((int)mn->size() == (int)20); nnContactNC *v1 = new nnContactNC(); res = mn->addContact(12, 0, v1); CA_ASSERT(res == true); nnPoint p1(12, 0); nnPoint p2(10, 0); nnConnection::connectComponent(childs->getManager(), p1, p2); res = childs->getView()->updateDraw(); CA_ASSERT(res == true); bmpImage &bdraw = childs->getView()->getDraw(); for(unsigned int i=0;i<bdraw.getWidth();i+=100) bdraw.line(i,0,i,bdraw.getHeight(),255,0,0,0xfefefefe); for(unsigned int u=0;u<bdraw.getHeight();u+=100) bdraw.line(0,u,bdraw.getWidth(),u,0,0,255,0xfefefefe); bdraw.line(0,0,bdraw.getWidth(),bdraw.getHeight(),0,255,0,0xfefefefe); bdraw.line(0,0,200,bdraw.getHeight(),0,255,255,0xfefefefe); bdraw.frameRect(10,10,300,300,128,128,64,0xfefefefe); bdraw.frameRect(50,50,250,250,128,128,64,0xfefefefe); draw(&bdraw); MKDIR(".\\bmp",S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH); bdraw.copyToFile(X(".\\bmp\\test1_app.bmp")); }
int32_t FileUtil::create_directories(const char* path) { int i = 0; int ret; int len; char* path_copy; if (NULL == path) { return 0; } path_copy = strdup(path); len = strlen(path_copy); for (i = 0; i < len; i ++) { if ('\\' == path_copy[i] || '/' == path_copy[i]) { path_copy[i] = '\0'; ret = access(path_copy, 0); if (ret != 0) { ret = MKDIR(path_copy); if (ret != 0) { return -1; } } path_copy[i] = '/'; } } ret = access(path_copy, 0); if (ret != 0) { ret = MKDIR(path_copy); } free(path_copy); return ret; }
static int makedir(const char *newdir) { char *buffer; char *p; int len = (int)strlen(newdir); if (len <= 0) return 0; buffer = (char*)malloc(len+1); strcpy(buffer,newdir); if (buffer[len-1] == '/') { buffer[len-1] = '\0'; } if (MKDIR(buffer) == 0) { free(buffer); return 1; } p = buffer+1; while (1) { char hold; while(*p && *p != '\\' && *p != '/') p++; hold = *p; *p = 0; if ((MKDIR(buffer) == -1) && (errno == ENOENT)) { printf("couldn't create directory %s\n",buffer); free(buffer); return 0; } if (hold == 0) break; *p++ = hold; } free(buffer); return 1; }
static void recursive_mkdir(const char *dir) { char tmp[256]; char *p = NULL; size_t len; snprintf(tmp, sizeof(tmp), "%s", dir); len = strlen(tmp); if (tmp[len - 1] == '/') tmp[len - 1] = 0; for(p = tmp + 1; *p; p++) { if (*p == '/') { *p = 0; MKDIR(tmp); *p = '/'; } } MKDIR(tmp); }
void InitHomeDir(void) { const std::string & home = Settings::GetHomeDir(); if(! home.empty()) { const std::string home_maps = home + SEPARATOR + std::string("maps"); const std::string home_files = home + SEPARATOR + std::string("files"); const std::string home_files_save = home_files + SEPARATOR + std::string("save"); if(! IsDirectory(home)) MKDIR(home.c_str()); if(IsDirectory(home, true) && ! IsDirectory(home_maps)) MKDIR(home_maps.c_str()); if(IsDirectory(home, true) && ! IsDirectory(home_files)) MKDIR(home_files.c_str()); if(IsDirectory(home_files, true) && ! IsDirectory(home_files_save)) MKDIR(home_files_save.c_str()); } }
void ArkHdrPair::CreateBaseDirs(const char* baseDirpath) const { // ensure base dirs exist char dirpath[260]; for(int i=0; baseDirpath[i]!='\0'; i++) { if( (baseDirpath[i] == '\\') || (baseDirpath[i] == '/') ) { strcpy(dirpath, baseDirpath); dirpath[i] = '\0'; MKDIR(dirpath); } } }
bool ox_dir_create(const char* dir) { bool ret = false; if(ox_file_access(dir)) { ret = true; } else { ret = (MKDIR(dir)) == 0; } return ret; }
int savegame_simple () { char home[MAX_PATH], path[MAX_PATH]; #ifdef DREAMCAST uint8 addr, port, unit; addr = maple_first_vmu(); if(addr) { maple_create_port(addr, &port, &unit); sprintf(g_vmu_port, "%c%d", port + 'a', unit); } else { message_box("No VMU found."); return err_OK; } sprintf(path, VMU_PATH, g_vmu_port, game.id, slot); fs_unlink(path); #else if (get_app_dir (home, MAX_PATH) < 0) { message_box ("Couldn't save game."); return err_BadFileOpen; } sprintf (path, "%s/" DATA_DIR "/", home); MKDIR (path, 0755); sprintf (path, "%s/" DATA_DIR "/%05X.%s/", home, game.crc, game.id); MKDIR (path, 0711); sprintf (path, "%s/" DATA_DIR "/%05X.%s/%08d.sav", home, game.crc, game.id, 0); #endif printf("here?\n"); save_game (path, "Default savegame"); return err_OK; }
IO_METHOD(IoDirectory, create) { /*doc Directory create Create the directory if it doesn't exist. Returns self on success (or if the directory already exists), nil on failure. */ if (!opendir(CSTRING(DATA(self)->path))) { // not there, so make it int r = MKDIR(CSTRING(DATA(self)->path), S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH); return (r == 0) ? self : IONIL(self); } return self; }
static int pmkdir(const char *path, int perm) { char dpath[TQSL_MAX_PATH_LEN]; char npath[TQSL_MAX_PATH_LEN]; char *cp; strncpy(dpath, path, sizeof dpath); cp = strtok(dpath, "/\\"); npath[0] = 0; while (cp) { if (strlen(cp) > 0 && cp[strlen(cp)-1] != ':') { strcat(npath, "/"); strcat(npath, cp); if (MKDIR(npath, perm) != 0 && errno != EEXIST) return 1; } else strcat(npath, cp); cp = strtok(NULL, "/\\"); } return 0; }
void makedirs(const char* dir) { if (nullptr == dir) return; size_t len = strlen(dir); char * p = new char[len+1]; strcpy(p,dir); for (size_t i = 0; i<len; ++i) { char ch = p[i]; if ('\\' == ch ||'/' == ch) { p[i] = '\0'; MKDIR(p); p[i] = ch; } } delete[] p; }
// create a directory in current working directory or at specified path int createDir() { int i = 0; int error = 0; char xdir[FNBUFSIZE] = {'\0'}; //extraction path and dir if(strlen(out_path) == 0) strcat(out_path, "./"); else { char c = out_path[ strlen(out_path) - 1]; if( c != '/' && c != '\\' ) //make sure string ends with slash strcat(out_path, "/"); } strcat(out_path, "AUDIORIP_"); do { mkfname(i, 3, xdir, out_path, xdir_suffix); error = MKDIR(xdir); if(((error != 0) && (errno != EEXIST)) || (i > 999)) { cout << "Can't create extraction dir: \"" << xdir << "\""<< endl;; switch(errno) { case(EACCES) : cout << "Write permission is denied for the parent directory in which the new directory is to be added."; break; case(EMLINK) : cout << "The parent directory has too many links (entries)."; break; case(ENAMETOOLONG) : cout << "Path or name to long."; break; case(ENOENT) : cout << "A component of the path prefix does not name an existing directory."; break; case(ENOSPC) : cout << "The file system doesn't have enough room to create the new directory."; break; case(EROFS) : cout << "The parent directory of the directory being created is on a read-only file system and cannot be modified."; break; default : cout << strerror(errno); break; } cout << endl; return -1; } i++; } while(error!=0); strcat(xdir,"/"); strcpy(out_path, xdir); return 0; }
bool KDirectory::createFileDir(const KData& dir) { int pos = 0; while (true) { if ((pos = dir.find("/", pos)) == -1) break; KData dtDir = dir.substr(0, pos); pos++; if (!dtDir.isEmpty()) { if (!isDirectoryExist(dtDir)) { if (MKDIR(dtDir.getData()) != 0) { return false; } } } } return true; }
GSM_Error DUMMY_AddFolder(GSM_StateMachine *s, GSM_File *File) { char *path; size_t pos; pos = UnicodeLength(File->ID_FullName); if (pos > 0 && (File->ID_FullName[2*pos - 2] != 0 || File->ID_FullName[2*pos - 1] != '/')) { File->ID_FullName[2*pos + 1] = '/'; File->ID_FullName[2*pos + 0] = 0; pos++; } CopyUnicodeString(File->ID_FullName + 2 * pos, File->Name); path = DUMMY_GetFSFilePath(s, File->ID_FullName); if (MKDIR(path) != 0) { free(path); path=NULL; return DUMMY_Error(s, "mkdir failed"); } free(path); path=NULL; return ERR_NONE; }
static void unpack_pkg(void) { u64 i; u64 n_files; u32 fname_len; u32 fname_off; u64 file_offset; u32 flags; char fname[256]; u8 *tmp; n_files = be32(pkg + 0x14); for (i = 0; i < n_files; i++) { tmp = pkg + offset + i*0x20; fname_off = be32(tmp) + offset; fname_len = be32(tmp + 0x04); file_offset = be64(tmp + 0x08) + offset; size = be64(tmp + 0x10); flags = be32(tmp + 0x18); if (fname_len >= sizeof fname) fail("filename too long: %s", pkg + fname_off); memset(fname, 0, sizeof fname); strncpy(fname, (char *)(pkg + fname_off), fname_len); flags &= 0xff; if (flags == 4) MKDIR(fname, 0777); else if (flags == 1 || flags == 3) memcpy_to_file(fname, pkg + file_offset, size); else fail("unknown flags: %08x", flags); } }
int main(int argc, char *argv[]) { bool didhelp = false; feature_recorder::set_main_threadid(); #ifdef BROKEN std::cerr << "WARNING: YOU ARE USING AN EXPERIMENTAL VERSION OF TCPFLOW \n"; std::cerr << "THAT DOES NOT WORK PROPERLY. PLEASE USE A RELEASE DOWNLOADED\n"; std::cerr << "FROM http://digitalcorpora.org/downloads/tcpflow\n"; std::cerr << "\n"; #endif bool force_binary_output = false; const char *device = "<default>"; const char *lockname = 0; int need_usage = 0; std::string reportfilename; std::vector<std::string> Rfiles; // files for finishing std::vector<std::string> rfiles; // files to read tcpdemux &demux = *tcpdemux::getInstance(); // the demux object we will be using. std::string command_line = dfxml_writer::make_command_line(argc,argv); std::string opt_unk_packets; bool opt_quiet = false; /* Set up debug system */ progname = argv[0]; init_debug(progname,1); /* Make sure that the system was compiled properly */ if(sizeof(struct be13::ip4)!=20 || sizeof(struct be13::tcphdr)!=20){ fprintf(stderr,"COMPILE ERROR.\n"); fprintf(stderr," sizeof(struct ip)=%d; should be 20.\n", (int)sizeof(struct be13::ip4)); fprintf(stderr," sizeof(struct tcphdr)=%d; should be 20.\n", (int)sizeof(struct be13::tcphdr)); fprintf(stderr,"CANNOT CONTINUE\n"); exit(1); } bool trailing_input_list = false; int arg; while ((arg = getopt(argc, argv, "aA:Bb:cCd:DE:e:E:F:f:Hhi:JlL:m:o:pqR:r:S:sT:Vvw:x:X:Z")) != EOF) { switch (arg) { case 'a': demux.opt.post_processing = true; demux.opt.opt_md5 = true; be13::plugin::scanners_enable_all(); break; case 'A': fprintf(stderr,"-AH has been deprecated. Just use -a\n"); need_usage=true; break; case 'b': demux.opt.max_bytes_per_flow = atoi(optarg); if(debug > 1) { std::cout << "capturing max of " << demux.opt.max_bytes_per_flow << " bytes per flow." << std::endl; } break; case 'B': force_binary_output = true; demux.opt.output_strip_nonprint = false; DEBUG(10) ("converting non-printable characters to '.'"); break; case 'C': demux.opt.console_output = true; DEBUG(10) ("printing packets to console only"); demux.opt.suppress_header = 1; DEBUG(10) ("packet header dump suppressed"); break; case 'c': demux.opt.console_output = true; DEBUG(10) ("printing packets to console only"); break; case 'd': if ((debug = atoi(optarg)) < 0) { debug = DEFAULT_DEBUG_LEVEL; DEBUG(1) ("warning: -d flag with 0 debug level '%s'", optarg); } break; case 'D': demux.opt.output_hex = true;DEBUG(10) ("Console output in hex"); demux.opt.output_strip_nonprint = false; DEBUG(10) ("Will not convert non-printablesto '.'"); break; case 'E': be13::plugin::scanners_disable_all(); be13::plugin::scanners_enable(optarg); break; case 'e': be13::plugin::scanners_enable(optarg); demux.opt.post_processing = true; // enable post processing if anything is turned on break; case 'F': for(const char *cc=optarg;*cc;cc++){ switch(*cc){ case 'c': replace(flow::filename_template,"%c","%C"); break; case 'k': flow::filename_template = "%K/" + flow::filename_template; break; case 'm': flow::filename_template = "%M000-%M999/%M%K/" + flow::filename_template; break; case 'g': flow::filename_template = "%G000000-%G999999/%G%M000-%G%M999/%G%M%K/" + flow::filename_template; break; case 't': flow::filename_template = "%tT" + flow::filename_template; break; case 'T': flow::filename_template = "%T" + flow::filename_template; break; case 'X': demux.opt.store_output = false;break; case 'M': demux.opt.opt_md5 = true;break; default: fprintf(stderr,"-F invalid format specification '%c'\n",*cc); need_usage = true; } } break; case 'f': { int mnew = atoi(optarg); DEBUG(1)("changing max_fds from %d to %d",demux.max_fds,mnew); demux.max_fds = mnew; break; } case 'i': device = optarg; break; case 'J': demux.opt.use_color = 1; DEBUG(10) ("using colors"); break; case 'l': trailing_input_list = true; break; case 'L': lockname = optarg; break; case 'm': demux.opt.max_seek = atoi(optarg); DEBUG(10) ("max_seek set to %d",demux.opt.max_seek); break; case 'o': demux.outdir = optarg; flow::outdir = optarg; break; case 'p': opt_no_promisc = true; DEBUG(10) ("NOT turning on promiscuous mode"); break; case 'q': opt_quiet = true; break; case 'R': Rfiles.push_back(optarg); break; case 'r': rfiles.push_back(optarg); break; case 'S': { std::vector<std::string> params = split(optarg,'='); if(params.size()!=2){ std::cerr << "Invalid paramter: " << optarg << "\n"; exit(1); } be_config.namevals[params[0]] = params[1]; continue; } case 's': demux.opt.output_strip_nonprint = 1; DEBUG(10) ("converting non-printable characters to '.'"); break; case 'T': flow::filename_template = optarg; if(flow::filename_template.find("%c")==string::npos){ flow::filename_template += std::string("%C%c"); // append %C%c if not present } break; case 'V': std::cout << PACKAGE_NAME << " " << PACKAGE_VERSION << "\n"; exit (1); case 'v': debug = 10; break; case 'w': opt_unk_packets = optarg;break; case 'x': be13::plugin::scanners_disable(optarg);break; case 'X': reportfilename = optarg;break; case 'Z': demux.opt.gzip_decompress = 0; break; case 'H': be13::plugin::info_scanners(true,true,scanners_builtin,'e','x'); didhelp = true; break; case 'h': case '?': usage(); didhelp = true; break; default: DEBUG(1) ("error: unrecognized switch '%c'", arg); need_usage = 1; break; } } if(didhelp) exit(0); if(demux.opt.post_processing && !demux.opt.store_output){ std::cerr << "ERROR: post_processing currently requires storing output.\n"; exit(1); } argc -= optind; argv += optind; /* Load all the scanners and enable the ones we care about */ if(demux.opt.opt_md5) be13::plugin::scanners_enable("md5"); be13::plugin::load_scanners(scanners_builtin,be_config); be13::plugin::scanners_process_enable_disable_commands(); /* If there is no report filename, call it report.xml in the output directory */ if( reportfilename.size()==0 ){ reportfilename = demux.outdir + "/" + DEFAULT_REPORT_FILENAME; } /* print help and exit if there was an error in the arguments */ if (need_usage) { usage(); exit(1); } /* remaining arguments are either an input list (-l flag) or a pcap expression (default) */ std::string expression = ""; if(trailing_input_list) { for(int ii = 0; ii < argc; ii++) { rfiles.push_back(argv[ii]); } } else { /* get the user's expression out of remainder of the arg... */ for(int i=0;i<argc;i++){ if(expression.size()>0) expression+=" "; expression += argv[i]; } } /* More option processing */ /* was a semaphore provided for the lock? */ if(lockname){ #if defined(HAVE_SEMAPHORE_H) && defined(HAVE_PTHREAD) semlock = sem_open(lockname,O_CREAT,0777,1); // get the semaphore #else fprintf(stderr,"%s: attempt to create lock pthreads not present\n",argv[0]); exit(1); #endif } if(force_binary_output) demux.opt.output_strip_nonprint = false; /* make sure outdir is a directory. If it isn't, try to make it.*/ struct stat stbuf; if(stat(demux.outdir.c_str(),&stbuf)==0){ if(!S_ISDIR(stbuf.st_mode)){ std::cerr << "outdir is not a directory: " << demux.outdir << "\n"; exit(1); } } else { if(MKDIR(demux.outdir.c_str(),0777)){ std::cerr << "cannot create " << demux.outdir << ": " << strerror(errno) << "\n"; exit(1); } } std::string input_fname; if(rfiles.size() > 0) { input_fname = rfiles.at(0); if(rfiles.size() > 1) { input_fname += ssprintf(" + %d more", rfiles.size() - 1); } } /* report file specified? */ if(reportfilename.size()>0){ xreport = new dfxml_writer(reportfilename,false); dfxml_create(*xreport,command_line); demux.xreport = xreport; } if(opt_unk_packets.size()>0){ if(input_fname.size()==0){ std::cerr << "currently the -w option requires the -r option\n"; exit(1); } if(access(input_fname.c_str(),R_OK)) die("cannot read: %s: %s",input_fname.c_str(),strerror(errno)); demux.save_unk_packets(opt_unk_packets,input_fname); } scanner_info si; si.config = &be_config; /* Debug prefix set? */ std::string debug_prefix=progname; si.get_config("debug-prefix",&debug_prefix,"Prefix for debug output"); init_debug(debug_prefix.c_str(),0); argc -= optind; argv += optind; DEBUG(10) ("%s version %s ", PACKAGE_NAME, PACKAGE_VERSION); feature_file_names_t feature_file_names; be13::plugin::get_scanner_feature_file_names(feature_file_names); feature_recorder_set fs(0); fs.init(feature_file_names,input_fname.size()>0 ? input_fname : device,demux.outdir,0); the_fs = &fs; demux.fs = &fs; si.get_config("tdelta",&datalink_tdelta,"Time offset for packets"); if(demux.xreport) demux.xreport->xmlout("tdelta",datalink_tdelta); /* Process r files and R files */ if(rfiles.size()==0 && Rfiles.size()==0){ /* live capture */ #if defined(HAVE_SETUID) && defined(HAVE_GETUID) /* Since we don't need network access, drop root privileges */ if(setuid(getuid())){ perror("setuid"); } #endif demux.start_new_connections = true; process_infile(expression,device,""); input_fname = device; } else { /* first pick up the new connections with -r */ demux.start_new_connections = true; for(std::vector<std::string>::const_iterator it=rfiles.begin();it!=rfiles.end();it++){ process_infile(expression,device,*it); } /* now pick up the outstanding connection with -R, but don't start new connections */ demux.start_new_connections = false; for(std::vector<std::string>::const_iterator it=Rfiles.begin();it!=Rfiles.end();it++){ process_infile(expression,device,*it); } } /* -1 causes pcap_loop to loop forever, but it finished when the input file is exhausted. */ DEBUG(2)("Open FDs at end of processing: %d",(int)demux.open_flows.size()); DEBUG(2)("demux.max_open_flows: %d",(int)demux.max_open_flows); DEBUG(2)("Flow map size at end of processing: %d",(int)demux.flow_map.size()); DEBUG(2)("Flows seen: %d",(int)demux.flow_counter); demux.close_all_fd(); be13::plugin::phase_shutdown(fs); /* * Note: funny formats below are a result of mingw problems with PRId64. */ const std::string total_flow_processed("Total flows processed: %" PRId64); const std::string total_packets_processed("Total packets processed: %" PRId64); DEBUG(2)(total_flow_processed.c_str(),demux.flow_counter); DEBUG(2)(total_packets_processed.c_str(),demux.packet_counter); if(xreport){ demux.remove_all_flows(); // empty the map to capture the state xreport->add_rusage(); xreport->pop(); // bulk_extractor xreport->close(); delete xreport; } if(demux.flow_counter > tcpdemux::WARN_TOO_MANY_FILES){ if(!opt_quiet){ /* Start counting how many files we have in the output directory. * If we find more than 10,000, print the warning, and keep counting... */ uint64_t filecount=0; DIR *dirp = opendir(demux.outdir.c_str()); if(dirp){ struct dirent *dp=0; while((dp=readdir(dirp))!=NULL){ filecount++; if(filecount==10000){ std::cerr << "*** tcpflow WARNING:\n"; std::cerr << "*** Modern operating systems do not perform well \n"; std::cerr << "*** with more than 10,000 entries in a directory.\n"; std::cerr << "***\n"; } } closedir(dirp); } if(filecount>=10000){ std::cerr << "*** tcpflow created " << filecount << " files in output directory " << demux.outdir << "\n"; std::cerr << "***\n"; std::cerr << "*** Next time, specify command-line options: -Fk , -Fm , or -Fg \n"; std::cerr << "*** This will automatically bin output into subdirectories.\n"; std::cerr << "*** type 'tcpflow -hhh' for more information.\n"; } } } exit(0); // return(0) causes crash on Windows }
void makeScreenShot () { char fname[256]; int ret; int align; int dlen, ishot, iline, w = window_width, h = window_height; unsigned char *pixels; SDL_Surface *surf; #if SDL_BYTEORDER == SDL_BIG_ENDIAN int rmask = 0x00ff0000; int gmask = 0x0000ff00; int bmask = 0x000000ff; #else int rmask = 0x000000ff; int gmask = 0x0000ff00; int bmask = 0x00ff0000; #endif int amask = 0x00000000; /* see if the screenshots directory exists */ safe_snprintf (fname, sizeof (fname), "%sscreenshots", configdir); ret = file_exists(fname); if(ret == 0) { if(MKDIR(fname) < 0) { LOG_ERROR ("Unable to create directory \"%s\"\n", fname); return; } } else if (ret == -1) { return; } dlen = strlen (fname); /* try to find a file name which isn't taken yet */ for (ishot = 1; ishot < 1000; ishot++) { safe_snprintf (fname+dlen, sizeof(fname)-dlen, "/elscreen%03d.png", ishot); ret = file_exists(fname); if(ret == 0) { break; } else if(ret == -1) { return; //we hit an error, it's already reported } } /* if all numbered file names have been taken, use the default */ if (ishot >= 1000) { LOG_TO_CONSOLE(c_red2, max_screenshots_warning_str); safe_snprintf (fname+dlen, sizeof(fname)-dlen, "/elscreen.png"); } LOG_TO_CONSOLE(c_green1, fname); /* read the pixels from the GL scene */ glGetIntegerv(GL_PACK_ALIGNMENT, &align); pixels = malloc(h * align * ((3 * w - 1) / align + 1)); glReadPixels (0, 0, w, h, GL_RGB, GL_UNSIGNED_BYTE, pixels); /* Let SDL worry about creating a BMP from it: create a surface */ surf = SDL_CreateRGBSurface (SDL_SWSURFACE, w, h, 24, rmask, gmask, bmask, amask); /* simply memcpy'ing the pixels results in an upside-down image, * so copy the lines in reverse order */ if (SDL_MUSTLOCK(surf)) SDL_LockSurface(surf); for (iline = 0; iline < h; iline++) memcpy ((char *)surf->pixels + surf->pitch*iline, pixels + surf->pitch*(h-iline-1), 3*w); if (SDL_MUSTLOCK(surf)) SDL_UnlockSurface(surf); //SDL_SaveBMP (surf, fname); IMG_SavePNG (surf, fname); free (pixels); SDL_FreeSurface (surf); }
int zipExtractCurrentfile(unzFile uf, int overwrite, const char* password) { char filename_inzip[256]; char* filename_withoutpath; char* p; int err=UNZ_OK; FILE *fout=NULL; void* buf; uInt size_buf; unz_file_info file_info; err = unzGetCurrentFileInfo(uf,&file_info,filename_inzip,sizeof(filename_inzip),NULL,0,NULL,0); if( err != UNZ_OK ) { printf("error %d with zipfile in unzGetCurrentFileInfo\n",err); return 0; } size_buf = WRITEBUFFERSIZE; buf = (void*)malloc(size_buf); p = filename_withoutpath = filename_inzip; while ((*p) != '\0') { if (((*p)=='/') || ((*p)=='\\')) filename_withoutpath = p+1; p++; } if ((*filename_withoutpath)=='\0') { MKDIR(filename_inzip); }else{ const char* write_filename; int skip=0; write_filename = filename_inzip; err = unzOpenCurrentFilePassword(uf,password); if (err!=UNZ_OK) { printf("error %d with zipfile in unzOpenCurrentFilePassword\n",err); } if ((overwrite==0) && (err==UNZ_OK)) { FILE* ftestexist = fopen(write_filename,"rb"); if (ftestexist!=NULL) { fclose(ftestexist); skip = 1; } } if ((skip==0) && (err==UNZ_OK)) { fout=fopen(write_filename,"wb"); /* some zipfile don't contain directory alone before file */ if( (fout==NULL) && (filename_withoutpath!=(char*)filename_inzip) ) { char c=*(filename_withoutpath-1); *(filename_withoutpath-1)='\0'; makedir(write_filename); *(filename_withoutpath-1)=c; fout=fopen(write_filename,"wb"); } if( fout == NULL ) { printf("error opening %s\n",write_filename); } } if (fout!=NULL) { printf(" extracting: %s\n",write_filename); do { err = unzReadCurrentFile(uf,buf,size_buf); if( err < 0 ) { printf("error %d with zipfile in unzReadCurrentFile\n",err); break; } if( err > 0 ) { if (fwrite(buf,err,1,fout)!=1) { printf("error in writing extracted file\n"); err=UNZ_ERRNO; break; } } }while( err > 0 ); if( fout ) fclose(fout); } if(err == UNZ_OK) { err = unzCloseCurrentFile (uf); if( err != UNZ_OK ) { printf("error %d with zipfile in unzCloseCurrentFile\n",err); } }else{ unzCloseCurrentFile(uf); /* don't lose the error */ } } free(buf); return 1; }
int create_tmpdir ( int tracing ) { int fixedname = ipa && ( option[OPT_KEEP_TEMPS].flag ); if ( ipa ) { if ( fixedname ) { tmpdir = concat_names ( outfilename, ".ipakeep" ); } else { char *tmpdir_env_var; if ((tmpdir_env_var = getenv("TMPDIR")) != NULL) { char *filename; tmpdir_env_var = concat_names ( tmpdir_env_var, DIR_SEP_CHAR); if ((filename = strrchr(outfilename, DIR_SEP_CHAR)) != NULL) filename++; else filename = outfilename; tmpdir = concat_names ( tmpdir_env_var, filename); } else tmpdir = outfilename; tmpdir = concat_names ( tmpdir, ".ipaXXXXXX" ); } } else { tmpdir = concat_names ( DEFAULT_TMPDIR, "XXXXXX" ); } if ( ! fixedname ) { tmpdir = mktemp ( tmpdir ); } tmpdir_length = strlen ( tmpdir ); if ( cmask == 0 ) { cmask = umask (0); (void) umask (cmask); } if ( MKDIR (tmpdir, 0777 & ~cmask) != 0 ) { if ( errno == EEXIST && fixedname ) { /* We have an old instance of this directory -- clear it out: */ DIR *dirp; struct direct *entryp; char *prefix; dirp = opendir ( tmpdir ); if ( dirp != NULL ) { prefix = concat_names ( tmpdir, "/" ); while ( ( entryp = readdir(dirp) ) != NULL ) { /* Don't bother with names of one or two characters, e.g. '.' * and '..', since we don't create temporary files with such * names: */ #if defined(_DIRENT_HAVE_D_NAMLEN) if ( entryp->d_namlen > 2 ) #else if (_D_EXACT_NAMLEN(entryp) > 2) #endif { string fname = concat_names ( prefix, entryp->d_name); unlink (fname); FREE (fname); } } FREE (prefix); closedir ( dirp ); } } else { perror(""cannot create temporary directory for code generation"); return -1; } } add_to_tmp_file_list ( tmpdir ); return 0; } /* create_tmpdir */
bool QDir::mkdir( const QString &dirName, bool acceptAbsPath ) const { return MKDIR( QFile::encodeName(filePath(dirName,acceptAbsPath)), 0777 ) == 0; }
bool sbbs_t::email(int usernumber, const char *top, const char *subj, long mode) { char str[256],str2[256],msgpath[256],title[LEN_TITLE+1],ch ,buf[SDT_BLOCK_LEN]; char tmp[512]; char pid[128]; char* editor=NULL; ushort msgattr=0; uint16_t xlat=XLAT_NONE; ushort nettype; int i,j,x,file; long l; long length; ulong offset; uint32_t crc=0xffffffffUL; FILE* instream; node_t node; smbmsg_t msg; SAFECOPY(title,subj); if(useron.etoday>=cfg.level_emailperday[useron.level] && !SYSOP && !(useron.exempt&FLAG('M'))) { bputs(text[TooManyEmailsToday]); return(false); } if(usernumber==1 && useron.rest&FLAG('S') && (cfg.node_valuser!=1 || useron.fbacks || useron.emails)) { /* ! val fback */ bprintf(text[R_Feedback],cfg.sys_op); return(false); } if(usernumber!=1 && useron.rest&FLAG('E') && (cfg.node_valuser!=usernumber || useron.fbacks || useron.emails)) { bputs(text[R_Email]); return(false); } if(!usernumber) { bputs(text[UnknownUser]); return(false); } getuserrec(&cfg,usernumber,U_MISC,8,str); l=ahtoul(str); if(l&(DELETED|INACTIVE)) { /* Deleted or Inactive User */ bputs(text[UnknownUser]); return(false); } if((l&NETMAIL) && (cfg.sys_misc&SM_FWDTONET)) { getuserrec(&cfg,usernumber,U_NETMAIL,LEN_NETMAIL,str); bprintf(text[UserNetMail],str); if((mode & WM_FORCEFWD) || text[ForwardMailQ][0]==0 || yesno(text[ForwardMailQ])) /* Forward to netmail address */ return(netmail(str,subj,mode)); } bprintf(text[Emailing],username(&cfg,usernumber,tmp),usernumber); action=NODE_SMAL; nodesync(); sprintf(str,"%sfeedback.*", cfg.exec_dir); if(usernumber==cfg.node_valuser && useron.fbacks && fexist(str)) { exec_bin("feedback",&main_csi); if(main_csi.logic!=LOGIC_TRUE) return(false); } if(cfg.sys_misc&SM_ANON_EM && useron.exempt&FLAG('A') && !noyes(text[AnonymousQ])) msgattr|=MSG_ANONYMOUS; if(cfg.sys_misc&SM_DELREADM) msgattr|=MSG_KILLREAD; msg_tmp_fname(useron.xedit, msgpath, sizeof(msgpath)); username(&cfg,usernumber,str2); if(!writemsg(msgpath,top,title,mode,INVALID_SUB,str2,&editor)) { bputs(text[Aborted]); return(false); } if(mode&WM_FILE && !SYSOP && !(cfg.sys_misc&SM_FILE_EM)) mode&=~WM_FILE; if(mode&WM_FILE) { sprintf(str2,"%sfile/%04u.in", cfg.data_dir,usernumber); MKDIR(str2); sprintf(str2,"%sfile/%04u.in/%s", cfg.data_dir,usernumber,title); if(fexistcase(str2)) { bputs(text[FileAlreadyThere]); remove(msgpath); return(false); } { /* Remote */ xfer_prot_menu(XFER_UPLOAD); mnemonics(text[ProtocolOrQuit]); strcpy(str,"Q"); for(x=0;x<cfg.total_prots;x++) if(cfg.prot[x]->ulcmd[0] && chk_ar(cfg.prot[x]->ar,&useron,&client)) { sprintf(tmp,"%c",cfg.prot[x]->mnemonic); strcat(str,tmp); } ch=(char)getkeys(str,0); if(ch=='Q' || sys_status&SS_ABORT) { bputs(text[Aborted]); remove(msgpath); return(false); } for(x=0;x<cfg.total_prots;x++) if(cfg.prot[x]->ulcmd[0] && cfg.prot[x]->mnemonic==ch && chk_ar(cfg.prot[x]->ar,&useron,&client)) break; if(x<cfg.total_prots) /* This should be always */ protocol(cfg.prot[x],XFER_UPLOAD,str2,nulstr,true); } safe_snprintf(tmp,sizeof(tmp),"%s%s",cfg.temp_dir,title); if(!fexistcase(str2) && fexistcase(tmp)) mv(tmp,str2,0); l=(long)flength(str2); if(l>0) bprintf(text[FileNBytesReceived],title,ultoac(l,tmp)); else { bprintf(text[FileNotReceived],title); remove(msgpath); return(false); } } bputs(text[WritingIndx]); if((i=smb_stack(&smb,SMB_STACK_PUSH))!=0) { errormsg(WHERE,ERR_OPEN,"MAIL",i); return(false); } sprintf(smb.file,"%smail", cfg.data_dir); smb.retry_time=cfg.smb_retry_time; smb.subnum=INVALID_SUB; if((i=smb_open(&smb))!=0) { smb_stack(&smb,SMB_STACK_POP); errormsg(WHERE,ERR_OPEN,smb.file,i,smb.last_error); return(false); } if(smb_fgetlength(smb.shd_fp)<1) { /* Create it if it doesn't exist */ smb.status.max_crcs=cfg.mail_maxcrcs; smb.status.max_age=cfg.mail_maxage; smb.status.max_msgs=0; smb.status.attr=SMB_EMAIL; if((i=smb_create(&smb))!=0) { smb_close(&smb); smb_stack(&smb,SMB_STACK_POP); errormsg(WHERE,ERR_CREATE,smb.file,i,smb.last_error); return(false); } } if((i=smb_locksmbhdr(&smb))!=0) { smb_close(&smb); smb_stack(&smb,SMB_STACK_POP); errormsg(WHERE,ERR_LOCK,smb.file,i,smb.last_error); return(false); } length=(long)flength(msgpath)+2; /* +2 for translation string */ if(length&0xfff00000UL) { smb_unlocksmbhdr(&smb); smb_close(&smb); smb_stack(&smb,SMB_STACK_POP); errormsg(WHERE,ERR_LEN,msgpath,length); return(false); } if((i=smb_open_da(&smb))!=0) { smb_unlocksmbhdr(&smb); smb_close(&smb); smb_stack(&smb,SMB_STACK_POP); errormsg(WHERE,ERR_OPEN,smb.file,i,smb.last_error); return(false); } if(cfg.sys_misc&SM_FASTMAIL) offset=smb_fallocdat(&smb,length,1); else offset=smb_allocdat(&smb,length,1); smb_close_da(&smb); if((instream=fnopen(&file,msgpath,O_RDONLY|O_BINARY))==NULL) { smb_freemsgdat(&smb,offset,length,1); smb_unlocksmbhdr(&smb); smb_close(&smb); smb_stack(&smb,SMB_STACK_POP); errormsg(WHERE,ERR_OPEN,msgpath,O_RDONLY|O_BINARY); return(false); } setvbuf(instream,NULL,_IOFBF,2*1024); smb_fseek(smb.sdt_fp,offset,SEEK_SET); xlat=XLAT_NONE; smb_fwrite(&smb,&xlat,2,smb.sdt_fp); x=SDT_BLOCK_LEN-2; /* Don't read/write more than 255 */ while(!feof(instream)) { memset(buf,0,x); j=fread(buf,1,x,instream); if(j<1) break; if(j>1 && (j!=x || feof(instream)) && buf[j-1]==LF && buf[j-2]==CR) buf[j-1]=buf[j-2]=0; if(cfg.mail_maxcrcs) { for(i=0;i<j;i++) crc=ucrc32(buf[i],crc); } smb_fwrite(&smb,buf,j,smb.sdt_fp); x=SDT_BLOCK_LEN; } smb_fflush(smb.sdt_fp); fclose(instream); crc=~crc; memset(&msg,0,sizeof(smbmsg_t)); msg.hdr.version=smb_ver(); msg.hdr.attr=msgattr; if(mode&WM_FILE) msg.hdr.auxattr|=MSG_FILEATTACH; msg.hdr.when_written.time=msg.hdr.when_imported.time=time32(NULL); msg.hdr.when_written.zone=msg.hdr.when_imported.zone=sys_timezone(&cfg); if(cfg.mail_maxcrcs) { i=smb_addcrc(&smb,crc); if(i) { smb_freemsgdat(&smb,offset,length,1); smb_unlocksmbhdr(&smb); smb_close(&smb); smb_stack(&smb,SMB_STACK_POP); attr(cfg.color[clr_err]); bputs(text[CantPostMsg]); return(false); } } msg.hdr.offset=offset; username(&cfg,usernumber,str); smb_hfield_str(&msg,RECIPIENT,str); sprintf(str,"%u",usernumber); smb_hfield_str(&msg,RECIPIENTEXT,str); SAFECOPY(str,useron.alias); smb_hfield_str(&msg,SENDER,str); sprintf(str,"%u",useron.number); smb_hfield_str(&msg,SENDEREXT,str); if(useron.misc&NETMAIL) { if(useron.rest&FLAG('G')) smb_hfield_str(&msg,REPLYTO,useron.name); nettype=smb_netaddr_type(useron.netmail); if(nettype!=NET_NONE && nettype!=NET_UNKNOWN) { smb_hfield(&msg,REPLYTONETTYPE,sizeof(nettype),&nettype); smb_hfield_str(&msg,REPLYTONETADDR,useron.netmail); } } /* Security logging */ msg_client_hfields(&msg,&client); smb_hfield_str(&msg,SENDERSERVER,startup->host_name); smb_hfield_str(&msg,SUBJECT,title); /* Generate FidoNet Program Identifier */ smb_hfield_str(&msg,FIDOPID,msg_program_id(pid)); if(editor!=NULL) smb_hfield_str(&msg,SMB_EDITOR,editor); smb_dfield(&msg,TEXT_BODY,length); i=smb_addmsghdr(&smb,&msg,SMB_SELFPACK); // calls smb_unlocksmbhdr() smb_close(&smb); smb_stack(&smb,SMB_STACK_POP); smb_freemsgmem(&msg); if(i!=SMB_SUCCESS) { smb_freemsgdat(&smb,offset,length,1); errormsg(WHERE,ERR_WRITE,smb.file,i,smb.last_error); return(false); } if(usernumber==1) logon_fbacks++; else logon_emails++; user_sent_email(&cfg, &useron, 1, usernumber==1); bprintf(text[Emailed],username(&cfg,usernumber,tmp),usernumber); safe_snprintf(str,sizeof(str),"%s sent e-mail to %s #%d" ,useron.alias,username(&cfg,usernumber,tmp),usernumber); logline("E+",str); if(mode&WM_FILE && online==ON_REMOTE) autohangup(); if(msgattr&MSG_ANONYMOUS) /* Don't tell user if anonymous */ return(true); for(i=1;i<=cfg.sys_nodes;i++) { /* Tell user, if online */ getnodedat(i,&node,0); if(node.useron==usernumber && !(node.misc&NODE_POFF) && (node.status==NODE_INUSE || node.status==NODE_QUIET)) { safe_snprintf(str,sizeof(str),text[EmailNodeMsg],cfg.node_num,useron.alias); putnmsg(&cfg,i,str); break; } } if(i>cfg.sys_nodes) { /* User wasn't online, so leave short msg */ safe_snprintf(str,sizeof(str),text[UserSentYouMail],useron.alias); putsmsg(&cfg,usernumber,str); } return(true); }