/** * \brief Periodically prints statistics about proccessing speed * * @param config Output Manager configuration * @return 0; */ static void *statistics_thread(void* config) { struct output_manager_config *conf = (struct output_manager_config *) config; time_t begin = time(NULL), time_now, run_time; /* Create statistics config */ conf->stats.total_cpu = 0; conf->stats.threads = NULL; conf->stats.cpus = sysconf(_SC_NPROCESSORS_ONLN); snprintf(conf->stats.tasks_dir, MAX_DIR_LEN, "/proc/%d/task/", getpid()); /* If statistics are enabled (using -S), printing them to console is default */ uint8_t print_stat_to_file = 0; uint8_t print_stat_to_console = 1; /* Process XML config */ char *full_stat_out_file_path = NULL; xmlNode *node = conf->plugins_config->collector_node; while (node != NULL) { /* Skip processing this node in case it's a comment */ if (node->type == XML_COMMENT_NODE) { node = node->next; continue; } /* Jump to collectingProcess tree, since 'statisticsFile' belongs to it (if present) */ if (xmlStrcmp(node->name, (const xmlChar *) "collectingProcess") == 0) { node = node->xmlChildrenNode; } if (xmlStrcmp(node->name, (const xmlChar *) "statisticsFile") == 0) { /* Disable printing statistics to console when printing to file */ print_stat_to_console = 0; char *stat_out_file_path = (char *) xmlNodeGetContent(node->xmlChildrenNode); if (stat_out_file_path && strlen(stat_out_file_path) > 0) { print_stat_to_file = 1; /* Determine statistics file path, i.e., full path minus basename */ char stat_out_path[strlen(stat_out_file_path) + 1]; strncpy_safe(stat_out_path, stat_out_file_path, strlen(stat_out_file_path) - strlen(basename(stat_out_file_path))); /* Check whether statistics file path exists */ DIR *stat_out_dir; if ((stat_out_dir = opendir(stat_out_path)) == NULL) { MSG_ERROR(msg_module, "Statistics file directory '%s' does not exist", stat_out_path); xmlFree(stat_out_file_path); /* Skip to next XML node in configuration */ node = node->next; continue; } else { closedir(stat_out_dir); } /* Clean up previous statistics files */ char glob_path[strlen(stat_out_file_path) + 2]; // +2 is for wildcard (*) and null-terminating char strncpy_safe(glob_path, stat_out_file_path, strlen(stat_out_file_path) + 1); glob_path[strlen(stat_out_file_path)] = '*'; glob_path[strlen(stat_out_file_path) + 1] = '\0'; /* Search for files using glob */ int glob_ret, glob_flags = 0; glob_t glob_results; if ((glob_ret = glob(glob_path, glob_flags, NULL, &glob_results)) == 0) { uint16_t i, stat_files_deleted = 0; for (i = 0; i < glob_results.gl_pathc; ++i) { if ((remove(glob_results.gl_pathv[i])) == 0) { ++stat_files_deleted; } else { MSG_ERROR(msg_module, "An error occurred while deleting statistics file '%s'", glob_results.gl_pathv[i]); } } MSG_INFO(msg_module, "Cleaned up %u old statistics file(s)", stat_files_deleted); globfree(&glob_results); } else if (glob_ret == GLOB_NOMATCH) { /* No matching files/directories found; do nothing */ } else { /* Another glob error occurred; do nothing */ } /* Consists of the following elements: * strlen(stat_out_file_path) - length of supplied path * 1 - dot (.) * 5 - we assume that a PID has a maximum length of 5 digits * 1 - null-terminating character */ uint8_t max_len = strlen(stat_out_file_path) + 1 + 5 + 1; full_stat_out_file_path = calloc(max_len, sizeof(char)); /* snprintf ensures null-termination if (max_len != 0), which is always true */ snprintf(full_stat_out_file_path, max_len, "%s.%d", stat_out_file_path, getpid()); } else { MSG_ERROR(msg_module, "Configuration error: 'statisticsFile' node has no value"); } xmlFree(stat_out_file_path); /* No need to continue tree traversal, because 'statisticsFile' is only node to look for */ break; } node = node->next; } /* Set thread name */ prctl(PR_SET_NAME, "ipfixcol:stats", 0, 0, 0); FILE *stat_out_file = NULL; while (conf->stat_interval && !conf->stats.done) { /* stats.done can be set by Output Manager */ /* Sleep */ struct timespec tv; tv.tv_sec = conf->stat_interval; tv.tv_nsec = 0; /* Reconfiguration (SIGUSR1) cause sleep interruption */ while (nanosleep(&tv, &tv) == -1 && errno == EINTR && !conf->stats.done); /* Compute time */ time_now = time(NULL); run_time = time_now - begin; /* Print info */ if (print_stat_to_file) { if (full_stat_out_file_path) { stat_out_file = fopen(full_stat_out_file_path, "w"); if (!stat_out_file) { MSG_ERROR(msg_module, "Could not open statistics file '%s'; stopping statistics thread", full_stat_out_file_path); break; } fprintf(stat_out_file, "%s=%lu\n", "TIME", time_now); fprintf(stat_out_file, "%s=%lu\n", "RUN_TIME", run_time); } else { MSG_ERROR(msg_module, "Could not determine statistics file path; stopping statistics thread"); break; } } else if (print_stat_to_console) { MSG_ALWAYS("Statistics", NULL); MSG_ALWAYS(" | Time: %lu, run time: %lu", time_now, run_time); MSG_ALWAYS(" | %10s %15s %15s %15s %15s %15s %20s", "ODID", "packets", "data rec.", "lost data rec.", "packets/s", "data records/s", "lost data records/s"); } /* Variables for calculating sums */ uint64_t packets_total = 0; uint64_t data_records_total = 0; uint64_t lost_data_records_total = 0; /* Variables for calculating delta (to previous measurement) */ uint32_t delta_packets; uint32_t delta_data_records; uint32_t delta_lost_data_records; struct input_info_node *aux_node = input_info_list; uint8_t aux_node_count = 0; while (aux_node) { delta_packets = aux_node->input_info->packets - aux_node->last_packets; delta_data_records = aux_node->input_info->data_records - aux_node->last_data_records; delta_lost_data_records = aux_node->input_info->sequence_number - aux_node->input_info->data_records - aux_node->last_lost_data_records; if (print_stat_to_file) { fprintf(stat_out_file, "%s_%u=%" PRIu64 "\n", "PACKETS", aux_node->input_info->odid, aux_node->input_info->packets); fprintf(stat_out_file, "%s_%u=%" PRIu64 "\n", "DATA_REC", aux_node->input_info->odid, aux_node->input_info->data_records); fprintf(stat_out_file, "%s_%u=%" PRIu64 "\n", "LOST_DATA_REC", aux_node->input_info->odid, aux_node->input_info->sequence_number - aux_node->input_info->data_records); fprintf(stat_out_file, "%s_%u=%u\n", "PACKETS_SEC", aux_node->input_info->odid, delta_packets / conf->stat_interval); fprintf(stat_out_file, "%s_%u=%u\n", "DATA_REC_SEC", aux_node->input_info->odid, delta_data_records / conf->stat_interval); fprintf(stat_out_file, "%s_%u=%u\n", "LOST_DATA_REC_SEC", aux_node->input_info->odid, delta_lost_data_records / conf->stat_interval); } else if (print_stat_to_console) { MSG_ALWAYS(" | %10u %15lu %15lu %15lu %15u %15u %20u", aux_node->input_info->odid, aux_node->input_info->packets, aux_node->input_info->data_records, aux_node->input_info->sequence_number - aux_node->input_info->data_records, delta_packets / conf->stat_interval, delta_data_records / conf->stat_interval, delta_lost_data_records / conf->stat_interval); } /* Add values per ODID to sum */ packets_total += aux_node->input_info->packets; data_records_total += aux_node->input_info->data_records; lost_data_records_total += aux_node->input_info->sequence_number - aux_node->input_info->data_records; /* Update 'last' values */ aux_node->last_packets = aux_node->input_info->packets; aux_node->last_data_records = aux_node->input_info->data_records; aux_node->last_lost_data_records = aux_node->input_info->sequence_number - aux_node->input_info->data_records; aux_node = aux_node->next; ++aux_node_count; } if (print_stat_to_console && aux_node_count > 1) { /* Print totals row, but only in case there is more than one ODID */ MSG_ALWAYS(" | %s", "----------------------------------------------------------"); MSG_ALWAYS(" | %10s %15lu %15lu %15lu", "Total:", packets_total, data_records_total, lost_data_records_total); } /* Print CPU usage by threads */ statistics_print_cpu(&(conf->stats), stat_out_file); /* Print buffer usage */ statistics_print_buffers(conf, stat_out_file); /* Flush input stream and close file */ if (print_stat_to_file) { fflush(stat_out_file); fclose(stat_out_file); } } if (print_stat_to_file) { free(full_stat_out_file_path); } return NULL; }
int CreateFileList(struct CommandLineArgsTag CLA) { char command[256]; glob_t globbuf; FILE *fp; size_t errorcode; float minimumF,maximumF; strcpy(command,CLA.inputdirectory); strcat(command,"/*SFT*"); globbuf.gl_offs = 1; glob(command, GLOB_ERR, NULL, &globbuf); /* read in file names */ if(globbuf.gl_pathc==0) { fprintf(stderr,"No SFTs in directory %s ... Exiting.\n",CLA.inputdirectory); return 1; } while (filenumber< globbuf.gl_pathc) { strcpy(filelist[filenumber],globbuf.gl_pathv[filenumber]); filenumber++; if (filenumber > MAXFILES) { fprintf(stderr,"Too many files in directory! Exiting... \n"); return 1; } } fprintf(stdout,"%d files in directory\n",filenumber); globfree(&globbuf); /* open FIRST file and get info from it*/ fp=fopen(filelist[0],"r"); /* read in the header from the file */ errorcode=fread((void*)&header,sizeof(header),1,fp); if (errorcode!=1) { fprintf(stderr,"No header in data file %s\n",filelist[0]); return 1; } /* check that data is correct endian order */ if (header.endian!=1.0) { fprintf(stderr,"First object in file %s is not (double)1.0!\n",filelist[0]); fprintf(stderr,"It could be a file format error (big/little\n"); fprintf(stderr,"endian) or the file might be corrupted\n\n"); return 2; } fclose(fp); sTsft=header.tbase; // Time baseline of short SFTs lTsft=CLA.number*header.tbase; // Time baseline of long SFTs OrigB=((float)header.nsamples) / sTsft; // Original bandwidth of SFTs minimumF=150.0; //150.0 maximumF=160.0; //1300.0 is what we agreed with map ifmin=floor(minimumF*sTsft) - CLA.Dterms; ifmax=ceil(maximumF*sTsft) + CLA.Dterms; if0=floor(minimumF*sTsft); if1=ceil(maximumF*sTsft); B=((float) CLA.number*(if1-if0))/(CLA.number*sTsft); return 0; }
/* Rename a VM instance */ int vm_rename_instance(vm_instance_t *vm, char *name) { char *old_name; char *old_lock_file = NULL; FILE *old_lock_fd = NULL; glob_t globbuf; size_t i; char *pattern = NULL; char *filename; int do_rename = 0; if (name == NULL || vm == NULL) goto err_invalid; /* invalid argument */ if (vm->status != VM_STATUS_HALTED) goto err_not_stopped; /* VM is not stopped */ if (strcmp(vm->name, name) == 0) return(0); /* same name, done */ if (registry_exists(name,OBJ_TYPE_VM)) goto err_exists; /* name already exists */ old_name = vm->name; vm->name = NULL; if(!(vm->name = strdup(name))) goto err_strdup; /* out of memory */ /* get new lock */ do_rename = ( vm_file_naming_type != 1 ); if (do_rename) { old_lock_file = vm->lock_file; old_lock_fd = vm->lock_fd; vm->lock_file = NULL; vm->lock_fd = NULL; if (vm_get_lock(vm) == -1) goto err_lock; } if (registry_rename(old_name,vm->name,OBJ_TYPE_VM)) goto err_registry; /* failed to rename */ vm_log(vm,"VM","renamed from '%s' to '%s'",old_name,vm->name); /* rename files (best effort) */ if (do_rename) { fclose(old_lock_fd); unlink(old_lock_file); free(old_lock_file); vm_close_log(vm); if ((pattern = dyn_sprintf("%s_%s_*",vm_get_type(vm),old_name)) == NULL) goto skip_rename; if (glob(pattern, GLOB_NOSORT, NULL, &globbuf) != 0) goto skip_rename; for (i = 0; i < globbuf.gl_pathc; i++) { if ((filename = dyn_sprintf("%s_%s_%s",vm_get_type(vm),vm->name,globbuf.gl_pathv[i] + strlen(pattern) - 1)) == NULL) break; /* out of memory */ rename(globbuf.gl_pathv[i], filename); free(filename); } globfree(&globbuf); skip_rename: free(pattern); vm_reopen_log(vm); } free(old_name); return(0); // done err_registry: err_lock: err_strdup: free(vm->name); vm->name = old_name; if (do_rename) { vm_release_lock(vm,TRUE); vm->lock_file = old_lock_file; vm->lock_fd = old_lock_fd; } err_exists: err_not_stopped: err_invalid: return(-1); }
void dirlist(char *name, FILE * client, char verbose,int bshow_hiden_files) { DIR *directory; FILE *can_see_file; int show_nonreadable_files = FALSE; char *local_cwd = NULL; int i; int show_hidden_files = FALSE; glob_t globbuf; // 0.不支持配置文件配置,直接设置成显示所有文件包括隐藏文件 #if 0 if (! strcasecmp( config_getoption("SHOW_HIDDEN_FILES"), "yes") ) #endif show_hidden_files = bshow_hiden_files; if (! strcasecmp( config_getoption("SHOW_NONREADABLE_FILES"), "yes") ) show_nonreadable_files = TRUE; if ((strstr(name, "/.")) && strchr(name, '*')) return; /* DoS protection */ if ((directory = opendir(name))) { closedir(directory); local_cwd = bftpd_cwd_getcwd(); chdir(name); glob("*", 0, NULL, &globbuf); if (show_hidden_files) glob(".*", GLOB_APPEND, NULL, &globbuf); } else { if ( (name[0] == '*') && (show_hidden_files) ) { glob(name, 0, NULL, &globbuf); glob(".*", GLOB_APPEND, NULL, &globbuf); } else glob(name, 0, NULL, &globbuf); } for (i = 0; i < globbuf.gl_pathc; i++) { if (! show_nonreadable_files) { if ( (can_see_file = fopen(globbuf.gl_pathv[i], "r") ) == NULL) continue; else fclose(can_see_file); } dirlist_one_file(globbuf.gl_pathv[i], client, verbose); } globfree(&globbuf); if (local_cwd) { chdir(local_cwd); free(local_cwd); } }
static int send_files(char** fname, uint fnames) { char path[MAX_PATH+1]; int i; uint errors; uint fnum; uint cps; glob_t g; int gi; BOOL success=TRUE; long fsize; ulong sent_bytes; ulong total_bytes=0; time_t t,startfile; time_t startall; FILE* fp; startall=time(NULL); /****************************************************/ /* Search through all to find total files and bytes */ /****************************************************/ for(fnum=0;fnum<fnames;fnum++) { if(glob(fname[fnum],0,NULL,&g)) { lprintf(LOG_WARNING,"%s not found",fname[fnum]); continue; } for(i=0;i<(int)g.gl_pathc;i++) { if(isdir(g.gl_pathv[i])) continue; xm.total_files++; xm.total_bytes+=flength(g.gl_pathv[i]); } globfree(&g); } if(xm.total_files<1) { lprintf(LOG_ERR,"No files to send"); return(-1); } if(xm.total_files>1) lprintf(LOG_INFO,"Sending %u files (%lu KB total)" ,xm.total_files,xm.total_bytes/1024); zm.files_remaining = xm.total_files; zm.bytes_remaining = xm.total_bytes; /***********************************************/ /* Send every file matching names or filespecs */ /***********************************************/ for(fnum=0;fnum<fnames;fnum++) { if(glob(fname[fnum],0,NULL,&g)) { lprintf(LOG_WARNING,"%s not found",fname[fnum]); continue; } for(gi=0;gi<(int)g.gl_pathc;gi++) { SAFECOPY(path,g.gl_pathv[gi]); if(isdir(path)) continue; if((fp=fnopen(NULL,path,O_RDONLY|O_BINARY))==NULL && (fp=fopen(path,"rb"))==NULL) { lprintf(LOG_ERR,"Error %d opening %s for read",errno,path); continue; } setvbuf(fp,NULL,_IOFBF,0x10000); fsize=filelength(fileno(fp)); errors=0; success=FALSE; startfile=time(NULL); lprintf(LOG_INFO,"Sending %s (%lu KB) via %s" ,path,fsize/1024 ,mode&XMODEM ? "Xmodem" : mode&YMODEM ? "Ymodem" : "Zmodem"); if(mode&ZMODEM) success=zmodem_send_file(&zm, path, fp, /* ZRQINIT? */fnum==0, &startfile, &sent_bytes); else /* X/Ymodem */ success=xmodem_send_file(&xm, path, fp, &startfile, &sent_bytes); fclose(fp); if((t=time(NULL)-startfile)<=0) t=1; if((cps=sent_bytes/t)==0) cps=1; if(success) { xm.sent_files++; xm.sent_bytes+=fsize; lprintf(LOG_INFO,"Successful - Time: %lu:%02lu CPS: %lu" ,t/60,t%60,cps); if(xm.total_files-xm.sent_files) lprintf(LOG_INFO,"Remaining - Time: %lu:%02lu Files: %u KBytes: %lu" ,((xm.total_bytes-xm.sent_bytes)/cps)/60 ,((xm.total_bytes-xm.sent_bytes)/cps)%60 ,xm.total_files-xm.sent_files ,(xm.total_bytes-xm.sent_bytes)/1024 ); } else lprintf(LOG_WARNING,"File Transfer %s", aborted ? "Aborted" : "Failure"); /* DSZLOG entry */ if(logfp) { lprintf(LOG_DEBUG,"Updating DSZLOG: %s", dszlog); fprintf(logfp,"%c %7lu %5u bps %6lu cps %3u errors %5u %4u " "%s -1\n" ,success ? (mode&ZMODEM ? 'z':'S') : (mode&ZMODEM && zm.file_skipped) ? 's' : 'E' ,sent_bytes ,115200 /* baud */ ,cps ,mode&ZMODEM ? zm.errors : xm.errors ,flows ,mode&ZMODEM ? zm.block_size : xm.block_size ,dszlog_filename(path)); fflush(logfp); } total_bytes += sent_bytes; if(aborted) { xm.cancelled=FALSE; xmodem_cancel(&xm); break; } if(xm.cancelled || zm.cancelled) break; } /* while(gi<(int)g.gl_pathc) */ if(gi<(int)g.gl_pathc)/* error occurred */ break; } if(mode&ZMODEM && !zm.cancelled && is_connected(NULL)) zmodem_get_zfin(&zm); if(fnum<fnames) /* error occurred */ return(-1); if(!success) return(-1); if(mode&XMODEM) return(0); if(mode&YMODEM) { if(xmodem_get_mode(&xm)) { lprintf(LOG_INFO,"Sending Ymodem termination block"); memset(block,0,128); /* send short block for terminator */ xmodem_put_block(&xm, block, 128 /* block_size */, 0 /* block_num */); if(!xmodem_get_ack(&xm,6,0)) { lprintf(LOG_WARNING,"Failed to receive ACK after terminating block"); } } } if(xm.total_files>1) { t=time(NULL)-startall; if(!t) t=1; lprintf(LOG_INFO,"Overall - Time %02lu:%02lu KBytes: %lu CPS: %lu" ,t/60,t%60,total_bytes/1024,total_bytes/t); } return(0); /* success */ }
/* * Read and parse an interactive command. * The first word on the line is assigned to "cmd". If * there are no arguments on the command line, then "curdir" * is returned as the argument. If there are arguments * on the line they are returned one at a time on each * successive call to getcmd. Each argument is first assigned * to "name". If it does not start with "/" the pathname in * "curdir" is prepended to it. Finally "canon" is called to * eliminate any embedded ".." components. */ static void getcmd(char *curdir, char *cmd, char *name, size_t size, struct arglist *ap) { char *cp; static char input[BUFSIZ]; char output[BUFSIZ]; # define rawname input /* save space by reusing input buffer */ /* * Check to see if still processing arguments. */ if (ap->argcnt > 0) goto retnext; if (nextarg != NULL) goto getnext; /* * Read a command line and trim off trailing white space. */ do { fprintf(stderr, "restore > "); fflush(stderr); if (fgets(input, BUFSIZ, terminal) == NULL) { strcpy(cmd, "quit"); return; } } while (input[0] == '\n'); for (cp = &input[strlen(input) - 2]; *cp == ' ' || *cp == '\t'; cp--) /* trim off trailing white space and newline */; *++cp = '\0'; /* * Copy the command into "cmd". */ cp = copynext(input, cmd); ap->cmd = cmd; /* * If no argument, use curdir as the default. */ if (*cp == '\0') { strncpy(name, curdir, size); name[size - 1] = '\0'; return; } nextarg = cp; /* * Find the next argument. */ getnext: cp = copynext(nextarg, rawname); if (*cp == '\0') nextarg = NULL; else nextarg = cp; /* * If it is an absolute pathname, canonicalize it and return it. */ if (rawname[0] == '/') { canon(rawname, name, size); } else { /* * For relative pathnames, prepend the current directory to * it then canonicalize and return it. */ snprintf(output, sizeof(output), "%s/%s", curdir, rawname); canon(output, name, size); } if (glob(name, GLOB_ALTDIRFUNC, NULL, &ap->glob) < 0) fprintf(stderr, "%s: out of memory\n", ap->cmd); if (ap->glob.gl_pathc == 0) return; ap->freeglob = 1; ap->argcnt = ap->glob.gl_pathc; retnext: strncpy(name, ap->glob.gl_pathv[ap->glob.gl_pathc - ap->argcnt], size); name[size - 1] = '\0'; if (--ap->argcnt == 0) { ap->freeglob = 0; globfree(&ap->glob); } # undef rawname }
static void config_rescan(GVC_t *gvc, char *config_path) { FILE *f = NULL; glob_t globbuf; char *config_glob, *config_re, *path, *libdir; int i, rc, re_status; gvplugin_library_t *library; regex_t re; #ifndef WIN32 char *plugin_glob = "libgvplugin_*"; #endif #if defined(DARWIN_DYLIB) char *plugin_re_beg = "[^0-9]\\."; char *plugin_re_end = "\\.dylib$"; #elif defined(__MINGW32__) char *plugin_glob = "libgvplugin_*"; char *plugin_re_beg = "[^0-9]-"; char *plugin_re_end = "\\.dll$"; #elif defined(__CYGWIN__) plugin_glob = "cyggvplugin_*"; char *plugin_re_beg = "[^0-9]-"; char *plugin_re_end = "\\.dll$"; #elif defined(WIN32) char *plugin_glob = "gvplugin_*"; char *plugin_re_beg = "[^0-9]"; char *plugin_re_end = "\\.dll$"; #elif ((defined(__hpux__) || defined(__hpux)) && !(defined(__ia64))) char *plugin_re_beg = "\\.sl\\."; char *plugin_re_end = "$"; #else /* Everyone else */ char *plugin_re_beg = "\\.so\\."; char *plugin_re_end= "$"; #endif if (config_path) { f = fopen(config_path,"w"); if (!f) { agerr(AGERR,"failed to open %s for write.\n", config_path); exit(1); } fprintf(f, "# This file was generated by \"dot -c\" at time of install.\n\n"); fprintf(f, "# You may temporarily disable a plugin by removing or commenting out\n"); fprintf(f, "# a line in this file, or you can modify its \"quality\" value to affect\n"); fprintf(f, "# default plugin selection.\n\n"); fprintf(f, "# Manual edits to this file **will be lost** on upgrade.\n\n"); } libdir = gvconfig_libdir(gvc); config_re = gmalloc(strlen(plugin_re_beg) + 20 + strlen(plugin_re_end) + 1); #if defined(WIN32) && !defined(__MINGW32__) && !defined(__CYGWIN__) sprintf(config_re,"%s%s", plugin_re_beg, plugin_re_end); #elif defined(GVPLUGIN_VERSION) sprintf(config_re,"%s%d%s", plugin_re_beg, GVPLUGIN_VERSION, plugin_re_end); #else sprintf(config_re,"%s[0-9]+%s", plugin_re_beg, plugin_re_end); #endif if (regcomp(&re, config_re, REG_EXTENDED|REG_NOSUB) != 0) { agerr(AGERR,"cannot compile regular expression %s", config_re); } config_glob = gmalloc(strlen(libdir) + 1 + strlen(plugin_glob) + 1); strcpy(config_glob, libdir); strcat(config_glob, DIRSEP); strcat(config_glob, plugin_glob); /* load all libraries even if can't save config */ #if defined(WIN32) rc = glob(gvc, config_glob, GLOB_NOSORT, NULL, &globbuf); #else rc = glob(config_glob, GLOB_NOSORT, NULL, &globbuf); #endif if (rc == 0) { for (i = 0; i < globbuf.gl_pathc; i++) { re_status = regexec(&re, globbuf.gl_pathv[i], (size_t) 0, NULL, 0); if (re_status == 0) { library = gvplugin_library_load(gvc, globbuf.gl_pathv[i]); if (library) { gvconfig_plugin_install_from_library(gvc, globbuf.gl_pathv[i], library); } } } /* rescan with all libs loaded to check cross dependencies */ for (i = 0; i < globbuf.gl_pathc; i++) { re_status = regexec(&re, globbuf.gl_pathv[i], (size_t) 0, NULL, 0); if (re_status == 0) { library = gvplugin_library_load(gvc, globbuf.gl_pathv[i]); if (library) { path = strrchr(globbuf.gl_pathv[i],DIRSEP[0]); if (path) path++; if (f && path) gvconfig_write_library_config(gvc, path, library, f); } } } } regfree(&re); globfree(&globbuf); free(config_glob); free(config_re); if (f) fclose(f); }
N_NIMCALL(NimStringDesc*, getpackagename_153825)(NimStringDesc* path) { NimStringDesc* result; NI parents; { result = 0; parents = ((NI) 0); { { NimStringDesc* d_153831; NimStringDesc* current_153888; d_153831 = 0; current_153888 = copyString(path); { while (1) { current_153888 = nosparentDir(current_153888); { if (!((current_153888 ? current_153888->Sup.len : 0) == ((NI) 0))) goto LA7; goto LA3; } LA7: ; d_153831 = current_153888; { NIM_BOOL LOC11; LOC11 = 0; LOC11 = nsthasKey(packagecache_153601, d_153831); if (!LOC11) goto LA12; result = nstGet(packagecache_153601, d_153831); goto BeforeRet; } LA12: ; parents += ((NI) 1); { NimStringDesc* file_153841; NimStringDesc* HEX3Atmp_153855; glob_t f_153859; NI res_153861; int LOC15; file_153841 = 0; HEX3Atmp_153855 = 0; HEX3Atmp_153855 = HEX2F_118292(d_153831, ((NimStringDesc*) &TMP1433)); memset((void*)(&f_153859), 0, sizeof(f_153859)); res_153861 = 0; f_153859.gl_offs = ((NI) 0); f_153859.gl_pathc = ((NI) 0); f_153859.gl_pathv = NIM_NIL; LOC15 = 0; LOC15 = glob(HEX3Atmp_153855->data, ((int) 0), NIM_NIL, (&f_153859)); res_153861 = ((NI) (LOC15)); { if (!(res_153861 == ((NI) 0))) goto LA18; { NI i_153863; NI HEX3Atmp_153865; NI res_153867; i_153863 = 0; HEX3Atmp_153865 = 0; HEX3Atmp_153865 = (NI)(f_153859.gl_pathc - ((NI) 1)); res_153867 = ((NI) 0); { while (1) { TY118589 LOC23; if (!(res_153867 <= HEX3Atmp_153865)) goto LA22; i_153863 = res_153867; file_153841 = cstrToNimstr(f_153859.gl_pathv[(i_153863)- 0]); memset((void*)(&LOC23), 0, sizeof(LOC23)); nossplitFile(file_153841, (&LOC23)); result = copyString(LOC23.Field1); goto LA1; res_153867 += ((NI) 1); } LA22: ; } } } LA18: ; globfree((&f_153859)); } { NimStringDesc* file_153842; NimStringDesc* HEX3Atmp_153871; glob_t f_153875; NI res_153877; int LOC25; file_153842 = 0; HEX3Atmp_153871 = 0; HEX3Atmp_153871 = HEX2F_118292(d_153831, ((NimStringDesc*) &TMP1434)); memset((void*)(&f_153875), 0, sizeof(f_153875)); res_153877 = 0; f_153875.gl_offs = ((NI) 0); f_153875.gl_pathc = ((NI) 0); f_153875.gl_pathv = NIM_NIL; LOC25 = 0; LOC25 = glob(HEX3Atmp_153871->data, ((int) 0), NIM_NIL, (&f_153875)); res_153877 = ((NI) (LOC25)); { if (!(res_153877 == ((NI) 0))) goto LA28; { NI i_153879; NI HEX3Atmp_153881; NI res_153883; i_153879 = 0; HEX3Atmp_153881 = 0; HEX3Atmp_153881 = (NI)(f_153875.gl_pathc - ((NI) 1)); res_153883 = ((NI) 0); { while (1) { TY118589 LOC33; if (!(res_153883 <= HEX3Atmp_153881)) goto LA32; i_153879 = res_153883; file_153842 = cstrToNimstr(f_153875.gl_pathv[(i_153879)- 0]); memset((void*)(&LOC33), 0, sizeof(LOC33)); nossplitFile(file_153842, (&LOC33)); result = copyString(LOC33.Field1); goto LA1; res_153883 += ((NI) 1); } LA32: ; } } } LA28: ; globfree((&f_153875)); } } } LA3: ; } } LA1: ; { if (!result == 0) goto LA36; result = copyString(((NimStringDesc*) &TMP39)); } LA36: ; { NimStringDesc* d_153843; NimStringDesc* current_153892; d_153843 = 0; current_153892 = copyString(path); { while (1) { current_153892 = nosparentDir(current_153892); { if (!((current_153892 ? current_153892->Sup.len : 0) == ((NI) 0))) goto LA43; goto LA39; } LA43: ; d_153843 = current_153892; nstPut(packagecache_153601, d_153843, result); parents -= ((NI) 1); { if (!(parents <= ((NI) 0))) goto LA47; goto LA38; } LA47: ; } } LA39: ; } LA38: ; }BeforeRet: ; return result; }
static gboolean location_key_pressed(GntTree *tree, const char *key, GntFileSel *sel) { char *path; char *str; #if 0 int count; glob_t gl; struct stat st; int glob_ret; #endif if (strcmp(key, "\r") && strcmp(key, "\n")) return FALSE; str = (char*)gnt_entry_get_text(GNT_ENTRY(sel->location)); if (*str == G_DIR_SEPARATOR) path = g_strdup(str); else path = g_strdup_printf("%s" G_DIR_SEPARATOR_S "%s", sel->current, str); str = process_path(path); g_free(path); path = str; if (gnt_file_sel_set_current_location(sel, path)) goto success; path = g_path_get_dirname(str); g_free(str); if (!gnt_file_sel_set_current_location(sel, path)) { g_free(path); return FALSE; } #if 0 /* XXX: there needs to be a way to allow other methods for globbing, * like the read_fn stuff. */ glob_ret = glob(path, GLOB_MARK, NULL, &gl); if (!glob_ret) { /* XXX: do something with the return value */ char *loc = g_path_get_dirname(gl.gl_pathv[0]); stat(gl.gl_pathv[0], &st); gnt_file_sel_set_current_location(sel, loc); /* XXX: check the return value */ g_free(loc); if (!S_ISDIR(st.st_mode) && !sel->dirsonly) { gnt_tree_remove_all(GNT_TREE(sel->files)); for (count = 0; count < gl.gl_pathc; count++) { char *tmp = process_path(gl.gl_pathv[count]); loc = g_path_get_dirname(tmp); if (g_utf8_collate(sel->current, loc) == 0) { char *base = g_path_get_basename(tmp); char size[128]; snprintf(size, sizeof(size), "%ld", (long)st.st_size); gnt_tree_add_row_after(GNT_TREE(sel->files), base, gnt_tree_create_row(GNT_TREE(sel->files), base, size, ""), NULL, NULL); } g_free(loc); g_free(tmp); } gnt_widget_draw(sel->files); } } else if (sel->files) { gnt_tree_remove_all(GNT_TREE(sel->files)); gnt_widget_draw(sel->files); } globfree(&gl); #endif success: g_free(path); return TRUE; }
static gboolean pk_backend_config_parse (PkBackendConfig *config, const gchar *filename, PkBackendConfigSection *section, GError **error) { GFile *file; GFileInputStream *is; GDataInputStream *input; gchar *key, *str, *line = NULL; guint num = 1; GError *e = NULL; g_return_val_if_fail (config != NULL, FALSE); g_return_val_if_fail (filename != NULL, FALSE); file = g_file_new_for_path (filename); is = g_file_read (file, NULL, &e); if (is == NULL) { g_propagate_error (error, e); g_object_unref (file); return FALSE; } input = g_data_input_stream_new (G_INPUT_STREAM (is)); for (;; g_free (line), ++num) { line = g_data_input_stream_read_line (input, NULL, NULL, &e); if (line != NULL) { g_strstrip (line); } else { break; } /* skip empty lines */ if (*line == '\0' || *line == '#') { continue; } /* remove trailing comments */ for (str = line; *str != '\0' && *str != '#'; ++str); *str-- = '\0'; /* change sections */ if (*line == '[' && *str == ']') { *str = '\0'; str = line + 1; if (*str == '\0') { g_set_error (&e, ALPM_ERROR, ALPM_ERR_CONFIG_INVALID, "empty section name"); break; } section = pk_backend_config_enter_section (config, str); continue; } /* parse a directive */ if (section == NULL) { g_set_error (&e, ALPM_ERROR, ALPM_ERR_CONFIG_INVALID, "directive must belong to a section"); break; } str = line; key = strsep (&str, "="); g_strchomp (key); if (str != NULL) { g_strchug (str); } if (str == NULL) { /* set a boolean directive */ if (pk_backend_config_section_match (section, "options") == 0 && pk_backend_config_set_boolean (config, key)) { continue; } /* report error below */ } else if (g_strcmp0 (key, "Include") == 0) { gsize i; glob_t match = { 0 }; /* ignore globbing errors */ if (glob (str, GLOB_NOCHECK, NULL, &match) != 0) { continue; } /* parse the files that matched */ for (i = 0; i < match.gl_pathc; ++i) { if (!pk_backend_config_parse (config, match.gl_pathv[i], section, &e)) { break; } } globfree (&match); if (e != NULL) { break; } else { continue; } } else if (pk_backend_config_section_match (section, "options") == 0) { /* set a string or list directive */ if (pk_backend_config_set_string (config, key, str) || pk_backend_config_set_list (config, key, str)) { continue; } /* report error below */ } else if (g_strcmp0 (key, "Server") == 0) { if (!pk_backend_config_add_server (config, section, str, &e)) { break; } else { continue; } } if (g_strcmp0 (key, "SigLevel") == 0 && str != NULL) { pk_backend_config_add_siglevel (config, section, str); continue; } /* report errors from above */ g_set_error (&e, ALPM_ERROR, ALPM_ERR_CONFIG_INVALID, "unrecognised directive '%s'", key); break; } g_object_unref (input); g_object_unref (is); g_object_unref (file); if (e != NULL) { g_propagate_prefixed_error (error, e, "%s:%u", filename, num); return FALSE; } else { return TRUE; } }
int main(int argc, char **argv) { char str[256],*p; int i,j,file; ulong length,max_users=0xffffffff; uint32_t l; sub_status_t *sub_status; scfg_t cfg; glob_t gl; size_t glp; fprintf(stderr,"\nSMBACTIV Version %s (%s) - Synchronet Message Base Activity " "Monitor\n", SMBACTIV_VER, PLATFORM_DESC); if(argc>1) max_users=atol(argv[1]); if(!max_users) { lprintf("\nusage: SMBACTIV [max_users]\n\n"); lprintf("max_users = limit output to subs read by this many users " "or less\n"); return(0); } p=getenv("SBBSCTRL"); if(p==NULL) { printf("\nSBBSCTRL environment variable not set.\n"); #ifdef __unix__ printf("\nExample: export SBBSCTRL=/sbbs/ctrl\n"); #else printf("\nExample: SET SBBSCTRL=C:\\SBBS\\CTRL\n"); #endif return(1); } memset(&cfg,0,sizeof(cfg)); cfg.size=sizeof(cfg); SAFECOPY(cfg.ctrl_dir,p); if(!load_cfg(&cfg,NULL,TRUE,str)) { fprintf(stderr,"!ERROR loading configuration files: %s\n",str); return(1); } chdir(cfg.ctrl_dir); if((sub_status=(sub_status_t *)MALLOC (cfg.total_subs*sizeof(sub_status_t)))==NULL) { printf("ERROR Allocating memory for sub_status\r\n"); return(1); } lprintf("\nReading sub-board "); for(i=0;i<cfg.total_subs;i++) { lprintf("%5d of %-5d\b\b\b\b\b\b\b\b\b\b\b\b\b\b",i+1,cfg.total_subs); sprintf(smb.file,"%s%s",cfg.sub[i]->data_dir,cfg.sub[i]->code); if((j=smb_open(&smb))!=0) { lprintf("Error %d opening %s\r\n",j,smb.file); sub_status[i].read=0; sub_status[i].firstmsg=0L; continue; } sub_status[i].read=0; sub_status[i].firstmsg=first_msg(); smb_close(&smb); } sprintf(str,"%suser/ptrs/*.ixb",cfg.data_dir); if(glob(str, GLOB_MARK, NULL, &gl)) { lprintf("Unable to find any user pointer files.\n"); globfree(&gl); free(sub_status); return(1); } lprintf("\nComparing user pointers "); for(glp=0; glp<gl.gl_pathc; glp++) { lprintf("%-5d\b\b\b\b\b",glp); SAFECOPY(str,gl.gl_pathv[glp]); if((file=nopen(str,O_RDONLY|O_BINARY))==-1) { continue; } length=filelength(file); for(i=0;i<cfg.total_subs;i++) { if(sub_status[i].read>max_users) continue; if(length<(cfg.sub[i]->ptridx+1)*10UL) continue; else { lseek(file,((long)cfg.sub[i]->ptridx*10L)+4L,SEEK_SET); read(file,&l,4); } if(l>sub_status[i].firstmsg) sub_status[i].read++; } close(file); } globfree(&gl); printf("NumUsers Sub-board\n"); printf("-------- -------------------------------------------------" "-----------\n"); for(i=0;i<cfg.total_subs;i++) { if(sub_status[i].read>max_users) continue; printf("%8lu %-*s %-*s\n" ,sub_status[i].read ,LEN_GSNAME,cfg.grp[cfg.sub[i]->grp]->sname ,LEN_SLNAME,cfg.sub[i]->lname); } return(0); }
/* return handle for kernel pps, or -1 */ static int init_kernel_pps(struct gps_device_t *session) { int ldisc = 18; /* the PPS line discipline */ pps_params_t pp; glob_t globbuf; size_t i; /* to match type of globbuf.gl_pathc */ char pps_num = 0; /* /dev/pps[pps_num] is our device */ char path[GPS_PATH_MAX] = ""; session->kernelpps_handle = -1; if ( !isatty(session->gpsdata.gps_fd) ) { gpsd_report(LOG_INF, "KPPS gps_fd not a tty\n"); return -1; } /* Attach the line PPS discipline, so no need to ldattach */ /* This activates the magic /dev/pps0 device */ /* Note: this ioctl() requires root */ if ( 0 > ioctl(session->gpsdata.gps_fd, TIOCSETD, &ldisc)) { gpsd_report(LOG_INF, "KPPS cannot set PPS line discipline: %s\n" , strerror(errno)); return -1; } /* uh, oh, magic file names!, this is not how RFC2783 was designed */ /* need to look in /sys/devices/virtual/pps/pps?/path * (/sys/class/pps/pps?/path is just a link to that) * to find the /dev/pps? that matches our serial port. * this code fails if there are more then 10 pps devices. * * yes, this could be done with libsysfs, but trying to keep the * number of required libs small */ memset( (void *)&globbuf, 0, sizeof(globbuf)); glob("/sys/devices/virtual/pps/pps?/path", 0, NULL, &globbuf); memset( (void *)&path, 0, sizeof(path)); for ( i = 0; i < globbuf.gl_pathc; i++ ) { int fd = open(globbuf.gl_pathv[i], O_RDONLY); if ( 0 <= fd ) { ssize_t r = read( fd, path, sizeof(path) -1); if ( 0 < r ) { path[r - 1] = '\0'; /* remove trailing \x0a */ } close(fd); } gpsd_report(LOG_INF, "KPPS checking %s, %s\n" , globbuf.gl_pathv[i], path); if ( 0 == strncmp( path, session->gpsdata.dev.path, sizeof(path))) { /* this is the pps we are looking for */ /* FIXME, now build the proper pps device path */ pps_num = globbuf.gl_pathv[i][28]; break; } memset( (void *)&path, 0, sizeof(path)); } /* done with blob, clear it */ globfree(&globbuf); if ( 0 == pps_num ) { gpsd_report(LOG_INF, "KPPS device not found.\n"); return -1; } /* contruct the magic device path */ (void)snprintf(path, sizeof(path), "/dev/pps%c", pps_num); /* root privs are required for this device open */ int ret = open(path, O_RDWR); if ( 0 > ret ) { gpsd_report(LOG_INF, "KPPS cannot open %s: %s\n" , path, strerror(errno)); return -1; } /* root privs are not required past this point */ if ( 0 > time_pps_create(ret, &session->kernelpps_handle )) { gpsd_report(LOG_INF, "KPPS time_pps_create(%d) failed: %s\n" , ret, strerror(errno)); return -1; } else { /* have kernel PPS handle */ int caps; /* get features supported */ if ( 0 > time_pps_getcap(session->kernelpps_handle, &caps)) { gpsd_report(LOG_ERROR, "KPPS time_pps_getcap() failed\n"); } else { gpsd_report(LOG_INF, "KPPS caps %0x\n", caps); } /* linux 2.6.34 can not PPS_ECHOASSERT | PPS_ECHOCLEAR */ memset( (void *)&pp, 0, sizeof(pps_params_t)); pp.mode = PPS_CAPTUREBOTH; if ( 0 > time_pps_setparams(session->kernelpps_handle, &pp)) { gpsd_report(LOG_ERROR, "KPPS time_pps_setparams() failed: %s\n", strerror(errno)); time_pps_destroy(session->kernelpps_handle); return -1; } } return 0; }
static int init_kernel_pps(struct inner_context_t *inner_context) /* return handle for kernel pps, or -1; requires root privileges */ { pps_params_t pp; int ret; #ifdef __linux__ /* These variables are only needed by Linux to find /dev/ppsN. */ int ldisc = 18; /* the PPS line discipline */ glob_t globbuf; #endif char path[PATH_MAX] = ""; volatile struct pps_thread_t *pps_thread = inner_context->pps_thread; inner_context->kernelpps_handle = -1; inner_context->pps_canwait = false; /* * This next code block abuses "ret" by storing the filedescriptor * to use for RFC2783 calls. */ #ifndef __clang_analyzer__ ret = -1; /* this ret will not be unneeded when the 'else' part * of the followinng ifdef becomes an #elif */ #endif /* __clang_analyzer__ */ #ifdef __linux__ /* * Some Linuxes, like the RasbPi's, have PPS devices preexisting. * Other OS have no way to automatically determine the proper /dev/ppsX. * Allow user to pass in an explicit PPS device path. * * (We use strncpy() here because this might be compiled where * strlcpy() is not available.) */ if (strncmp(pps_thread->devicename, "/dev/pps", 8) == 0) (void)strncpy(path, pps_thread->devicename, sizeof(path)); else { char pps_num = '\0'; /* /dev/pps[pps_num] is our device */ size_t i; /* to match type of globbuf.gl_pathc */ /* * Otherwise one must make calls to associate a serial port with a * /dev/ppsN device and then grovel in system data to determine * the association. */ /* Attach the line PPS discipline, so no need to ldattach */ /* This activates the magic /dev/pps0 device */ /* Note: this ioctl() requires root, and device is a tty */ if ( 0 > ioctl(pps_thread->devicefd, TIOCSETD, &ldisc)) { char errbuf[BUFSIZ] = "unknown error"; strerror_r(errno, errbuf, sizeof(errbuf)); pps_thread->log_hook(pps_thread, THREAD_INF, "KPPS:%s cannot set PPS line discipline %s\n", pps_thread->devicename, errbuf); return -1; } /* uh, oh, magic file names!, RFC2783 neglects to specify how * to associate the serial device and pps device names */ /* need to look in /sys/devices/virtual/pps/pps?/path * (/sys/class/pps/pps?/path is just a link to that) * to find the /dev/pps? that matches our serial port. * this code fails if there are more then 10 pps devices. * * yes, this could be done with libsysfs, but trying to keep * the number of required libs small, and libsysfs would still * be linux only */ memset( (void *)&globbuf, 0, sizeof(globbuf)); (void)glob("/sys/devices/virtual/pps/pps?/path", 0, NULL, &globbuf); memset( (void *)&path, 0, sizeof(path)); for ( i = 0; i < globbuf.gl_pathc; i++ ) { int fd = open(globbuf.gl_pathv[i], O_RDONLY); if ( 0 <= fd ) { ssize_t r = read( fd, path, sizeof(path) -1); if ( 0 < r ) { path[r - 1] = '\0'; /* remove trailing \x0a */ } (void)close(fd); } pps_thread->log_hook(pps_thread, THREAD_PROG, "KPPS:%s checking %s, %s\n", pps_thread->devicename, globbuf.gl_pathv[i], path); if ( 0 == strncmp( path, pps_thread->devicename, sizeof(path))) { /* this is the pps we are looking for */ /* FIXME, now build the proper pps device path */ pps_num = globbuf.gl_pathv[i][28]; break; } memset( (void *)&path, 0, sizeof(path)); } /* done with blob, clear it */ globfree(&globbuf); if ( 0 == (int)pps_num ) { pps_thread->log_hook(pps_thread, THREAD_INF, "KPPS:%s device not found.\n", pps_thread->devicename); return -1; } /* construct the magic device path */ (void)snprintf(path, sizeof(path), "/dev/pps%c", pps_num); } /* root privs are probably required for this device open * do not bother to check uid, just go for the open() */ ret = open(path, O_RDWR); if ( 0 > ret ) { char errbuf[BUFSIZ] = "unknown error"; (void)strerror_r(errno, errbuf, sizeof(errbuf)); pps_thread->log_hook(pps_thread, THREAD_INF, "KPPS:%s cannot open %s: %s\n", pps_thread->devicename, path, errbuf); return -1; } #else /* not __linux__ */ /* * On BSDs that support RFC2783, one uses the API calls on serial * port file descriptor. * * FIXME! need more specific than 'not linux' */ (void)strlcpy(path, pps_thread->devicename, sizeof(path)); // cppcheck-suppress redundantAssignment ret = pps_thread->devicefd; #endif /* assert(ret >= 0); */ pps_thread->log_hook(pps_thread, THREAD_INF, "KPPS:%s RFC2783 path:%s, fd is %d\n", pps_thread->devicename, path, ret); /* RFC 2783 implies the time_pps_setcap() needs priviledges * * keep root a tad longer just in case */ if ( 0 > time_pps_create(ret, (pps_handle_t *)&inner_context->kernelpps_handle )) { char errbuf[BUFSIZ] = "unknown error"; (void)strerror_r(errno, errbuf, sizeof(errbuf)); pps_thread->log_hook(pps_thread, THREAD_INF, "KPPS:%s time_pps_create(%d) failed: %s\n", pps_thread->devicename, ret, errbuf); return -1; } /* have kernel PPS handle */ /* get RFC2783 features supported */ inner_context->pps_caps = 0; if ( 0 > time_pps_getcap(inner_context->kernelpps_handle, &inner_context->pps_caps)) { char errbuf[BUFSIZ] = "unknown error"; inner_context->pps_caps = 0; (void)strerror_r(errno, errbuf, sizeof(errbuf)); pps_thread->log_hook(pps_thread, THREAD_INF, "KPPS:%s time_pps_getcap() failed: %.100s\n", pps_thread->devicename, errbuf); return -1; } else { pps_thread->log_hook(pps_thread, THREAD_INF, "KPPS:%s pps_caps 0x%02X\n", pps_thread->devicename, inner_context->pps_caps); } /* construct the setparms structure */ memset( (void *)&pp, 0, sizeof(pps_params_t)); pp.api_version = PPS_API_VERS_1; /* version 1 protocol */ if ( 0 == (PPS_TSFMT_TSPEC & inner_context->pps_caps ) ) { /* PPS_TSFMT_TSPEC means return a timespec * mandatory for driver to implement, require it */ pps_thread->log_hook(pps_thread, THREAD_WARN, "KPPS:%s fail, missing mandatory PPS_TSFMT_TSPEC\n", pps_thread->devicename); return -1; } if ( 0 != (PPS_CANWAIT & inner_context->pps_caps ) ) { /* we can wait! so no need for TIOCMIWAIT */ pps_thread->log_hook(pps_thread, THREAD_INF, "KPPS:%s have PPS_CANWAIT\n", pps_thread->devicename); inner_context->pps_canwait = true; } pp.mode = PPS_TSFMT_TSPEC; switch ( (PPS_CAPTUREASSERT | PPS_CAPTURECLEAR) & inner_context->pps_caps ) { case PPS_CAPTUREASSERT: pps_thread->log_hook(pps_thread, THREAD_WARN, "KPPS:%s missing PPS_CAPTURECLEAR, pulse may be offset\n", pps_thread->devicename); pp.mode |= PPS_CAPTUREASSERT; break; case PPS_CAPTURECLEAR: pps_thread->log_hook(pps_thread, THREAD_WARN, "KPPS:%s missing PPS_CAPTUREASSERT, pulse may be offset\n", pps_thread->devicename); pp.mode |= PPS_CAPTURECLEAR; break; case PPS_CAPTUREASSERT | PPS_CAPTURECLEAR: pp.mode |= PPS_CAPTUREASSERT | PPS_CAPTURECLEAR; break; default: /* THREAD_ERR in the calling routine */ pps_thread->log_hook(pps_thread, THREAD_INF, "KPPS:%s missing PPS_CAPTUREASSERT and CLEAR\n", pps_thread->devicename); return -1; } if ( 0 > time_pps_setparams(inner_context->kernelpps_handle, &pp)) { char errbuf[BUFSIZ] = "unknown error"; (void)strerror_r(errno, errbuf, sizeof(errbuf)); pps_thread->log_hook(pps_thread, THREAD_ERROR, "KPPS:%s time_pps_setparams(mode=0x%02X) failed: %s\n", pps_thread->devicename, pp.mode, errbuf); (void)time_pps_destroy(inner_context->kernelpps_handle); return -1; } return 0; }
int load_font_textures () { #ifndef NEW_TEXTURES int poor_man_save=poor_man; int use_mipmaps_save=use_mipmaps; #endif /* NEW_TEXTURES */ size_t i = 0; char *glob_pattern; #ifdef WINDOWS struct _finddata_t c_file; long hFile; #else //WINDOWS int ret; glob_t glob_res; size_t j; #endif //WINDOWS char file[60] = ""; char str[60] = ""; if (fonts[0] == NULL || fonts[1] == NULL || fonts[2] == NULL || fonts[3]==NULL ) { for (i = 0; i < FONTS_ARRAY_SIZE; i++) { if (fonts[i] != NULL) free (fonts[i]); fonts[i] = NULL; } if ( !init_fonts () ) return 0; } #ifndef NEW_TEXTURES poor_man=0; use_mipmaps=0; #endif /* NEW_TEXTURES */ #ifdef NEW_TEXTURES fonts[0]->texture_id = load_texture_cached("textures/font.dds", tt_font); #else /* NEW_TEXTURES */ fonts[0]->texture_id = load_texture_cache("./textures/font.bmp", 0); #endif /* NEW_TEXTURES */ i = 1; // Force the selection of the base font. add_multi_option("chat_font", "Type 1"); add_multi_option("name_font", "Type 1"); // Find what font's exist and load them glob_pattern = malloc(strlen(datadir)+sizeof(texture_dir)+10+1); //+10 = font*.bmp* #ifdef NEW_TEXTURES sprintf(glob_pattern, "%s%sfont*.dds", datadir, texture_dir); #else /* NEW_TEXTURES */ sprintf(glob_pattern, "%s%sfont*.bmp*", datadir, texture_dir); #endif /* NEW_TEXTURES */ #ifdef WINDOWS if( (hFile = _findfirst( glob_pattern, &c_file )) == -1L ){ free(glob_pattern); return 0; } do { int len; safe_strncpy(file, c_file.name, sizeof(file)); #else //!WINDOWS ret = glob(glob_pattern, 0, NULL, &glob_res); if(ret != 0) { LOG_ERROR("Unable to find any font textures\n"); free(glob_pattern); return 0; } j = 0; while (j < glob_res.gl_pathc && i < FONTS_ARRAY_SIZE) { int len; safe_strncpy(file, glob_res.gl_pathv[j]+sizeof(texture_dir)-1+strlen(datadir), sizeof(file)); #endif //WINDOWS len= strlen(file); #ifdef NEW_TEXTURES if (((len + sizeof(texture_dir) - 1) < sizeof(str)) && !strncasecmp(file, "font", 4) && has_suffix(file, len, ".dds", 4)) { safe_snprintf(str, sizeof(str), "./textures/%s", file); //Use a relative path here, load_texture_cache_deferred() is using the path wrappers. file[len - 4] = 0; fonts[i]->texture_id = load_texture_cached(str, tt_font); #else /* NEW_TEXTURES */ if (len+sizeof(texture_dir)-1 < sizeof(str) && !strncasecmp(file, "font", 4) && (has_suffix(file, len, ".bmp", 4) || has_suffix(file, len, ".bmp.gz", 7)) && (!has_suffix(file, len, "_alpha.bmp", 10)) && (!has_suffix(file, len, "_alpha.bmp.gz", 13))) { // Get the filename, remove the .bmp and add _alpha.bmp to a copy, then replace the .bmp safe_snprintf(str, sizeof(str), "./textures/%s", file); //Use a relative path here, load_texture_cache_deferred() is using the path wrappers. if(has_suffix(file, len, ".bmp.gz", 7)){ file[len - 7]= 0; } else { file[len - 4]= 0; } fonts[i]->texture_id = load_texture_cache_deferred(str, 0); #endif /* NEW_TEXTURES */ safe_snprintf(font_names[i], sizeof(font_names[i]), "Type %i - %s", i + 1, file); add_multi_option("chat_font", font_names[i]); add_multi_option("name_font", font_names[i]); i++; } #ifndef WINDOWS j++; #endif //WINDOWS } #ifdef WINDOWS while ( _findnext( hFile, &c_file ) == 0 ); _findclose( hFile ); #else //!WINDOWS globfree(&glob_res); #endif //WINDOWS free(glob_pattern); #ifndef NEW_TEXTURES poor_man=poor_man_save; use_mipmaps=use_mipmaps_save; #endif /* NEW_TEXTURES */ //set the default font cur_font_num = 0; font_text = fonts[0]->texture_id; return 1; } int set_font_parameters (int num) { int i; // error checking if(num < 0 || num >= FONTS_ARRAY_SIZE) { return -1; } // allocate space if needed if(fonts[num] == NULL) { fonts[num]=(font_info *)calloc(1, sizeof(font_info)); if(fonts[num] == NULL) { LOG_ERROR(cant_load_font); return -1; } } //watch the highest font if(num >= max_fonts) { max_fonts=num+1; } // set default font info my_strcp (fonts[num]->name, "default"); fonts[num]->spacing=0; // load font information // TODO: write this and remove the hack! if(num!=1||num!=2)for(i=0; i<FONTS_ARRAY_SIZE*FONT_CHARS_PER_LINE; i++) fonts[num]->widths[i]=12; if(num==1){ static int widths[]={ 4,2,7,11,8,12,12,2,7,7,9,10,3,8, 2,10,10,10,8,8,10,7,9,9,9,9,3,3, 10,10,10,9,12,12,9,10,10,9,9,10,9,8, 7,11,8,11,10,11,9,11,11,9,10,9,12,12, 12,12,10,6,10,6,10,12,3,11,9,9,9,9, 8,9,9,4,6,10,4,11,9,10,9,9,8,8, 8,9,10,12,10,10,9,8,2,8,10,8,12,12, 12,12,12,12,12,12,12,12,12,12,12,12,12,12, 12,12,12,12,12,12,12,12,12,12,12,12,12,12, 12,12,12,12,12,12,12,12,12,12,12,12,12,12, }; memcpy(fonts[num]->widths, widths, sizeof(widths)); fonts[num]->spacing=4; } if(num==2){ static int widths[]={ 8, 8, 8, 10, 8, 10, 10, 8, 8, 8, 8, 10, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 10, 10, 10, 8, 12, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 8, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 8, 8, 8, 8, 8, 8, 8, 10, 8, 8, 8, 8, 8, 8, 10, 8, 8, 8, 8, 8, 8, 8, 8, 8, 10, 8, 8, 8, 10, 8, 10, 10, 8, 10, 8, 8, 8, 10, 10, 10, 8, 10, 10, 8, 8, 8, 12, 12, 12, 10, 10, 12, 10, 12, 12, 12, }; memcpy(fonts[num]->widths, widths, sizeof(widths)); fonts[num]->spacing=2; } //and return return num; } int set_font(int num) { if(num >= 0 && num < max_fonts && fonts[num] && fonts[num]->texture_id >= 0) { cur_font_num=num; font_text=fonts[cur_font_num]->texture_id; } return cur_font_num; }
disk_t *fewf_init(const char *device, const int mode) { unsigned int num_files=0; char **filenames= NULL; disk_t *disk=NULL; struct info_fewf_struct *data; #if !defined( HAVE_LIBEWF_V2_API ) && defined( HAVE_GLOB_H ) glob_t globbuf; #endif data=(struct info_fewf_struct *)MALLOC(sizeof(struct info_fewf_struct)); memset(data, 0, sizeof(struct info_fewf_struct)); data->file_name = strdup(device); data->handle=NULL; data->mode = mode; #ifdef DEBUG_EWF #if defined( HAVE_LIBEWF_V2_API ) libewf_notify_set_stream( stderr, NULL ); libewf_notify_set_verbose( 1 ); #else libewf_set_notify_values( stderr, 1 ); #endif #endif #if defined( HAVE_LIBEWF_V2_API ) if( libewf_glob( data->file_name, strlen(data->file_name), LIBEWF_FORMAT_UNKNOWN, &filenames, (int *)&num_files, NULL ) != 1 ) { log_error("libewf_glob failed\n"); free(data); return NULL; } #elif defined( HAVE_GLOB_H ) { globbuf.gl_offs = 0; glob(data->file_name, GLOB_DOOFFS, NULL, &globbuf); if(globbuf.gl_pathc>0) { filenames=(char **)MALLOC(globbuf.gl_pathc * sizeof(*filenames)); for (num_files=0; num_files<globbuf.gl_pathc; num_files++) { filenames[num_files]=globbuf.gl_pathv[num_files]; } } } if(filenames==NULL) { globfree(&globbuf); free(data); return NULL; } #else { filenames=(char **)MALLOC(1*sizeof(*filenames)); filenames[num_files] = data->file_name; num_files++; } #endif if((mode&TESTDISK_O_RDWR)==TESTDISK_O_RDWR) { #if defined( HAVE_LIBEWF_V2_API ) if( libewf_handle_initialize( &( data->handle ), NULL ) != 1 ) { log_error("libewf_handle_initialize failed\n"); libewf_glob_free( filenames, num_files, NULL ); free(data); return NULL; } if( libewf_handle_open( data->handle, filenames, num_files, LIBEWF_OPEN_READ_WRITE, NULL ) != 1 ) { log_error("libewf_handle_open(%s) failed\n", device); } #else data->handle=libewf_open(filenames, num_files, LIBEWF_OPEN_READ_WRITE); if(data->handle==NULL) { log_error("libewf_open(%s) failed\n", device); } #endif /* defined( HAVE_LIBEWF_V2_API ) */ } if(data->handle==NULL) { data->mode&=~TESTDISK_O_RDWR; #if defined( HAVE_LIBEWF_V2_API ) if( libewf_handle_initialize( &( data->handle ), NULL ) != 1 ) { log_error("libewf_handle_initialize failed\n"); libewf_glob_free( filenames, num_files, NULL ); free(data); return NULL; } if( libewf_handle_open( data->handle, filenames, num_files, LIBEWF_OPEN_READ, NULL ) != 1 ) { log_error("libewf_handle_open(%s) failed\n", device); libewf_handle_free( &( data->handle ), NULL ); libewf_glob_free( filenames, num_files, NULL ); free(data); return NULL; } #else data->handle=libewf_open(filenames, num_files, LIBEWF_OPEN_READ); if(data->handle==NULL) { log_error("libewf_open(%s) failed\n", device); #if defined( HAVE_GLOB_H ) globfree(&globbuf); #endif free(filenames); free(data); return NULL; } #endif /* defined( HAVE_LIBEWF_V2_API ) */ } #if defined( HAVE_LIBEWF_V2_API ) if( libewf_handle_set_header_values_date_format( data->handle, LIBEWF_DATE_FORMAT_DAYMONTH, NULL ) != 1 ) { log_error("%s Unable to set header values date format\n", device); } #else if( libewf_parse_header_values( data->handle, LIBEWF_DATE_FORMAT_DAYMONTH) != 1 ) { log_error("%s Unable to parse EWF header values\n", device); } #endif disk=(disk_t *)MALLOC(sizeof(*disk)); init_disk(disk); disk->arch=&arch_none; disk->device=strdup(device); disk->data=data; disk->description=fewf_description; disk->description_short=fewf_description_short; disk->pread_fast=fewf_pread_fast; disk->pread=fewf_pread; disk->pwrite=(data->mode&TESTDISK_O_RDWR?fewf_pwrite:fewf_nopwrite); disk->sync=fewf_sync; disk->access_mode=(data->mode&TESTDISK_O_RDWR); disk->clean=fewf_clean; #if defined( HAVE_LIBEWF_V2_API ) || defined( LIBEWF_GET_BYTES_PER_SECTOR_HAVE_TWO_ARGUMENTS ) { uint32_t bytes_per_sector = 0; #if defined( HAVE_LIBEWF_V2_API ) if( libewf_handle_get_bytes_per_sector( data->handle, &bytes_per_sector, NULL ) != 1 ) #else if( libewf_get_bytes_per_sector(data->handle, &bytes_per_sector)<0) #endif { disk->sector_size=DEFAULT_SECTOR_SIZE; } else { disk->sector_size=bytes_per_sector; } } #else disk->sector_size=libewf_get_bytes_per_sector(data->handle); #endif // printf("libewf_get_bytes_per_sector %u\n",disk->sector_size); if(disk->sector_size==0) disk->sector_size=DEFAULT_SECTOR_SIZE; /* Set geometry */ disk->geom.cylinders=0; disk->geom.heads_per_cylinder=1; disk->geom.sectors_per_head=1; disk->geom.bytes_per_sector=disk->sector_size; /* Get disk_real_size */ #if defined( HAVE_LIBEWF_V2_API ) || defined( LIBEWF_GET_MEDIA_SIZE_HAVE_TWO_ARGUMENTS ) { size64_t media_size = 0; #if defined( HAVE_LIBEWF_V2_API ) if( libewf_handle_get_media_size( data->handle, &media_size, NULL ) != 1 ) #else if(libewf_get_media_size(data->handle, &media_size)<0) #endif { disk->disk_real_size=0; } else { disk->disk_real_size=media_size; } } #else disk->disk_real_size=libewf_get_media_size(data->handle); #endif update_disk_car_fields(disk); #if defined( HAVE_LIBEWF_V2_API ) libewf_glob_free( filenames, num_files, NULL ); #else #if defined( HAVE_GLOB_H ) globfree(&globbuf); #endif free(filenames); #endif return disk; }
int armour_config_read (armour_t *self, const char *filepath) { char *str, *fstart; int fd, flen; struct stat sb; enum { DEFAULT, ERROR } state; fd = open (filepath, O_RDONLY); if (fd < 0) { warn ("open %s", filepath); return -1; } if (fstat (fd, &sb) < 0) { warn ("fstat %s", filepath); return -1; } flen = sb.st_size; if (flen == 0) return 0; str = mmap (NULL, flen, PROT_READ, MAP_PRIVATE, fd, 0); if (str == MAP_FAILED) { warn ("mmap %s", filepath); return -1; } fstart = str; //TODO lock the file for reading! state = DEFAULT; while (str - fstart < flen) { char *start, *filepath = NULL, *linkname = NULL; // TODO so far we discard the options armour_options options = { 0 }; switch (state) { case DEFAULT: default: if (isspace (*str)) { while (isspace (*++str)); break; } else if (*str == '#') { while (*str++ != '\n'); break; } /* new entry */ else /* if (*str == '/') */{ start = str; while (!isspace (*str) && *str != '{' && *str++ != '*'); /* we only like absolute pathnames */ if (*start != '/') { //errno = EINVAL; //warn ("file %s", filepath); state = ERROR; break; } /* parse the filepath */ filepath = strndup (start, str - start); // null byte added if (*(str - 1) == '*') { /* globbing pathname */ glob_t gl; if (glob (filepath, 0, NULL, &gl) == 0) { size_t cc = gl.gl_pathc; while (cc--) { char *file = NULL; if (check_file (gl.gl_pathv[cc], &file) == 0) { armour_add_new (self, file? file: gl.gl_pathv[cc]); free (file); } } } else { state = ERROR; } globfree (&gl); free (filepath); break; } if (check_file (filepath, &linkname) < 0) { free (filepath); state = ERROR; break; } while (isspace (*++str)); if (*str == '{') { str++; /* optional parameters for 'filepath' */ while (*str != '}') { char *optag = NULL, **opval = NULL; while (isspace (*str)) str++; start = str; while (!isspace (*str) && *str != ':') str++; optag = strndup (start, str - start); if (strcmp (optag, "pidfile") == 0) opval = &options.pidfile; else if (strcmp (optag, "command") == 0) opval = &options.command; else if (strcmp (optag, "notify") == 0) opval = &options.notify; else { warn ("wrong option: %s", optag); state = ERROR; break; } while (isspace (*++str)); if (*str++ != ':') { free (optag); state = ERROR; break; } while (isspace (*++str)); start = str; if (*str == '"') { start++; while (*++str != '"') if (*str == '\\') str++; } else { while (!isspace (*++str)); } *opval = strndup (start, str - start); free (optag); while (isspace (*++str)); continue; } str++; } if (state != ERROR) { /* store entry */ if (linkname) { free (filepath); filepath = linkname; } armour_add_new (self, filepath); free (filepath); state = DEFAULT; } break; } case ERROR: state = DEFAULT; while (isspace (*str)) str++; if (*str != '{') break; while (*str++ != '}'); break; } } return 0; }
BOOL DLLCALL fexistcase(char *path) { #if defined(_WIN32) char* fname; long handle; struct _finddata_t f; if(access(path,0)==-1 && !strchr(path,'*') && !strchr(path,'?')) return(FALSE); if((handle=_findfirst((char*)path,&f))==-1) return(FALSE); _findclose(handle); if(f.attrib&_A_SUBDIR) return(FALSE); fname=getfname(path); /* Find filename in path */ strcpy(fname,f.name); /* Correct filename */ return(TRUE); #else /* Unix or OS/2 */ char globme[MAX_PATH*4+1]; char fname[MAX_PATH+1]; char tmp[5]; char *p; int i; glob_t glb; if(!strchr(path,'*') && !strchr(path,'?') && fnameexist(path)) return(TRUE); SAFECOPY(globme,path); p=getfname(globme); SAFECOPY(fname,p); *p=0; for(i=0;fname[i];i++) { if(isalpha(fname[i])) sprintf(tmp,"[%c%c]",toupper(fname[i]),tolower(fname[i])); else sprintf(tmp,"%c",fname[i]); strncat(globme,tmp,MAX_PATH*4); } #if 0 if(strcspn(path,"?*")!=strlen(path)) { sprintf(path,"%.*s",MAX_PATH,globme); return(fexist(path)); } #endif if(glob(globme,GLOB_MARK,NULL,&glb) != 0) return(FALSE); if(glb.gl_pathc>0) { for(i=0;i<glb.gl_pathc;i++) { if(*lastchar(glb.gl_pathv[i]) != '/') break; } if(i<glb.gl_pathc) { sprintf(path,"%.*s",MAX_PATH,glb.gl_pathv[i]); globfree(&glb); return TRUE; } } globfree(&glb); return FALSE; #endif }
tAsyncCall* System_IO_FileInternal_GetFileSystemEntries(PTR pThis_, PTR pParams, PTR pReturnValue) { //HEAP_PTR pathHP = ((HEAP_PTR*)pParams)[0]; HEAP_PTR pathPatternHP = ((HEAP_PTR*)pParams)[1]; U32 attrs = ((U32*)pParams)[2]; U32 mask = ((U32*)pParams)[3]; U32* pError = ((U32**)pParams)[4]; U32 /*pathLen,*/ pathPatternLen; //STRING2 path = SystemString_GetString(pathHP, &pathLen); STRING2 pathPattern = SystemString_GetString(pathPatternHP, &pathPatternLen); HEAP_PTR retArray; U32 tempStoreSize = 32, tempStoreOfs = 0, i; HEAP_PTR *pTempStore = malloc(tempStoreSize * sizeof(void*)); PTR arrayElements; #ifdef WIN32 unsigned short pathPatternNullTerm[256]; HANDLE hFind; WIN32_FIND_DATA find; memcpy(pathPatternNullTerm, pathPattern, pathPatternLen << 1); pathPatternNullTerm[pathPatternLen] = 0; hFind = FindFirstFileW(pathPatternNullTerm, &find); if (hFind != INVALID_HANDLE_VALUE) { do { if ((find.dwFileAttributes & mask) == attrs) { HEAP_PTR str; // Want this file, so store it in tempStore if (tempStoreOfs >= tempStoreSize) { tempStoreSize <<= 1; pTempStore = realloc(pTempStore, tempStoreSize * sizeof(void*)); } str = SystemString_FromCharPtrUTF16(find.cFileName); // Need to temporarily make these undeletable, in case a GC happens before they're in the array Heap_MakeUndeletable(str); pTempStore[tempStoreOfs++] = str; } } while (FindNextFile(hFind, &find) != 0); FindClose(hFind); } #else unsigned char path8[256]; glob_t gl; for (i=0; i<pathPatternLen; i++) { path8[i] = (U8)pathPattern[i]; } path8[i] = 0; i = glob(path8, GLOB_NOSORT, NULL, &gl); if (i == 0) { for (i=0; i<gl.gl_pathc; i++) { unsigned char *pResult = gl.gl_pathv[i]; U32 fileAttrs = Attrs(pResult, pError); if (fileAttrs == (U32)-1) { break; } if ((fileAttrs & mask) == attrs) { HEAP_PTR str; // Want this file, so store it in tempStore if (tempStoreOfs >= tempStoreSize) { tempStoreSize <<= 1; pTempStore = realloc(pTempStore, tempStoreSize * sizeof(void*)); } str = SystemString_FromCharPtrASCII(pResult); // Need to temporarily make these undeletable, in case a GC happens before they're in the array Heap_MakeUndeletable(str); pTempStore[tempStoreOfs++] = str; } } globfree(&gl); } else { *pError = errno; } #endif // Move the temp-store values into the final returnable array retArray = SystemArray_NewVector(types[TYPE_SYSTEM_ARRAY_STRING], tempStoreOfs); arrayElements = SystemArray_GetElements(retArray); memcpy(arrayElements, pTempStore, tempStoreOfs * sizeof(void*)); free(pTempStore); *(HEAP_PTR*)pReturnValue = retArray; // Make the strings deletable again for (i=0; i<tempStoreOfs; i++) { Heap_MakeDeletable(((HEAP_PTR*)arrayElements)[i]); } return NULL; }
/* * Read and execute commands from the terminal. */ void runcmdshell(void) { struct entry *np; ufs1_ino_t ino; struct arglist arglist; char curdir[MAXPATHLEN]; char name[MAXPATHLEN]; char cmd[BUFSIZ]; arglist.freeglob = 0; arglist.argcnt = 0; arglist.glob.gl_flags = GLOB_ALTDIRFUNC; arglist.glob.gl_opendir = (void *)rst_opendir; arglist.glob.gl_readdir = (void *)glob_readdir; arglist.glob.gl_closedir = (void *)rst_closedir; arglist.glob.gl_lstat = glob_stat; arglist.glob.gl_stat = glob_stat; canon("/", curdir, sizeof(curdir)); loop: if (setjmp(reset) != 0) { if (arglist.freeglob != 0) { arglist.freeglob = 0; arglist.argcnt = 0; globfree(&arglist.glob); } nextarg = NULL; volno = 0; } runshell = 1; getcmd(curdir, cmd, name, sizeof(name), &arglist); switch (cmd[0]) { /* * Add elements to the extraction list. */ case 'a': if (strncmp(cmd, "add", strlen(cmd)) != 0) goto bad; ino = dirlookup(name); if (ino == 0) break; if (mflag) pathcheck(name); treescan(name, ino, addfile); break; /* * Change working directory. */ case 'c': if (strncmp(cmd, "cd", strlen(cmd)) != 0) goto bad; ino = dirlookup(name); if (ino == 0) break; if (inodetype(ino) == LEAF) { fprintf(stderr, "%s: not a directory\n", name); break; } strcpy(curdir, name); break; /* * Delete elements from the extraction list. */ case 'd': if (strncmp(cmd, "delete", strlen(cmd)) != 0) goto bad; np = lookupname(name); if (np == NULL || (np->e_flags & NEW) == 0) { fprintf(stderr, "%s: not on extraction list\n", name); break; } treescan(name, np->e_ino, deletefile); break; /* * Extract the requested list. */ case 'e': if (strncmp(cmd, "extract", strlen(cmd)) != 0) goto bad; createfiles(); createlinks(); setdirmodes(0); if (dflag) checkrestore(); volno = 0; break; /* * List available commands. */ case 'h': if (strncmp(cmd, "help", strlen(cmd)) != 0) goto bad; /* FALLTHROUGH */ case '?': fprintf(stderr, "%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s", "Available commands are:\n", "\tls [arg] - list directory\n", "\tcd arg - change directory\n", "\tpwd - print current directory\n", "\tadd [arg] - add `arg' to list of", " files to be extracted\n", "\tdelete [arg] - delete `arg' from", " list of files to be extracted\n", "\textract - extract requested files\n", "\tsetmodes - set modes of requested directories\n", "\tquit - immediately exit program\n", "\twhat - list dump header information\n", "\tverbose - toggle verbose flag", " (useful with ``ls'')\n", "\thelp or `?' - print this list\n", "If no `arg' is supplied, the current", " directory is used\n"); break; /* * List a directory. */ case 'l': if (strncmp(cmd, "ls", strlen(cmd)) != 0) goto bad; printlist(name, curdir); break; /* * Print current directory. */ case 'p': if (strncmp(cmd, "pwd", strlen(cmd)) != 0) goto bad; if (curdir[1] == '\0') fprintf(stderr, "/\n"); else fprintf(stderr, "%s\n", &curdir[1]); break; /* * Quit. */ case 'q': if (strncmp(cmd, "quit", strlen(cmd)) != 0) goto bad; return; case 'x': if (strncmp(cmd, "xit", strlen(cmd)) != 0) goto bad; return; /* * Toggle verbose mode. */ case 'v': if (strncmp(cmd, "verbose", strlen(cmd)) != 0) goto bad; if (vflag) { fprintf(stderr, "verbose mode off\n"); vflag = 0; break; } fprintf(stderr, "verbose mode on\n"); vflag++; break; /* * Just restore requested directory modes. */ case 's': if (strncmp(cmd, "setmodes", strlen(cmd)) != 0) goto bad; setdirmodes(FORCE); break; /* * Print out dump header information. */ case 'w': if (strncmp(cmd, "what", strlen(cmd)) != 0) goto bad; printdumpinfo(); break; /* * Turn on debugging. */ case 'D': if (strncmp(cmd, "Debug", strlen(cmd)) != 0) goto bad; if (dflag) { fprintf(stderr, "debugging mode off\n"); dflag = 0; break; } fprintf(stderr, "debugging mode on\n"); dflag++; break; /* * Unknown command. */ default: bad: fprintf(stderr, "%s: unknown command; type ? for help\n", cmd); break; } goto loop; }
/* Read directories attributes */ int read_attr(config *syscheck, char *dirs, char **g_attrs, char **g_values) { char *xml_check_all = "check_all"; char *xml_check_sum = "check_sum"; char *xml_check_sha1sum = "check_sha1sum"; char *xml_check_md5sum = "check_md5sum"; char *xml_check_size = "check_size"; char *xml_check_owner = "check_owner"; char *xml_check_group = "check_group"; char *xml_check_perm = "check_perm"; char *xml_real_time = "realtime"; char *xml_report_changes = "report_changes"; char *xml_restrict = "restrict"; char *restrictfile = NULL; char **dir; char *tmp_str; dir = OS_StrBreak(',', dirs, MAX_DIR_SIZE); /* Max number */ char **dir_org = dir; int ret = 0, i; /* Dir can not be null */ if(dir == NULL) { return(0); } /* Doing it for each directory */ while(*dir) { int i = 0; int opts = 0; char *tmp_dir; char **attrs = NULL; char **values = NULL; tmp_dir = *dir; restrictfile = NULL; /* Removing spaces at the beginning */ while(*tmp_dir == ' ') { tmp_dir++; } /* Removing spaces at the end */ tmp_str = strchr(tmp_dir, ' '); if(tmp_str) { tmp_str++; /* Checking if it is really at the end */ if((*tmp_str == '\0') || (*tmp_str == ' ')) { tmp_str--; *tmp_str = '\0'; } } /* Getting the options */ if(!g_attrs || !g_values) { merror(SYSCHECK_NO_OPT, ARGV0, dirs); ret = 0; goto out_free; } attrs = g_attrs; values = g_values; while(*attrs && *values) { /* Checking all */ if(strcmp(*attrs, xml_check_all) == 0) { if(strcmp(*values, "yes") == 0) { opts|=CHECK_MD5SUM; opts|=CHECK_SHA1SUM; opts|=CHECK_PERM; opts|=CHECK_SIZE; opts|=CHECK_OWNER; opts|=CHECK_GROUP; } else if(strcmp(*values, "no") == 0) { } else { merror(SK_INV_OPT, ARGV0, *values, *attrs); ret = 0; goto out_free; } } /* Checking sum */ else if(strcmp(*attrs, xml_check_sum) == 0) { if(strcmp(*values, "yes") == 0) { opts|=CHECK_MD5SUM; opts|=CHECK_SHA1SUM; } else if(strcmp(*values, "no") == 0) { } else { merror(SK_INV_OPT, ARGV0, *values, *attrs); ret = 0; goto out_free; } } /* Checking md5sum */ else if(strcmp(*attrs, xml_check_md5sum) == 0) { if(strcmp(*values, "yes") == 0) { opts|=CHECK_MD5SUM; } else if(strcmp(*values, "no") == 0) { } else { merror(SK_INV_OPT, ARGV0, *values, *attrs); ret = 0; goto out_free; } } /* Checking sha1sum */ else if(strcmp(*attrs, xml_check_sha1sum) == 0) { if(strcmp(*values, "yes") == 0) { opts|=CHECK_SHA1SUM; } else if(strcmp(*values, "no") == 0) { } else { merror(SK_INV_OPT, ARGV0, *values, *attrs); ret = 0; goto out_free; } } /* Checking permission */ else if(strcmp(*attrs, xml_check_perm) == 0) { if(strcmp(*values, "yes") == 0) { opts|=CHECK_PERM; } else if(strcmp(*values, "no") == 0) { } else { merror(SK_INV_OPT, ARGV0, *values, *attrs); ret = 0; goto out_free; } } /* Checking size */ else if(strcmp(*attrs, xml_check_size) == 0) { if(strcmp(*values, "yes") == 0) { opts|=CHECK_SIZE; } else if(strcmp(*values, "no") == 0) { } else { merror(SK_INV_OPT, ARGV0, *values, *attrs); ret = 0; goto out_free; } } /* Checking owner */ else if(strcmp(*attrs, xml_check_owner) == 0) { if(strcmp(*values, "yes") == 0) { opts|=CHECK_OWNER; } else if(strcmp(*values, "no") == 0) { } else { merror(SK_INV_OPT, ARGV0, *values, *attrs); ret = 0; goto out_free; } } /* Checking group */ else if(strcmp(*attrs, xml_check_group) == 0) { if(strcmp(*values, "yes") == 0) { opts|=CHECK_GROUP; } else if(strcmp(*values, "no") == 0) { } else { merror(SK_INV_OPT, ARGV0, *values, *attrs); ret = 0; goto out_free; } } else if(strcmp(*attrs, xml_real_time) == 0) { if(strcmp(*values, "yes") == 0) { opts|=CHECK_REALTIME; } else if(strcmp(*values, "no") == 0) { } else { merror(SK_INV_OPT, ARGV0, *values, *attrs); ret = 0; goto out_free; } } else if(strcmp(*attrs, xml_report_changes) == 0) { if(strcmp(*values, "yes") == 0) { opts|=CHECK_SEECHANGES; } else if(strcmp(*values, "no") == 0) { } else { merror(SK_INV_OPT, ARGV0, *values, *attrs); ret = 0; goto out_free; } } else if(strcmp(*attrs, xml_restrict) == 0) { os_strdup(*values, restrictfile); } else { merror(SK_INV_ATTR, ARGV0, *attrs); ret = 0; goto out_free; } attrs++; values++; } /* You must have something set */ if(opts == 0) { merror(SYSCHECK_NO_OPT, ARGV0, dirs); if(restrictfile) free(restrictfile); ret = 0; goto out_free; } /* Adding directory - looking for the last available */ i = 0; while(syscheck->dir && syscheck->dir[i]) { int str_len_i; int str_len_dir; str_len_dir = strlen(tmp_dir); str_len_i = strlen(syscheck->dir[i]); if(str_len_dir > str_len_i) { str_len_dir = str_len_i; } /* Duplicate entry */ if(strcmp(syscheck->dir[i], tmp_dir) == 0) { merror(SK_DUP, ARGV0, tmp_dir); ret = 1; goto out_free; } i++; } /* Checking for glob. */ #ifndef WIN32 if(strchr(tmp_dir, '*') || strchr(tmp_dir, '?') || strchr(tmp_dir, '[')) { int gindex = 0; glob_t g; if(glob(tmp_dir, 0, NULL, &g) != 0) { merror(GLOB_ERROR, ARGV0, tmp_dir); ret = 1; goto out_free; } if(g.gl_pathv[0] == NULL) { merror(GLOB_NFOUND, ARGV0, tmp_dir); ret = 1; goto out_free; } while(g.gl_pathv[gindex]) { dump_syscheck_entry(syscheck, g.gl_pathv[gindex], opts, 0, restrictfile); gindex++; } globfree(&g); } else { dump_syscheck_entry(syscheck, tmp_dir, opts, 0, restrictfile); } #else dump_syscheck_entry(syscheck, tmp_dir, opts, 0, restrictfile); #endif if(restrictfile) { free(restrictfile); restrictfile = NULL; } /* Next entry */ dir++; } ret = 1; out_free: i = 0; while(dir_org[i]) free(dir_org[i++]); free(dir_org); return ret; }
int main(int argc, char* argv[]) { if (argc < 4 || argc > 6) { printf("Usage: ./test ./speller id submission_name memory [verbose]\n"); return 1; } float totalloadtime = 0; float totalchecktime = 0; float totalsizetime = 0; float totalunloadtime = 0; float totaltime = 0; float vals[8]; char linebuf[30]; char* path = "/home/cs50/pset6/texts/"; short int pathSize = strlen(path); glob_t data; glob_t data2; switch(glob("/home/cs50/pset6/texts/*.txt", 0, NULL, &data )) { case 0: break; case GLOB_NOSPACE: printf( "Out of memory\n" ); break; case GLOB_ABORTED: printf( "Reading error\n" ); break; case GLOB_NOMATCH: printf( "No files found\n" ); break; default: break; } switch(glob("/home/jharvard/Dropbox/spellerBigBoard/results", 0, NULL, &data2 )) { case 0: break; case GLOB_NOSPACE: printf( "Out of memory\n" ); break; case GLOB_ABORTED: printf( "Reading error\n" ); break; case GLOB_NOMATCH: printf( "directory /results not found\n" ); printf( "making /results \n" ); system("mkdir /home/jharvard/Dropbox/spellerBigBoard/results"); break; default: break; } char com[200]; char fname[100]; // data.gl_pathc for(int i = 0; i < data.gl_pathc; i++) { short int fcount = 0; for(int j = pathSize; j < strlen(data.gl_pathv[i]); j++) { fname[fcount] = data.gl_pathv[i][j]; fname[fcount+1] ='\0'; fcount++; } //printf( "%s %s\n", data.gl_pathv[i] , fname ); sprintf(com, "%s %s > results/%s", argv[1], data.gl_pathv[i], fname); system(com); } // prepare a data holder u may call it a file FILE* outfile = fopen("submis.txt","a+"); // collect the data data.gl_pathc int ntest = 0; for(int i = 0; i < data.gl_pathc; i++) { short int fcount = 0; for(int j = pathSize; j < strlen(data.gl_pathv[i]); j++) { fname[fcount] = data.gl_pathv[i][j]; fname[fcount+1] ='\0'; fcount++; } sprintf(com, "results/%s", fname); FILE* infile = fopen(com, "r"); if (infile) { fseek(infile,-150, SEEK_END); fgets(linebuf, sizeof(linebuf),infile); for(int j = 0; j < 6; j++) { fgets(linebuf, sizeof(linebuf),infile); int k = 20; int k2 = 0; while(linebuf[k] != '\n') { com[k2] = linebuf[k]; k++; k2++; } com[k2] = '\0'; vals[j] = atof(com); } } if (infile) { fclose(infile); } totalloadtime = totalloadtime + vals[0]; totalchecktime = totalchecktime + vals[1]; totalsizetime = totalsizetime + vals[2]; totalunloadtime = totalunloadtime + vals[3]; totaltime = totaltime + vals[4]; if (argc == 6) { sprintf(com, "%s,%1.4f,%1.4f,%1.4f,%1.4f,%1.4f\n", \ fname, vals[4], vals[0], vals[1], vals[2], vals[3] ); printf("%s", com); } ntest++; } sprintf(com, "%s,%s,%1.4f,%1.4f,%1.4f,%1.4f,%1.4f,%s\r\n", \ argv[2], argv[3], totaltime/ntest, totalloadtime/ntest, totalchecktime/ntest, \ totalsizetime/ntest, totalunloadtime/ntest, argv[4]); fwrite(com, strlen(com), 1, outfile); fclose(outfile); printf("%s", com); globfree(&data); return 0; }
gboolean tm_workspace_create_global_tags(const char *pre_process, const char **includes, int includes_count, const char *tags_file, int lang) { #ifdef HAVE_GLOB_H glob_t globbuf; size_t idx_glob; #endif int idx_inc; char *command; guint i; FILE *fp; TMWorkObject *source_file; GPtrArray *tags_array; GHashTable *includes_files_hash; GList *includes_files = NULL; gchar *temp_file = create_temp_file("tmp_XXXXXX.cpp"); gchar *temp_file2 = create_temp_file("tmp_XXXXXX.cpp"); if (NULL == temp_file || NULL == temp_file2 || NULL == theWorkspace || NULL == (fp = g_fopen(temp_file, "w"))) { g_free(temp_file); g_free(temp_file2); return FALSE; } includes_files_hash = g_hash_table_new_full (tm_file_inode_hash, g_direct_equal, NULL, g_free); #ifdef HAVE_GLOB_H globbuf.gl_offs = 0; if (includes[0][0] == '"') /* leading \" char for glob matching */ for(idx_inc = 0; idx_inc < includes_count; idx_inc++) { int dirty_len = strlen(includes[idx_inc]); char *clean_path = g_malloc(dirty_len - 1); strncpy(clean_path, includes[idx_inc] + 1, dirty_len - 1); clean_path[dirty_len - 2] = 0; #ifdef TM_DEBUG g_message ("[o][%s]\n", clean_path); #endif glob(clean_path, 0, NULL, &globbuf); #ifdef TM_DEBUG g_message ("matches: %d\n", globbuf.gl_pathc); #endif for(idx_glob = 0; idx_glob < globbuf.gl_pathc; idx_glob++) { #ifdef TM_DEBUG g_message (">>> %s\n", globbuf.gl_pathv[idx_glob]); #endif if (!g_hash_table_lookup(includes_files_hash, globbuf.gl_pathv[idx_glob])) { char* file_name_copy = strdup(globbuf.gl_pathv[idx_glob]); g_hash_table_insert(includes_files_hash, file_name_copy, file_name_copy); #ifdef TM_DEBUG g_message ("Added ...\n"); #endif } } globfree(&globbuf); g_free(clean_path); } else #endif /* no glob support or globbing not wanted */ for(idx_inc = 0; idx_inc < includes_count; idx_inc++) { if (!g_hash_table_lookup(includes_files_hash, includes[idx_inc])) { char* file_name_copy = strdup(includes[idx_inc]); g_hash_table_insert(includes_files_hash, file_name_copy, file_name_copy); } } /* Checks for duplicate file entries which would case trouble */ g_hash_table_foreach(includes_files_hash, tm_move_entries_to_g_list, &includes_files); includes_files = g_list_reverse (includes_files); #ifdef TM_DEBUG g_message ("writing out files to %s\n", temp_file); #endif if (pre_process != NULL) write_includes_file(fp, includes_files); else append_to_temp_file(fp, includes_files); g_list_free (includes_files); g_hash_table_destroy(includes_files_hash); includes_files_hash = NULL; includes_files = NULL; fclose(fp); /* FIXME: The following grep command removes the lines * G_BEGIN_DECLS and G_END_DECLS from the header files. The reason is * that in tagmanager, the files are not correctly parsed and the typedefs * following these lines are incorrectly parsed. The real fix should, * of course be in tagmanager (c) parser. This is just a temporary fix. */ if (pre_process != NULL) { command = g_strdup_printf("%s %s | grep -v -E '^\\s*(G_BEGIN_DECLS|G_END_DECLS)\\s*$' > %s", pre_process, temp_file, temp_file2); #ifdef TM_DEBUG g_message("Executing: %s", command); #endif system(command); g_free(command); g_unlink(temp_file); g_free(temp_file); } else { /* no pre-processing needed, so temp_file2 = temp_file */ g_unlink(temp_file2); g_free(temp_file2); temp_file2 = temp_file; temp_file = NULL; } source_file = tm_source_file_new(temp_file2, TRUE, tm_source_file_get_lang_name(lang)); if (NULL == source_file) { g_unlink(temp_file2); return FALSE; } g_unlink(temp_file2); g_free(temp_file2); if ((NULL == source_file->tags_array) || (0 == source_file->tags_array->len)) { tm_source_file_free(source_file); return FALSE; } tags_array = tm_tags_extract(source_file->tags_array, tm_tag_max_t); if ((NULL == tags_array) || (0 == tags_array->len)) { if (tags_array) g_ptr_array_free(tags_array, TRUE); tm_source_file_free(source_file); return FALSE; } if (FALSE == tm_tags_sort(tags_array, global_tags_sort_attrs, TRUE)) { tm_source_file_free(source_file); return FALSE; } if (NULL == (fp = g_fopen(tags_file, "w"))) { tm_source_file_free(source_file); return FALSE; } fprintf(fp, "# format=tagmanager\n"); for (i = 0; i < tags_array->len; ++i) { tm_tag_write(TM_TAG(tags_array->pdata[i]), fp, tm_tag_attr_type_t | tm_tag_attr_scope_t | tm_tag_attr_arglist_t | tm_tag_attr_vartype_t | tm_tag_attr_pointer_t); } fclose(fp); tm_source_file_free(source_file); g_ptr_array_free(tags_array, TRUE); return TRUE; }
void ngx_close_glob(ngx_glob_t *gl) { globfree(&gl->pglob); }
/** * Read a BIND9 like files with trust anchors in named.conf format. * Performs wildcard processing of name. * @param anchors: anchor storage. * @param buffer: parsing buffer. * @param pat: pattern string. (can be wildcarded) * @return false on error. */ static int anchor_read_bind_file_wild(struct val_anchors* anchors, sldns_buffer* buffer, const char* pat) { #ifdef HAVE_GLOB glob_t g; size_t i; int r, flags; if(!strchr(pat, '*') && !strchr(pat, '?') && !strchr(pat, '[') && !strchr(pat, '{') && !strchr(pat, '~')) { return anchor_read_bind_file(anchors, buffer, pat); } verbose(VERB_QUERY, "wildcard found, processing %s", pat); flags = 0 #ifdef GLOB_ERR | GLOB_ERR #endif #ifdef GLOB_NOSORT | GLOB_NOSORT #endif #ifdef GLOB_BRACE | GLOB_BRACE #endif #ifdef GLOB_TILDE | GLOB_TILDE #endif ; memset(&g, 0, sizeof(g)); r = glob(pat, flags, NULL, &g); if(r) { /* some error */ if(r == GLOB_NOMATCH) { verbose(VERB_QUERY, "trusted-keys-file: " "no matches for %s", pat); return 1; } else if(r == GLOB_NOSPACE) { log_err("wildcard trusted-keys-file %s: " "pattern out of memory", pat); } else if(r == GLOB_ABORTED) { log_err("wildcard trusted-keys-file %s: expansion " "aborted (%s)", pat, strerror(errno)); } else { log_err("wildcard trusted-keys-file %s: expansion " "failed (%s)", pat, strerror(errno)); } /* ignore globs that yield no files */ return 1; } /* process files found, if any */ for(i=0; i<(size_t)g.gl_pathc; i++) { if(!anchor_read_bind_file(anchors, buffer, g.gl_pathv[i])) { log_err("error reading wildcard " "trusted-keys-file: %s", g.gl_pathv[i]); globfree(&g); return 0; } } globfree(&g); return 1; #else /* not HAVE_GLOB */ return anchor_read_bind_file(anchors, buffer, pat); #endif /* HAVE_GLOB */ }
static int SetupGlobChain(char const *dirname, IncludeStruct *i) { DynamicBuffer pattern; char *dir; size_t l; int r; glob_t glob_buf; DirectoryFilenameChain *dc = CachedDirectoryChains; i->chain = NULL; if (!*dirname) return E_CANT_OPEN; dir = StrDup(dirname); if (!dir) return E_NO_MEM; /* Strip trailing slashes off directory */ l = strlen(dir); while(l) { if (*(dir+l-1) == '/') { l--; *(dir+l) = 0; } else { break; } } /* Repair root directory :-) */ if (!l) { *dir = '/'; } /* Check the cache */ while(dc) { if (!strcmp(dc->dirname, dir)) { if (DebugFlag & DB_TRACE_FILES) { fprintf(ErrFp, "Found cached directory listing for `%s'\n", dir); } free(dir); i->chain = dc->chain; return OK; } dc = dc->next; } if (DebugFlag & DB_TRACE_FILES) { fprintf(ErrFp, "Scanning directory `%s' for *.rem files\n", dir); } if (ShouldCache) { dc = malloc(sizeof(DirectoryFilenameChain)); if (dc) { dc->dirname = StrDup(dir); if (!dc->dirname) { free(dc); dc = NULL; } } if (dc) { if (DebugFlag & DB_TRACE_FILES) { fprintf(ErrFp, "Caching directory `%s' listing\n", dir); } dc->chain = NULL; dc->next = CachedDirectoryChains; CachedDirectoryChains = dc; } } DBufInit(&pattern); DBufPuts(&pattern, dir); DBufPuts(&pattern, "/*.rem"); free(dir); r = glob(DBufValue(&pattern), 0, NULL, &glob_buf); DBufFree(&pattern); if (r == GLOB_NOMATCH) { globfree(&glob_buf); return OK; } if (r != 0) { globfree(&glob_buf); return -1; } /* Add the files to the chain backwards to preserve sort order */ for (r=glob_buf.gl_pathc-1; r>=0; r--) { FilenameChain *ch = malloc(sizeof(FilenameChain)); if (!ch) { globfree(&glob_buf); FreeChain(i->chain); i->chain = NULL; return E_NO_MEM; } /* TODO: stat the file and only add if it's a plain file and readable by us */ ch->filename = StrDup(glob_buf.gl_pathv[r]); if (!ch->filename) { globfree(&glob_buf); FreeChain(i->chain); i->chain = NULL; free(ch); return E_NO_MEM; } ch->next = i->chain; i->chain = ch; } if (dc) { dc->chain = i->chain; } globfree(&glob_buf); return OK; }
FILE * ftpd_popen(char *program, char *type, int do_stderr, int no_glob) { char *cp; FILE *iop; int argc, gargc, pdes[2], pid; char **pop, *argv[MAXARGS], *gargv[MAXGLOBS]; char *foo; if (strcmp(type, "r") && strcmp(type, "w")) return (NULL); if (!pids) { /* This function is ugly and should be rewritten, in * modern unices there is no such thing as a maximum * filedescriptor. */ fds = getdtablesize(); pids = (int*)calloc(fds, sizeof(int)); if(!pids) return NULL; } if (pipe(pdes) < 0) return (NULL); /* break up string into pieces */ foo = NULL; for (argc = 0, cp = program; argc < MAXARGS - 1; cp = NULL) { if (!(argv[argc++] = strtok_r(cp, " \t\n", &foo))) break; } argv[MAXARGS - 1] = NULL; gargv[0] = (char*)ftp_rooted(argv[0]); /* glob each piece */ for (gargc = argc = 1; argv[argc] && gargc < MAXGLOBS - 1; argc++) { glob_t gl; int flags = GLOB_BRACE|GLOB_NOCHECK|GLOB_QUOTE|GLOB_TILDE | #ifdef GLOB_MAXPATH GLOB_MAXPATH #else GLOB_LIMIT #endif ; memset(&gl, 0, sizeof(gl)); if (no_glob || glob(argv[argc], flags, NULL, &gl) || gl.gl_pathc == 0) gargv[gargc++] = strdup(argv[argc]); else for (pop = gl.gl_pathv; *pop && gargc < MAXGLOBS - 1; pop++) gargv[gargc++] = strdup(*pop); globfree(&gl); } gargv[gargc] = NULL; iop = NULL; switch(pid = fork()) { case -1: /* error */ close(pdes[0]); close(pdes[1]); goto pfree; /* NOTREACHED */ case 0: /* child */ if (*type == 'r') { if (pdes[1] != STDOUT_FILENO) { dup2(pdes[1], STDOUT_FILENO); close(pdes[1]); } if(do_stderr) dup2(STDOUT_FILENO, STDERR_FILENO); close(pdes[0]); } else { if (pdes[0] != STDIN_FILENO) { dup2(pdes[0], STDIN_FILENO); close(pdes[0]); } close(pdes[1]); } execv(gargv[0], gargv); gargv[0] = argv[0]; execv(gargv[0], gargv); _exit(1); } /* parent; assume fdopen can't fail... */ if (*type == 'r') { iop = fdopen(pdes[0], type); close(pdes[1]); } else { iop = fdopen(pdes[1], type); close(pdes[0]); } pids[fileno(iop)] = pid; pfree: for (argc = 1; gargv[argc] != NULL; argc++) free(gargv[argc]); return (iop); }
//=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== quakefile_t *FindQuakeFilesWithPakFilter(char *pakfilter, char *filter) { #ifdef _WIN32 WIN32_FIND_DATA filedata; HWND handle; struct _stat statbuf; int done; #else glob_t globbuf; struct stat statbuf; int j; #endif quakefile_t *qfiles, *lastqf, *qf; char pakfile[_MAX_PATH], filename[_MAX_PATH], *str; qfiles = NULL; lastqf = NULL; if (pakfilter && strlen(pakfilter)) { #ifdef _WIN32 handle = FindFirstFile(pakfilter, &filedata); done = (handle == INVALID_HANDLE_VALUE); while(!done) { _splitpath(pakfilter, pakfile, NULL, NULL, NULL); _splitpath(pakfilter, NULL, &pakfile[strlen(pakfile)], NULL, NULL); AppendPathSeperator(pakfile, _MAX_PATH); strcat(pakfile, filedata.cFileName); _stat(pakfile, &statbuf); #else glob(pakfilter, 0, NULL, &globbuf); for (j = 0; j < globbuf.gl_pathc; j++) { strcpy(pakfile, globbuf.gl_pathv[j]); stat(pakfile, &statbuf); #endif //if the file with .pak or .pk3 is a folder if (statbuf.st_mode & S_IFDIR) { strcpy(filename, pakfilter); AppendPathSeperator(filename, _MAX_PATH); strcat(filename, filter); qf = FindQuakeFilesWithPakFilter(NULL, filename); if (lastqf) lastqf->next = qf; else qfiles = qf; lastqf = qf; while(lastqf->next) lastqf = lastqf->next; } //end if else { #ifdef _WIN32 str = StringContains(pakfile, ".pk3", false); #else str = StringContains(pakfile, ".pk3", true); #endif if (str && str == pakfile + strlen(pakfile) - strlen(".pk3")) { qf = FindQuakeFilesInZip(pakfile, filter); } //end if else { qf = NULL; } //end else // if (qf) { if (lastqf) lastqf->next = qf; else qfiles = qf; lastqf = qf; while(lastqf->next) lastqf = lastqf->next; } //end if } //end else // #ifdef _WIN32 //find the next file done = !FindNextFile(handle, &filedata); } //end while #else } //end for globfree(&globbuf); #endif } //end if else { #ifdef _WIN32 handle = FindFirstFile(filter, &filedata); done = (handle == INVALID_HANDLE_VALUE); while(!done) { _splitpath(filter, filename, NULL, NULL, NULL); _splitpath(filter, NULL, &filename[strlen(filename)], NULL, NULL); AppendPathSeperator(filename, _MAX_PATH); strcat(filename, filedata.cFileName); #else glob(filter, 0, NULL, &globbuf); for (j = 0; j < globbuf.gl_pathc; j++) { strcpy(filename, globbuf.gl_pathv[j]); #endif // qf = malloc(sizeof(quakefile_t)); if (!qf) Error("out of memory"); memset(qf, 0, sizeof(quakefile_t)); strcpy(qf->pakfile, ""); strcpy(qf->filename, filename); strcpy(qf->origname, filename); qf->length = 0; qf->type = QuakeFileType(filename); //add the file ot the list qf->next = NULL; if (lastqf) lastqf->next = qf; else qfiles = qf; lastqf = qf; #ifdef _WIN32 //find the next file done = !FindNextFile(handle, &filedata); } //end while #else } //end for globfree(&globbuf); #endif } //end else return qfiles; } //end of the function FindQuakeFilesWithPakFilter
// get the next file in the directory // automatically wrap if we've hit the end BOOL LLDir_Solaris::getNextFileInDir(const std::string &dirname, const std::string &mask, std::string &fname, BOOL wrap) { glob_t g; BOOL result = FALSE; fname = ""; if(!(dirname == mCurrentDir)) { // different dir specified, close old search mCurrentDirIndex = -1; mCurrentDirCount = -1; mCurrentDir = dirname; } std::string tmp_str; tmp_str = dirname; tmp_str += mask; if(glob(tmp_str.c_str(), GLOB_NOSORT, NULL, &g) == 0) { if(g.gl_pathc > 0) { if((int)g.gl_pathc != mCurrentDirCount) { // Number of matches has changed since the last search, meaning a file has been added or deleted. // Reset the index. mCurrentDirIndex = -1; mCurrentDirCount = g.gl_pathc; } mCurrentDirIndex++; if((mCurrentDirIndex >= (int)g.gl_pathc) && wrap) { mCurrentDirIndex = 0; } if(mCurrentDirIndex < (int)g.gl_pathc) { // llinfos << "getNextFileInDir: returning number " << mCurrentDirIndex << ", path is " << g.gl_pathv[mCurrentDirIndex] << llendl; // The API wants just the filename, not the full path. //fname = g.gl_pathv[mCurrentDirIndex]; char *s = strrchr(g.gl_pathv[mCurrentDirIndex], '/'); if(s == NULL) s = g.gl_pathv[mCurrentDirIndex]; else if(s[0] == '/') s++; fname = s; result = TRUE; } } globfree(&g); } return(result); }
int FileFindClose(void) { globfree(&glob_a); return 0; }
int fileop( char **src_p, int mode ) { char *name; int result = ERROR; int i; name = pop_s(); if ( !name ) { if ( mode == FILEOP_CHDIR ) { name = make_string_object( "~", -1 ); } else { cprintf( ERROR, CONT, "no file name given\n" ); return ( ERROR ); } } name = convert_home_path( name ); if ( mode == FILEOP_USE ) { glob_t g; glob( name, GLOB_TILDE | GLOB_MARK | GLOB_BRACE, NULL, &g ); if ( g.gl_pathc == 0 ) { cprintf( ERROR, CONT, "??? file \"%s\"\n", name ); return ( ERROR ); } else if ( (g.gl_pathc != 1) && (mode != FILEOP_USE) ) { cprintf( ERROR, CONT, "can not write into multiple files \"%s\"\n", name ); return ( ERROR ); } for ( i = 0; i < g.gl_pathc; i++ ) { result = fileop_use_by_name( (g.gl_pathv)[ i ] ); } globfree( &g ); } else if ( mode == FILEOP_PUT ) result = fileop_put_by_name( name ); else if ( mode == FILEOP_SAVE ) result = fileop_save_by_name( name ); else if ( mode == FILEOP_CHDIR ) { chdir( name ); result = NO_ERROR; } else result = ERROR; dispose_string_object( name ); return ( result ); }